PageSourceSearch

https://www.rankgale.ai/assets/index-D5miE-hU.js

js rankgale.ai collected 2026-10-05 14:56:57 UTC 1,944,129 bytes, 554 lines download raw bytes

1const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/KeywordsResearchPrototypeView-Do7pU-gA.js","assets/vendor-BqVFF4tb.js","assets/echarts-CazuOVAO.js","assets/SeoNewFlowView-XXkq9XxY.js","assets/AeoGeoNewFlowView-BXyy8Y4q.js","assets/ContentRefreshNewFlowView-Dsl_IpDG.js","assets/ContentGenerationFlowView-By5pYiqM.js","assets/StepsSidebar-atwVdyRn.js","assets/aeo_geo_flow-BR1Xruqk.js","assets/generated_content-ay1BBbbr.js","assets/PrototypeHomeView-DQZPmlhA.js","assets/HomeWorkflowsView-VmWIc6Ed.js","assets/SeoFlowView-mo0OxcKg.js","assets/AeoGeoFlowView-BQcGPuHi.js","assets/ContentRefreshFlowView-DMXhVQG1.js","assets/CompetitorDetailPage-Def0LlbR.js"])))=>i.map(i=>d[i]);
2import{cs as Mh,ct as Yc,bE as v,bH as e,bI as Lt,bF as r,bX as mt,cu as sc,bL as Ms,bM as Pt,cv as Na,bZ as is,cj as Al,ck as Jo,cw as Gn,cx as Xo,cy as nu,cz as Rh,c3 as Ks,cA as ru,cB as ac,cm as ns,bK as $t,bJ as wt,c5 as Ps,bN as eo,c9 as kt,cc as _r,cn as Ma,cC as Dr,c7 as Gs,cD as Rs,cE as ka,cF as Ri,c1 as Is,cG as Bt,cH as Cn,cI as to,cJ as Wn,cK as Vn,cp as Ha,cL as nc,cg as He,cM as gs,cN as Jc,c8 as Qt,bY as an,cO as Ja,c0 as Qs,bP as us,cP as Di,b$ as es,cq as qr,cQ as Ra,cR as Vs,b_ as cn,ce as Qn,cS as ci,c2 as Ws,bS as dn,cT as Sn,cU as Ss,cV as Ys,cW as Ga,cX as Dh,cY as ou,cZ as rn,cl as rc,c_ as oc,c$ as Lh,d0 as zh,ch as vs,d1 as $h,d2 as Fh,d3 as Lr,d4 as Qi,d5 as Oh,bU as En,d6 as Bh,bV as qa,cf as un,ci as Ua,d7 as Wa,d8 as Hs,d9 as nn,da as ja,db as Ka,dc as ic,cd as on,cb as iu,dd as lu,de as Uh,df as cu,cr as go,dg as ln,dh as du,di as Kh,ca as di,dj as Gh,c6 as mu,dk as as,dl as mi,dm as lc,bQ as _o,bR as uu,dn as xu,dp as hu,bT as Zn,dq as pu,dr as gu,ds as Wh,dt as Vh,du as Hh,dv as qh,dw as Yh,dx as Xc,dy as er,dz as Jh,V as Xh,dA as Zi,dB as Qh,dC as cc,dD as dc,dE as Zh,dF as mc,dG as ui,bW as Li,dH as zi,dI as qn,dJ as _a,dK as fu,dL as fo,dM as ep,dN as tp,dO as so,dP as Qc,dQ as sp,dR as ap,dS as Qo,dT as Zo,dU as ei,dV as yr,dW as Yr,dX as ti,dY as si,dZ as np,d_ as rp,d$ as op,e0 as ip,e1 as lp,e2 as cp,e3 as dp,e4 as mp,e5 as up,e6 as xp,e7 as hp,e8 as pp,e9 as gp,ea as fp,eb as yp,ec as bp,ed as wp,ee as jp,ef as vp,eg as Np,eh as kp,ei as _p,ej as Cp,ek as uc,el as Sp,em as Ep,en as Ap,eo as Tp,ep as Pp,eq as Kr,er as Ip,es as Mp,et as Rp,eu as yu,ev as Dp,ew as Lp,ex as zp,ey as $p,ez as Fp,eA as Op,eB as Bp,eC as Up,eD as Zc,eE as Kp,eF as Gp,eG as Wp,eH as Vp,eI as ed,eJ as Hp,eK as td,eL as qp,eM as Yp,eN as Jp}from"./vendor-BqVFF4tb.js";import{E as Cr}from"./echarts-CazuOVAO.js";(function(){const s=document.createElement("link").relList;if(s&&s.supports&&s.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))n(o);new MutationObserver(o=>{for(const i of o)if(i.type==="childList")for(const l of i.addedNodes)l.tagName==="LINK"&&l.rel==="modulepreload"&&n(l)}).observe(document,{childList:!0,subtree:!0});function a(o){const i={};return o.integrity&&(i.integrity=o.integrity),o.referrerPolicy&&(i.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?i.credentials="include":o.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function n(o){if(o.ep)return;o.ep=!0;const i=a(o);fetch(o.href,i)}})();const sd={BASE_URL:"/",DEV:!1,MODE:"production",PROD:!0,SSR:!1};class wa{static getString(s,a){if(typeof window<"u"){const i=window?.__APP_CONFIG__?.[s];if(typeof i=="string"&&i.trim())if(a?.pattern&&!a.pattern.test(i))console.warn(`[config] ${s} does not match pattern at runtime`);else return i}const n=sd?.[s];if(typeof n=="string"&&n.trim())if(a?.pattern&&!a.pattern.test(n))console.warn(`[config] ${s} does not match pattern at build time`);else return n;a?.required&&console.error(`[config] missing required key: ${s}`);const o=sd[s];if(o)return o}static getUrl(s,a){return this.getString(s,{required:a?.required,pattern:/^https?:\/\//})}}const Xp={},xi="logto_post_sign_in_url",xc="logto_landing_to_dashboard";class hc{constructor(){this.client=null}static{this.instance=null}getClient(){if(this.client)return this.client;const s=wa.getString("VITE_LOGTO_ENDPOINT"),a=wa.getString("VITE_LOGTO_APP_ID"),n=this.computeBaseUrl();if(!s||!a)throw console.error("[logto] Missing required config: VITE_LOGTO_ENDPOINT or VITE_LOGTO_APP_ID"),new Error("Logto configuration is missing. Please set VITE_LOGTO_ENDPOINT and VITE_LOGTO_APP_ID.");const o=s.replace(/\/+$/,"");try{new URL(o)}catch{throw console.error("[logto] Invalid VITE_LOGTO_ENDPOINT:",s),new Error("Invalid Logto endpoint URL.")}const i=wa.getString("VITE_LOGTO_RESOURCE"),l=i?[i]:void 0;
2i&&!l&&console.warn("[logto] VITE_LOGTO_RESOURCE is not a valid absolute URI; auto-normalization failed:",i);const c=["openid","profile","email","phone"],d=wa.getString("VITE_LOGTO_SCOPES"),m=d?d.split(",").map(f=>f.trim()).filter(Boolean):[],h=new Set([...c,...m]),p=Array.from(h);return this.client=new Mh({endpoint:o,appId:a,resources:l,scopes:p}),typeof window<"u"&&(window.__LOGTO_BASE_URL__=n),this.client}computeBaseUrl(){if(typeof window>"u")return Xp?.VITE_PUBLIC_BASE_URL||"http://localhost:5173";const{protocol:s,host:a}=window.location;return`${s}//${a}`}static getInstance(){return this.instance||(this.instance=new hc),this.instance}async isAuthenticated(){try{return await this.getClient().isAuthenticated()}catch{return!1}}async signIn(){const s=this.getClient(),n=`${this.computeBaseUrl()}/auth/logto/callback`;try{try{typeof window<"u"&&sessionStorage.setItem(xi,window.location.href)}catch(o){console.warn("⚠️ [logto] Failed to persist post sign-in url:",o)}console.debug("[logto] signIn params",{redirectUri:n,locationHref:typeof window<"u"?window.location.href:""}),await s.signIn({redirectUri:n,prompt:Yc.Login})}catch(o){throw console.error("[logto] signIn failed:",o),new Error("Failed to start sign-in. Check Logto configuration.")}}async signUp(){const s=this.getClient(),n=`${this.computeBaseUrl()}/auth/logto/callback`;try{try{typeof window<"u"&&sessionStorage.setItem(xi,window.location.href)}catch(o){console.warn("⚠️ [logto] Failed to persist post sign-in url:",o)}console.debug("[logto] signUp params",{redirectUri:n,locationHref:typeof window<"u"?window.location.href:""}),await s.signIn({redirectUri:n,firstScreen:"register",prompt:Yc.Login})}catch(o){throw console.error("[logto] signUp failed:",o),new Error("Failed to start sign-up. Check Logto configuration.")}}async signOut(){const a=`${this.computeBaseUrl()}/`;try{if(!this.client)try{this.getClient()}catch(n){console.warn("⚠️ [logto] Cannot initialize client for signOut:",n);return}this.client&&await this.client.signOut(a)}catch(n){throw console.warn("⚠️ [logto] signOut failed, may be due to expired session:",n),n}}async handleCallback(){const s=this.getClient();try{const a=window.location.href,n=new URL(a),o=Object.fromEntries(n.searchParams.entries());console.debug("[logto] handleCallback href & params",{href:a,params:o}),await s.handleSignInCallback(a)}catch(a){throw console.error("[logto] handleCallback failed:",a),new Error("Failed to handle sign-in callback.")}}async getBackendAccessToken(){const s=this.getClient();try{const a=wa.getString("VITE_LOGTO_RESOURCE");if(a){const n=await s.getAccessToken(a);if(n){const o=n.includes(".")&&n.split(".").length===3;return n}}else{const n=await s.getAccessToken();if(n){const o=n.includes(".")&&n.split(".").length===3;return n}}throw new Error("Failed to get access token.")}catch{return console.error("[logto] getBackendAccessToken failed:"),null}}async getLogtoAccessTokenForUserInfo(){try{try{const i=await this.getClient().getAccessToken();if(i)return i}catch{}const s=wa.getString("VITE_LOGTO_APP_ID");if(!s)return console.warn("[logto] VITE_LOGTO_APP_ID not configured"),null;const a=`logto:${s}:accessToken`,n=localStorage.getItem(a);if(!n)return console.debug("[logto] No access token found in localStorage for key:",a),null;try{const o=JSON.parse(n);if(o&&typeof o=="object"){try{const i=o["@"];if(i&&typeof i=="object"&&i.token)return i.token}catch{}for(const[i,l]of Object.entries(o))if(l&&typeof l=="object"&&l.token)return l.token;if(o.token)return o.token}if(typeof o=="string")return o}catch{return n}return null}catch(s){return console.error("[logto] Failed to get Logto access token from localStorage:",s),null}}async getUserProfile(){const s=this.getClient();try{const a=await s.getIdTokenClaims();if(!a)return null;const n=String(a.sub||""),o=a.email??null,i=a.name||a.preferred_username||null;return n?{id:n,email:o,name:i}:null}catch{return null}}}const rs=hc.getInstance(),Qp={BASE_URL:"/",DEV:!1,MODE:"production",PROD:!0,SSR:!1},yo=()=>{try{const t=localStorage.getItem("access_token");return t?JSON.parse(t):null}catch(t){return console.warn("⚠️ [authStorage] Failed to parse auth from localStorage:",t),null}};function bu(){try{localStorage.removeItem("access_token");const t=Qp?.VITE_LOGTO_APP_ID;if(t){const a=`logto:${t}:`,n=[];for(let o=0;o<localStorage.length;o++){const i=localStorage.key(o);i&&i.startsWith(a)&&n.push(i)}n.forEach(o=>localStorage.removeItem(o))}const s=[];for(let a=0;a<localStorage.length;a++){const n=localStorage.key(a);n&&n.startsWith("logto:")&&s.push(n)}s.forEach(a=>localStorage.removeItem(a)),console.log("🧹 [authStorage] Cleared authentication storage")}catch(t){console.error("❌ [authStorage] Failed to clear auth storage:",t)}}let el=null;const wu=async()=>
2{if(el)return el;const t=await rs.getUserProfile();if(t){const s=t.name||"",a={id:t.id,email:t.email||"",name:t.name||"",username:s,company:"",created_at:Date.now(),preference:{model_provider:"",model_name:""},email_verified:void 0};return el=a,a}throw new Error("Unauthorized")};async function An(){await rs.signIn()}async function ad(){await rs.signUp()}async function Zp(){try{await rs.signOut()}catch(t){console.warn("⚠️ [auth] Logto signOut failed, clearing local storage anyway:",t)}finally{bu()}}function jt(t,s,a={}){try{let n=t==="home"?"/app":`/app/${t}`;if(s){const i=new URLSearchParams(s).toString();i&&(n+=`?${i}`)}window.location.pathname+window.location.search!==n&&(a.replace?window.history.replaceState({},"",n):window.history.pushState({},"",n),window.dispatchEvent(new PopStateEvent("popstate")))}catch{}}function nd(t,s){try{let a=t==="home"?"/app":`/app/${t}`;if(s){const o=new URLSearchParams(s).toString();o&&(a+=`?${o}`)}window.open(a,"_blank","noopener,noreferrer")}catch{}}function da(){try{return new URLSearchParams(window.location.search).get("campaign")}catch{return null}}function hi(t){const s=(t||"/").split("/").filter(Boolean);if(s[0]!=="app")return;if(s.length===1||s[1]==="homepage"||s[1]==="workflow")return"home";if(s[1]==="prototype"||s[1]==="prototpye")return s[2]?s[2]==="seo"||s[2]==="keywords-research"?"seo_new_flow":s[2]==="aeo-geo"||s[2]==="ai-visibility"?"aeo_geo_new_flow":s[2]==="content-refresh"||s[2]==="content_refresh"?"content_refresh_new_flow":s[2]==="content-generation"||s[2]==="content_generation"?"content_generation_new_flow":"prototype_home":"prototype_home";if(s[1]==="workflow"&&s[2]==="competitors_keywords"&&s[3]==="prototype")return"workflow_prototype";if(s[1]==="setup"&&s[2]==="prototype")return"setup_prototype";const a=s[1]||"landing";return["landing","homepage","workflow","workflow_prototype","setup_prototype","app_prototype","seo_new_flow","aeo_geo_new_flow","content_refresh_new_flow","content_generation_new_flow","seo_flow","aeo_geo_flow","content_refresh_flow","content_generation_flow","prototype_home","company","campaigns","worksheets","keywords","keyword-groups","content","knowledge","data_report","page_tracking","report","subscription","usage_history","integration","attribution_insight","table","table-new","components_test","competitors","keywords_tracking","keyword_research","keyword_gap","geo_prompt","content_generated","setup","admin"].includes(a)?a:"landing"}function rd(){try{const s=window.location.pathname.split("/").filter(Boolean);if(s[0]==="app"&&s[1]==="knowledge"){const a=s[2]||null;if(s[3]==="document"){const n=s[4]||null;return{kbId:a,docId:n}}return{kbId:a,docId:null}}return{kbId:null,docId:null}}catch{return{kbId:null,docId:null}}}function Gr(){try{const t="/app/knowledge";window.location.pathname!==t&&(window.history.pushState({},"",t),window.dispatchEvent(new PopStateEvent("popstate")))}catch{}}function Qa(t){try{const s=`/app/knowledge/${t}`;window.location.pathname!==s&&(window.history.pushState({},"",s),window.dispatchEvent(new PopStateEvent("popstate")))}catch{}}function ai(t,s){try{const a=`/app/knowledge/${t}/document/${s}`;window.location.pathname!==a&&(window.history.pushState({},"",a),window.dispatchEvent(new PopStateEvent("popstate")))}catch{}}function eg(t){try{const s=`/app/competitors/detail?domain=${encodeURIComponent(t)}`;window.location.pathname+window.location.search!==s&&(window.history.pushState({},"",s),window.dispatchEvent(new PopStateEvent("popstate")))}catch{}}function tg(t){try{const s=`/app/workflow/${t}`;window.location.pathname!==s&&(window.history.pushState({},"",s),window.dispatchEvent(new PopStateEvent("popstate")))}catch{}}function sg(t="landing"){const[s,a]=v.useState(()=>hi(window.location.pathname)||t);return v.useEffect(()=>{const n=()=>{const o=hi(window.location.pathname)||t;a(o)};return window.addEventListener("popstate",n),()=>window.removeEventListener("popstate",n)},[t]),s}function dr({className:t,alt:s="RankGale",imgClassName:a,loading:n="eager"}){return e.jsx("div",{className:Lt("overflow-hidden bg-slate-900",t),children:e.jsx("img",{src:"/logo.png",alt:s,loading:n,draggable:!1,
2className:Lt("w-full h-full object-cover",a)})})}const ag=()=>{const[t,s]=r.useState(!1),[a,n]=r.useState(!1),[o,i]=r.useState(null),[l,c]=r.useState(!1);r.useEffect(()=>{let f=!0;return(async()=>{try{const b=await rs.isAuthenticated();if(!f)return;if(n(b),b){const y=await rs.getUserProfile();f&&y&&i(y)}}catch{f&&n(!1)}})(),()=>{f=!1}},[]),r.useEffect(()=>{const f=()=>{c(window.scrollY>50)};return window.addEventListener("scroll",f),()=>window.removeEventListener("scroll",f)},[]);async function d(f){f.preventDefault();try{await rs.isAuthenticated()?jt("homepage"):await An()}catch{await An()}}async function m(f){f.preventDefault();try{await rs.isAuthenticated()?jt("homepage"):await ad()}catch{await ad()}}const h=()=>{document.getElementById("booking")?.scrollIntoView({behavior:"smooth"})},p=o?.name||o?.email||o?.id||"";return e.jsxs("nav",{className:`fixed w-full z-50 transition-all duration-300 ${l?"bg-white/95 backdrop-blur-md border-b border-slate-200 shadow-sm":"bg-white/80 backdrop-blur-md border-b border-slate-100"}`,children:[e.jsx("div",{className:"max-w-7xl mx-auto px-4 sm:px-6 lg:px-8",children:e.jsxs("div",{className:"flex justify-between h-16 items-center",children:[e.jsxs("div",{className:"flex-shrink-0 flex items-center gap-2 cursor-pointer",onClick:()=>window.scrollTo(0,0),children:[e.jsx(dr,{className:"w-8 h-8 rounded-lg",alt:"RankGale"}),e.jsx("span",{className:"font-bold text-xl tracking-tight text-slate-900",children:"RankGale"})]}),e.jsxs("div",{className:"hidden md:flex space-x-8 items-center",children:[e.jsx("a",{href:"#features",className:"text-slate-600 hover:text-blue-600 font-medium transition-colors font-display",children:"Features"}),e.jsx("a",{href:"#pricing",className:"text-slate-600 hover:text-blue-600 font-medium transition-colors font-display",children:"Pricing"}),e.jsx("a",{href:"/blogs",className:"text-slate-600 hover:text-blue-600 font-medium transition-colors font-display",children:"Blog"}),a&&o?e.jsxs("button",{onClick:()=>jt("homepage"),className:"flex items-center gap-2 bg-slate-100 text-slate-700 px-4 py-2 rounded-lg font-medium cursor-pointer hover:bg-slate-200 transition-colors",title:`${o.email||p} - Click to go to homepage`,children:[e.jsx("div",{className:"w-6 h-6 bg-blue-600 rounded-full flex items-center justify-center text-white text-xs font-bold",children:p.charAt(0).toUpperCase()}),e.jsx("span",{className:"max-w-[120px] truncate",children:p})]}):e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("a",{href:"#",onClick:d,className:"text-slate-600 hover:text-slate-900 px-4 py-2 rounded-lg font-medium transition-colors font-display",children:"Log In"}),e.jsx("a",{href:"#",onClick:m,className:"bg-slate-900 text-white px-4 py-2 rounded-lg font-medium hover:bg-slate-800 transition-colors font-display",children:"Get Started"}),e.jsx("button",{onClick:h,className:"bg-blue-600 text-white px-4 py-2 rounded-lg font-medium hover:bg-blue-700 transition-colors font-display",children:"Book Demo"})]})]}),e.jsx("div",{className:"md:hidden flex items-center",children:e.jsx("button",{onClick:()=>s(!t),className:"text-slate-600",children:t?e.jsx(mt,{size:24}):e.jsx(sc,{size:24})})})]})}),t&&e.jsx("div",{className:"md:hidden bg-white border-b border-slate-200 absolute w-full shadow-lg",children:e.jsxs("div",{className:"px-4 pt-2 pb-6 space-y-2",children:[e.jsx("a",{href:"#features",onClick:()=>s(!1),className:"block px-3 py-2 rounded-md text-base font-medium text-slate-700 hover:bg-slate-50 font-display",children:"Features"}),e.jsx("a",{href:"#pricing",onClick:()=>s(!1),className:"block px-3 py-2 rounded-md text-base font-medium text-slate-700 hover:bg-slate-50 font-display",children:"Pricing"}),e.jsx("a",{href:"/blogs",onClick:()=>s(!1),className:"block px-3 py-2 rounded-md text-base font-medium text-slate-700 hover:bg-slate-50 font-display",children:"Blog"}),e.jsx("div",{className:"pt-4 space-y-2",children:a&&o?e.jsx("button",{onClick:()=>{jt("homepage"),s(!1)},className:"block w-full text-center bg-slate-900 text-white px-5 py-3 rounded-lg font-medium hover:bg-slate-800",children:"Go to Dashboard"}):e.jsxs(e.Fragment,{children:[e.jsx("a",{href:"#",onClick:f=>{m(f),s(!1)},className:"block w-full text-center bg-slate-900 text-white px-5 py-3 rounded-lg font-medium hover:bg-slate-800",children:"Get Started"}),e.jsx("button",{onClick:()=>{h(),s(!1)},className:"block w-full text-center bg-blue-600 text-white px-5 py-3 rounded-lg font-medium hover:bg-blue-700",children:"Book Demo"})]})})]})})]})},ng=({className:t="w-5 h-5"})=>e.jsxs("svg",{viewBox:"0 0 24 24",className:t,children:[e.jsx("path",{fill:"#4285F4",d:"M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"}),e.jsx("path",{fill:"#34A853",d:"M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"}),e.jsx("path",{fill:"#FBBC05",d:"M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z"}),e.jsx("path",{fill:"#EA4335",d:"M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z"})]}),rg=({className:t="w-5 h-5"})=>e.jsx("svg",{viewBox:"0 0 24 24",className:t,fill:"#10a37f",children:e.jsx("path",{d:"M22.282 9.821a5.985 5.985 0 0 0-.516-4.91 6.046 6.046 0 0 0-6.51-2.9A6.065 6.065 0 0 0 4.981 4.18a5.985 5.985 0 0 0-3.998 2.9 6.046 6.046 0 0 0 .743 7.097 5.98 5.98 0 0 0 .51 4.911 6.051 6.051 0 0 0 6.515 2.9A5.985 5.985 0 0 0 13.26 24a6.056 6.056 0 0 0 5.772-4.206 5.99 5.99 0 0 0 3.997-2.9 6.056 6.056 0 0 0-.747-7.073zM13.26 22.43a4.476 4.476 0 0 1-2.876-1.04l.141-.081 4.779-2.758a.795.795 0 0 0 .392-.681v-6.737l2.02 1.168a.071.071 0 0 1 .038.052v5.583a4.504 4.504 0 0 1-4.494 4.494zM3.6 18.304a4.47 4.47 0 0 1-.535-3.014l.142.085 4.783 2.759a.771.771 0 0 0 .78 0l5.843-3.369v2.332a.08.08 0 0 1-.033.062L9.74 19.95a4.5 4.5 0 0 1-6.14-1.646zM2.34 7.896a4.485 4.485 0 0 1 2.366-1.973V11.6a.766.766 0 0 0 .388.676l5.815 3.355-2.02 1.168a.076.076 0 0 1-.071 0l-4.83-2.786A4.504 4.504 0 0 1 2.34 7.872zm16.597 3.855l-5.833-3.387L15.119 7.2a.076.076 0 0 1 .071 0l4.83 2.791a4.494 4.494 0 0 1-.676 8.105v-5.678a.79.79 0 0 0-.407-.667zm2.01-3.023l-.141-.085-4.774-2.782a.776.776 0 0 0-.785 0L9.409 9.23V6.897a.066.066 0 0 1 .028-.061l4.83-2.787a4.5 4.5 0 0 1 6.68 4.66zm-12.64 4.135l-2.02-1.164a.08.08 0 0 1-.038-.057V6.075a4.5 4.5 0 0 1 7.375-3.453l-.142.08L8.704 5.46a.795.795 0 0 0-.393.681zm1.097-2.365l2.602-1.5 2.607 1.5v2.999l-2.597 1.5-2.607-1.5z"})}),og=({className:t="w-5 h-5"})=>e.jsx("img",{src:"/perplexity-logo.png",alt:"Perplexity",className:t}),ig=({className:t="w-5 h-5"})=>e.jsx("img",{src:"/claude-logo.svg",alt:"Claude",className:t}),lg=({className:t="w-5 h-5"})=>e.jsx("img",{src:"/grok-logo.svg",alt:"Grok",className:t}),od=[{name:"Google",Logo:ng},{name:"ChatGPT",Logo:rg},{name:"Perplexity",Logo:og},{name:"Claude",Logo:ig},{name:"Grok",Logo:lg}],cg=()=>{const[t,s]=r.useState(!1),[a,n]=r.useState(0);r.useEffect(()=>{let c=!0;return(async()=>{try{const d=await rs.isAuthenticated();c&&s(d)}catch{c&&s(!1)}})(),()=>{c=!1}},[]),r.useEffect(()=>{const c=setInterval(()=>{n(d=>(d+1)%od.length)},2e3);return()=>clearInterval(c)},[]);const o=async c=>{c.preventDefault();try{await rs.isAuthenticated()?jt("homepage"):await An()}catch(d){console.error("Auth error:",d),await An()}},i=()=>{document.getElementById("booking")?.scrollIntoView({behavior:"smooth"})},l=od[a];return e.jsxs("section",{className:"relative min-h-[90vh] flex items-center justify-center overflow-hidden bg-gradient-to-b from-slate-50 via-white to-blue-50/30",children:[e.jsx("div",{className:"absolute inset-0 bg-[linear-gradient(to_right,#e2e8f0_1px,transparent_1px),linear-gradient(to_bottom,#e2e8f0_1px,transparent_1px)] bg-[size:4rem_4rem] opacity-40"}),e.jsx("div",{className:"absolute top-1/4 left-1/4 w-96 h-96 bg-blue-200/30 rounded-full blur-[120px]"}),e.jsx("div",{className:"absolute bottom-1/4 right-1/4 w-96 h-96 bg-cyan-200/30 rounded-full blur-[120px]"}),e.jsxs("div",{className:"relative z-10 w-full mx-auto px-6 py-28 text-center overflow-hidden",children:[e.jsxs("h1",{className:"text-5xl md:text-6xl lg:text-7xl xl:text-8xl font-display font-normal italic text-slate-900 mb-10 tracking-tight leading-[1.15] flex flex-wrap md:flex-nowrap items-center justify-center gap-x-4 gap-y-3 md:gap-x-5 lg:gap-x-6",children:[e.jsx("span",{className:"whitespace-normal text-balance",children:"One Engine for Visibility Across"}),e.jsx("span",{className:"inline-flex items-center animate-fade-in",children:l&&e.jsx(l.Logo,{className:"w-12 h-12 md:w-14 md:h-14 lg:w-16 lg:h-16 xl:w-20 xl:h-20"})},`logo-${l?.name}`)]}),e.jsxs("p",{className:"text-lg md:text-xl text-slate-600 mb-12 max-w-3xl mx-auto leading-relaxed font-sans",children:[e.jsx("span",{className:"font-semibold text-slate-800",children:"From research to results:"})," ","uncover opportunities, create content, win visibility across AI and search — fully automated with"," ",e.jsx("span",{className:"underline decoration-slate-300 underline-offset-4",children:"top 1% expertise"}),"."]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4 justify-center items-center mb-20",children:[e.jsxs("button",{onClick:o,className:"group flex items-center gap-2 bg-slate-900 text-white px-8 py-4 rounded-full font-medium text-lg hover:bg-slate-800 transition-all duration-200 shadow-lg hover:shadow-xl hover:scale-[1.02]",children:[t?"Go to Dashboard":"Start Free",e.jsx(Ms,{className:"w-5 h-5 group-hover:translate-x-1 transition-transform"})]}),e.jsx("button",{onClick:i,className:"flex items-center gap-2 bg-white text-slate-900 px-8 py-4 rounded-full font-medium text-lg border-2 border-slate-200 hover:border-slate-900 transition-all duration-200 shadow-sm hover:shadow-md",children:"Book a Demo"})]}),e.jsxs("div",{className:"w-full max-w-5xl mx-auto pt-8 border-t border-slate-200/50",children:[e.jsx("p",{className:"text-base text-slate-500 mb-10 tracking-wide",children:"Trusted and built by talents from"}),e.jsxs("div",{className:"relative overflow-hidden",children:[e.jsx("div",{className:"absolute left-0 top-0 bottom-0 w-24 bg-gradient-to-r from-blue-50/90 to-transparent z-10 pointer-events-none"}),e.jsx("div",{className:"absolute right-0 top-0 bottom-0 w-24 bg-gradient-to-l from-blue-50/90 to-transparent z-10 pointer-events-none"}),e.jsxs("div",{className:"flex animate-marquee",children:[e.jsxs("div",{className:"flex items-center gap-20 px-10 shrink-0",children:[e.jsx("img",{src:"/logos/y-combinator.svg",alt:"Y Combinator",className:"h-10 w-auto opacity-70 hover:opacity-100 transition-opacity duration-300"}),e.jsx("img",{src:"/logos/Stanford_University-Logo.wine.svg",alt:"Stanford",className:"h-9 w-auto opacity-70 hover:opacity-100 transition-opacity duration-300"}),e.jsx("img",{src:"/logos/Massachusetts_Institute_of_Technology-Logo.wine.svg",alt:"MIT",className:"h-9 w-auto opacity-70 hover:opacity-100 transition-opacity duration-300"}),e.jsx("img",{src:"/logos/University_of_California,_Berkeley-Logo.wine.svg",alt:"Berkeley",className:"h-9 w-auto opacity-70 hover:opacity-100 transition-opacity duration-300"}),e.jsx("img",{src:"/logos/google-1-1.svg",alt:"Google",className:"h-10 w-auto opacity-70 hover:opacity-100 transition-opacity duration-300"}),e.jsx("img",{src:"/logos/Meta_Platforms-Logo.wine.svg",alt:"Meta",className:"h-9 w-auto opacity-70 hover:opacity-100 transition-opacity duration-300"}),e.jsx("img",{src:"/logos/amazon-com-logo-1.svg",alt:"Amazon",className:"h-9 w-auto opacity-70 hover:opacity-100 transition-opacity duration-300"})]}),e.jsxs("div",{className:"flex items-center gap-20 px-10 shrink-0",children:[e.jsx("img",{src:"/logos/y-combinator.svg",alt:"Y Combinator",className:"h-10 w-auto opacity-70 hover:opacity-100 transition-opacity duration-300"}),e.jsx("img",{src:"/logos/Stanford_University-Logo.wine.svg",alt:"Stanford",className:"h-9 w-auto opacity-70 hover:opacity-100 transition-opacity duration-300"}),e.jsx("img",{src:"/logos/Massachusetts_Institute_of_Technology-Logo.wine.svg",alt:"MIT",className:"h-9 w-auto opacity-70 hover:opacity-100 transition-opacity duration-300"}),e.jsx("img",{src:"/logos/University_of_California,_Berkeley-Logo.wine.svg",alt:"Berkeley",className:"h-9 w-auto opacity-70 hover:opacity-100 transition-opacity duration-300"}),e.jsx("img",{src:"/logos/google-1-1.svg",alt:"Google",className:"h-10 w-auto opacity-70 hover:opacity-100 transition-opacity duration-300"}),e.jsx("img",{src:"/logos/Meta_Platforms-Logo.wine.svg",alt:"Meta",className:"h-9 w-auto opacity-70 hover:opacity-100 transition-opacity duration-300"}),e.jsx("img",{src:"/logos/amazon-com-logo-1.svg",alt:"Amazon",className:"h-9 w-auto opacity-70 hover:opacity-100 transition-opacity duration-300"})]})]})]})]})]}),e.jsx("style",{children:`
3        @keyframes fadeIn {
4          from { opacity: 0; transform: translateY(10px); }
5          to { opacity: 1; transform: translateY(0); }
6        }
7        .animate-fade-in {
8          animation: fadeIn 0.4s ease-out forwards;
9        }
10        @keyframes marquee {
11          0% { transform: translateX(0); }
12          100% { transform: translateX(-50%); }
13        }
14        .animate-marquee {
15          animation: marquee 25s linear infinite;
16        }
17        .animate-marquee:hover {
18          animation-play-state: paused;
19        }
20      `})]})},id=({size:t=16,className:s=""})=>
20e.jsx("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"currentColor",className:s,children:e.jsx("path",{d:"M22.282 9.821a5.985 5.985 0 0 0-.516-4.91 6.046 6.046 0 0 0-6.51-2.9A6.065 6.065 0 0 0 4.981 4.18a5.985 5.985 0 0 0-3.998 2.9 6.046 6.046 0 0 0 .743 7.097 5.98 5.98 0 0 0 .51 4.911 6.051 6.051 0 0 0 6.515 2.9A5.985 5.985 0 0 0 13.26 24a6.056 6.056 0 0 0 5.772-4.206 5.99 5.99 0 0 0 3.997-2.9 6.056 6.056 0 0 0-.747-7.073zM13.26 22.43a4.476 4.476 0 0 1-2.876-1.04l.141-.081 4.779-2.758a.795.795 0 0 0 .392-.681v-6.737l2.02 1.168a.071.071 0 0 1 .038.052v5.583a4.504 4.504 0 0 1-4.494 4.494zM3.6 18.304a4.47 4.47 0 0 1-.535-3.014l.142.085 4.783 2.759a.771.771 0 0 0 .78 0l5.843-3.369v2.332a.08.08 0 0 1-.033.062L9.74 19.95a4.5 4.5 0 0 1-6.14-1.646zM2.34 7.896a4.485 4.485 0 0 1 2.366-1.973V11.6a.766.766 0 0 0 .388.676l5.815 3.355-2.02 1.168a.076.076 0 0 1-.071 0l-4.83-2.786A4.504 4.504 0 0 1 2.34 7.872zm16.597 3.855l-5.833-3.387L15.119 7.2a.076.076 0 0 1 .071 0l4.83 2.791a4.494 4.494 0 0 1-.676 8.105v-5.678a.79.79 0 0 0-.407-.667zm2.01-3.023l-.141-.085-4.774-2.782a.776.776 0 0 0-.785 0L9.409 9.23V6.897a.066.066 0 0 1 .028-.061l4.83-2.787a4.5 4.5 0 0 1 6.68 4.66zm-12.64 4.135l-2.02-1.164a.08.08 0 0 1-.038-.057V6.075a4.5 4.5 0 0 1 7.375-3.453l-.142.08L8.704 5.46a.795.795 0 0 0-.393.681zm1.097-2.365l2.602-1.5 2.607 1.5v2.999l-2.597 1.5-2.607-1.5z"})}),ld=({size:t=16,className:s=""})=>e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",className:s,children:[e.jsx("path",{d:"M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z",fill:"#4285F4"}),e.jsx("path",{d:"M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z",fill:"#34A853"}),e.jsx("path",{d:"M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z",fill:"#FBBC05"}),e.jsx("path",{d:"M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z",fill:"#EA4335"})]}),cd=[{id:"keyword",icon:e.jsx(Pt,{className:"w-5 h-5"}
20),title:"AI-Powered Keywords & Prompt Research",shortDesc:"Stop Guessing, Start Executing",fullDesc:'Automatically process massive datasets of your product and competitor landscape, identify the exact keyword clusters and prompt structures that drive visibility across Google and LLMs—and surface clear "blue ocean" opportunities your competitors missed.',cta:"Learn more"},{id:"prompt",icon:e.jsx(Na,{className:"w-5 h-5"}),title:"Holistic Tracking & Growth Insights",shortDesc:"Master Your Market Dynamics",fullDesc:"Stay ahead with real-time monitoring of your (and your competitors') performance. Track Keywords, Pages, and Prompts in one unified dashboard to see exactly what's moving the needle in the ever-changing search and AI landscape.",cta:"Learn more"},{id:"content",icon:e.jsx(is,{className:"w-5 h-5"}),title:"Expert-Grade AI Content & Template Engine",shortDesc:"RankingOS, The Creative Brain for Elite AI Content Creation",fullDesc:"Deploy proven templates and generate high-quality content powered by RankingOS. It continuously learns your product, users, brand and competitors, combining that knowledge with an understanding of Google's ranking signals and LLM indexing preferences and top1% marketers' expertise to generate content that's most likely to be ranked and cited.",cta:"Learn more"},{id:"knowledge",icon:e.jsx(Al,{className:"w-5 h-5"}),title:"Brand-Deep Knowledge Base",shortDesc:"Know Your Brand Better, Create Content Better",fullDesc:"Infuse your AI with your company's DNA—from pain points and unique solutions to core values and culture. The more your Knowledge Base grows, the more precise, authentic, and high-converting your content becomes.",cta:"Learn more"}],$i=({children:t,title:s})=>e.jsxs("div",{className:"bg-white rounded-2xl shadow-2xl shadow-slate-200/50 border border-slate-200 overflow-hidden",children:[e.jsxs("div",{className:"bg-slate-50 border-b border-slate-200 px-4 py-3 flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("div",{className:"w-3 h-3 rounded-full bg-red-400"}),e.jsx("div",{className:"w-3 h-3 rounded-full bg-yellow-400"}),e.jsx("div",{className:"w-3 h-3 rounded-full bg-green-400"})]}),e.jsx("span",{className:"text-sm text-slate-600 font-medium",children:s})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{className:"p-1 hover:bg-slate-200 rounded transition-colors",children:e.jsx(kt,{className:"w-4 h-4 text-slate-400"})}),e.jsx("button",{className:"p-1 hover:bg-slate-200 rounded transition-colors",children:e.jsx(_r,{className:"w-4 h-4 text-slate-400"})})]})]}),t]}),dg=()=>{const[t,s]=r.useState(null),[a,n]=r.useState(null),[o,i]=r.useState([0]),[l,c]=r.useState(null),d=["10 Best AI Sales Tools for B2B in 2024","Ultimate Guide to CRM for Startups","How to Automate Your Sales Pipeline","AI-Powered Lead Generation Strategies"],m=["Introduction: In today's competitive B2B landscape, AI sales tools have become essential...","Chapter 1: Understanding modern CRM systems and their impact on startup growth...","The ultimate guide to sales automation begins with understanding your pipeline..."],[h,p]=r.useState([{group:"AI Sales Tools",topic:"10 Best AI Sales Tools for B2B in 2024",content:"Introduction: In today's competitive B2B landscape...",publish:"published"},{group:"CRM Solutions",topic:"",content:"",publish:"idle"},{group:"AI Sales Tools",topic:"How ChatGPT Transforms Sales Automation",content:"",publish:"idle"},{group:"Customer Support",topic:"",content:"",publish:"idle"},{group:"Lead Generation",topic:"Automated Lead Scoring Best Practices",content:"The ultimate guide to lead scoring...",publish:"idle"},{group:"Sales Intelligence",topic:"",content:"",publish:"idle"}]),f=(x,u)=>{u==="publish"?(p(g=>{const w=[...g];return w[x]={...w[x],publish:"publishing"},w}),setTimeout(()=>{p(g=>{const w=[...g];return w[x]={...w[x],publish:"published"},w})},2e3)):(c({row:x,col:u}),setTimeout(()=>{p(g=>{const w=[...g];return u==="topic"?w[x]={...w[x],topic:d[Math.floor(Math.random()*d.length)]}
20:u==="content"&&(w[x]={...w[x],content:m[Math.floor(Math.random()*m.length)]}),w}),c(null)},1500))},b=(x,u)=>l?.row===x&&l?.col===u,y=(x,u)=>a?.row===x&&a?.col===u;return e.jsxs($i,{title:"Content Strategy Q4 — RankGale",children:[e.jsx("div",{className:"px-4 py-2.5 border-b border-slate-200 flex items-center bg-white",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"flex items-center bg-slate-100 rounded-lg p-0.5",children:[e.jsx("button",{className:"px-3 py-1 text-xs font-medium rounded-md bg-white text-slate-900 shadow-sm",children:"Table"}),e.jsx("button",{className:"px-3 py-1 text-xs font-medium rounded-md text-slate-500 hover:text-slate-700",children:"Kanban"})]}),e.jsx("div",{className:"w-px h-5 bg-slate-200 mx-1"}),e.jsxs("button",{className:"flex items-center gap-1.5 px-2.5 py-1.5 text-xs text-slate-600 hover:bg-slate-100 rounded-lg transition-colors",children:[e.jsx(eo,{className:"w-3.5 h-3.5"}),"Filter"]}),e.jsxs("button",{className:"flex items-center gap-1.5 px-2.5 py-1.5 text-xs text-slate-600 hover:bg-slate-100 rounded-lg transition-colors",children:[e.jsx(Pt,{className:"w-3.5 h-3.5"}),"Search"]})]})}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm border-collapse",children:[e.jsx("thead",{className:"bg-slate-50 text-slate-600 text-xs",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-3 py-2.5 text-left font-medium w-8 border-b border-r border-slate-200",children:e.jsx("input",{type:"checkbox",className:"rounded border-slate-300 w-3.5 h-3.5"})}),e.jsx("th",{className:"px-3 py-2.5 text-left font-medium border-b border-r border-slate-200 w-[130px]",children:"Keyword Group"}),e.jsx("th",{className:"px-3 py-2.5 text-left font-medium border-b border-r border-slate-200",children:"Topic / Title"}),e.jsx("th",{className:"px-3 py-2.5 text-left font-medium border-b border-r border-slate-200 w-[180px]",children:"Content"}),e.jsx("th",{className:"px-3 py-2.5 text-left font-medium border-b border-slate-200 w-[100px]",children:"Publish"})]})}),e.jsx("tbody",{children:h.map((x,u)=>e.jsxs("tr",{className:`transition-colors ${t===u?"bg-slate-50":o.includes(u)?"bg-blue-50/40":""}`,onMouseEnter:()=>s(u),onMouseLeave:()=>s(null),children:[e.jsx("td",{className:"px-3 py-2.5 border-b border-r border-slate-200",children:e.jsx("input",{type:"checkbox",className:"rounded border-slate-300 w-3.5 h-3.5",checked:o.includes(u),onChange:()=>{i(g=>g.includes(u)?g.filter(w=>w!==u):[...g,u])}})}),e.jsx("td",{className:"px-3 py-2.5 border-b border-r border-slate-200",children:e.jsx("span",{className:"text-slate-700 text-sm",children:x.group})}),e.jsx("td",{className:"px-3 py-2.5 border-b border-r border-slate-200 relative group/cell",onMouseEnter:()=>n({row:u,col:"topic"}),onMouseLeave:()=>n(null),children:b(u,"topic")?e.jsxs("div",{className:"flex items-center gap-2 text-slate-400",children:[e.jsx("div",{className:"w-4 h-4 border-2 border-slate-300 border-t-slate-600 rounded-full animate-spin"}),e.jsx("span",{className:"text-sm",children:"Generating..."})]}):x.topic?e.jsx("span",{className:"text-slate-900 text-sm",children:x.topic}):e.jsxs("div",{className:"h-6 flex items-center justify-between",children:[e.jsx("span",{className:"text-slate-300 text-sm",children:"—"}),(y(u,"topic")||u===1)&&e.jsx("button",{onClick:()=>f(u,"topic"),className:"absolute right-2 top-1/2 -translate-y-1/2 w-6 h-6 flex items-center justify-center bg-slate-100 hover:bg-slate-200 rounded transition-colors",title:"Run",children:e.jsx("svg",{className:"w-3.5 h-3.5 text-slate-600",viewBox:"0 0 24 24",fill:"currentColor",children:e.jsx("path",{d:"M8 5v14l11-7z"})})})]})}),e.jsx("td",{className:"px-3 py-2.5 border-b border-r border-slate-200 relative group/cell",onMouseEnter:()=>n({row:u,col:"content"}),onMouseLeave:()=>n(null),children:b(u,"content")?e.jsxs("div",{className:"flex items-center gap-2 text-slate-400",children:[e.jsx("div",{className:"w-4 h-4 border-2 border-slate-300 border-t-slate-600 rounded-full animate-spin"}),e.jsx("span",{className:"text-sm",children:"Generating..."})]}):x.content?e.jsx("span",{className:"text-slate-700 text-sm truncate block max-w-[160px]",children:x.content}):e.jsxs("div",{className:"h-6 flex items-center justify-between",children:[e.jsx("span",{className:"text-slate-300 text-sm",children:"—"}),(y(u,"content")||u===2)&&e.jsx("button",{onClick:()=>f(u,"content"),className:"absolute right-2 top-1/2 -translate-y-1/2 w-6 h-6 flex items-center justify-center bg-slate-100 hover:bg-slate-200 rounded transition-colors",title:"Run",children:e.jsx("svg",{className:"w-3.5 h-3.5 text-slate-600",viewBox:"0 0 24 24",fill:"
20currentColor",children:e.jsx("path",{d:"M8 5v14l11-7z"})})})]})}),e.jsx("td",{className:"px-3 py-2.5 border-b border-slate-200 relative",onMouseEnter:()=>n({row:u,col:"publish"}),onMouseLeave:()=>n(null),children:e.jsx("div",{className:"flex items-center justify-between",children:x.publish==="publishing"?e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("div",{className:"w-3 h-3 border-2 border-slate-300 border-t-slate-600 rounded-full animate-spin"}),e.jsx("span",{className:"text-slate-500 text-xs",children:"Publishing..."})]}):x.publish==="published"?e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(ac,{className:"w-3.5 h-3.5 text-green-600"}),e.jsx("span",{className:"text-green-700 text-xs font-medium",children:"Published"})]}):e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-slate-400 text-xs",children:"Not published"}),(y(u,"publish")||u===4)&&e.jsx("button",{onClick:()=>f(u,"publish"),className:"w-6 h-6 flex items-center justify-center bg-slate-100 hover:bg-slate-200 rounded transition-colors",title:"Publish",children:e.jsx("svg",{className:"w-3.5 h-3.5 text-slate-600",viewBox:"0 0 24 24",fill:"currentColor",children:e.jsx("path",{d:"M8 5v14l11-7z"})})})]})})})]},u))})]})}),e.jsxs("div",{className:"px-4 py-2.5 bg-slate-50 border-t border-slate-200 flex items-center justify-between text-xs",children:[e.jsxs("span",{className:"text-slate-500",children:[o.length," of ",h.length," rows selected"]}),e.jsx("span",{className:"text-slate-400",children:"6 rows"})]})]})},mg=()=>{const[t,s]=r.useState("weekly"),[a,n]=r.useState(""),[o,i]=r.useState(!1),c=[{id:"1",prompt:"What are the best AI sales tools for B2B?",periods:[{period:"W51",openai:{mentioned:!0},google:{mentioned:!0}},{period:"W50",openai:{mentioned:!0},google:{mentioned:!1}}],status:"high"},{id:"2",prompt:"Top CRM software for startups in 2024",periods:[{period:"W51",openai:{mentioned:!0},google:{mentioned:!0}},{period:"W50",openai:{mentioned:!0},google:{mentioned:!0}}],status:"high"},{id:"3",prompt:"How to automate customer outreach?",periods:[{period:"W51",openai:{mentioned:!1},google:{mentioned:!0}},{period:"W50",openai:{mentioned:!1},google:{mentioned:!1}}],status:"medium"},{id:"4",prompt:"Best lead generation tools for SaaS",periods:[{period:"W51",openai:{mentioned:!0},google:{mentioned:!0}},{period:"W50",openai:{mentioned:!1},google:{mentioned:!0}}],status:"medium"},{id:"5",prompt:"AI tools for content marketing strategy",periods:[{period:"W51",openai:{mentioned:!0},google:{mentioned:!0}},{period:"W50",openai:{mentioned:!0},google:{mentioned:!0}}],status:"high"}].filter(m=>a.trim()===""||m.prompt.toLowerCase().includes(a.toLowerCase())),d=t==="weekly"?["W51","W50"]:["Dec","Nov"];return e.jsxs($i,{title:"GEO Prompt Tracking — RankGale",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-slate-200 flex items-center justify-between bg-white",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Pt,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400"}),e.jsx("input",{type:"text",placeholder:"Search prompts...",value:a,onChange:m=>n(m.target.value),onFocus:()=>i(!0),onBlur:()=>i(!1),className:`pl-9 pr-8 py-1.5 text-sm border border-slate-200 rounded-lg transition-all ${o?"w-56 ring-2 ring-blue-100":"w-48"}`}),a&&e.jsx("button",{onClick:()=>n(""),className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 hover:bg-slate-100 rounded",children:e.jsx("span",{className:"text-slate-400 text-xs",children:"✕"})})]}),e.jsx("div",{className:"h-6 w-px bg-slate-200"}),e.jsxs("div",{className:"flex items-center bg-slate-100 rounded-lg p-0.5",children:[e.jsx("button",{onClick:()=>s("weekly"),className:`px-3 py-1 text-xs font-medium rounded-md transition-all ${t==="weekly"?"bg-white text-slate-900 shadow-sm":"text-slate-600 hover:text-slate-900"}`,children:"Weekly"}),e.jsx("button",{onClick:()=>s("monthly"),className:`px-3 py-1 text-xs font-medium rounded-md transition-all ${t==="monthly"?"bg-white text-slate-900 shadow-sm":"text-slate-600 hover:text-slate-900"}`,children:"Monthly"})]})]}),e.jsxs("button",{className:"flex items-center gap-1.5 bg-slate-800 hover:bg-slate-700 text-white px-3 py-1.5 rounded-lg text-sm font-medium transition-colors",children:[e.jsx($t,{className:"w-4 h-4"}),"Track New Prompt"]})]}),e.jsx("div",{className:"grid grid-cols-3 border-b border-slate-200",children:[{label:"Tracked Prompts",value:"24",change:"+3"},{label:"ChatGPT Mentions",value:"67%",change:"+12%",icon:e.jsx(id,{size:14,className:"text-slate-500"})},{label:"Gemini Mentions",value:"54%",change:"+8%",icon:e.jsx(ld,{size:14})}].map((m,h)=>e.jsxs("div",{className:`px-4 py-3 ${h>0?"border-l border-slate-200":""}`,children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-slate-500 mb-1",children:[m.icon,e.jsx("span",{children:m.label})]}),e.jsxs("div",{className:"flex items-baseline gap-2",children:[e.jsx("span",{className:"text-xl font-bold text-slate-900",children:m.value}),e.jsx("span",{className:"text-xs text-green-600 font-medium",children:m.change})]})]},h))}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"text-left text-slate-500 bg-slate-50 border-b border-slate-200",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-3 py-3 font-semibold text-slate-700 min-w-[280px]",children:"Prompt"}),d.map(m=>e.jsx("th",{className:"px-2 py-3 font-semibold text-slate-700 text-center min-w-[80px]",children:e.jsxs("div",{className:"flex flex-col items-center",children:[e.jsx("span",{className:"text-xs",children:m}),e.jsxs("div",{className:"flex gap-2 mt-1.5 items-center justify-center",children:[e.jsx(id,{size:12,className:"text-slate-500"}),e.jsx(ld,{size:12})]})]})},m)),e.jsx("th",{className:"px-4 py-3 font-semibold text-slate-700 text-center min-w-[120px]",children:"Status"})]})}),e.jsx("tbody",{className:"divide-y divide-slate-100",children:c.map(m=>{const h=m.periods[0],p=h.openai.mentioned&&h.google.mentioned;return e.jsxs("tr",{className:"hover:bg-slate-50/50 transition-colors cursor-pointer",children:[e.jsx("td",{className:"px-3 py-3 font-medium text-slate-900",children:e.jsx("span",{className:"truncate block max-w-[260px]",title:m.prompt,children:m.prompt})}),d.map(f=>{const b=m.periods.find(y=>
20y.period===f)||{openai:{mentioned:!1},google:{mentioned:!1}};return e.jsx("td",{className:"px-2 py-3 text-center",children:e.jsxs("div",{className:"flex justify-center gap-2 items-center",children:[e.jsx("span",{className:`flex items-center justify-center w-5 ${b.openai.mentioned?"text-emerald-500":"text-slate-300"}`,children:b.openai.mentioned?e.jsx(wt,{size:14,strokeWidth:3}):e.jsx(Ps,{size:14})}),e.jsx("span",{className:`flex items-center justify-center w-5 ${b.google.mentioned?"text-emerald-500":"text-slate-300"}`,children:b.google.mentioned?e.jsx(wt,{size:14,strokeWidth:3}):e.jsx(Ps,{size:14})})]})},f)}),e.jsx("td",{className:"px-4 py-3 text-center",children:e.jsx("span",{className:`inline-flex items-center px-2.5 py-1 rounded-full text-xs font-medium whitespace-nowrap ${p?"bg-emerald-50 text-emerald-700 border border-emerald-200":"bg-amber-50 text-amber-700 border border-amber-200"}`,children:p?"High visibility":"Opportunity"})})]},m.id)})})]})})]})},ug=()=>{const[t,s]=r.useState(null),a=[{title:"10 Best AI CRM Tools for Startups in 2024",group:"CRM Tools",status:"published",clicks:1247,impressions:8420},{title:"How to Use ChatGPT for Sales Automation",group:"AI Sales",status:"published",clicks:892,impressions:5310},{title:"Complete Guide to AI Customer Support",group:"Support",status:"draft",clicks:0,impressions:0},{title:"B2B Lead Generation with AI: Ultimate Guide",group:"Lead Gen",status:"generating",clicks:0,impressions:0},{title:"AI-Powered Email Sequences That Convert",group:"AI Sales",status:"published",clicks:654,impressions:3890},{title:"Enterprise AI Integration Best Practices",group:"Support",status:"published",clicks:423,impressions:2150}];return e.jsxs($i,{title:"Content Workshop — RankGale",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-slate-100 flex items-center justify-between bg-white",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("select",{className:"bg-slate-100 border-0 rounded-lg px-3 py-1.5 text-sm text-slate-600 font-medium",children:[e.jsx("option",{children:"All Groups"}),e.jsx("option",{children:"CRM Tools"}),e.jsx("option",{children:"AI Sales"}),e.jsx("option",{children:"Support"})]}),e.jsxs("select",{className:"bg-slate-100 border-0 rounded-lg px-3 py-1.5 text-sm text-slate-600 font-medium",children:[e.jsx("option",{children:"All Status"}),e.jsx("option",{children:"Published"}),e.jsx("option",{children:"Draft"})]})]}),e.jsxs("button",{className:"flex items-center gap-1.5 bg-blue-600 text-white px-3 py-1.5 rounded-lg text-sm font-medium hover:bg-blue-700 transition-colors",children:[e.jsx(Ks,{className:"w-4 h-4"}),"Generate Article"]})]}),e.jsx("div",{className:"divide-y divide-slate-100",children:a.map((n,o)=>e.jsx("div",{className:`px-4 py-4 transition-all cursor-pointer ${t===o?"bg-blue-50/30":"hover:bg-slate-50/50"}`,onMouseEnter:()=>s(o),onMouseLeave:()=>s(null),children:e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3 flex-1",children:[e.jsx(ru,{className:"w-4 h-4 text-slate-300 cursor-grab"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-slate-900 truncate",children:n.title}),e.jsxs("div",{className:"flex items-center gap-3 mt-1",children:[e.jsx("span",{className:"text-xs text-slate-500",children:n.group}),n.status==="published"&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-xs text-slate-400",children:"•"}),e.jsxs("span",{className:"text-xs text-slate-500",children:[n.clicks.toLocaleString()," clicks"]}),e.jsx("span",{className:"text-xs text-slate-400",children:"•"}),e.jsxs("span",{className:"text-xs text-slate-500",children:[n.impressions.toLocaleString()," impressions"]})]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[n.status==="published"?e.jsxs("span",{className:"flex items-center gap-1 text-xs bg-green-100 text-green-700 px-2 py-1 rounded font-medium",children:[e.jsx(ac,{className:"w-3 h-3"})," Published"]}):n.status==="generating"?e.jsxs("span",{className:"flex items-center gap-1 text-xs bg-blue-100 text-blue-700 px-2 py-1 rounded font-medium animate-pulse",children:[e.jsx(Ks,{className:"w-3 h-3"})," Generating..."]}):e.jsx("span",{className:"text-xs bg-slate-100 text-slate-600 px-2 py-1 rounded font-medium",children:"Draft"}),e.jsx("button",{className:"p-1.5 hover:bg-slate-100 rounded transition-colors",children:e.jsx(ns,{className:"w-4 h-4 text-slate-400"})})]})]})},o))}),e.jsxs("div",{className:"px-4 py-4 bg-slate-50 border-t border-slate-100 grid grid-cols-3 gap-4",children:[e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"text-xl font-bold text-slate-900",children:"2,139"}),e.jsx("div",{className:"text-xs text-slate-500",children:"Total Clicks"})]}),e.jsxs("div",{className:"text-center border-x border-slate-200",children:[e.jsx("div",{className:"text-xl font-bold text-slate-900",children:"13.7K"}),e.jsx("div",{className:"text-xs text-slate-500",children:"Total Impressions"})]}),e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"text-xl font-bold text-green-600",children:"+23%"}),e.jsx("div",{className:"text-xs text-slate-500",children:"CTR Growth"})]})]})]})},xg=()=>{const[t,s]=r.useState(null),a=[{name:"Product Documentation",description:"Feature specs, API docs, user guides",docs:24,updated:"Dec 20, 2024"},{name:"Brand Assets",description:"Logo, colors, tone of voice guidelines",docs:12,updated:"Dec 18, 2024"},{name:"Competitor Intel",description:"Pricing, features, positioning analysis",docs:8,updated:"Dec 15, 2024"},{name:"Customer Research",description:"Personas, interviews, feedback",docs:15,updated:"Dec 12, 2024"},{name:"Sales Materials",description:"Pitch decks, case studies, demos",docs:19,updated:"Dec 10, 2024"}];return e.jsxs($i,{title:"Knowledge Base — RankGale",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-slate-100 flex items-center justify-between bg-white",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("button",{className:"flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium text-slate-700 bg-white border border-slate-200 rounded-lg hover:bg-slate-50 transition-colors",children:[e.jsx(Jo,{className:"w-4 h-4"}),"New folder"]}),e.jsxs("button",{className:"flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium text-slate-700 bg-white border border-slate-200 rounded-lg hover:bg-slate-50 transition-colors",children:[e.jsx(Gn,{className:"w-4 h-4"}),"File upload"]}),e.jsxs("button",{className:"flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium text-slate-700 bg-white border border-slate-200 rounded-lg hover:bg-slate-50 transition-colors",children:[e.jsx(Xo,{className:"w-4 h-4"}),"Folder upload"]})]}),e.jsxs("div",{className:"flex items-center gap-2 bg-slate-100 rounded-full px-3 py-1.5",children:[e.jsx(Pt,{className:"w-4 h-4 text-slate-400"}),e.jsx("span",{className:"text-sm text-slate-500",children:"Search in Drive"})]})]}),e.jsx("div",{className:"overflow-auto max-h-[320px]",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"text-left text-slate-500 border-b border-slate-200 sticky top-0 bg-white",children:e.jsxs("tr",{children:[e.jsx("th",{className:"py-3 px-4 font-medium",children:"Name"}),e.jsx("th",{className:"py-3 px-4 font-medium",children:"Description"}),e.jsx("th",{className:"py-3 px-4 font-medium text-center",children:"Documents"}),e.jsx("th",{className:"py-3 px-4 font-medium",children:"Updated"}),e.jsx("th",{className:"py-3 px-4 font-medium w-12"})]})}),e.jsx("tbody",{children:a.map((n,o)=>e.jsxs("tr",{onClick:()=>s(o),className:`border-b border-slate-50 cursor-pointer transition-colors group ${t===o?"bg-blue-50":"hover:bg-slate-50"}`,children:[e.jsx("td",{className:"py-3 px-4 font-medium text-slate-900",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(nu,{className:"w-5 h-5 text-slate-400 fill-slate-400/20"}),e.jsx("span",{children:n.name})]})}),e.jsx("td",{className:"py-3 px-4 text-slate-500 max-w-xs truncate",children:n.description}),e.jsx("td",{className:"py-3 px-4 text-center text-slate-600",children:n.docs}),e.jsx("td",{className:"py-3 px-4 text-slate-500",children:n.updated}),e.jsx("td",{className:"py-3 px-4",children:e.jsx("button",{className:"p-1 hover:bg-slate-100 rounded opacity-0 group-hover:opacity-100 transition-opacity",children:e.jsx(Rh,{className:"w-4 h-4 text-slate-400"})})})]},o))})]})}),e.jsxs("div",{className:"mx-4 my-4 p-3 bg-gradient-to-r from-blue-50 to-cyan-50 border border-blue-100 rounded-xl flex items-center gap-3",children:[e.jsx(Ks,{className:"w-5 h-5 text-blue-600 flex-shrink-0"}),e.jsxs("p",{className:"text-xs text-blue-700",children:[e.jsx("span",{className:"font-semibold",children:"Pro tip:"})," The more context you add, the better RankingOS understands your brand voice and generates authentic content."]})]})]})},hg={keyword:e.jsx(dg,{}),prompt:e.jsx(mg,{}),content:e.jsx(ug,{}),knowledge:e.jsx(xg,{})},pg=()=>{const[t,s]=r.useState("keyword"),a=cd.find(n=>n.id===t);return e.jsx("section",{id:"features",className:"py-24 bg-gradient-to-b from-slate-50 via-white to-slate-50",children:e.jsxs("div",{className:"max-w-[90rem] mx-auto px-6 lg:px-12",children:[e.jsx("div",{className:"text-center mb-16",children:e.jsx("h2",{className:"text-4xl md:text-5xl font-display italic text-slate-900 mb-4",children:"Everything You Need to Win AI Search"})}),e.jsx("div",{className:"flex flex-wrap justify-center gap-2 mb-12",children:cd.map(n=>e.jsxs("button",{onClick:()=>s(n.id),className:`flex items-center gap-2 px-5 py-2.5 rounded-full text-sm font-medium transition-all ${t===n.id?"bg-slate-900 text-white shadow-lg":"bg-white text-slate-600 border border-slate-200 hover:border-slate-300 hover:shadow-sm"}`,children:[n.icon,e.jsx("span",{className:"hidden sm:inline",children:n.title})]},n.id))}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-12 gap-8 items-center",children:[e.jsxs("div",{className:"lg:col-span-3",children:[e.jsx("p",{className:"text-lg md:text-xl font-bold text-slate-900 leading-relaxed mb-3 font-display",children:a.shortDesc}),e.jsx("p",{className:"text-sm text-slate-500 leading-relaxed font-sans",children:a.fullDesc})]}),e.jsx("div",{className:"lg:col-span-9",children:e.jsx("div",{className:"transform transition-all duration-500 hover:scale-[1.005]",children:hg[t]})})]})]})})},gg=()=>e.jsxs("svg",{viewBox:"0 0 24 24",className:"w-5 h-5",children:[e.jsx("path",{fill:"#4285F4",d:"M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"}),e.jsx("path",{fill:"#34A853",d:"M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"}),e.jsx("path",{fill:"#FBBC05",d:"M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z"}),e.jsx("path",{fill:"#EA4335",d:"M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z"})]}),fg=()=>e.jsx("svg",{viewBox:"0 0 24 24",className:"w-5 h-5",fill:"#10a37f",children:e.jsx("path",{d:"M22.282 9.821a5.985 5.985 0 0 0-.516-4.91 6.046 6.046 0 0 0-6.51-2.9A6.065 6.065 0 0 0 4.981 4.18a5.985 5.985 0 0 0-3.998 2.9 6.046 6.046 0 0 0 .743 7.097 5.98 5.98 0 0 0 .51 4.911 6.051 6.051 0 0 0 6.515 2.9A5.985 5.985 0 0 0 13.26 24a6.056 6.056 0 0 0 5.772-4.206 5.99 5.99 0 0 0 3.997-2.9 6.056 6.056 0 0 0-.747-7.073zM13.26 22.43a4.476 4.476 0 0 1-2.876-1.04l.141-.081 4.779-2.758a.795.795 0 0 0 .392-.681v-6.737l2.02 1.168a.071.071 0 0 1 .038.052v5.583a4.504 4.504 0 0 1-4.494 4.494zM3.6 18.304a4.47 4.47 0 0 1-.535-3.014l.142.085 4.783 2.759a.771.771 0 0 0 .78 0l5.843-3.369v2.332a.08.08 0 0 1-.033.062L9.74 19.95a4.5 4.5 0 0 1-6.14-1.646zM2.34 7.896a4.485 4.485 0 0 1 2.366-1.973V11.6a.766.766 0 0 0 .388.676l5.815 3.355-2.02 1.168a.076.076 0 0 1-.071 0l-4.83-2.786A4.504 4.504 0 0 1 2.34 7.872zm16.597 3.855l-5.833-3.387L15.119 7.2a.076.076 0 0 1 .071 0l4.83 2.791a4.494 4.494 0 0 1-.676 8.105v-5.678a.79.79 0 0 0-.407-.667zm2.01-3.023l-.141-.085-4.774-2.782a.776.776 0 0 0-.785 0L9.409 9.23V6.897a.066.066 0 0 1 .028-.061l4.83-2.787a4.5 4.5 0 0 1 6.68 4.66zm-12.64 4.135l-2.02-1.164a.08.08 0 0 1-.038-.057V6.075a4.5 4.5 0 0 1 7.375-3.453l-.142.08L8.704 5.46a.795.795 0 0 0-.393.681zm1.097-2.365l2.602-1.5 2.607 1.5v2.999l-2.597 1.5-2.607-1.5z"})}),yg=()=>e.jsx("img",{src:"/perplexity-logo.png",alt:"Perplexity",className:"w-5 h-5"}),bg=()=>e.jsx("img",{src:"/claude-logo.svg",alt:"Claude",className:"w-5 h-5"}),wg=()=>e.jsx("img",{src:"/grok-logo.svg",alt:"Grok",className:"w-5 h-5"}),jg=()=>e.jsx("div",{className:"w-10 h-10 rounded-xl bg-gradient-to-br from-sky-4
2000 to-blue-500 flex items-center justify-center shadow-lg shadow-sky-200/50",children:e.jsx(is,{className:"w-5 h-5 text-white"})}),vg=()=>e.jsx("div",{className:"w-10 h-10 rounded-xl bg-gradient-to-br from-emerald-400 to-teal-500 flex items-center justify-center shadow-lg shadow-emerald-200/50",children:e.jsx(Ma,{className:"w-5 h-5 text-white"})}),Ng=()=>e.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",className:"w-4 h-4 text-slate-400",children:[e.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",stroke:"currentColor",strokeWidth:"1.5"}),e.jsx("path",{d:"M3 9h18M9 21V9",stroke:"currentColor",strokeWidth:"1.5"})]}),kg=()=>e.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",className:"w-4 h-4 text-slate-400",children:[e.jsx("circle",{cx:"12",cy:"8",r:"4",stroke:"currentColor",strokeWidth:"1.5"}),e.jsx("path",{d:"M4 20c0-4 4-6 8-6s8 2 8 6",stroke:"currentColor",strokeWidth:"1.5"})]}),_g=()=>e.jsx("svg",{viewBox:"0 0 24 24",fill:"none",className:"w-4 h-4 text-slate-400",children:e.jsx("path",{d:"M7 7h10M7 12h10M7 17h6",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"})}),Cg=()=>e.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",className:"w-4 h-4 text-slate-400",children:[e.jsx("path",{d:"M8 9l3 3-3 3M13 15h3",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"}),e.jsx("rect",{x:"3",y:"4",width:"18",height:"16",rx:"2",stroke:"currentColor",strokeWidth:"1.5"})]}),Sg=()=>e.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",className:"w-4 h-4 text-slate-400",children:[e.jsx("circle",{cx:"12",cy:"12",r:"3",stroke:"currentColor",strokeWidth:"1.5"}),e.jsx("path",{d:"M12 2v4M12 18v4M2 12h4M18 12h4",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"})]}),Eg=()=>e.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",className:"w-4 h-4 text-slate-400",children:[e.jsx("path",{d:"M3 12l4-4 4 4 6-6 4 4",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"}),e.jsx("circle",{cx:"21",cy:"6",r:"2",fill:"currentColor"})]}),Ag=()=>{const t=[{icon:Ng,label:"Product Data"},{icon:kg,label:"Competitor Landscape"},{icon:_g,label:"Keyword Clusters"},{icon:Cg,label:"Prompt Structures"},{icon:Sg,label:"LLM Preferences"},{icon:Eg,label:"Google Signals"}],s=["Top 1% marketers' expertise","Google's ranking signals","LLM indexing preferences","Continuous brand learning"],a=[{name:"Google",logo:gg,score:4},{name:"ChatGPT",logo:fg,score:5},{name:"Perplexity",logo:yg,score:5},{name:"Claude",logo:bg,score:5},{name:"Grok",logo:wg,score:4}];return e.jsx("section",{className:"py-24 md:py-32 bg-gradient-to-b from-slate-50/50 to-white",children:e.jsxs("div",{className:"max-w-6xl mx-auto px-6",children:[e.jsxs("div",{className:"text-center mb-20",children:[e.jsx("h2",{className:"text-4xl md:text-5xl font-display italic text-slate-900 mb-6",children:"How RankingOS Works"}),e.jsx("p",{className:"text-lg text-slate-500 max-w-3xl mx-auto leading-relaxed font-sans",children:"Beyond simple AI writing, RankGale deconstructs the strategies of the top 1% of marketers to help you out-research, out-create, and out-rank your competition."})]}),e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"absolute left-1/2 top-0 bottom-0 w-px bg-gradient-to-b from-slate-200 via-slate-300 to-slate-200 -translate-x-1/2 hidden md:block"}),e.jsx("div",{className:"relative mb-24 md:mb-32",children:e.jsxs("div",{className:"flex flex-col md:flex-row items-center gap-8 md:gap-16",children:[e.jsx("div",{className:"w-full md:w-1/2 md:pr-16",children:e.jsxs("div",{className:"bg-white rounded-2xl p-8 border border-slate-200/80 shadow-sm hover:shadow-lg transition-all duration-300",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-6",children:[e.jsx(jg,{}),e.jsx("h4",{className:"text-lg font-semibold text-slate-800",children:"Intelligence Hub"})]}),e.jsx("div",{className:"grid grid-cols-2 gap-3",children:t.map((n,o)=>{const i=n.icon;return e.jsxs("div",{className:"bg-slate-50/80 rounded-xl px-4 py-3.5 flex items-center gap-3 border border-slate-100 hover:border-slate-200 hover:bg-slate-50 transition-colors",children:[e.jsx(i,{}),e.jsx("span",{className:"text-sm text-slate-600 font-medium",children:n.label})]},o)})})]})}),e.jsx("div",{className:"hidden md:flex absolute left-1/2 -translate-x-1/2 flex-col items-center z-10",children:e.jsx("div",{className:"w-12 h-12 rounded-full bg-white border-2 border-slate-200 flex items-center justify-center text-sm font-bold text-slate-500 shadow-sm",children:"01"})}),e.jsx("div",{className:"w-full md:w-1/2 md:pl-16 text-center md:text-left",children:e.jsxs("div",{className:"inline-block md:block",children:[e.jsx("h3",{className:"text-3xl md:text-4xl font-display italic text-slate-900 mb-5",children:"AI-Powered Keywords & Prompt Research"}),e.jsx("p",{className:"text-slate-500 leading-relaxed max-w-md",children:"Automatically process massive datasets of your product and competitor landscape, identify the exact keyword clusters and prompt structures that drive visibility across Google and LLMs, saving you weeks of manual research."})]})})]})}),e.jsxs("div",{className:"relative mb-24 md:mb-32",children:[e.jsx("div",{className:"flex justify-center mb-6",children:e.jsx("div",{className:"w-12 h-12 rounded-full bg-white border-2 border-slate-200 flex items-center justify-center text-sm font-bold text-slate-500 shadow-sm z-10",children:"02"})}),e.jsxs("div",{className:"text-center mb-10",children:[e.jsx("h3",{className:"text-3xl md:text-4xl font-display italic text-slate-900 mb-5",children:"Opportunity Discovery & Strategic Actions"}),e.jsx("p",{className:"text-slate-500 leading-relaxed max-w-2xl mx-auto",children:'Get a clear roadmap of high-impact opportunities. Pinpoints the "Blue Ocean" keywords your competitors missed and the high-performing prompts they rely on, turning competitive gaps into your ranking advantage.'})]}),e.jsx("div",{className:"max-w-4xl mx-auto px-4",children:e.jsx("div",{className:"bg-white rounded-2xl p-8 md:p-10 border border-slate-200/80 shadow-lg",children:e.jsxs("div",{className:"flex flex-col md:flex-row gap-8 md:gap-12 items-stretch",children:[e.jsx("div",{className:"flex-1 space-y-5 py-2",children:s.map((n,o)=>e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"w-6 h-6 rounded-full bg-sky-100 flex items-center justify-center flex-shrink-0",children:e.jsx(wt,{className:"w-4 h-4 text-sky-600"})}),e.jsx("span",{className:"text-base text-slate-700 font-semibold",children:n})]},o))}),e.jsxs("div",{className:"flex-1 bg-slate-50 rounded-xl p-6 min-w-[280px] md:min-w-[320px] border border-slate-100",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-5",children:[e.jsx("div",{className:"w-3 h-3 rounded-full bg-red-400"}),e.jsx("div",{className:"w-3 h-3 rounded-full bg-amber-400"}),e.jsx("div",{className:"w-3 h-3 rounded-full bg-emerald-400"}),e.jsx("span",{className:"text-xs text-slate-400 ml-3 font-mono uppercase tracking-wider",children:"RANKINGOS_CORE_SIMULATOR"})]}),e.jsx("p",{className:"text-sm text-slate-400 font-mono mb-8 leading-relaxed",children:"Waiting for strategy trigger..."}),e.jsx("button",{className:"w-full py-3.5 bg-slate-900 text-white text-sm font-bold rounded-xl hover:bg-slate-800 transition-colors uppercase tracking-wide shadow-sm",children:"RUN LIVE SIMULATION"})]})]})})})]}),e.jsx("div",{className:"relative",children:e.jsxs("div",{className:"flex flex-col md:flex-row items-center gap-8 md:gap-16",children:[e.jsx("div",{className:"w-full md:w-1/2 md:pr-16 text-center md:text-left order-2 md:order-1",children:e.jsxs("div",{className:"inline-block md:block",children:[e.jsx("h3",{className:"text-3xl md:text-4xl font-display italic text-slate-900 mb-5",children:"Expert-Grade AI Content & Template Engine"}),e.jsx("p",{className:"text-slate-500 leading-relaxed max-w-md",children:"Deploy proven templates and generate high-quality content powered by RankingOS. It continuously learns your product, users, brand and competitors, combining that knowledge with Google's ranking signals and LLM indexing preferences to generate content that's most likely to be ranked and cited."})]})}),e.jsx("div",{className:"hidden md:flex absolute left-1/2 -translate-x-1/2 flex-col items-center z-10",children:e.jsx("div",{className:"w-12 h-12 rounded-full bg-white border-2 border-slate-200 flex items-center justify-center text-sm font-bold text-slate-500 shadow-sm",children:"03"})}),e.jsx("div",{className:"w-full md:w-1/2 md:pl-16 order-1 md:order-2",children:e.jsxs("div",{className:"bg-white rounded-2xl p-8 border border-slate-200/80 shadow-sm hover:shadow-lg transition-all duration-300",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-6",children:[e.jsx(vg,{}),e.jsx("h4",{className:"text-lg font-semibold text-slate-800",children:"Visibility Across"})]}),e.jsx("div",{className:"space-y-3",children:a.map((n,o)=>{const i=n.logo;return e.jsxs("div",{className:"flex items-center justify-between py-3 px-4 bg-slate-50/80 rounded-xl border border-slate-100 hover:border-slate-200 hover:bg-slate-50 transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-8 h-8 rounded-lg bg-white flex items-center justify-center shadow-sm border border-slate-100",children:e.jsx(Pt,{className:"w-4 h-4 text-slate-300"})}),e.jsx("div",{className:"w-6 h-6 flex items-center justify-center",children:e.jsx(i,{})}),e.jsx("span",{className:"text-sm font-medium text-slate-700",children:n.name})]}),e.jsx("div",{className:"flex gap-1",children:[...Array(5)].map((l,c)=>e.jsx("div",{className:`w-1.5 h-5 rounded-full ${c<n.score?"bg-emerald-500":"bg-slate-200"}`},c))})]},o)})})]})})]})})]})]})})};function Tg({onBookDemo:t,features:s}){return e.jsx("div",{className:"mt-10 max-w-6xl mx-auto",children:e.jsxs("div",{className:"rounded-2xl border border-slate-200 bg-white shadow-sm overflow-hidden",children:[e.jsxs("div",{className:"px-8 py-7 flex flex-col md:flex-row md:items-center md:justify-between gap-6",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-xs font-bold uppercase tracking-wide text-slate-500",children:"Enterprise"}),e.jsx("div",{className:"mt-1 text-2xl font-display italic text-slate-900",children:"Full-scale growth with vetted talents"}),e.jsxs("div",{className:"mt-3 flex items-end gap-2",children:[e.jsx("div",{className:"text-4xl font-bold text-slate-900",children:"Custom"}),e.jsx("div",{className:"text-sm text-slate-500 mb-1",children:"pricing"})]})]}),e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("button",{onClick:t,className:"w-full md:w-[220px] py-3 px-6 rounded-xl font-semibold text-sm transition-all duration-200 bg-slate-900 text-white hover:bg-slate-800",children:"Book a demo"}),e.jsx("div",{className:"text-[11px] text-slate-500",children:"Get a tailored plan and onboarding support."})]})]}),e.jsx("div",{className:"border-t border-slate-200 px-8 py-6 bg-slate-50/40",children:e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-x-10 gap-y-2",children:s.map(a=>e.jsxs("div",{className:"flex items-center justify-between gap-3 py-2 border-b border-slate-200/60 last:border-b-0",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsx("div",{className:"flex-shrink-0 w-5 h-5 rounded-full flex items-center justify-center bg-blue-100",children:e.jsx(wt,{className:"w-3 h-3 text-blue-600"})}),e.jsx("div",{className:"text-sm text-slate-700 truncate",children:a.label})]}),e.jsx("div",{className:"text-sm font-medium text-slate-900 flex-shrink-0",children:a.value})]},`${a.label}:${a.value}`))})})]})})}
20const Pg={starter:6e3,growth:8e4,pro:1e6},Ig={starter:3,growth:35,pro:100},Mg={starter:100,growth:300,pro:5e3},Rg={starter:5,growth:60,pro:750},Dg={starter:10,growth:150,pro:2e3},Lg={free:1,starter:50,growth:100,pro:1e3},zg={free:1,starter:2,growth:35,pro:400},$g={credits:Pg,competitor_analysis:Ig,keywords_research_per_competitor:Mg,page_content_creations:Rg,page_optimizations_geo:Dg,tracked_keywords:Lg,tracked_prompts:zg};class Fg{constructor(s){this.config=s}normalizePlanType(s){const a=String(s||"").toLowerCase().trim();return a==="basic"?"growth":a==="free"||a==="starter"||a==="growth"||a==="pro"?a:null}getLimit(s,a){const n=this.normalizePlanType(a);if(!n)return null;const o=this.config[s];return o?Number(o[n]):null}formatLimit(s){return s==null||!Number.isFinite(s)?"—":Math.round(s).toLocaleString()}getFormattedLimit(s,a){return this.formatLimit(this.getLimit(s,a))}}const Nt=new Fg($g),Og=[{id:"starter",name:"Starter Plan",description:"Self-serve for individuals",monthlyPrice:"$19.9",yearlyPrice:"$199",monthlyPriceNote:"/mo",yearlyPriceNote:"/year",cta:"Start free",ctaType:"start",features:[{label:"Credits",value:Nt.getFormattedLimit("credits","starter")},{label:"Competitor Analysis",value:Nt.getFormattedLimit("competitor_analysis","starter")},{label:"Keywords Research",value:Nt.getFormattedLimit("keywords_research_per_competitor","starter")},{label:"Page Creations",value:Nt.getFormattedLimit("page_content_creations","starter")},{label:"Page Optimizations (GEO)",value:Nt.getFormattedLimit("page_optimizations_geo","starter")},{label:"Technical SEO QA",value:"10"},{label:"Crawlability & Indexation",value:"3"},{label:"Tracked Pages",value:"3"},{label:"Tracked Keywords",value:Nt.getFormattedLimit("tracked_keywords","starter")},{label:"Tracked Prompts",value:Nt.getFormattedLimit("tracked_prompts","starter")},{label:"AI Models",value:"GPT, Gemini 3, Anthropic"},{label:"CMS & SEO Integrations",value:"Basic"},{label:"Knowledge Bases RAG",value:"Standard"},{label:"Content Strategy",value:"Automated"},{label:"Support",value:"Standard"}]},{id:"basic",name:"Basic Plan",description:"Self-serve for startups",monthlyPrice:"$199",yearlyPrice:"$1,990",monthlyPriceNote:"/mo",yearlyPriceNote:"/year",cta:"Start free",ctaType:"start",features:[{label:"Credits",value:Nt.getFormattedLimit("credits","growth")},{label:"Competitor Analysis",value:Nt.getFormattedLimit("competitor_analysis","growth")},{label:"Keywords Research",value:Nt.getFormattedLimit("keywords_research_per_competitor","growth")},{label:"Page Creations",value:Nt.getFormattedLimit("page_content_creations","growth")},{label:"Page Optimizations (GEO)",value:Nt.getFormattedLimit("page_optimizations_geo","growth")},{label:"Technical SEO QA",value:"150"},{label:"Crawlability & Indexation",value:"35"},{label:"Tracked Pages",value:"35"},{label:"Tracked Keywords",value:Nt.getFormattedLimit("tracked_keywords","growth")},{label:"Tracked Prompts",value:Nt.getFormattedLimit("tracked_prompts","growth")},{label:"AI Models",value:"GPT, Gemini 3, Anthropic"},{label:"CMS & SEO Integrations",value:"Basic"},{label:"Knowledge Bases RAG",value:"Standard"},{label:"Content Strategy",value:"Automated"},{label:"Support",value:"Standard"}]},{id:"pro",name:"Pro Plan",description:"Self-serve for scaling teams",monthlyPrice:"$1,999",yearlyPrice:"$19,990",monthlyPriceNote:"/mo",yearlyPriceNote:"/year",cta:"Get started",ctaType:"start",highlighted:!0,badge:"Most popular",features:[{label:"Credits",value:Nt.getFormattedLimit("credits","pro")},{label:"Competitor Analysis",value:Nt.getFormattedLimit("competitor_analysis","pro")},{label:"Keywords Research",value:Nt.getFormattedLimit("keywords_research_per_competitor","pro")},{label:"Page Creations",value:Nt.getFormattedLimit("page_content_creations","pro")},{label:"Page Optimizations (GEO)",value:Nt.getFormattedLimit("page_optimizations_geo","pro")},{label:"Technical SEO QA",value:"2,000"},{label:"Crawlability & Indexation",value:"400"},{label:"Tracked Pages",value:"400"},{label:"Tracked Keywords",value:Nt.getFormattedLimit("tracked_keywords","pro")},{label:"Tracked Prompts",value:Nt.getFormattedLimit("tracked_prompts","pro")},{label:"AI Models",value:"GPT, Gemini 3, Anthropic"},{label:"CMS & SEO Integrations",value:"Advanced"},{label:"Knowledge Bases RAG",value:"Advanced"},{label:"Content Strategy",value:"Advanced"},{label:"Support",value:"1:1 Strategic"}
20]}],Bg=[{label:"Credits",value:"Custom"},{label:"Competitor Analysis",value:"Unlimited"},{label:"Keywords Research",value:"Unlimited"},{label:"Page Creations",value:"Unlimited"},{label:"Page Optimizations (GEO)",value:"Unlimited"},{label:"Technical SEO QA",value:"Custom"},{label:"Crawlability & Indexation",value:"Custom"},{label:"Tracked Pages",value:"Unlimited"},{label:"Tracked Keywords",value:"Unlimited"},{label:"Tracked Prompts",value:"Unlimited"},{label:"AI Models",value:"Custom / All Models"},{label:"CMS & SEO Integrations",value:"Custom"},{label:"Knowledge Bases RAG",value:"Custom"},{label:"Content Strategy",value:"Expert-assisted"},{label:"Support",value:"Dedicated Vetted Operator"}],Ug=()=>{const[t,s]=r.useState("yearly"),a=i=>{const c=parseFloat(i.replace(/[$,]/g,""))/12;return c<100?`$${c.toFixed(1)}`:c<1e3?`$${Math.round(c)}`:`$${Math.round(c).toLocaleString()}`},n=async(i,l)=>{l.preventDefault();const d={starter:"starter",basic:"growth",pro:"pro"}[i];if(!d){console.warn("🟡 [PricingTable] Unknown plan id; ignoring:",i);return}const h=`/app/subscription/checkout?${new URLSearchParams({plan_type:d,billing_interval:t,return_to:"/app",src:"landing_home"}).toString()}`;try{window.history.pushState({},"",h),window.dispatchEvent(new PopStateEvent("popstate"))}catch(p){console.warn("⚠️ [PricingTable] Navigation failed; falling back to hard redirect:",p),window.location.href=h}},o=()=>{document.getElementById("booking")?.scrollIntoView({behavior:"smooth"})};return e.jsx("section",{id:"pricing",className:"py-24 bg-gradient-to-b from-white via-blue-50/30 to-white",children:e.jsxs("div",{className:"max-w-7xl mx-auto px-6",children:[e.jsxs("div",{className:"text-center mb-10",children:[e.jsx("h2",{className:"text-4xl md:text-5xl font-display italic text-slate-900 mb-4",children:"How to Get Started"}),e.jsx("p",{className:"text-lg text-slate-600 font-sans",children:"Flexible Pricing from Self-Serve to Enterprise."})]}),e.jsx("div",{className:"flex justify-center mb-12",children:e.jsxs("div",{className:"inline-flex items-center bg-slate-100 rounded-full p-1",children:[e.jsx("button",{onClick:()=>s("monthly"),className:`px-6 py-2.5 rounded-full text-sm font-medium transition-all duration-200 ${t==="monthly"?"bg-white text-slate-900 shadow-sm":"text-slate-600 hover:text-slate-900"}`,children:"Monthly"}),e.jsxs("button",{onClick:()=>s("yearly"),className:`px-6 py-2.5 rounded-full text-sm font-medium transition-all duration-200 flex items-center gap-2 ${t==="yearly"?"bg-white text-slate-900 shadow-sm":"text-slate-600 hover:text-slate-900"}`,children:["Yearly",e.jsx("span",{className:"bg-emerald-100 text-emerald-700 text-xs font-semibold px-2 py-0.5 rounded-full",children:"Save 17%"})]})]})}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-6 max-w-6xl mx-auto",children:Og.map(i=>e.jsxs("div",{className:`relative rounded-2xl p-8 transition-all duration-300 flex flex-col ${i.highlighted?"bg-gradient-to-br from-blue-600 to-cyan-500 text-white shadow-2xl shadow-blue-500/25 scale-105 z-10":"bg-white text-slate-900 border border-slate-200 hover:border-blue-200 hover:shadow-xl"}`,children:[i.badge&&e.jsx("div",{className:"absolute -top-3 right-6",children:e.jsxs("span",{className:"flex items-center gap-1 bg-amber-400 text-slate-900 text-xs font-bold px-3 py-1 rounded-full shadow-lg",children:[e.jsx(Dr,{className:"w-3 h-3 fill-current"}),i.badge]})}),e.jsxs("div",{className:"mb-6",children:[e.jsx("h3",{className:`text-2xl font-display italic mb-1 ${i.highlighted?"text-white":"text-slate-900"}`,children:i.name}),e.jsx("p",{className:`text-sm ${i.highlighted?"text-blue-100":"text-slate-500"}`,children:i.description})]}),e.jsxs("div",{className:"mb-6",children:[e.jsx("span",{className:`text-4xl font-bold ${i.highlighted?"text-white":"text-slate-900"}`,children:t==="monthly"?i.monthlyPrice:a(i.yearlyPrice)}),e.jsx("span",{className:`text-sm ml-1 ${i.highlighted?"text-blue-100":"text-slate-500"}`,children:t==="monthly"?i.monthlyPriceNote:"/mo"}),t==="yearly"&&e.jsxs("div",{className:`text-xs mt-1 ${i.highlighted?"text-blue-200":"text-slate-400"}`,children:["Billed ",i.yearlyPrice,"/year"]})]}),e.jsx("button",{onClick:i.ctaType==="start"?l=>n(i.id,l):o,className:`w-full py-3 px-6 rounded-xl font-semibold text-sm transition-all duration-200 mb-8 ${i.highlighted?"bg-white text-blue-600 hover:bg-blue-50 shadow-lg":"bg-slate-900 text-white hover:bg-slate-800"}`,children:e.jsx("span",{children:i.cta})}),e.jsx("div",{className:"flex-1",children:e.jsx("ul",{className:"space-y-3",children:i.features.map((l,c)=>e.jsxs("li",{className:"flex items-start gap-3",children:[e.jsx("div",{className:`flex-shrink-0 w-5 h-5 rounded-full flex items-center justify-center mt-0.5 ${i.highlighted?"bg-white/20":"bg-blue-100"}`,children:e.jsx(wt,{className:`w-3 h-3 ${i.highlighted?"text-white":"text-blue-600"}`})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("span",{className:`text-xs font-medium ${i.highlighted?"text-blue-200":"text-slate-500"}`,children:[l.label,":"]}
20),e.jsx("span",{className:`text-sm ml-1 ${i.highlighted?"text-blue-50":"text-slate-600"}`,children:l.value})]})]},c))})})]},i.id))}),e.jsx(Tg,{onBookDemo:o,features:Bg})]})})},Kg=[{question:"What makes RankGale different from those generic AI content tools?",answer:e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"mb-3",children:['Most AI tools produce generic, "AI-ish" content that risks penalties because they lack strategic depth. RankGale is powered by our proprietary ',e.jsx("strong",{children:"RankingOS"}),", which is built on a deep understanding of SEO/GEO mechanics and integrated with the experience of top 1% marketers."]}),e.jsx("p",{children:"By infusing your unique brand culture and customer needs into this engine, we ensure every piece of content is high-quality, authentic, and strategically aligned with your goals."})]})},{question:"How does RankGale increase AI search mention rate?",answer:e.jsx("p",{children:"We analyze how AI models like ChatGPT, Perplexity, and Claude source and cite information. Then we optimize your content structure, authority signals, and citation patterns to maximize the chances of being referenced in AI-generated responses."})},{question:"What LLMs does RankGale optimize for?",answer:e.jsx("p",{children:"RankGale optimizes for all major AI search engines including ChatGPT, Perplexity, Claude, Gemini, and emerging platforms. We continuously update our optimization strategies as these models evolve."})},{question:"How is RankGale different from traditional SEO agencies?",answer:e.jsx("p",{children:`Traditional SEO agencies focus on Google's "10 blue links." RankGale focuses on the new paradigm: AI-generated answers. We combine SEO best practices with GEO (Generative Engine Optimization) to ensure your brand is visible across both traditional search and AI assistants.`})},{question:"How fast can I expect results on AI search?",answer:e.jsx("p",{children:"Most clients see measurable improvements in AI visibility within 4-8 weeks. However, significant ranking changes typically occur within 90 days. Our fastest case study achieved #1 ChatGPT ranking in under 90 days."})},{question:"Does RankGale replace internal marketing or SEO teams?",answer:e.jsx("p",{children:"No, RankGale is designed to augment your existing teams. We provide the AI-powered tools and strategic frameworks while your team maintains brand voice and content direction. Many clients find their teams become 10x more productive with RankGale."})}],Gg=()=>{const[t,s]=r.useState(0),a=n=>{s(t===n?null:n)};return e.jsx("section",{id:"faqs",className:"py-24 bg-slate-50",children:e.jsxs("div",{className:"max-w-4xl mx-auto px-6",children:[e.jsxs("div",{className:"text-center mb-12",children:[e.jsx("h2",{className:"text-4xl md:text-5xl font-display italic text-slate-900 mb-4",children:"FAQs"}),e.jsx("p",{className:"text-lg text-slate-600 font-sans",children:"Generative Engine Optimization is still very new. We've got you covered."})]}),e.jsx("div",{className:"space-y-3",children:Kg.map((n,o)=>e.jsxs("div",{className:"bg-white rounded-xl border border-slate-200 overflow-hidden transition-all duration-200 hover:border-slate-300",children:[e.jsxs("button",{onClick:()=>a(o),className:"w-full flex items-center justify-between p-6 text-left",children:[e.jsx("span",{className:"text-slate-900 font-medium pr-4",children:n.question}),e.jsx(Gs,{className:`w-5 h-5 text-slate-400 flex-shrink-0 transition-transform duration-200 ${t===o?"rotate-180":""}`})]}),e.jsx("div",{className:`overflow-hidden transition-all duration-300 ${t===o?"max-h-96":"max-h-0"}`,children:e.jsx("div",{className:"px-6 pb-6 text-slate-600 leading-relaxed",children:n.answer})})]},o))})]})})},Da=()=>{const t=wa.getString("VITE_API_BASE_URL");if(t)return t;if(ao())return"http://localhost:8030";if(typeof window<"u"){const{hostname:s,protocol:a}=window.location;return`${a}//${s}/api`}return"http://localhost:8030"},Wg=()=>Da();function ao(){if(typeof window>"u")return!1;const t=window.location.hostname;return t==="localhost"||t==="127.0.0.1"||t.startsWith("192.")||t.startsWith("172.")}const Vg=["gmail.com","yahoo.com","hotmail.com","outlook.com","aol.com","icloud.com","mail.com","protonmail.com","yandex.com","zoho.com","gmx.com","live.com","msn.com","qq.com","163.com","sina.com"],Hg=t=>{const a=t.toLowerCase().trim().split("@")[1];return a?Vg.some(n=>a===n||a.endsWith(`.${n}`)):!1},qg=()=>{const[t,s]=r.useState({name:"",email:"",company:"",website:""}),[a,n]=r.useState(!1),[o,i]=r.useState("idle"),[l,c]=r.useState(""),d=h=>{const{name:p,value:f}=h.target;s(b=>({...b,[p]:f})),o==="error"&&(i("idle"),c(""))},m=async h=>{if(h.preventDefault(),Hg(t.email)){i("error"),c("Please use a work email address.");return}n(!0),i("idle"),c("");try{if(!(await fetch(`${Da()}/api/contact-requests`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:t.name,email:t.email,company:t.company,website:t.website,source:"landing_page_booking"})})).ok)throw new Error("Failed to submit");i("success"),s({name:"",email:"",company:"",website:""})}catch{i("error"),c("Something went wrong. Please try again.")}finally{n(!1)}};return e.jsx("section",{id:"booking",className:"py-24 bg-slate-900",children:e.jsx("div",{className:"max-w-6xl mx-auto px-6",children:e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-12 items-center",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"text-4xl md:text-5xl font-display italic text-white mb-6",children:["The only GEO platform",e.jsx("br",{}),"you will ever need"]}),e.jsx("p",{className:"text-lg text-slate-400 mb-8 font-sans",children:"Join hundreds of growth teams using RankGale to dominate AI search and drive qualified pipeline."}),e.jsx("div",{className:"space-y-4",children:["Setup in under 10 minutes","Dedicated onboarding support"].map((h,p)=>e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Rs,{className:"w-5 h-5 text-blue-400"}),e.jsx("span",{className:"text-slate-300",children:h})]},p))})]}),e.jsx("div",{className:"bg-white rounded-2xl p-8 shadow-2xl",children:o==="success"?e.jsxs("div",{className:"text-center py-8",children:[e.jsx("div",{className:"w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-4",children:e.jsx(Rs,{className:"w-8 h-8 text-green-600"})}),e.jsx("h3",{className:"text-2xl font-semibold text-slate-900 mb-2",children:"Thank y
20ou!"}),e.jsx("p",{className:"text-slate-600",children:"We'll be in touch within 24 hours."})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-3 mb-6",children:[e.jsx("div",{className:"w-10 h-10 bg-blue-100 rounded-lg flex items-center justify-center",children:e.jsx(ka,{className:"w-5 h-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-semibold text-slate-900",children:"Book a Demo"}),e.jsx("p",{className:"text-sm text-slate-500",children:"See RankGale in action"})]})]}),e.jsxs("form",{onSubmit:m,className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-slate-700 mb-1",children:"Full Name"}),e.jsx("input",{type:"text",name:"name",value:t.name,onChange:d,required:!0,className:"w-full px-4 py-3 border border-slate-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all",placeholder:"John Doe"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-slate-700 mb-1",children:"Work Email"}),e.jsx("input",{type:"email",name:"email",value:t.email,onChange:d,required:!0,className:"w-full px-4 py-3 border border-slate-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all",placeholder:"[email protected]"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-slate-700 mb-1",children:"Company"}),e.jsx("input",{type:"text",name:"company",value:t.company,onChange:d,required:!0,className:"w-full px-4 py-3 border border-slate-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all",placeholder:"Acme Inc"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-slate-700 mb-1",children:"Website"}),e.jsx("input",{type:"url",name:"website",value:t.website,onChange:d,className:"w-full px-4 py-3 border border-slate-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all",placeholder:"https://company.com"})]}),o==="error"&&e.jsx("p",{className:"text-red-600 text-sm",children:l}),e.jsx("button",{type:"submit",disabled:a,className:"w-full bg-blue-600 text-white py-4 px-6 rounded-xl font-semibold hover:bg-blue-700 transition-colors duration-200 flex items-center justify-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed",children:a?"Submitting...":e.jsxs(e.Fragment,{children:["Get a Demo",e.jsx(Ri,{className:"w-4 h-4"})]})})]})]})})]})})})},Yg=()=>e.jsx("svg",{className:"w-5 h-5",fill:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{d:"M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z"})}),Jg=()=>e.jsx("svg",{className:"w-5 h-5",fill:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{d:"M20.447 20.452h-3.554v-5.569c0-1.328-.027-3.037-1.852-3.037-1.853 0-2.136 1.445-2.136 2.939v5.667H9.351V9h3.414v1.561h.046c.477-.9 1.637-1.85 3.37-1.85 3.601 0 4.267 2.37 4.267 5.455v6.286zM5.337 7.433c-1.144 0-2.063-.926-2.063-2.065 0-1.138.92-2.063 2.063-2.063 1.14 0 2.064.925 2.064 2.063 0 1.139-.925 2.065-2.064 2.065zm1.782 13.019H3.555V9h3.564v11.452zM22.225 0H1.771C.792 0 0 .774 0 1.729v20.542C0 23.227.792 24 1.771 24h20.451C23.2 24 24 23.227 24 22.271V1.729C24 .774 23.2 0 22.222 0h.003z"})}),Xg=()=>e.jsx("svg",{className:"w-5 h-5",fill:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{d:"M20.317 4.369a19.791 19.791 0 0 0-4.885-1.515.074.074 0 0 0-.079.037c-.211.375-.444.864-.608 1.249a18.27 18.27 0 0 0-5.487 0 12.64 12.64 0 0 0-.617-1.249.077.077 0 0 0-.079-.037A19.736 19.736 0 0 0 3.677 4.37a.07.07 0 0 0-.032.027C.533 8.976-.32 13.43.099 17.823a.083.083 0 0 0 .031.056 19.919 19.919 0 0 0 5.993 3.03.077.077 0 0 0 .084-.027c.462-.63.874-1.295 1.226-1.994a.076.076 0 0 0-.041-.105 13.102 13.102 0 0 1-1.872-.892.077.077 0 0 1-.007-.128c.126-.094.252-.192.372-.291a.074.074 0 0 1 .077-.01c3.927 1.793 8.18 1.793 12.061 0a.074.074 0 0 1 .078.01c.12.099.246.198.373.292a.077.077 0 0 1-.006.127 12.299 12.299 0 0 1-1.873.892.077.077 0 0 0-.04.106c.36.698.772 1.363 1.225 1.993a.076.076 0 0 0 .084.028 19.876 19.876 0 0 0 6.002-3.03.077.077 0 0 0 .031-.055c.5-5.177-.838-9.593-3.549-13.426a.061.061 0 0 0-.031-.028ZM8.02 15.331c-1.183 0-2.157-1.087-2.157-2.419 0-1.332.955-2.419 2.157-2.419 1.21 0 2.184 1.095 2.157 2.419 0 1.332
20-.955 2.419-2.157 2.419Zm7.975 0c-1.183 0-2.157-1.087-2.157-2.419 0-1.332.955-2.419 2.157-2.419 1.21 0 2.184 1.095 2.157 2.419 0 1.332-.946 2.419-2.157 2.419Z"})}),Qg=[{label:"Discord",href:"https://discord.gg/zMUQUXgbdf",icon:e.jsx(Xg,{})},{label:"X",href:"https://x.com/Rankgale_AI",icon:e.jsx(Yg,{})},{label:"LinkedIn",href:"https://www.linkedin.com/company/rankgaleai/",icon:e.jsx(Jg,{})}],Zg=()=>{const t=new Date().getFullYear();return e.jsx("footer",{className:"bg-slate-900 border-t border-slate-800",children:e.jsx("div",{className:"max-w-7xl mx-auto px-6 py-8",children:e.jsxs("div",{className:"flex flex-col md:flex-row items-center justify-between gap-4",children:[e.jsx("div",{className:"flex items-center gap-6",children:Qg.map(s=>e.jsx("a",{href:s.href,target:"_blank",rel:"noopener noreferrer",className:"text-slate-400 hover:text-white transition-colors","aria-label":s.label,title:s.label,children:s.icon},s.label))}),e.jsxs("nav",{className:"flex items-center gap-6 text-sm text-slate-400",children:[e.jsx("a",{href:"/sms",className:"hover:text-white transition-colors",children:"SMS Updates"}),e.jsx("a",{href:"/privacy",className:"hover:text-white transition-colors",children:"Privacy Policy"}),e.jsx("a",{href:"/terms",className:"hover:text-white transition-colors",children:"Terms of Use"})]}),e.jsxs("p",{className:"text-slate-500 text-sm",children:["© ",t," RankGale. All rights reserved."]})]})})})},e0=()=>{const[t,s]=r.useState(!1);r.useEffect(()=>{const n=()=>{window.scrollY>300?s(!0):s(!1)};return window.addEventListener("scroll",n),()=>{window.removeEventListener("scroll",n)}},[]);const a=()=>{window.scrollTo({top:0,behavior:"smooth"})};return t?e.jsx("button",{onClick:a,className:"fixed bottom-8 right-8 z-50 bg-white text-slate-900 p-3 rounded-full border border-slate-200 shadow-lg hover:bg-slate-50 transition-all hover:shadow-xl hover:-translate-y-1 focus:outline-none focus:ring-2 focus:ring-slate-900 focus:ring-offset-2","aria-label":"Scroll to top",children:e.jsx(Is,{size:24})}):null},t0=({title:t,description:s,keywords:a,ogImage:n="https://rankgale.ai/logo.png",ogUrl:o="https://rankgale.ai/",canonicalUrl:i="https://rankgale.ai/",noindex:l=!1})=>(r.useEffect(()=>{const c=(m,h,p=!1)=>{const f=p?"property":"name";let b=document.querySelector(`meta[${f}="${m}"]`);b||(b=document.createElement("meta"),b.setAttribute(f,m),document.head.appendChild(b)),b.setAttribute("content",h)};t&&(document.title=t,c("title",t)),s&&(c("description",s),c("og:description",s,!0),c("twitter:description",s)),a&&c("keywords",a),t&&(c("og:title",t,!0),c("twitter:title",t)),c("og:url",o,!0),c("og:image",n,!0),c("twitter:url",o),c("twitter:image",n);let d=document.querySelector('link[rel="canonical"]');d||(d=document.createElement("link"),d.setAttribute("rel","canonical"),document.head.appendChild(d)),d.setAttribute("href",i),l?c("robots","noindex, nofollow"):c("robots","index, follow")},[t,s,a,n,o,i,l]),null);function s0(){const t={"@context":"https://schema.org","@graph":[{"@type":"Organization","@id":"https://rankgale.ai/#organization",name:"RankGale.ai",url:"https://rankgale.ai",logo:"https://rankgale.ai/logo.png",description:"AI-first rank engine that transforms deep product research and competitor intelligence into a high-ranking content moat.",sameAs:["https://discord.gg/zMUQUXgbdf","https://x.com/Rankgale_AI","https://www.linkedin.com/company/rankgaleai/"],contactPoint:{"@type":"ContactPoint",contactType:"Sales",availableLanguage:["English"]}},{"@type":"SoftwareApplication","@id":"https://rankgale.ai/#product",name:"RankGale",applicationCategory:"BusinessApplication",operatingSystem:"Web",provider:{"@id":"https://rankgale.ai/#organization"},description:"One engine for visibility across Search and LLMs. AI-first rank engine for SEO and GEO optimization.",offers:[{"@type":"Offer",name:"Basic Plan",price:"199",priceCurrency:"USD",priceValidUntil:"2026-12-31",description:"Self-serve for startups - 80,000 credits, 40 page creations, 40 page optimizations"},{"@type":"Offer",name:"Pro Plan",price:"1999",priceCurrency:"USD",priceValidUntil:"2026-12-31",description:"Self-serve for scaling teams - 1,000,000 credits, 80 page creations, 80 page optimizations"},{"@type":"Offer",name:"Enterprise",description:"Full-scale growth with vetted talents - Custom credit limits, unlimited features"}]},{"@type":"WebSite","@id":"https://rankgale.ai/#website",url:"https://rankgale.ai",name:"RankGale.ai",description:"One engine for visibility across Search and LLMs - AI-first rank engine for modern marketing teams",publisher:{"@id":"https://rankgale.ai/#organization"}}]};return e.jsxs(e.Fragment,{children:[e.jsx(t0,{title:"RankGale.ai — One Engine for Visibility Across Search and LLMs | AI-First Rank Engine",description:"AI-first rank engine that transforms deep product research and competitor intelligence into a high-ranking content moat. Help modern teams out-rank competitors and become the sources LLMs cite. Powered by RankingOS with top 1% expertise strategy.",keywords:"AI rank engine, SEO optimization, GEO optimization, LLM citation, content strategy, keyword research, competitor intelligence, RankingOS, ChatGPT optimization, Claude optimization, Perplexity optimization, Google ranking, AI content, Blue Ocean keywords",ogUrl:"https://rankgale.ai/",ogImage:"https://rankgale.ai/logo.png",canonicalUrl:"https://rankgale.ai/"}),e.jsx("script",{type:"application/ld+json",dangerouslySetInnerHTML:{__html:JSON.stringify(t)}}),e.jsxs("div",{className:"min-h-screen bg-white",children:[e.jsx(ag,{}),e.jsxs("main",{role:"main",children:[e.jsx("article",{id:"narrative",itemScope:!0,itemType:"https://schema.org/Article",children:e.jsx(cg,{})}),e.jsx("section",{id:"features","aria-label":"Features",children:e.jsx(pg,{})}),e.jsx("section",{id:"rankingos-flow","aria-label":"How RankingOS Works",children:e.jsx(Ag,{})}),e.jsx("section",{id:"pricing","aria-label":"Pricing Plans",children:e.jsx(Ug,{})}),e.jsx("section",{id:"faqs","aria-label":"Frequently Asked Questions",children:e.jsx(Gg,{})}),e.jsx("section",{id:"booking","aria-label":"Book a Demo",children:e.jsx(qg,{})})]}),e.jsx(Zg,{}),e.jsx(e0,{})]})]})}function a0(){try{return sessionStorage.getItem(xc)==="1"}catch{return!1}}
20function n0(){try{sessionStorage.removeItem(xc)}catch{}}function pi(){return r.useEffect(()=>{if(a0()){n0();let s=!0;return(async()=>{try{await rs.isAuthenticated()&&s&&(console.log("✅ [LandingPage] First login detected, redirecting to /app"),jt("home"))}catch(a){console.error("❌ [LandingPage] Failed to check authentication:",a)}})(),()=>{s=!1}}},[]),e.jsx(s0,{})}function r0(){return e.jsx(pi,{})}function o0(){const[t,s]=r.useState("Authorizing..."),a=r.useRef(!1);return r.useEffect(()=>{a.current||(a.current=!0,(async()=>{try{const n=new URLSearchParams(window.location.search),o=n.get("code"),i=n.get("error")||n.get("error_description");if(i){try{window.opener&&typeof window.opener.postMessage=="function"&&window.opener.postMessage({source:"google_oauth",error:i},window.opener.location.origin)}catch{}s("Authorization failed"),window.close();return}if(!o){try{window.opener&&typeof window.opener.postMessage=="function"&&window.opener.postMessage({source:"google_oauth",error:"Missing authorization code"},window.opener.location.origin)}catch{}s("Missing authorization code"),window.close();return}const{getGoogleAuthCallback:l}=await Bt(async()=>{const{getGoogleAuthCallback:c}=await Promise.resolve().then(()=>x0);return{getGoogleAuthCallback:c}},void 0);await l(o);try{window.opener&&typeof window.opener.postMessage=="function"&&window.opener.postMessage({source:"google_oauth",success:!0},window.opener.location.origin)}catch{}s("Authorized, you can close this window."),window.close()}catch(n){const o=n?.message||"Authorization error";try{window.opener&&typeof window.opener.postMessage=="function"&&window.opener.postMessage({source:"google_oauth",error:o},"*")}catch{}s("Authorization error");try{window.close()}catch{}}})())},[]),e.jsx("div",{style:{fontFamily:"system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial",padding:16},children:e.jsx("div",{children:t})})}const i0=t=>{const{response:s,request:a,message:n}=t;if(!s)return a?{type:"error",message:"Network connection failed. Please check your internet connection and try again."}:{type:"error",message:"Request configuration error. Please try again."};const{status:o,data:i}=s;let l="Unknown error occurred";if(i&&typeof i=="object"){const c=i;c.message?l=c.message:c.detail?typeof c.detail=="string"?l=c.detail:(c.detail.message||c.detail.error&&c.detail.message)&&(l=c.detail.message):c.error&&(l=c.error)}switch(o){case 400:return{type:"error",message:l||"Invalid request parameters. Please check your input.",statusCode:o};case 401:return{type:"warning",message:"Your session has expired. Please log in again.",statusCode:o,shouldRedirect:!0};case 403:return{type:"error",message:l||"Access denied. You don't have permission to perform this action.",statusCode:o};case 404:return{type:"error",message:l||"The requested resource was not found.",statusCode:o};case 409:return{type:"error",message:l||"Resource conflict. The operation cannot be completed.",statusCode:o};case 422:return{type:"error",message:l||"Validation failed. Please check your input data.",statusCode:o};case 429:return{type:"warning",message:"Too many requests. Please wait a moment before trying again.",statusCode:o};case 500:return{type:"error",message:"Internal server error. Please try again later or contact support.",statusCode:o};case 502:case 503:case 504:return{type:"error",message:"Service temporarily unavailable. Please try again later.",statusCode:o};default:return o>=500?{type:"error",message:"Server error occurred. Please try again later.",statusCode:o}:o>=400?{type:"error",message:l||"Client error occurred. Please check your request.",statusCode:o}:{type:"error",message:l||"An unexpected error occurred.",statusCode:o}}};class zr extends Error{constructor(s){const a=i0(s);super(a.message),this.name="EnhancedError",this.errorInfo=a}getMessageProps(){return{type:this.errorInfo.type,content:this.errorInfo.message}}}let zo=null;const l0=()=>(zo||(zo=Cn.create({baseURL:Da(),timeout:6e5}),d0(zo)),zo);let dd=!1;const c0=async()=>{if(!(typeof window>"u")&&!dd&&!window.location.pathname.startsWith("/auth/logto/callback")){dd=!0;try{console.warn("⚠️ [ajax] 401 Unauthorized: redirecting to sign-in"),bu(),await rs.signIn()}catch(t){console.error("❌ [ajax] Failed to redirect to sign-in:",t);try{window.location.href="/"}catch{}}}},ju=async(t,s)=>{try{const a=t.response?.status,n=t.config;a===401&&n&&await c0()}catch(a){console.warn("⚠️ [ajax] Failed to handle unauthorized redirect:",a)}throw new zr(t)},d0=t=>{t.interceptors.request.use(async s=>{s.headers=s.headers||{};try{const a=await rs.getBackendAccessToken();if(a)s.headers.Authorization=`Bearer ${a}`;else{const n=yo();n&&n.access_token&&(s.headers.Authorization=`Bearer ${n.access_token}`)}}catch{const a=yo();a&&a.access_token&&(s.headers.Authorization=`Bearer ${a.access_token}`)}return s.data instanceof FormData||(s.headers=s.headers||{},s.headers["Content-Type"]="application/json"),s},s=>Promise.reject(s)),t.interceptors.response.use(s=>s,s=>ju(s))},Co=t=>{const s=m0();if(!t&&(t=Da(),s[t])||s[t])return s[t];const a=Cn.create({baseURL:t,timeout:6e5});return a.interceptors.request.use(async n=>{n.headers=n.headers||{};try{const o=await rs.getBackendAccessToken();if(o){n.headers.Authorization=`Bearer ${o}`;try{const i=o.length>20?`${o.slice(0,12)}...${o.slice(-6)}`:"<short>",l=o.includes(".")&&o.split(".").length===3;ao()&&console.debug("[ajax] attach Authorization (logto) | jwtLike=",l,"| preview=",i)}catch{}}else{const i=yo();if(i&&i.access_token){n.headers.Authorization=`Bearer ${i.access_token}`;try{const l=i.access_token,c=l.length>20?`${l.slice(0,12)}...${l.slice(-6)}`:"<short>",d=l.includes(".")&&l.split(".").length===3;ao()&&console.debug("[ajax] attach Authorization (local) | jwtLike=",d,"| preview=",c)}catch{}}}}catch{const o=yo();if(o&&o.access_token){n.headers.Authorization=`Bearer ${o.access_token}`;try{const i=o.access_token,l=i.length>20?`${i.slice(0,12)}...${i.slice(-6)}`:"<short>",c=i.includes(".")&&i.split(".").length===3;ao()&&console.debug("[ajax] attach Authorization (fallback local) | jwtLike=",c,"| preview=",l)}catch{}}}return n.data instanceof FormData||(n.headers=n.headers||{},n.headers["Content-Type"]="application/json"),n},n=>Promise.reject(n)),a.interceptors.response.use(n=>n,n=>ju(n)),s[t]=a,a},tl={},m0=()=>{const t=Da();return tl[t]||(tl[t]=l0()),tl},ya=t=>t instanceof zr?t.getMessageProps():{type:"error",content:t.message||"An unexpected error occurred"},ot=async(t,s,a,n)=>(await Co(n).get(t,{params:s,...a})).data,Je=async(t,s,a,n)=>(await Co(n).post(t,s,a)).data,Ca=async(t,s,a)=>(await Co(a).delete(t,s)).data,$r=async(t,s,a,n)=>(await Co(n).put(t,s,a)).data,V1=async(t,s,a,n)=>(await Co(n).patch(t,s,a)).data,u0=()=>
20{if(ao())return"http://localhost:5173/auth/google/callback";if(typeof window>"u")return"https://www.getu.ai/auth/google/callback";const{hostname:t,protocol:s}=window.location;return`${s}//${t}/auth/google/callback`},vu=()=>u0(),Nu=async()=>await ot("/google/oauth/exists"),ku=async()=>await Je("/google/oauth/build_url",{redirect_url:vu()}),pc=async t=>await Je("/google/oauth/callback",{code:t,redirect_url:vu()}),gc=async()=>(await ku()).authorization_url,_u=async()=>await ot("/google/oauth/delete"),x0=Object.freeze(Object.defineProperty({__proto__:null,buildGoogleAuthUrl:gc,deleteGoogleAuth:_u,getGoogleAuthCallback:pc,getGoogleAuthExists:Nu,getGoogleAuthUrl:ku},Symbol.toStringTag,{value:"Module"})),Cu=async()=>await ot("/webflow/credential_exists"),Su=async(t,s,a,n,o)=>await Je("/webflow/save_credential",{api_key:t,site_id:s,site_url:a,site_name:n,api_version:o}),Eu=async()=>await ot("/webflow/delete_credential"),Au=async(t,s)=>await Je("/webflow/test_connection",{api_key:t,api_version:s}),h0=async(t,s)=>await Je("/webflow/list_sites_by_key",{api_key:t,api_version:s}),no=Object.freeze(Object.defineProperty({__proto__:null,deleteWebflowCredential:Eu,getWebflowCredentialExists:Cu,listSitesByKey:h0,saveWebflowCredential:Su,testWebflowConnection:Au},Symbol.toStringTag,{value:"Module"})),bo=async()=>await ot("/shopify/shops"),md=async t=>await Je("/shopify/start_oauth",{shop_name:t}),gi=async t=>await Je("/shopify/revalidate_shop",{shop_id:t}),p0=async t=>await Ca(`/shopify/shop/${t}`),g0=async t=>await ot("/shopify/blogs",{shop_id:t}),f0=async t=>await ot("/shopify/template_suffixes",{shop_id:t});async function y0(){const t=await rs.getLogtoAccessTokenForUserInfo();return ot("/account/get",t?{app_ak:t}:void 0)}async function b0(){const t=await rs.getLogtoAccessTokenForUserInfo();return ot("/account/init_user_account",t?{app_ak:t}:void 0)}async function w0(t,s){return Je("/account/update_setup_status",{step:t,status:s})}async function Tl(t){return await Je("/api/referral/activate",{code:t})}async function j0(t){return await ot(`/api/referral/status/${encodeURIComponent(t)}`)}async function v0(t){return await ot(`/api/referral/report/${encodeURIComponent(t)}`)}async function N0(t,s){return await Je(`/api/referral/report/${encodeURIComponent(t)}/competitors/keywords_batch`,{competitor_domains:s})}async function k0(t){return await ot(`/api/referral/report/${encodeURIComponent(t)}/own_keywords`)}const Pl=async()=>await ot("/attribution_open/credential_exists"),Tu=async(t,s)=>await Je("/attribution_open/save_credential",{api_key:t,api_origin:s||null}),_0=async()=>await ot("/attribution_open/delete_credential"),Pu=async(t,s)=>await Je("/attribution_open/test_connection",{api_key:t,api_origin:s||null}),C0=async()=>await Je("/attribution_open/test_saved_connection",{}),S0=async t=>await Je("/attribution_open/dashboard/metrics",t),E0=async t=>await Je("/attribution_open/dashboard/events_trend",t),A0=async t=>await Je("/attribution_open/dashboard/utm_source_performance",t),T0=async t=>await Je("/attribution_open/dashboard/campaign_performance",t),P0=async t=>await Je("/attribution_open/dashboard/url_flow",t),I0=async t=>await Je("/company/create",{url:t.url,analyze_competitors:t.analyze_competitors??!0,max_keywords:t.max_keywords??10,max_competitors:t.max_competitors??10}),M0=async t=>await Je("/company/create_async",{url:t.url,analyze_competitors:t.analyze_competitors??!0,max_keywords:t.max_keywords??10,max_competitors:t.max_competitors??10}),R0=async t=>await ot("/company/task_status",{task_id:t}),D0=async t=>await Je("/company/recreate",{url:t.url,analyze_competitors:t.analyze_competitors??!0,max_keywords:t.max_keywords??10,max_competitors:t.max_competitors??10}),L0=async t=>await ot("/company/info",{company_id:t}),Dn=async()=>await ot("/company/my_info"),z0=async t=>await ot("/company/detail",{company_id:t}),$0=async t=>await ot("/company/get",{company_id:t}),F0=async t=>await ot("/company/list",t),O0=async t=>await Je("/company/delete",void 0,{params:{company_id:t}}),Iu=async t=>await Je("/company/update",{company_id:t.company_id,name:t.name,about:t.about,competitor_analysis_insights:t.competitor_analysis_insights}),B0=Object.freeze(Object.defineProperty({__proto__:null,createCompany:I0,createCompanyAsync:M0,deleteCompany:O0,getCompany:$0,getCompanyDetail:z0,getCompanyInfo:L0,getCompanyTaskStatus:R0,getMyCompanyInfo:Dn,listCompanies:F0,recreateCompany:D0,updateCompany:Iu},Symbol.toStringTag,{value:"Module"}));class Il{static{this.initialized=!1}static{this.initializing=null}static async initOnce(s){if(this.initialized){s?.userId&&this.setUserIdBestEffort(s.userId);return}if(this.initializing){await this.initializing,s?.userId&&this.setUserIdBestEffort(s.userId);return}const{apiKey:a,apiEndpoint:n}=this.readConfig();if(!a){console.error("❌ Failed to initialize Getu Attribution SDK: VITE_PUBLIC_ATTRIBUTION_API_KEY is not set");return}const o=this.normalizeUserId(s?.userId??await this.resolveInitialUserId());this.initializing=(async()=>{try{n||console.warn("⚠️ Getu Attribution SDK apiEndpoint is not set; using SDK default"),await to.init({apiKey:a,apiEndpoint:n||void 0,autoTrack:!0,autoTrackPageView:!0,userId:o||void 0}),this.initialized=!0,console.log("✅ Getu Attribution SDK initialized")}catch(i){console.error("❌ Failed to initialize Getu Attribution SDK:",i)}finally{this.initializing=null}})(),await this.initializing}static setUserIdBestEffort(s){const a=this.normalizeUserId(s);
20if(a)try{to.setUserId(a),console.debug("🧭 Getu Attribution SDK userId set")}catch(n){console.warn("⚠️ Failed to set Getu Attribution SDK userId:",n)}}static readConfig(){const s=wa.getString("VITE_PUBLIC_ATTRIBUTION_API_KEY"),a=wa.getString("VITE_PUBLIC_ATTRIBUTION_API_ENDPOINT");return{apiKey:s,apiEndpoint:a}}static normalizeUserId(s){return String(s??"").trim()}static async resolveInitialUserId(){try{const s=to.getUserId();if(s)return s}catch{}try{return await rs.isAuthenticated()?(await rs.getUserProfile())?.id??null:null}catch{return null}}}function ud(t){try{if(t.startsWith("/")){window.history.replaceState({},"",t),window.dispatchEvent(new PopStateEvent("popstate"));return}}catch(s){console.warn("⚠️ [LogtoCallback] SPA navigation failed, falling back:",s)}window.location.replace(t)}function Mu(){try{return sessionStorage.getItem(xi)}catch{return null}}function xd(){try{sessionStorage.removeItem(xi)}catch{}}function Ru(t){const s=(t||"/").replace(/\/+$/,"")||"/";return s==="/app"||s==="/app/landing"||s==="/landingpage"||s==="/app/landingpage"||s==="/"}function hd(){try{sessionStorage.setItem(xc,"1")}catch{}}function U0(){const s=Mu();if(!s)return"/";try{const a=new URL(s,window.location.origin);if(a.origin!==window.location.origin)return"/";const n=`${a.pathname}${a.search}${a.hash}`||"/";return Ru(a.pathname)?"/":n}catch{return"/"}}function K0(){const[t,s]=r.useState("Processing authentication...");return r.useEffect(()=>{(async()=>{try{console.debug("🚀 [LogtoCallback] Starting authentication process"),await rs.handleCallback(),console.debug("✅ [LogtoCallback] Authentication completed successfully");const a=Mu(),n=U0();xd();try{const i=new URL(n,window.location.origin).pathname;(!a||Ru(i))&&hd()}catch{a||hd()}s("Authentication successful, redirecting...");let o="/app/setup";try{console.debug("🧩 [logto] Step 1: Starting initUserAccount");const i=await b0();console.debug("🧩 [logto] Account info received:",{user_id:i.user_id,credits:i.credits_balance,signup_success:i.signup_success});const l=String(i.setup_company_analysis_status||"").toLowerCase()==="completed",c=String(i.setup_init_status||"").toLowerCase()==="completed";o=l&&c?"/app":"/app/setup",console.debug("🧩 [logto] Step 2: Fetching current user info");const d=await wu(),m=d.id;await Il.initOnce({userId:m}),Il.setUserIdBestEffort(m),i.signup_success?(console.debug("🧭 [logto] Step 3: Tracking signup"),await to.trackSignup(m,{email:d.email,name:d.name,company:d.company})):(console.debug("🧭 [logto] Step 3: Tracking login"),await to.trackLogin(m,{email:d.email,name:d.name,company:d.company}))}catch(i){console.error("⚠️ [logto] Post-callback init failed:",i)}console.debug("↩️ [LogtoCallback] Redirecting to:",o,{sessionTarget:n}),ud(o)}catch(a){console.error("❌ [LogtoCallback] Authentication failed:",a),s(a?.message||"Authentication error"),xd(),setTimeout(()=>ud("/"),1200)}})()},[]),e.jsxs("div",{style:{padding:24,fontFamily:"Inter, system-ui, sans-serif"},children:[e.jsx("h3",{children:"Signing you in..."}),e.jsx("div",{style:{color:"#475569",marginTop:8},children:t})]})}function G0(){const t=s=>{window.location.pathname!==s&&(window.history.pushState({},"",s),window.dispatchEvent(new PopStateEvent("popstate")))};return e.jsxs("div",{className:"min-h-screen bg-white",children:[e.jsx("header",{className:"border-b border-gray-200",children:e.jsx("div",{className:"max-w-4xl mx-auto px-6 py-8",children:e.jsxs("button",{onClick:()=>t("/"),className:"inline-flex items-center gap-3 text-2xl font-bold text-black hover:text-gray-700 transition-colors",children:[e.jsx(dr,{className:"w-8 h-8 rounded-lg",alt:"RankGale"}),e.jsx("span",{children:"RankGale.ai"})]})})}),e.jsxs("main",{className:"max-w-4xl mx-auto px-6 py-12",children:[e.jsx("h1",{className:"text-4xl font-bold text-black mb-4",children:"Privacy Policy"}),e.jsx("p",{className:"text-sm text-gray-600 mb-12",children:"Last updated: May 25, 2025"}),e.jsxs("div",{className:"prose prose-lg prose-gray max-w-none",children:[e.jsxs("p",{className:"text-gray-700 leading-relaxed mb-6",children:["This Privacy Notice for ",e.jsx("strong",{children:"Optiminds Inc."}),' ("we," "us," or "our") describes how and why we might access, collect, store, use, and/or share ("process") your personal information when you use our services ("Services"), including when you:']}),e.jsxs("ul",{className:"list-disc pl-6 mb-8 text-gray-700 space-y-2",children:[e.jsxs("li",{children:["Visit our website at ",e.jsx("strong",{children:"https://www.rankgale.ai"}),", or any website of ours that links to this Privacy Notice"]}),e.jsxs("li",{children:['Use our web or mobile applications (collectively, "',e.jsx("strong",{children:"RankGale"}),'") or any other application of ours that links to this Privacy Notice']}),e.jsx("li",{children:"Engage with us in other related ways, including any sales, marketing, or events"})]}),e.jsxs("p",{className:"text-gray-700 leading-relaxed mb-12",children:[e.jsx("strong",{children:"Questions or concerns?"})," Reading this Privacy Notice will help you understand your privacy rights and choices. We are responsible for making decisions about how your personal information is processed. If you do not agree with our policies and practices, please do not use our Services. If you still have any questions or concerns, please contact us at ",e.jsx("a",{href:"mailto:[email protected]",className:"text-black underline hover:text-gray-700",children:"[email protected]"}),"."]}),e.jsxs("section",{className:"mb-12",children:[e.jsx("h2",{className:"text-2xl font-bold text-black mb-6 pb-2 border-b border-gray-200",children:"SUMMARY OF KEY POINTS"}),e.jsxs("div",{className:"space-y-4 text-gray-700",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-black mb-2",children:"What personal information do we process?"}),e.jsx("p",{children:"When you visit, use, or navigate our Services, we may process personal information depending on how you interact with us and the Services, the choices you make, and the products and features you use."})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-black mb-2",children:"Do we process any sensitive personal information?"}),e.jsxs("p",{children:['Some of the information may be considered "special" or "sensitive" in certain 
20jurisdictions (e.g., racial or ethnic origin, sexual orientation, religious beliefs). ',e.jsx("strong",{children:"We do not process sensitive personal information."})]})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-black mb-2",children:"Do we collect any information from third parties?"}),e.jsx("p",{children:"We do not collect information from unaffiliated third parties for profiling or enrichment. We may receive limited information from identity, payment, or analytics providers in order to provide the Services."})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-black mb-2",children:"How do we process your information?"}),e.jsx("p",{children:"We process your information to provide, improve, and administer our Services, communicate with you, for security and fraud prevention, and to comply with law. We may also process your information for other purposes with your consent."})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-black mb-2",children:"How do we keep your information safe?"}),e.jsx("p",{children:"We have organizational and technical measures designed to protect your personal information. However, no electronic transmission or storage can be guaranteed 100% secure."})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-black mb-2",children:"What are your rights?"}),e.jsx("p",{children:"Depending on where you live, you may have certain privacy rights regarding your personal information."})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-black mb-2",children:"How do you exercise your rights?"}),e.jsxs("p",{children:["The easiest way to exercise your rights is by submitting a data subject request or contacting us at ",e.jsx("a",{href:"mailto:[email protected]",className:"text-black underline hover:text-gray-700",children:"[email protected]"}),". We will consider and act upon any request in accordance with applicable data protection laws."]})]})]})]}),e.jsxs("section",{className:"mb-12",children:[e.jsx("h2",{className:"text-2xl font-bold text-black mb-6 pb-2 border-b border-gray-200",children:"TABLE OF CONTENTS"}),e.jsxs("ol",{className:"list-decimal pl-6 space-y-2 text-gray-700",children:[e.jsx("li",{children:e.jsx("a",{href:"#section-1",className:"hover:text-black underline",children:"WHAT INFORMATION DO WE COLLECT?"})}),e.jsx("li",{children:e.jsx("a",{href:"#section-2",className:"hover:text-black underline",children:"HOW DO WE PROCESS YOUR INFORMATION?"})}),e.jsx("li",{children:e.jsx("a",{href:"#section-3",className:"hover:text-black underline",children:"WHAT LEGAL BASES DO WE RELY ON TO PROCESS YOUR PERSONAL INFORMATION?"})}),e.jsx("li",{children:e.jsx("a",{href:"#section-4",className:"hover:text-black underline",children:"WHEN AND WITH WHOM DO WE SHARE YOUR PERSONAL INFORMATION?"})}),e.jsx("li",{children:e.jsx("a",{href:"#section-5",className:"hover:text-black underline",children:"DO WE USE COOKIES AND OTHER TRACKING TECHNOLOGIES?"})}),e.jsx("li",{children:e.jsx("a",{href:"#section-6",className:"hover:text-black underline",children:"DO WE OFFER ARTIFICIAL INTELLIGENCE-BASED PRODUCTS?"})}),e.jsx("li",{children:e.jsx("a",{href:"#section-7",className:"hover:text-black underline",children:"HOW DO WE HANDLE YOUR SOCIAL LOGINS?"})}),e.jsx("li",{children:e.jsx("a",{href:"#section-8",className:"hover:text-black underline",children:"HOW LONG DO WE KEEP YOUR INFORMATION?"})}),e.jsx("li",{children:e.jsx("a",{href:"#section-9",className:"hover:text-black underline",children:"HOW DO WE KEEP YOUR INFORMATION SAFE?"})}),e.jsx("li",{children:e.jsx("a",{href:"#section-10",className:"hover:text-black underline",children:"DO WE COLLECT INFORMATION FROM MINORS?"})}),e.jsx("li",{children:e.jsx("a",{href:"#section-11",className:"hover:text-black underline",children:"WHAT ARE YOUR PRIVACY RIGHTS?"})}),e.jsx("li",{children:e.jsx("a",{href:"#section-12",className:"hover:text-black underline",children:"CONTROLS FOR DO-NOT-TRACK FEATURES"})}),e.jsx("li",{children:e.jsx("a",{href:"#section-13",className:"hover:text-black underline",children:"DO UNITED STATES RESIDENTS HAVE SPECIFIC PRIVACY RIGHTS?"})}),e.jsx("li",{children:e.jsx("a",{href:"#section-14",className:"hover:text-black underline",children:"DO OTHER REGIONS HAVE SPECIFIC PRIVACY RIGHTS?"})}),e.jsx("li",{children:e.jsx("a",{href:"#section-15",className:"hover:text-black underline",children:"DO WE MAKE UPDATES TO THIS NOTICE?"})}),e.jsx("li",{children:e.jsx("a",{href:"#section-16",className:"hover:text-black underline",children:"HOW CAN YOU CONTACT US ABOUT THIS NOTICE?"})}),e.jsx("li",{children:e.jsx("a",{href:"#section-17",className:"hover:text-black underline",children:"HOW CAN YOU REVIEW, UPDATE, OR DELETE THE DATA WE COLLECT FROM YOU?"})}),e.jsx("li",{children:e.jsx("a",{href:"#section-18",className:"hover:text-black underline",children:"SMS AND TEXT MESSAGING"})})]})]}),e.jsxs("section",{id:"section-1",className:"mb-12 scroll-mt-8",children:[e.jsx("h2",{className:"text-2xl font-bold text-black mb-6 pb-2 border-b border-gray-200",children:"1. WHAT INFORMATION DO WE COLLECT?"}),e.jsx("h3",{className:"text-xl font-semibold text-black mb-4",children:"Personal information you disclose to us"}),e.jsxs("p",{className:"text-gray-700 mb-4",children:[e.jsx("strong",{children:"In Short:"})," We collect personal information that you provide to us."]}),e.jsx("p",{className:"text-gray-700 mb-4",children:"We collect personal information that you voluntarily provide to us when you register on the Services, express an interest in obtaining information about us or our products and Services, participate in activities on the Services, or otherwise contact us."}),e.jsx("p",{className:"text-gray-700 mb-2",children:e.jsx("strong",{children:"Personal Information Provided by You"})}),e.jsx("p",{className:"text-gray-700 mb-2",children:"The personal information we collect depends on the context of your interactions and the features you use. It may include:"}),e.jsxs("ul",{className:"list-disc pl-6 mb-6 text-gray-700 space-y-1",children:[e.jsx("li",{children:"names, job titles"}),e.jsx("li",{children:"phone numbers, email addresses, mailing addresses"}),e.jsx("li",{children:"usernames, passwords, contact preferences"}),e.jsx("li",{children:"contact or authentication data"}),e.jsx("li",{children:"billing addresses, debit/credit card numbers (tokenized via our processor)"})]}),e.jsxs("p",{className:"text-gray-700 mb-4",children:[e.jsx("strong",{children:"Sensitive Information:"})," We do not process sensitive information."]}),e.jsxs("p",{className:"text-gray-700 mb-4",children:[e.jsx("strong",{children:"Payment Data:"})," We may collect data necessary to process your payment if you make purchases (e.g., payment instrument number and security code). ",e.jsx("strong",{children:"All payment data is handled and stored by Stripe"}),". See ",e.jsx("a",{href:"https://stripe.com/privacy",target:"_blank",rel:"noopener noreferrer",className:"text-black underline hover:text-gray-700",children:"https://stripe.com/privacy"}),"."]}),e.jsxs("p",{className:"text-gray-700 mb-4",children:[e.jsx("strong",{children:"Social Media Login Data:"})," You may be able to register using social accounts (e.g., Facebook, X). If you choose to do so, we will c
20ollect certain profile information as described in Section 7."]}),e.jsxs("p",{className:"text-gray-700 mb-2",children:[e.jsx("strong",{children:"Application Data:"})," If you use our application(s), we may collect:"]}),e.jsxs("ul",{className:"list-disc pl-6 mb-6 text-gray-700 space-y-1",children:[e.jsxs("li",{children:[e.jsx("strong",{children:"Geolocation Information."})," With your permission, we may collect location data to provide certain features."]}),e.jsxs("li",{children:[e.jsx("strong",{children:"Mobile Device Access."})," With your permission, we may access Bluetooth, calendar, camera, microphone, etc."]}),e.jsxs("li",{children:[e.jsx("strong",{children:"Mobile Device Data."})," We automatically collect device information, OS, identifiers, IP, ISP/carrier, and app interaction data."]}),e.jsxs("li",{children:[e.jsx("strong",{children:"Push Notifications."})," With permission, we may send push notifications. You can disable these in your device settings."]})]}),e.jsx("p",{className:"text-gray-700 mb-6",children:"All personal information you provide must be true, complete, and accurate, and you must notify us of any changes."}),e.jsx("h3",{className:"text-xl font-semibold text-black mb-4",children:"Information automatically collected"}),e.jsxs("p",{className:"text-gray-700 mb-4",children:[e.jsx("strong",{children:"In Short:"})," Some information — such as IP address and/or device characteristics — is collected automatically when you visit our Services."]}),e.jsx("p",{className:"text-gray-700 mb-4",children:"We automatically collect device and usage information (e.g., IP address, browser, device/OS, language preferences, referring URLs, pages viewed, actions taken, error reports). We also collect information via cookies and similar technologies (see Section 5)."}),e.jsxs("p",{className:"text-gray-700 mb-4",children:[e.jsx("strong",{children:"Google API:"})," Our use of information received from Google APIs adheres to the ",e.jsx("strong",{children:"Google API Services User Data Policy"}),", including the ",e.jsx("strong",{children:"Limited Use"})," requirements."]}),e.jsxs("p",{className:"text-gray-700",children:[e.jsx("strong",{children:"Information collected when you use our Facebook application(s):"})," By default, we may access your basic Facebook account information and other permissions you grant. See the ",e.jsx("strong",{children:"Facebook Permissions Reference"})," for more."]})]}),e.jsxs("section",{id:"section-2",className:"mb-12 scroll-mt-8",children:[e.jsx("h2",{className:"text-2xl font-bold text-black mb-6 pb-2 border-b border-gray-200",children:"2. HOW DO WE PROCESS YOUR INFORMATION?"}),e.jsxs("p",{className:"text-gray-700 mb-4",children:[e.jsx("strong",{children:"In Short:"})," We process your information to provide, improve, and administer the Services; communicate with you; for security/fraud prevention; and to comply with law. We may also process your information with your consent."]}),e.jsx("p",{className:"text-gray-700 mb-2",children:"We process personal information to:"}),e.jsxs("ul",{className:"list-disc pl-6 text-gray-700 space-y-1",children:[e.jsx("li",{children:"Create and authenticate accounts; manage user profiles"}),e.jsx("li",{children:"Deliver Services (e.g., SEO dashboards, analytics, reporting)"}),e.jsx("li",{children:"Respond to inquiries and provide support"}),e.jsx("li",{children:"Send administrative information (e.g., product updates, policy changes)"}),e.jsx("li",{children:"Fulfill and manage orders, payments, returns, and exchanges"}),e.jsx("li",{children:"Request feedback and contact you about your use of the Services"}),e.jsx("li",{children:"Send marketing and promotional communications (consistent with your preferences)"}),e.jsx("li",{children:"Deliver tailored content/advertising"}),e.jsx("li",{children:"Protect the Services (e.g., security, fraud monitoring, abuse prevention)"}),e.jsx("li",{children:"Identify usage trends and improve our Services"}),e.jsx("li",{children:"Determine the effectiveness of marketing campaigns"}),e.jsx("li",{children:"Save or protect an individual's vital interest"})]})]}),e.jsxs("section",{id:"section-3",className:"mb-12 scroll-mt-8",children:[e.jsx("h2",{className:"text-2xl font-bold text-black mb-6 pb-2 border-b border-gray-200",children:"3. WHAT LEGAL BASES DO WE RELY ON TO PROCESS YOUR PERSONAL INFORMATION?"}),e.jsxs("p",{className:"text-gray-700 mb-4",children:[e.jsx("strong",{children:"In Short:"})," We process your information when we have a valid legal basis under applicable law (e.g., consent, contract, legitimate interests, legal obligations, vital interests)."]}),e.jsxs("p",{className:"text-gray-700 mb-4",children:[e.jsx("strong",{children:"EU/UK GDPR"})," legal bases may include: ",e.jsx("strong",{children:"consent"}),", ",e.jsx("strong",{children:"performance of a contract"}),", ",e.jsx("strong",{children:"legitimate interests"}),", ",e.jsx("strong",{children:"legal obligations"}),", and ",e.jsx("strong",{children:"vital interests"}),"."]}),e.jsxs("p",{className:"text-gray-700",children:[e.jsx("strong",{children:"Canada:"})," we rely on ",e.jsx("strong",{children:"express or implied consent"}),", and in limited cases, other grounds permitted by law."]})]}),e.jsxs("section",{id:"section-4",className:"mb-12 scroll-mt-8",children:[e.jsx("h2",{className:"text-2xl font-bold text-black mb-6 pb-2 border-b border-gray-200",children:"4. WHEN AND WITH WHOM DO WE SHARE YOUR PERSONAL INFORMATION?"}),e.jsxs("p",{className:"text-gray-700 mb-4",children:[e.jsx("strong",{children:"In Short:"})," We share information in specific situations and with specific categories of third parties."]}),e.jsxs("p",{className:"text-gray-700 mb-2",children:[e.jsx("strong",{children:"Vendors/Service Providers"})," (under contract and subject to confidentiality):"]}),e.jsxs("ul",{className:"list-disc pl-6 mb-4 text-gray-700 space-y-1",children:[e.jsx("li",{children:"Ad Networks, Data Analytics Services"}),e.jsx("li",{children:"Finance & Accounting Tools, Payment Processors"}),e.jsx("li",{children:"Sales & Marketing Tools, User Authentication Services"}),e.jsx("li",{children:"Performance Monitoring Tools, AI Platforms"})]}),e.jsxs("p",{className:"text-gray-700 mb-4",children:[e.jsx("strong",{children:"Business Transfers:"})," In connection with a merger, sale, financing, or acquisition."]}),e.jsxs("p",{className:"text-gray-700 mb-4",children:[e.jsx("strong",{children:"Google Maps Platform APIs:"})," We may use certain Google Maps Platform APIs. We may cache location data on your device for up to six (6) months. You may revoke consent by contacting us (see Section 16)."]}),e.jsxs("p",{className:"text-gray-700 mb-4",children:[e.jsx("strong",{children:"Business Partners:"})," To offer products, services, or promotions."]}),e.jsxs("p",{className:"text-gray-700",children:[e.jsx("strong",{children:"Offer Wall:"})," If displayed, it may show third-party offers; when you click, you leave our app. A unique identifier may be shared to credit rewards."]})]}),e.jsxs("section",{id:"section-5",className:"mb-12 scroll-mt-8",children:[e.jsx("h2",{className:"text-2xl font-bold text-black mb-6 pb-2 border-b border-gray-200",children:"5. DO WE USE COOKIES AND OTHER TRACKING TECHNOLOGIES?"}),e.jsxs("p",{className:"text-gray-700 mb-4",children:[e.jsx("strong",{children:"In Short:"})," We may use cookies and similar technologies for functionality, analytics, and advertising."]}),e.jsxs("p",{className:"text-gray-700 mb-4",children:["We and certain third parties use cookies/pixels to maintain security, save preferences, analyze usage, and personalize ads (see also Section 13 for US state law choices). See our ",e.jsx("strong",{children:"Cookie Notice"})," for details and controls."]}),e.jsxs("p",{className:"text-gray-700",children:[e.jsx("strong",{children:"Google Analytics:"})," You can opt out via ",e.jsx("a",{href:"https://tools.google.com/dlpage/gaoptout",target:"_blank",rel:"noopener noreferrer",className:"text-black underline hover:text-gray-700",children:"https://tools.google.com/dlpage/gaoptout"})," or industry tools (e.g., ",e.jsx("a",{href:"http://optout.networka
20dvertising.org/",target:"_blank",rel:"noopener noreferrer",className:"text-black underline hover:text-gray-700",children:"http://optout.networkadvertising.org/"}),"). See Google's Privacy & Terms for more."]})]}),e.jsxs("section",{id:"section-6",className:"mb-12 scroll-mt-8",children:[e.jsx("h2",{className:"text-2xl font-bold text-black mb-6 pb-2 border-b border-gray-200",children:"6. DO WE OFFER ARTIFICIAL INTELLIGENCE-BASED PRODUCTS?"}),e.jsxs("p",{className:"text-gray-700 mb-4",children:[e.jsx("strong",{children:"In Short:"}),' Yes. We offer AI-powered features/tools ("AI Products").']}),e.jsxs("p",{className:"text-gray-700 mb-4",children:[e.jsx("strong",{children:"AI Service Providers"})," may include ",e.jsx("strong",{children:"OpenAI, Anthropic, and Google Cloud AI"}),". Your inputs/outputs may be processed by these providers to enable AI features, consistent with this Notice and applicable laws. Do not use AI Products in ways that violate provider terms."]}),e.jsxs("p",{className:"text-gray-700",children:[e.jsx("strong",{children:"Use Cases"})," may include content suggestions, keyword clustering, anomaly detection, and SEO insights."]})]}),e.jsxs("section",{id:"section-7",className:"mb-12 scroll-mt-8",children:[e.jsx("h2",{className:"text-2xl font-bold text-black mb-6 pb-2 border-b border-gray-200",children:"7. HOW DO WE HANDLE YOUR SOCIAL LOGINS?"}),e.jsx("p",{className:"text-gray-700",children:"If you register or log in using social accounts, we receive certain profile data from the provider. We use such data only for purposes described in this Notice or disclosed to you at collection. Review the social provider's privacy notice for their practices."})]}),e.jsxs("section",{id:"section-8",className:"mb-12 scroll-mt-8",children:[e.jsx("h2",{className:"text-2xl font-bold text-black mb-6 pb-2 border-b border-gray-200",children:"8. HOW LONG DO WE KEEP YOUR INFORMATION?"}),e.jsxs("p",{className:"text-gray-700",children:[e.jsx("strong",{children:"In Short:"})," We retain personal information as long as necessary to fulfill the purposes in this Notice unless a longer period is required/permitted by law. When no ongoing legitimate business need exists, we delete or anonymize; if not possible (e.g., backups), we securely store and isolate until deletion is feasible."]})]}),e.jsxs("section",{id:"section-9",className:"mb-12 scroll-mt-8",children:[e.jsx("h2",{className:"text-2xl font-bold text-black mb-6 pb-2 border-b border-gray-200",children:"9. HOW DO WE KEEP YOUR INFORMATION SAFE?"}),e.jsx("p",{className:"text-gray-700",children:"We implement appropriate technical and organizational measures to protect personal information. However, no method is 100% secure; transmission is at your own risk. Access the Services within a secure environment."})]}),e.jsxs("section",{id:"section-10",className:"mb-12 scroll-mt-8",children:[e.jsx("h2",{className:"text-2xl font-bold text-black mb-6 pb-2 border-b border-gray-200",children:"10. DO WE COLLECT INFORMATION FROM MINORS?"}),e.jsxs("p",{className:"text-gray-700",children:[e.jsx("strong",{children:"In Short:"})," We do not knowingly collect or market to children under 18 (or the equivalent age in your jurisdiction), nor knowingly sell such data. If we learn that data from under-18 users has been collected, we will deactivate the account and delete such data. Contact ",e.jsx("a",{href:"mailto:[email protected]",className:"text-black underline hover:text-gray-700",children:"[email protected]"})," if you believe we collected such data."]})]}),e.jsxs("section",{id:"section-11",className:"mb-12 scroll-mt-8",children:[e.jsx("h2",{className:"text-2xl font-bold text-black mb-6 pb-2 border-b border-gray-200",children:"11. WHAT ARE YOUR PRIVACY RIGHTS?"}),e.jsx("p",{className:"text-gray-700 mb-4",children:"Depending on your location, you may have rights to access, rectify, erase, restrict processing, data portability, object, and to not be subject to automated decisions with legal or similarly significant effects. If a decision is made solely by automated means, we will inform you and offer a way to request human review."}),e.jsxs("p",{className:"text-gray-700 mb-4",children:[e.jsx("strong",{children:"Marketing Communications:"})," You can unsubscribe via links in our emails or by contacting us. We may still send service/transaction messages."]}),e.jsx("p",{className:"text-gray-700 mb-2",children:e.jsx("strong",{children:"Account Information:"})}),e.jsxs("ul",{className:"list-disc pl-6 mb-4 text-gray-700 space-y-1",children:[e.jsx("li",{children:"Update your profile in account settings; or"}),e.jsx("li",{children:"Contact us using the information below."})]}),e.jsx("p",{className:"text-gray-700 mb-4",children:"Upon account termination, we delete or anonymize personal data subject to legal holds and our legitimate interests (e.g., fraud prevention)."}),e.jsxs("p",{className:"text-gray-700",children:["If you have questions about your rights, email ",e.jsx("a",{href:"mailto:[email protected]",className:"text-black underline hover:text-gray-700",children:"[email protected]"}),"."]})]}),e.jsxs("section",{id:"section-12",className:"mb-12 scroll-mt-8",children:[e.jsx("h2",{className:"text-2xl font-bold text-black mb-6 pb-2 border-b border-gray-200",children:"12. CONTROLS FOR DO-NOT-TRACK FEATURES"}),e.jsx("p",{className:"text-gray-700",children:"Browsers/apps may offer DNT settings. No standard currently exists; we do not respond to DNT signals. If a standard is adopted, we will update this Notice."})]}),e.jsxs("section",{id:"section-13",className:"mb-12 scroll-mt-8",children:[e.jsx("h2",{className:"text-2xl font-bold text-black mb-6 pb-2 border-b border-gray-200",children:"13. DO UNITED STATES RESIDENTS HAVE SPECIFIC PRIVACY RIGHTS?"}),e.jsxs("p",{className:"text-gray-700 mb-4",children:[e.jsx("strong",{children:"In Short:"})," Some US states grant residents specific rights (e.g., access, correction, deleti
20on, portability, opt-out of targeted ads/sale/sharing, limit use of sensitive data)."]}),e.jsxs("p",{className:"text-gray-700 mb-4",children:[e.jsx("strong",{children:"Categories Collected (past 12 months):"})," A–K as defined below; ",e.jsx("strong",{children:"L (Sensitive):"})," NO.",e.jsx("br",{}),"We may disclose personal information to service providers for business purposes (see Section 4). We have ",e.jsx("strong",{children:"not sold or shared"})," personal information for monetary consideration in the past twelve (12) months."]}),e.jsxs("p",{className:"text-gray-700 mb-4",children:[e.jsx("strong",{children:"Collected Categories:"}),e.jsx("br",{}),"A (Identifiers), B (Customer Records), C (Protected characteristics), D (Commercial), E (Biometric), F (Internet activity), G (Geolocation), H (Audio/Visual), I (Professional), J (Education), K (Inferences).",e.jsx("br",{}),e.jsx("strong",{children:"Retention:"})," As long as the user has an account, unless otherwise required by law."]}),e.jsxs("p",{className:"text-gray-700 mb-4",children:[e.jsx("strong",{children:"Your Rights & How to Exercise:"}),e.jsx("br",{}),"Submit requests via ",e.jsx("a",{href:"mailto:[email protected]",className:"text-black underline hover:text-gray-700",children:"[email protected]"})," or our DSAR portal (if available). We honor ",e.jsx("strong",{children:"Global Privacy Control (GPC)"})," signals where required. You may designate an authorized agent (we will verify identity/authority). ",e.jsx("strong",{children:"Appeals:"})," Email ",e.jsx("a",{href:"mailto:[email protected]",className:"text-black underline hover:text-gray-700",children:"[email protected]"})," if we decline your request."]}),e.jsxs("p",{className:"text-gray-700",children:[e.jsx("strong",{children:'California "Shine the Light."'})," California residents may request details once per year about categories of personal information disclosed for direct marketing (see Section 16)."]})]}),e.jsxs("section",{id:"section-14",className:"mb-12 scroll-mt-8",children:[e.jsx("h2",{className:"text-2xl font-bold text-black mb-6 pb-2 border-b border-gray-200",children:"14. DO OTHER REGIONS HAVE SPECIFIC PRIVACY RIGHTS?"}),e.jsxs("p",{className:"text-gray-700 mb-4",children:[e.jsx("strong",{children:"Australia/New Zealand:"})," We comply with the Privacy Act 1988 (AU) and Privacy Act 2020 (NZ). You may request access/correction; complaints may be filed with OAIC (AU) or NZ Privacy Commissioner."]}),e.jsxs("p",{className:"text-gray-700 mb-4",children:[e.jsx("strong",{children:"Republic of South Africa:"})," You may request access/correction. Complaints may be submitted to the Information Regulator (",e.jsx("a",{href:"mailto:[email protected]",className:"text-black underline hover:text-gray-700",children:"[email protected]"}),"; ",e.jsx("a",{href:"mailto:[email protected]",className:"text-black underline hover:text-gray-700",children:"[email protected]"}),"; ",e.jsx("a",{href:"mailto:[email protected]",className:"text-black underline hover:text-gray-700",children:"[email protected]"}),")."]}),e.jsxs("p",{className:"text-gray-700",children:[e.jsx("strong",{children:"EEA/UK/Switzerland:"})," You may lodge complaints with your local Data Protection Authority."]})]}),e.jsxs("section",{id:"section-15",className:"mb-12 scroll-mt-8",children:[e.jsx("h2",{className:"text-2xl font-bold text-black mb-6 pb-2 border-b border-gray-200",children:"15. DO WE MAKE UPDATES TO THIS NOTICE?"}),e.jsxs("p",{className:"text-gray-700",children:[e.jsx("strong",{children:"In Short:"})," Yes. We may update this Notice periodically. The updated version will be indicated by a revised date. Material changes may be notified via prominent notice or direct communication."]})]}),e.jsxs("section",{id:"section-16",className:"mb-12 scroll-mt-8",children:[e.jsx("h2",{className:"text-2xl font-bold text-black mb-6 pb-2 border-b border-gray-200",children:"16. HOW CAN YOU CONTACT US ABOUT THIS NOTICE?"}),e.jsxs("p",{className:"text-gray-700 mb-4",children:["If you have questions or comments, email ",e.jsx("a",{href:"mailto:[email protected]",className:"text-black underline hover:text-gray-700",children:"[email protected]"})," or contact us by post at:"]}),e.jsxs("address",{className:"not-italic text-gray-700 mb-4",children:[e.jsx("strong",{children:"Optiminds Inc."}),e.jsx("br",{}),"20411 Via Paviso B36",e.jsx("br",{}),"Cupertino, CA 95014",e.jsx("br",{}),"United States"]}),e.jsxs("p",{className:"text-gray-700",children:["For privacy-specific inquiries: ",e.jsx("a",{href:"mailto:[email protected]",className:"text-black underline hover:text-gray-700",children:"[email protected]"}),e.jsx("br",{}),"For data protection officer: ",e.jsx("a",{href:"mailto:[email protected]",className:"text-black underline hover:text-gray-700",children:"[email protected]"})]})]}),e.jsxs("section",{id:"section-17",className:"mb-12 scroll-mt-8",children:[e.jsx("h2",{className:"text-2xl font-bold text-black mb-6 pb-2 border-b border-gray-200",children:"17. HOW CAN YOU REVIEW, UPDATE, OR DELETE THE DATA WE COLLECT FROM YOU?"}),e.jsxs("p",{className:"text-gray-700",children:["Depending on your jurisdiction, you may request access to personal information we collect from you, details of processing, corrections, deleti
20on, or withdrawal of consent. To submit a request, contact ",e.jsx("a",{href:"mailto:[email protected]",className:"text-black underline hover:text-gray-700",children:"[email protected]"})," or ",e.jsx("a",{href:"mailto:[email protected]",className:"text-black underline hover:text-gray-700",children:"[email protected]"}),"."]})]}),e.jsxs("section",{id:"section-18",className:"mb-12 scroll-mt-8",children:[e.jsx("h2",{className:"text-2xl font-bold text-black mb-6 pb-2 border-b border-gray-200",children:"18. SMS AND TEXT MESSAGING"}),e.jsxs("p",{className:"text-gray-700 mb-4",children:[e.jsx("strong",{children:"In Short:"})," When you provide your phone number and consent, we may send you text messages. Consent is optional, you can opt out anytime, and we never sell or share your mobile number."]}),e.jsxs("p",{className:"text-gray-700 mb-4",children:["When you provide your phone number and consent on our website (including through our text-updates sign-up at ",e.jsx("a",{href:"https://www.rankgale.ai/sms",className:"text-black underline hover:text-gray-700",children:"https://www.rankgale.ai/sms"}),"), you agree that ",e.jsx("strong",{children:"RankGale (Optiminds, Inc.)"})," may contact you by SMS/text message, including through automated technology. Message frequency varies. Message and data rates may apply."]}),e.jsxs("p",{className:"text-gray-700 mb-4",children:["You can reply ",e.jsx("strong",{children:"STOP"})," to any text message to opt out at any time, or reply ",e.jsx("strong",{children:"HELP"})," for assistance. Consent to receive text messages is ",e.jsx("strong",{children:"not a condition"})," of any purchase or service."]}),e.jsxs("p",{className:"text-gray-700 mb-4",children:[e.jsx("strong",{children:"No mobile information will be shared with third parties or affiliates for marketing or promotional purposes."})," RankGale (Optiminds, Inc.) does not sell, rent, or share your mobile phone number or any personal information collected in connection with SMS/text messaging with any third parties for their marketing purposes."]}),e.jsxs("p",{className:"text-gray-700 mb-4",children:[e.jsx("strong",{children:"Text messaging originator opt-in data and consent will not be shared with any third parties."})," This information is used solely to deliver the text messages you have requested and is excluded from every information-sharing category described elsewhere in this Privacy Notice."]}),e.jsx("p",{className:"text-gray-700",children:"Mobile carriers are not liable for delayed or undelivered messages."})]})]})]}),e.jsx("footer",{className:"border-t border-gray-200 mt-16",children:e.jsx("div",{className:"max-w-4xl mx-auto px-6 py-8",children:e.jsxs("div",{className:"flex flex-col sm:flex-row justify-between items-center gap-4 text-sm text-gray-600",children:[e.jsx("p",{children:"© 2025 Optiminds Inc. All rights reserved."}),e.jsxs("div",{className:"flex gap-6",children:[e.jsx("button",{onClick:()=>t("/privacy"),className:"hover:text-black transition-colors",children:"Privacy Policy"}),e.jsx("button",{onClick:()=>t("/terms"),className:"hover:text-black transition-colors",children:"Terms of Use"})]})]})})})]})}function W0(){const t=s=>{window.location.pathname!==s&&(window.history.pushState({},"",s),window.dispatchEvent(new PopStateEvent("popstate")))};return e.jsxs("div",{className:"min-h-screen bg-white",children:[e.jsx("header",{className:"border-b border-gray-200",children:e.jsx("div",{className:"max-w-4xl mx-auto px-6 py-8",children:e.jsxs("button",{onClick:()=>t("/"),className:"inline-flex items-center gap-3 text-2xl font-bold text-black hover:text-gray-700 transition-colors",children:[e.jsx(dr,{className:"w-8 h-8 rounded-lg",alt:"RankGale"}),e.jsx("span",{children:"RankGale.ai"})]})})}),e.jsxs("main",{className:"max-w-4xl mx-auto px-6 py-12",children:[e.jsx("h1",{className:"text-4xl font-bold text-black mb-4",children:"Terms of Use"}),e.jsx("p",{className:"text-sm text-gray-600 mb-12",children:"Effective Date: May 29, 2025"}),e.jsxs("div",{className:"prose prose-lg prose-gray max-w-none",children:[e.jsxs("p",{className:"text-gray-700 leading-relaxed mb-6",children:["Welcome to ",e.jsx("strong",{children:"RankGale.ai"}),' (the "Website"), a service offered by ',e.jsx("strong",{children:"Optiminds Inc"}),' ("Optiminds," "we," "us," or "our"). These Terms of Use ("Terms") govern your access to and use of our Website and related SEO services (collectively, the "Service").']}),e.jsxs("p",{className:"text-gray-700 leading-relaxed mb-12",children:['By accessing or using the Website or Service, you ("User," "you," or "your") agree to be bound by these Terms and our Privacy Policy (available at'," ",e.jsx("button",{onClick:()=>t("/privacy"),className:"text-black underline hover:text-gray-700",children:"https://www.rankgale.ai/privacy"}),"), which is incorporated herein by reference. If you do not agree to all of these Terms, please do not access or use the Service."]}),e.jsxs("section",{className:"mb-12",children:[e.jsx("h2",{className:"text-2xl font-bold text-black mb-6 pb-2 border-b border-gray-200",children:"1. Acceptance of Terms"}),e.jsx("p",{className:"text-gray-700",children:"By creating an account, accessing the Website, or using the Service, you represent that you have read, understood, and agree to be bound by these Terms. If you are entering into these Terms on behalf of a company or other legal entity, you represent that you have the authority to bind such entity to these Terms."})]}),e.jsxs("section",{className:"mb-12",children:[e.jsx("h2",{className:"text-2xl font-bold text-black mb-6 pb-2 border-b border-gray-200",children:"2. Description of Service"}),e.jsxs("p",{className:"text-gray-700 mb-4",children:["RankGale.ai is an"," ",e.jsx("strong",{children:"AI-powered SEO optimization platform"})," designed to help users improve their website visibility, keyword performance, and search engine ranking through data-driven insights and automation tools."]}),e.jsx("p",{className:"text-gray-700",children:"The Service may include—but is not limited to—keyword tracking, on-page optimization, backlink analysis, AI-generated SEO content recommendations, competitor benchmarking, and performance analytics. We may modify or update the Service at any time, including adding, remov
20ing, or changing features."})]}),e.jsxs("section",{className:"mb-12",children:[e.jsx("h2",{className:"text-2xl font-bold text-black mb-6 pb-2 border-b border-gray-200",children:"3. User Accounts"}),e.jsx("h3",{className:"text-xl font-semibold text-black mb-4",children:"Registration"}),e.jsx("p",{className:"text-gray-700 mb-6",children:"To access certain features of the Service, you may be required to register for an account. You must provide accurate, current, and complete information during registration and keep your account information updated."}),e.jsx("h3",{className:"text-xl font-semibold text-black mb-4",children:"Account Security"}),e.jsx("p",{className:"text-gray-700 mb-6",children:"You are responsible for safeguarding your account password and for any activities or actions under your account, whether or not you have authorized such activities."}),e.jsx("h3",{className:"text-xl font-semibold text-black mb-4",children:"Account Responsibility"}),e.jsx("p",{className:"text-gray-700",children:'You are solely responsible for all activities that occur under your account and for any data, content, or SEO campaigns you upload or manage through the Service ("User Input").'})]}),e.jsxs("section",{className:"mb-12",children:[e.jsx("h2",{className:"text-2xl font-bold text-black mb-6 pb-2 border-b border-gray-200",children:"4. Permitted Use and Restrictions"}),e.jsx("h3",{className:"text-xl font-semibold text-black mb-4",children:"License"}),e.jsx("p",{className:"text-gray-700 mb-6",children:"Subject to your compliance with these Terms, we grant you a limited, non-exclusive, non-transferable, and revocable license to access and use the Service for your personal or business SEO purposes."}),e.jsx("h3",{className:"text-xl font-semibold text-black mb-4",children:"Prohibited Conduct"}),e.jsx("p",{className:"text-gray-700 mb-2",children:"You agree not to:"}),e.jsxs("ul",{className:"list-disc pl-6 mb-6 text-gray-700 space-y-1",children:[e.jsx("li",{children:"Use the Service for any illegal, fraudulent, or unauthorized purpose."}),e.jsx("li",{children:"Interfere with or disrupt the performance or integrity of the Service."}),e.jsx("li",{children:"Attempt to gain unauthorized access to the Service or its networks."}),e.jsx("li",{children:"Reverse engineer, decompile, or disassemble any part of the Service, except as permitted by law."}),e.jsx("li",{children:"Copy, resell, or lease the Service or its components."}),e.jsx("li",{children:"Use automated scripts or scraping tools to collect data from the Service without authorization."}),e.jsx("li",{children:"Upload or distribute any malicious code."}),e.jsx("li",{children:"Generate or distribute misleading SEO content, false ranking data, or spam backlinks."}),e.jsx("li",{children:"Violate any applicable laws or third-party rights."})]}),e.jsx("h3",{className:"text-xl font-semibold text-black mb-4",children:"Malicious Use and Disinformation"}),e.jsx("p",{className:"text-gray-700 mb-2",children:"You must not use the Service to generate, disseminate, or facilitate:"}),e.jsxs("ul",{className:"list-disc pl-6 mb-4 text-gray-700 space-y-1",children:[e.jsx("li",{children:"Fraudulent schemes, scams, or deceptive marketing practices."}),e.jsx("li",{children:'Mass unsolicited communications ("spam") or unauthorized advertising.'}),e.jsx("li",{children:'Content designed to mislead or manipulate public opinion in connection with elections, legislation, or other civic processes ("disinformation campaigns").'}),e.jsx("li",{children:"Technical instructions, exploits, or tools intended to gain unauthorized access to systems, data, or networks."}),e.jsx("li",{children:"Any activity intended to harass, intimidate, or endanger individuals or groups."})]}),e.jsx("p",{className:"text-gray-700 mb-6",children:"We reserve the right to suspend or terminate accounts engaged in such activities without notice."}),e.jsx("h3",{className:"text-xl font-semibold text-black mb-4",children:"Abuse Monitoring"}),e.jsx("p",{className:"text-gray-700",children:"We may employ automated tools, human review, or both to monitor activity and content generated via the Service for purposes including, but not limited to, detecting prohibited conduct, preventing abuse, and ensuring compliance with these Terms. We may remove, block, or refuse to deliver any content that, in our sole discretion, violates these Terms or applicable law."})]}),e.jsxs("section",{className:"mb-12",children:[e.jsx("h2",{className:"text-2xl font-bold text-black mb-6 pb-2 border-b border-gray-200",children:"5. Intellectual Property Rights"}),e.jsx("h3",{className:"text-xl font-semibold text-black mb-4",children:"Our IP"}),e.jsxs("p",{className:"text-gray-700 mb-6",children:["The Service and its original content, features, and functionality are and will remain the exclusive property of"," ",e.jsx("strong",{children:"Optiminds Inc"})," and its licensors."]}),e.jsx("h3",{className:"text-xl font-semibold text-black mb-4",children:"User Input"}),e.jsxs("p",{className:"text-gray-700 mb-6",children:["You retain all ownership rights to your User Input. However, by submitting User Input to the Service, you grant"," ",e.jsx("strong",{children:"Optiminds Inc"})," a worldwide, non-exclusive, royalty-free, sublicensable, and transferable license to use, reproduce, distribute, prepare derivative works of, display, and perform the User Input for the purpose of operating, maintaining, and improving the Service."]}),e.jsx("h3",{className:"text-xl font-semibold text-black mb-4",children:"Output"}),e.jsxs("p",{className:"text-gray-700 mb-6",children:["Subject to your compliance with these Terms,"," ",e.jsx("strong",{children:"Optiminds Inc"}
20),' grants you a license to use the output generated by the Service based on your User Input ("Output") for your lawful purposes. You are responsible for the Output you generate and its use. You acknowledge that Output may be similar or identical to Output generated for other users.']}),e.jsx("h3",{className:"text-xl font-semibold text-black mb-4",children:"Non-Confidential and Non-Unique Output"}),e.jsx("p",{className:"text-gray-700 mb-6",children:"Output generated by the Service may not be unique and may be provided to other users. You should not input confidential, proprietary, or trade secret information into the Service if you require that it remain private. We make no representation or warranty that Output will remain confidential, and you waive any claim that similar or identical Output generated for another user infringes or misappropriates your proprietary rights."}),e.jsx("h3",{className:"text-xl font-semibold text-black mb-4",children:"Feedback"}),e.jsx("p",{className:"text-gray-700",children:'If you provide us with any suggestions, comments, or other feedback relating to the Service ("Feedback"), such Feedback is and will be given voluntarily. We will be free to use, disclose, reproduce, license, or otherwise distribute and exploit the Feedback in any manner without any obligation, royalty, or restriction.'})]}),e.jsxs("section",{className:"mb-12",children:[e.jsx("h2",{className:"text-2xl font-bold text-black mb-6 pb-2 border-b border-gray-200",children:"6. SEO- and AI-Specific Acknowledgements and Disclaimers"}),e.jsx("h3",{className:"text-xl font-semibold text-black mb-4",children:"Nature of AI"}),e.jsx("p",{className:"text-gray-700 mb-6",children:"You understand and acknowledge that the Service utilizes artificial intelligence and machine learning technologies that may produce unpredictable results."}),e.jsx("h3",{className:"text-xl font-semibold text-black mb-4",children:"No Guarantees (SEO and AI)"}),e.jsx("p",{className:"text-gray-700 mb-6",children:"We do not guarantee improvements in keyword rankings, organic traffic, domain authority, conversions, or any specific SEO outcomes. We also do not guarantee the accuracy, reliability, suitability, or quality of any Output. The Output is provided for informational purposes only."}),e.jsx("h3",{className:"text-xl font-semibold text-black mb-4",children:"User Responsibility for Output"}),e.jsx("p",{className:"text-gray-700 mb-6",children:"You are solely responsible for reviewing, editing, and verifying any Output generated by the Service before using or publishing it. You are also responsible for ensuring that your use of the Output complies with all applicable laws and does not infringe upon the rights of any third party."}),e.jsx("h3",{className:"text-xl font-semibold text-black mb-4",children:"No Liability for Automated Execution"}),e.jsx("p",{className:"text-gray-700 mb-6",children:"Where you implement our Output in an automated campaign execution system (including automated content publishing, link building, or technical SEO changes), you acknowledge and agree that you are solely responsible for implementing independent safeguards, limits, and monitoring. We shall have no liability for any financial losses, penalties, or performance shortfalls resulting from automated actions taken without human review."}),e.jsx("h3",{className:"text-xl font-semibold text-black mb-4",children:"No Professional Advice"}),e.jsxs("p",{className:"text-gray-700 mb-6",children:["The Service and its Output do not constitute legal, financial, medical, or any other professional advice. Always seek the advice of a qualified professional for any such concerns."," ",e.jsx("strong",{children:"Optiminds Inc"})," is not liable for any actions taken based on the Output."]}),e.jsx("h3",{className:"text-xl font-semibold text-black mb-4",children:"Important AI Risk Acknowledgements"}),e.jsx("p",{className:"text-gray-700 mb-2",children:"By using our AI-powered Service, you acknowledge and accept that:"}),e.jsxs("ul",{className:"list-disc pl-6 text-gray-700 space-y-1",children:[e.jsx("li",{children:"AI systems may generate false, misleading, or nonsensical information (hallucinations)."}),e.jsx("li",{children:"AI outputs may reflect biases present in training data."}
20),e.jsx("li",{children:"AI behavior may be inconsistent or unexpected in edge cases."}),e.jsx("li",{children:"AI may produce factual errors, grammatical mistakes, or inappropriate content."}),e.jsx("li",{children:"AI may misinterpret instructions or context."}),e.jsx("li",{children:"You must always review AI-generated content before use."})]})]}),e.jsxs("section",{className:"mb-12",children:[e.jsx("h2",{className:"text-2xl font-bold text-black mb-6 pb-2 border-b border-gray-200",children:"7. Fees and Payment"}),e.jsx("h3",{className:"text-xl font-semibold text-black mb-4",children:"Subscription Fees"}),e.jsx("p",{className:"text-gray-700 mb-6",children:"Access to certain features of the Service may require payment of subscription fees. All fees are non-refundable except as required by law or as explicitly stated by us."}),e.jsx("h3",{className:"text-xl font-semibold text-black mb-4",children:"Payment"}),e.jsx("p",{className:"text-gray-700 mb-6",children:"You agree to pay all applicable fees as described on the Website for the Service you select. We may use a third-party payment processor to bill you."}),e.jsx("h3",{className:"text-xl font-semibold text-black mb-4",children:"Changes in Fees"}),e.jsx("p",{className:"text-gray-700 mb-6",children:"We reserve the right to change our fees at any time. We will provide you with reasonable prior notice of any change in fees."}),e.jsx("h3",{className:"text-xl font-semibold text-black mb-4",children:"Taxes"}),e.jsx("p",{className:"text-gray-700",children:"You are responsible for all taxes associated with your purchase of the Service (excluding taxes based on our net income)."})]}),e.jsxs("section",{className:"mb-12",children:[e.jsx("h2",{className:"text-2xl font-bold text-black mb-6 pb-2 border-b border-gray-200",children:"8. Term and Termination"}),e.jsx("h3",{className:"text-xl font-semibold text-black mb-4",children:"Term"}),e.jsx("p",{className:"text-gray-700 mb-6",children:"These Terms will remain in full force and effect while you use the Service."}),e.jsx("h3",{className:"text-xl font-semibold text-black mb-4",children:"Termination by You"}),e.jsxs("p",{className:"text-gray-700 mb-6",children:["You may terminate your account and these Terms at any time by contacting us at"," ",e.jsx("a",{href:"mailto:[email protected]",className:"text-black underline hover:text-gray-700",children:"[email protected]"})," ","or by using any account deletion feature we may provide."]}),e.jsx("h3",{className:"text-xl font-semibold text-black mb-4",children:"Termination by Us"}),e.jsx("p",{className:"text-gray-700 mb-6",children:"We may suspend or terminate your access to the Service or your account, at our sole discretion, at any time and without notice or liability to you, including, without limitation, if you breach these Terms, or if we believe your use of the Service could cause harm or liability to us or others."}),e.jsx("h3",{className:"text-xl font-semibold text-black mb-4",children:"Effect of Termination"}),e.jsx("p",{className:"text-gray-700",children:"Upon termination, your right to use the Service will immediately cease. All provisions of these Terms which by their nature should survive termination shall survive, including, without limitation, ownership provisions, warranty disclaimers, indemnity, and limitations of liability."})]}),e.jsxs("section",{className:"mb-12",children:[e.jsx("h2",{className:"text-2xl font-bold text-black mb-6 pb-2 border-b border-gray-200",children:"9. Disclaimer of Warranties"}),e.jsx("p",{className:"text-gray-700 mb-4",children:'The Website and the Service are provided on an "as is" and "as available" basis.'}),e.jsxs("p",{className:"text-gray-700 mb-4",children:["To the fullest extent permitted by applicable law,"," ",e.jsx("strong",{children:"Optiminds Inc"})," and its affiliates, licensors, and suppliers expressly disclaim all warranties of any kind, whether express or implied, including, but not limited to, the implied warranties of merchantability, fitness for a particular purpose, title, and non-infringement."]}),e.jsx("p",{className:"text-gray-700",children:"We make no warranty that the Service will be uninterrupted, timely, secure, error-free, or free from viruses or other harmful components, or that any Output will be accurate, reliable, complete, or suitable for your needs. You acknowledge that your use of the Service is at your sole risk."})]}),e.jsxs("section",{className:"mb-12",children:[e.jsx("h2",{className:"text-2xl font-bold text-black mb-6 pb-2 border-b border-gray-200",children:"10. Limitation of Liability"}),e.jsx("p",{className:"text-gray-700 mb-4",children:"To the fullest extent permitted by applicable law:"}),e.jsxs("p",{className:"text-gray-700 mb-4",children:["In no event shall ",e.jsx("strong",{children:"Optiminds Inc"}),", its affiliates, directors, employees, agents, suppliers, or licensors be liable for any indirect, incidental, special, consequential, punitive, or exemplary damages, including but not limited to, damages for loss of profits, revenue, goodwill, use, data, or other intangible losses (even if we have been advised of the possibility of such damages), arising out of or relating to:"]}),e.jsxs("ul",{className:"list-disc pl-6 mb-4 text-gray-700 space-y-1",children:[e.jsx("li",{children:"Your access to or use of or inability to access or use the Service;"}),e.jsx("li",{children:"Any conduct or content of any third party on the Service;"}),e.jsx("li",{children:"Any content or Output obtained from the Service;"}),e.jsx("li",{children:"Unauthorized access, use, or alteration of your transmissions or content;"}),e.jsx("li",{children:"Any other matter relating to the Service."})]}),e.jsxs("p",{className:"text-gray-700 mb-4",children:["In no event shall ",e.jsx("strong",{children:"Optiminds Inc"}),"'s aggregate liability for all claims relating to the Service exceed one hundred U.S. dollars (USD $100.00)."]}),e.jsx("p",{className:"text-gray-700",children:"Some jurisdictions do not allow the exclusion of certain warranties or the limitation or exclusion of liability for incidental or consequential damages. Accordingly, some of the above limitations may not apply to you."})]}),e.jsxs("section",{className:"mb-12",children:[e.jsx("h2",{className:"text-2xl font-bold text-black mb-6 pb-2 border-b border-gray-200",children:"11. Indemnification"}),e.jsxs("p",{className:"text-gray-700",children:["You agree to defend, indemnify, and hold harmless"," ",e.jsx("strong",{children:"Optiminds Inc"}),", its affiliates, licensors, and their respective officers, directors, employees, contractors, agents, licensors, suppliers, successors, and assigns from and against any claims, liabilities, damages, judgments, awards, losses, costs, expenses, or fees (including reasonable attorneys' fees) arising out of or relating to your violation of these Terms or your use of the Service, including, but not limited to, your User Input, any use of the Service's Output other than as expressly authorized in these Terms, or your use of any information obtained from the Service."]})]}),e.jsxs("section",{className:"mb-12",children:[e.jsx("h2",{className:"text-2xl font-bold text-black mb-6 pb-2 border-b border-gray-200",children:"12. Governing Law and Dispute Resolution"}),e.jsxs("p",{className:"text-gray-700 mb-4",children:["These Terms and any dispute or claim arising out of or related to them, their subject matter, or their formation (in each case, including non-contractual disputes or claims) shall be governed by and construed in accordance with the internal laws of the"," ",e.jsx("strong",{children:"State of California"})," without giving effect to any choice or conflict of law provision or rule."]}),e.jsx("p",{className:"text-gray-700",children:"Any legal suit, action, or proceeding arising out of, or related to, these Terms or the Service shall be instituted exclusively in the federal courts of the United States or the courts of the State of California located in the City of Cupertino and County of Santa Clara, although we retain the right to bring any suit, action, or proceeding against you for breach of these Terms in your country of residence or any other relevant country. You waive any and all objections to the exercise of jurisdiction over you by such courts and to venue in such courts."})]}),e.jsxs("section",{className:"mb-12",children:[e.jsx("h2",{className:"text-2xl font-bold text-black mb-6 pb-2 border-b border-gray-200",children:"13. Changes to Terms"}),e.jsx("p",{className:"text-gray-700 mb-4",children:"We reserve the right, at our sole discretion, to modify or replace these Terms at any time. If a revision is material, we will make reasonable efforts to provide at least thirty (30) days' notice prior to any new terms taking effect. What constitutes a material change will be determined at our sole discretion. Notice may be provided by posting the updated Terms on the Website, by sending you an email, or by other means we deem appropriate."}),e.jsx("p",{className:"text-gray-700",children:"By continuing to access or use our Service after those revisions become effective, you agree to be bound by the revised terms. If you do not agree to the new terms, in whole or in part, please stop using the Website and the Service."})]}),e.jsxs("section",{className:"mb-12",children:[e.jsx("h2",{className:"text-2xl font-bold text-black mb-6 pb-2 border-b border-gray-200",children:"14. Miscellaneous"}),e.jsx("h3",{className:"text-xl font-semibold text-black mb-4",children:"Entire Agreement"}),e.jsxs("p",{className:"text-gray-700 mb-6",children:["These Terms, together with our Privacy Policy and any other legal notices published by us on the Service, constitute the entire agreement between you and ",e.jsx("strong",{children:"Optiminds Inc"})," ","concerning the Service and supersede all prior or contemporaneous understandings and agreements, whether written or oral, concerning the Service."]}),e.jsx("h3",{className:"text-xl font-semibold text-black mb-4",children:"Severability"}),e.jsx("p",{className:"text-gray-700 mb-6",children:"If any provision of these Terms is held by a court or other tribunal of competent jurisdiction to be invalid, illegal, or unenforceable for any reason, such provision shall be eliminated or limited to the minimum extent such that the remaining provisions of the Terms will continue in full force and effect."}),e.jsx("h3",{className:"text-xl font-semibold text-black mb-4",children:"No Waiver"}),e.jsxs("p",{className:"text-gray-700 mb-6",children:["No waiver by ",e.jsx("strong",{children:"Optiminds Inc"})," of any term or condition set out in these Terms shall be deemed a further or continuing waiver of such term or condition or a 
20waiver of any other term or condition, and any failure of"," ",e.jsx("strong",{children:"Optiminds Inc"})," to assert a right or provision under these Terms shall not constitute a waiver of such right or provision."]}),e.jsx("h3",{className:"text-xl font-semibold text-black mb-4",children:"Assignment"}),e.jsxs("p",{className:"text-gray-700 mb-6",children:["You may not assign or transfer these Terms, by operation of law or otherwise, without ",e.jsx("strong",{children:"Optiminds Inc"}),"'s prior written consent. Any attempt by you to assign or transfer these Terms, without such consent, will be null. ",e.jsx("strong",{children:"Optiminds Inc"})," ","may assign or transfer these Terms, at its sole discretion, without restriction. Subject to the foregoing, these Terms will bind and inure to the benefit of the parties, their successors, and permitted assigns."]}),e.jsx("h3",{className:"text-xl font-semibold text-black mb-4",children:"Contact Information"}),e.jsxs("p",{className:"text-gray-700",children:["All notices of copyright infringement claims should be sent to the copyright agent designated in our Copyright Policy. All other feedback, comments, requests for technical support, and other communications relating to the Service should be directed to:"," ",e.jsx("a",{href:"mailto:[email protected]",className:"text-black underline hover:text-gray-700",children:"[email protected]"}),"."]})]}),e.jsxs("section",{className:"mb-12",children:[e.jsx("h2",{className:"text-2xl font-bold text-black mb-6 pb-2 border-b border-gray-200",children:"15. Data Protection and GDPR"}),e.jsx("h3",{className:"text-xl font-semibold text-black mb-4",children:"European Users"}),e.jsx("p",{className:"text-gray-700 mb-6",children:"If you are accessing the Service from the European Economic Area (EEA), United Kingdom, or Switzerland, additional data protection rights may apply under the General Data Protection Regulation (GDPR) and similar laws. Please refer to our Privacy Policy for detailed information about how we process your personal data and your rights."}),e.jsx("h3",{className:"text-xl font-semibold text-black mb-4",children:"Data Processing Lawful Basis"}),e.jsx("p",{className:"text-gray-700 mb-6",children:"We process your personal data based on various lawful bases including: (a) your consent, (b) performance of a contract with you, (c) compliance with legal obligations, (d) protection of vital interests, and (e) legitimate interests."}),e.jsx("h3",{className:"text-xl font-semibold text-black mb-4",children:"Cross-Border Data Transfers"}),e.jsx("p",{className:"text-gray-700",children:"Your data may be transferred to and processed in countries other than your country of residence. We ensure appropriate safeguards are in place for such transfers in accordance with applicable data protection laws."})]}),e.jsxs("section",{className:"mb-12",children:[e.jsx("h2",{className:"text-2xl font-bold text-black mb-6 pb-2 border-b border-gray-200",children:"16. Service Availability and Modifications"}),e.jsx("h3",{className:"text-xl font-semibold text-black mb-4",children:"Service Availability"}),e.jsx("p",{className:"text-gray-700 mb-6",children:"We strive to provide continuous access to the Service, but we do not guarantee that the Service will be available at all times. The Service may be temporarily unavailable due to maintenance, updates, or unforeseen technical issues."}),e.jsx("h3",{className:"text-xl font-semibold text-black mb-4",children:"Service Modifications"}),e.jsx("p",{className:"text-gray-700 mb-6",children:"We reserve the right to modify, suspend, or discontinue any aspect of the Service at any time, with or without notice. We may also impose limits on certain features or restrict access to parts or all of the Service without notice or liability."}),e.jsx("h3",{className:"text-xl font-semibold text-black mb-4",children:"Beta Features"}),e.jsx("p",{className:"text-gray-700",children:'We may offer beta, experimental, or preview features that are provided "as is" and may not function as intended. These features may be changed or discontinued at any time without notice.'})]}),e.jsxs("section",{className:"mb-12",children:[e.jsx("h2",{className:"text-2xl font-bold text-black mb-6 pb-2 border-b border-gray-200",children:"17. Age Restrictions and Parental Consent"}),e.jsx("h3",{className:"text-xl font-semibold text-black mb-4",children:"Minimum Age"}),e.jsx("p",{className:"text-gray-700 mb-6",children:"The Service is not intended for use by individuals under the age of 13. If you are under 18 years of age, you may only use the Service with the involvement and consent of a parent or guardian."}),e.jsx("h3",{className:"text-xl font-semibold text-black mb-4",children:"Parental Responsibility"}),e.jsx("p",{className:"text-gray-700",children:"Parents and guardians are responsible for supervising their minor children's use of the Service and ensuring compliance with these Terms. We recommend that parents review the AI-s
20pecific risks and limitations described in these Terms."})]}),e.jsxs("section",{className:"mb-12",children:[e.jsx("h2",{className:"text-2xl font-bold text-black mb-6 pb-2 border-b border-gray-200",children:"18. Third-Party Services and Integrations"}),e.jsx("h3",{className:"text-xl font-semibold text-black mb-4",children:"Third-Party Services"}),e.jsx("p",{className:"text-gray-700 mb-6",children:"The Service may integrate with or provide access to third-party services, websites, or applications. We are not responsible for the content, policies, or practices of these third-party services. Your use of third-party services is governed by their respective terms and conditions."}),e.jsx("h3",{className:"text-xl font-semibold text-black mb-4",children:"AI Service Providers"}),e.jsx("p",{className:"text-gray-700 mb-6",children:"Our AI functionality may be powered by third-party AI service providers. Your interactions with our AI features are subject to these providers' terms of service and privacy policies in addition to our own."}),e.jsx("h3",{className:"text-xl font-semibold text-black mb-4",children:"Payment Processors"}),e.jsx("p",{className:"text-gray-700",children:"We use third-party payment processors to handle subscription payments. These processors have their own privacy policies and terms of service that govern the processing of your payment information."})]}),e.jsxs("section",{className:"mb-12",children:[e.jsx("h2",{className:"text-2xl font-bold text-black mb-6 pb-2 border-b border-gray-200",children:"19. SMS and Text Messaging"}),e.jsxs("p",{className:"text-gray-700 mb-4",children:["If you provide your phone number and consent on our website (including through our text-updates sign-up at"," ",e.jsx("button",{onClick:()=>t("/sms"),className:"text-black underline hover:text-gray-700",children:"https://www.rankgale.ai/sms"}),"), you agree that ",e.jsx("strong",{children:"RankGale (Optiminds, Inc.)"})," may contact you by text message (SMS), including through automated technology. Consent to receive text messages is"," ",e.jsx("strong",{children:"not a condition"})," of purchasing any goods or services."]}),e.jsxs("p",{className:"text-gray-700 mb-4",children:["Message frequency varies based on your activity. Message and data rates may apply. You can reply ",e.jsx("strong",{children:"STOP"})," to any message to opt out at any time, or reply ",e.jsx("strong",{children:"HELP"})," for assistance. For help or questions about these text messages, you can also contact us at"," ",e.jsx("a",{href:"mailto:[email protected]",className:"text-black underline hover:text-gray-700",children:"[email protected]"}),"."]}),e.jsx("p",{className:"text-gray-700",children:"We do not sell or share your mobile number or your SMS opt-in consent with third parties or affiliates for their own marketing purposes. Mobile carriers are not liable for delayed or undelivered messages."})]}),e.jsxs("section",{className:"mb-12",children:[e.jsx("h2",{className:"text-2xl font-bold text-black mb-6 pb-2 border-b border-gray-200",children:"20. Contact Information"}),e.jsxs("address",{className:"not-italic text-gray-700 mb-4",children:[e.jsx("strong",{children:"Optiminds Inc"}),e.jsx("br",{}),e.jsx("br",{}),"Website:"," ",e.jsx("a",{href:"https://www.rankgale.ai",className:"text-black underline hover:text-gray-700",children:"https://www.rankgale.ai"}),e.jsx("br",{}),e.jsx("br",{}),"Address: 20411 Via Paviso B36, Cupertino, CA 95014",e.jsx("br",{}),e.jsx("br",{}),"Legal/Terms Inquiries Email:"," ",e.jsx("a",{href:"mailto:[email protected]",className:"text-black underline hover:text-gray-700",children:"[email protected]"}),e.jsx("br",{}),e.jsx("br",{}),"Data Protection Officer:"," ",e.jsx("a",{href:"mailto:[email protected]",className:"text-black underline hover:text-gray-700",children:"[email protected]"}),e.jsx("br",{}),e.jsx("br",{}),"Customer Support:"," ",e.jsx("a",{href:"mailto:[email protected]",className:"text-black underline hover:text-gray-700",children:"[email protected]"})]})]}),e.jsx("div",{className:"mt-16 pt-8 border-t border-gray-200",children:e.jsxs("p",{className:"text-gray-700 text-center",children:["By using ",e.jsx("strong",{children:"RankGale.ai"}),", you acknowledge that you have read, understood, and agree to be bound by these Terms of Use."]})})]})]}),e.jsx("footer",{className:"border-t border-gray-200 mt-16",children:e.jsx("div",{className:"max-w-4xl mx-auto px-6 py-8",children:e.jsxs("div",{className:"flex flex-col sm:flex-row justify-between items-center gap-4 text-sm text-gray-600",children:[e.jsx("p",{children:"© 2025 Optiminds Inc. All rights reserved."}),e.jsxs("div",{className:"flex gap-6",children:[e.jsx("button",{onClick:()=>t("/privacy"),className:"hover:text-black transition-colors",children:"Privacy Policy"}),e.jsx("button",{onClick:()=>t("/terms"),className:"hover:text-black transition-colors",children:"Terms of Use"})]})]})})})]})}function V0(){const t=y=>{window.location.pathname!==y&&(window.history.pushState({},"",y),window.dispatchEvent(new PopStateEvent("popstate")))},[s,a]=r.useState(""),[n,o]=r.useState(""),[i,l]=r.useState(!1),[c,d]=r.useState(!1),[m,h]=r.useState(null),p=n.replace(/\D/g,""),f=p.length>=10&&p.length<=15,b=async y=>{if(y.preventDefault(),h(null),!f){h("Please enter a valid phone number (10–15 digits).");return}l(!0);try{await fetch("/api/sms/opt-in",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({first_name:s.trim()||null,phone:n,consent:!0,consent_text_version:"2025-07-a2p",source:"web-sms-optin"})})}catch{}l(!1),d(!0)};return e.jsxs("div",{className:"min-h-screen bg-white flex flex-col",children:[e.jsx("header",{className:"border-b border-gray-200",children:e.jsx("div",{className:"max-w-4xl mx-auto w-full px-6 py-8",children:e.jsxs("button",{onClick:()=>t("/"),className:"inline-flex items-center gap-3 text-2xl font-bold text-black hover:text-gray-700 transition-colors",children:[e.jsx(dr,{className:"w-8 h-8 rounded-lg",alt:"RankGale"}),e.jsx("span",{children:"RankGale.ai"})]})})}),e.jsxs("main",{className:"max-w-xl mx-auto w-full px-6 py-16 flex-1",children:[e.jsx("h1",{className:"text-3xl font-bold text-black mb-3",children:"Get RankGale text updates"}),e.jsx("p",{className:"text-gray-600 mb-10",children:"Enter your mobile number to receive SMS updates about your account — including new leads and calls from your campaigns, plus SEO reports and service notifications. Consent is o
20ptional — it is never required to use RankGale."}),c?e.jsxs("div",{className:"rounded-2xl border border-gray-200 bg-gray-50 p-8 text-center",children:[e.jsx("h2",{className:"text-xl font-semibold text-black mb-2",children:"You're signed up"}),e.jsxs("p",{className:"text-gray-700",children:["Thanks — we've recorded your consent to receive text messages from RankGale. You can reply"," ",e.jsx("strong",{children:"STOP"})," to any message to opt out at any time, or"," ",e.jsx("strong",{children:"HELP"})," for help."]}),e.jsx("button",{onClick:()=>t("/"),className:"mt-6 inline-flex items-center justify-center rounded-lg bg-black px-5 py-2.5 text-white font-medium hover:bg-gray-800 transition-colors",children:"Back to RankGale.ai"})]}):e.jsxs("form",{onSubmit:b,noValidate:!0,className:"space-y-6",children:[e.jsxs("div",{children:[e.jsxs("label",{htmlFor:"firstName",className:"block text-sm font-medium text-gray-800 mb-1.5",children:["First name ",e.jsx("span",{className:"text-gray-400",children:"(optional)"})]}),e.jsx("input",{id:"firstName",name:"firstName",type:"text",autoComplete:"given-name",value:s,onChange:y=>a(y.target.value),className:"w-full rounded-lg border border-gray-300 px-4 py-2.5 text-black focus:border-black focus:outline-none focus:ring-1 focus:ring-black",placeholder:"Jane"})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"phone",className:"block text-sm font-medium text-gray-800 mb-1.5",children:"Mobile phone number"}),e.jsx("input",{id:"phone",name:"phone",type:"tel",autoComplete:"tel",required:!0,value:n,onChange:y=>o(y.target.value),className:"w-full rounded-lg border border-gray-300 px-4 py-2.5 text-black focus:border-black focus:outline-none focus:ring-1 focus:ring-black",placeholder:"(555) 123-4567"})]}),m&&e.jsx("p",{className:"text-sm text-red-600",role:"alert",children:m}),e.jsx("button",{type:"submit",disabled:i,className:"w-full inline-flex items-center justify-center rounded-lg bg-black px-5 py-3 text-white font-semibold hover:bg-gray-800 transition-colors disabled:opacity-60",children:i?"Submitting…":"Sign me up for text updates"}),e.jsxs("p",{className:"text-xs leading-relaxed text-gray-500",children:["By submitting, you agree to receive SMS text messages from RankGale (Optiminds, Inc.) at the phone number provided, including messages sent using automated technology. Consent is not a condition of any purchase. Message frequency varies. Message and data rates may apply. Reply STOP to opt out at any time, or HELP for help. See our"," ",e.jsx("button",{type:"button",onClick:()=>t("/terms"),className:"underline text-gray-700 hover:text-black",children:"Terms of Use"})," ","and"," ",e.jsx("button",{type:"button",onClick:()=>t("/privacy"),className:"underline text-gray-700 hover:text-black",children:"Privacy Policy"}),"."]})]})]}),e.jsx("footer",{className:"border-t border-gray-200 mt-16",children:e.jsx("div",{className:"max-w-4xl mx-auto w-full px-6 py-8",children:e.jsxs("div",{className:"flex flex-col sm:flex-row justify-between items-center gap-4 text-sm text-gray-600",children:[e.jsx("p",{children:"© 2025 Optiminds Inc. All rights reserved."}),e.jsxs("div",{className:"flex gap-6",children:[e.jsx("button",{onClick:()=>t("/privacy"),className:"hover:text-black transition-colors",children:"Privacy Policy"}),e.jsx("button",{onClick:()=>t("/terms"),className:"hover:text-black transition-colors",children:"Terms of Use"})]})]})})})]})}const ni=({children:t})=>{const s=a=>{window.history.pushState({},"",a),window.dispatchEvent(new PopStateEvent("popstate"))};return e.jsxs("div",{className:"blog-new min-h-screen",children:[e.jsx("header",{className:"site-header",children:e.jsxs("div",{className:"header-inner",children:[e.jsxs("a",{href:"/",className:"logo",onClick:a=>{a.preventDefault(),s("/")},children:["RankGale",e.jsx("span",{children:"."})]}),e.jsx("nav",{children:e.jsxs("ul",{className:"nav-links",children:[e.jsx("li",{children:e.jsx("a",{href:"/blog",onClick:a=>{a.preventDefault(),s("/blog")},children:"Blog"})}),e.jsx("li",{children:e.jsx("a",{href:"/product",onClick:a=>{a.preventDefault(),s("/product")},children:"Product"})}),e.jsx("li",{children:e.jsx("a",{href:"/pricing",onClick:a=>{a.preventDefault(),s("/pricing")},children:"Pricing"})}),e.jsx("li",{children:e.jsx("a",{href:"/about",onClick:a=>{a.preventDefault(),s("/about")},children:"About"})})]})})]})}),e.jsx("main",{children:t}),e.jsx("footer",{className:"site-footer",children:e.jsxs("div",{className:"footer-inner",children:[e.jsxs("span",{className:"footer-logo",children:["RankGale",e.jsx("span",{children:"."})]}),e.jsxs("ul",{className:"footer-links",children:[e.jsx("li",{children:e.jsx("a",{href:"/privacy",onClick:a=>{a.preventDefault(),s("/privacy")},children:"Privacy Policy"})}),e.jsx("li",{children:e.jsx("a",{href:"/terms",onClick:a=>{a.preventDefault(),s("/terms")},children:"Terms of Service"})}),e.jsx("li",{children:e.jsx("a",{href:"/contact",onClick:a=>{a.preventDefault(),s("/contact")},children:"Contact Us"})})]})]})})]})},fi=({className:t="",size:s})=>e.jsx("svg",{className:t||"w-4 h-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",width:s,height:s,children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M3.055 11H5a2 2 0 012 2v1a2 2 0 002 2 2 2 0 012 2v2.945M8 3.935V5.5A2.5 2.5 0 0010.5 8h.5a2 2 0 012 2 2 2 0 104 0 2 2 
200 012-2h1.064M15 20.488V18a2 2 0 012-2h3.064M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),H0=({className:t="",size:s})=>e.jsx("svg",{className:t||"w-4 h-4",viewBox:"0 0 24 24",fill:"currentColor",width:s,height:s,"aria-hidden":"true",focusable:"false",children:e.jsx("path",{d:"M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z"})}),q0=({className:t="",size:s})=>e.jsx("svg",{className:t||"w-4 h-4",viewBox:"0 0 24 24",fill:"currentColor",width:s,height:s,"aria-hidden":"true",focusable:"false",children:e.jsx("path",{d:"M20.447 20.452h-3.554v-5.569c0-1.328-.027-3.037-1.852-3.037-1.853 0-2.136 1.445-2.136 2.939v5.667H9.351V9h3.414v1.561h.046c.477-.9 1.637-1.85 3.37-1.85 3.601 0 4.267 2.37 4.267 5.455v6.286zM5.337 7.433c-1.144 0-2.063-.926-2.063-2.065 0-1.138.92-2.063 2.063-2.063 1.14 0 2.064.925 2.064 2.063 0 1.139-.925 2.065-2.064 2.065zm1.782 13.019H3.555V9h3.564v11.452zM22.225 0H1.771C.792 0 0 .774 0 1.729v20.542C0 23.227.792 24 1.771 24h20.451C23.2 24 24 23.227 24 22.271V1.729C24 .774 23.2 0 22.222 0h.003z"})}),Y0=({className:t="",size:s})=>e.jsxs("svg",{className:t||"w-4 h-4",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,width:s,height:s,"aria-hidden":"true",focusable:"false",children:[e.jsx("path",{d:"M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"}),e.jsx("path",{d:"M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"})]}),J0=({post:t,isFullPost:s=!1,relatedPosts:a=[]})=>{const[n,o]=r.useState(!1),[i,l]=r.useState(""),c=r.useRef(null),d=r.useRef(null),m=g=>{const _=[/^#{1,6}\s/m,/\*\*.*?\*\*/,/\*[^\*].*?\*/,/\[.*?\]\(.*?\)/,/!\[.*?\]\(.*?\)/,/`[^`]+`/,/^```/m,/^\|.*?\|/m,/^[-*+]\s/m,/^\d+\.\s/m,/^>\s/m].some(D=>D.test(g)),E=g.match(/<[a-z][\s\S]*?>/gi),N=E?E.length:0,S=g.match(/#{1,6}\s|^\s*[-*+]\s|^\s*\d+\.\s|\*\*|`{3}/gm)?.length||0;return _&&S>N},h=r.useCallback(g=>{window.history.pushState({},"",g),window.dispatchEvent(new PopStateEvent("popstate"))},[]),p=r.useCallback(g=>String(g).toLowerCase().replace(/[^\w\s-]/g,"").replace(/\s+/g,"-").replace(/-+/g,"-").trim(),[]),f=r.useCallback(g=>{const w=[],_=String(g||"").split(`
21`);for(const N of _){const S=N.match(/^##\s+(.+)$/);if(S){w.push({level:2,text:S[1].trim()});continue}const k=N.match(/^###\s+(.+)$/);k&&w.push({level:3,text:k[1].trim()})}const E=new Map;return w.map(N=>{const S=p(N.text),k=(E.get(S)||0)+1;E.set(S,k);const D=k===1?S:`${S}-${k}`;return{...N,id:D}})},[p]),b=r.useMemo(()=>m(t.content)?f(t.content):[],[f,t.content]),y=async g=>{const _=t.slug&&String(t.slug).trim()?`https://rankgale.ai/blog/${String(t.slug).trim()}`:window.location.href,E=t.title;switch(t.excerpt,g){case"twitter":window.open(`https://twitter.com/intent/tweet?text=${encodeURIComponent(E)}&url=${encodeURIComponent(_)}`,"_blank");break;case"linkedin":window.open(`https://www.linkedin.com/sharing/share-offsite/?url=${encodeURIComponent(_)}`,"_blank");break;case"facebook":window.open(`https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(_)}`,"_blank");break;case"copy":await navigator.clipboard.writeText(_);break}o(!1)},x=g=>{const _=g.split(" ").length;return Math.ceil(_/200)},u=t.readTime||x(t.content);if(s){const w=t.author?.name?.trim()||"RankGale Team",_=t.author?.email?.trim()||"",E=t.author?.avatar||"",N="The RankGale content team creates high-quality articles about SEO, AI-powered content creation, and digital marketing strategies.",S=r.useMemo(()=>{const R=String(t.content||""),L=[];for(const H of R.split(`
22`)){const K=H.match(/^[-*]\s+(.+)$/);if(!K)continue;const X=K[1].replace(/\*\*/g,"").trim();if(X&&(L.push(X),L.length>=4))break}if(L.length>=4)return L.slice(0,4);const $=["Key insights and practical guidance included","Expert strategies for better results","Step-by-step implementation tips","Best practices from industry leaders"];for(;L.length<4;)L.push($[L.length]);return L.slice(0,4)},[t.content]),k=R=>{const L=document.getElementById(R);L&&L.scrollIntoView({behavior:"smooth",block:"start"})},D=r.useRef(0);D.current=0;const F=()=>{const R=D.current;return D.current+=1,b[R]?.id||""};return r.useEffect(()=>{if(!m(t.content)||!c.current)return;const R=()=>{const $=c.current;if(!$)return;const H=Array.from($.querySelectorAll("h2[id], h3[id]"));if(H.length===0)return;let K="";for(const X of H){const V=X.offsetTop;window.scrollY>=V-150&&(K=X.getAttribute("id")||"")}K&&l(K)},L=()=>{d.current==null&&(d.current=window.requestAnimationFrame(()=>{d.current=null,R()}))};return window.addEventListener("scroll",L,{passive:!0}),R(),()=>{window.removeEventListener("scroll",L),d.current!=null&&(window.cancelAnimationFrame(d.current),d.current=null)}},[t.content]),e.jsxs("div",{children:[e.jsx("nav",{className:"breadcrumb","aria-label":"Breadcrumb",children:e.jsxs("ol",{className:"breadcrumb-list",children:[e.jsx("li",{children:e.jsx("a",{href:"/",onClick:R=>{R.preventDefault(),h("/")},children:"Home"})}),e.jsx("li",{className:"breadcrumb-separator",children:"›"}),e.jsx("li",{children:e.jsx("a",{href:"/blog",onClick:R=>{R.preventDefault(),h("/blog")},children:"Blog"})}),t.category?e.jsxs(e.Fragment,{children:[e.jsx("li",{className:"breadcrumb-separator",children:"›"}),e.jsx("li",{className:"breadcrumb-current",children:t.category})]}):null,e.jsx("li",{className:"breadcrumb-separator",children:"›"}),e.jsx("li",{className:"breadcrumb-current",children:t.title})]})}),e.jsxs("main",{className:"main-container",children:[e.jsxs("article",{className:"article",children:[e.jsxs("header",{className:"article-header",children:[e.jsxs("div",{className:"article-meta",children:[t.category?e.jsxs("a",{href:"/blog",className:"category-badge",onClick:R=>{R.preventDefault(),h("/blog")},children:[e.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[e.jsx("path",{d:"M20.59 13.41l-7.17 7.17a2 2 0 0 1-2.83 0L2 12V2h10l8.59 8.59a2 2 0 0 1 0 2.82z"}),e.jsx("line",{x1:"7",y1:"7",x2:"7.01",y2:"7"})]}),t.category]}):null,e.jsx("span",{className:"meta-divider"}),e.jsx("time",{className:"meta-item article-date",children:t.published_at?new Date(t.published_at).toLocaleDateString("en-US",{year:"numeric",month:"long",day:"numeric"}):""}),e.jsx("span",{className:"meta-divider"}),e.jsxs("span",{className:"meta-item reading-time",children:[u," min read"]})]}),e.jsx("h1",{className:"article-title",children:t.title}),t.excerpt?e.jsx("p",{className:"article-excerpt",children:t.excerpt}):null]}),e.jsxs("div",{className:"author-box-top",children:[E?e.jsx("img",{src:E,alt:w,className:"author-avatar"}
22):e.jsx("img",{src:`https://ui-avatars.com/api/?name=${encodeURIComponent(w)}&background=c9553d&color=fff&size=200`,alt:w,className:"author-avatar"}),e.jsxs("div",{className:"author-info",children:[e.jsx("h4",{children:e.jsx("a",{href:"/author/team",onClick:R=>{R.preventDefault(),h("/blog")},children:w})}),e.jsx("p",{className:"author-role",children:_||"Content Team"})]})]}),t.featuredImage?e.jsx("figure",{className:"featured-image",children:e.jsx("img",{src:t.featuredImage,alt:t.title,loading:"eager"})}):null,e.jsxs("aside",{className:"key-takeaways",children:[e.jsxs("h3",{children:[e.jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:e.jsx("path",{d:"M12 2L2 7l10 5 10-5-10-5zM2 17l10 5 10-5M2 12l10 5 10-5"})}),"Key Takeaways"]}),e.jsx("ul",{children:S.map((R,L)=>e.jsx("li",{children:R},L))})]}),e.jsx("div",{ref:c,className:"article-content",id:"article-content",children:m(t.content)?e.jsx(Wn,{remarkPlugins:[Vn],components:{h2:({children:R,...L})=>{const $=F();return e.jsx("h2",{id:$,...L,children:R})},h3:({children:R,...L})=>{const $=F();return e.jsx("h3",{id:$,...L,children:R})},code:({children:R,...L})=>e.jsx("code",{...L,children:R})},children:t.content}):e.jsx("div",{className:"html-content-isolation rich-html",dangerouslySetInnerHTML:{__html:t.content}})}),t.tags.length>0?e.jsxs("div",{className:"tags-section",children:[e.jsx("h4",{children:"Related Tags"}),e.jsx("div",{className:"tags-list",children:t.tags.map(R=>e.jsxs("a",{href:`/blog?tag=${encodeURIComponent(R)}`,className:"tag",onClick:L=>{L.preventDefault(),h(`/blog?tag=${encodeURIComponent(R)}`)},children:["#",R]},R))})]}):null,e.jsxs("aside",{className:"author-detail",children:[e.jsxs("div",{className:"author-detail-header",children:[e.jsx("img",{src:E||`https://ui-avatars.com/api/?name=${encodeURIComponent(w)}&background=c9553d&color=fff&size=200`,alt:w,className:"author-avatar"}),e.jsxs("div",{className:"author-detail-info",children:[e.jsx("h3",{children:e.jsx("a",{href:"/author/team",onClick:R=>{R.preventDefault(),h("/blog")},children:w})}),e.jsx("p",{className:"author-role",children:_||"Content Team"})]})]}),e.jsx("p",{className:"author-bio",children:N}),e.jsx("div",{className:"author-detail-footer",children:e.jsxs("a",{href:"/blog",className:"view-more-posts",onClick:R=>{R.preventDefault(),h("/blog")},children:["View More Articles",e.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:e.jsx("path",{d:"M5 12h14M12 5l7 7-7 7"})})]})})]})]}),e.jsxs("aside",{className:"sidebar",children:[e.jsxs("nav",{className:"toc","aria-label":"Table of Contents",children:[e.jsxs("h4",{children:[e.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[e.jsx("line",{x1:"8",y1:"6",x2:"21",y2:"6"}),e.jsx("line",{x1:"8",y1:"12",x2:"21",y2:"12"}),e.jsx("line",{x1:"8",y1:"18",x2:"21",y2:"18"}),e.jsx("line",{x1:"3",y1:"6",x2:"3.01",y2:"6"}),e.jsx("line",{x1:"3",y1:"12",x2:"3.01",y2:"12"}),e.jsx("line",{x1:"3",y1:"18",x2:"3.01",y2:"18"})]}),"Table of Contents"]}),e.jsx("ol",{className:"toc-list",children:b.map((R,L)=>{const $=i===R.id||!i&&L===0;return e.jsx("li",{className:R.level===3?"toc-h3":"",children:e.jsx("a",{href:`#${R.id}`,className:$?"active":"",onClick:H=>{H.preventDefault(),k(R.id)},children:R.text})},`${R.id}-${R.level}`)})})]}),e.jsxs("div",{className:"share-widget",children:[e.jsx("h4",{children:"Share Article"}),e.jsxs("div",{className:"share-buttons",children:[e.jsxs("button",{className:"share-btn",onClick:()=>y("twitter"),children:[e.jsx(H0,{}),"Share on Twitter"]}),e.jsxs("button",{className:"share-btn",onClick:()=>y("linkedin"),children:[e.jsx(q0,{}),"Share on LinkedIn"]}),e.jsxs("button",{className:"share-btn",onClick:()=>y("copy"),children:[e.jsx(Y0,{}),"Copy Link"]})]})]})]})]}),a.length>0?e.jsxs("section",{className:"related-posts",children:[e.jsx("h2",{children:"Related Articles"}),e.jsx("div",{className:"related-grid",children:a.slice(0,3).map(R=>e.jsxs("article",{className:"related-card",children:[R.featuredImage?e.jsx("img",{src:R.featuredImage,alt:R.title}):e.jsx("div",{style:{height:180,background:"#f0efe9"}}),e.jsxs("div",{className:"related-card-content",children:[e.jsx("p",{className:"related-card-category",children:R.category||"General"}),e.jsx("h3",{className:"related-card-title",children:e.jsx("a",{href:`/blog/${R.slug}`,onClick:L=>{L.preventDefault(),h(`/blog/${R.slug}`)},children:R.title})}),e.jsxs("p",{className:"related-card-meta",children:[R.readTime||x(R.content)," min read",R.published_at?` · ${new Date(R.published_at).toLocaleDateString("en-US",{month:"short",day:"numeric"})}`:""]})]})]},R.id))})]}):null]})}return e.jsxs("article",{className:"bg-white border border-gray-300 hover:border-black transition-all duration-200 hover:shadow-lg",children:[t.featuredImage&&e.jsx("div",{className:"aspect-video overflow-hidden",children:e.jsx("img",{src:t.featuredImage,alt:t.title,className:"w-full h-full object-cover hover:scale-105 transition-transform duration-200"})}),e.jsxs("div",{className:"p-6",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[t.category&&e.jsxs(e.Fragment,{children:[e.jsx("a",{href:`/blog?category=${encodeURIComponent(t.category)}`,onClick:g=>{g.preventDefault(),h(`/blog?category=${encodeURIComponent(t.category||"")}`)},className:"text-xs font-medium text-gray-500 uppercase tracking-wider hover:text-black transition-colors cursor-pointer",children:t.category}),e.jsx("span",{className:"text-gray-300",children:"•"})]}),e.jsx("time",{className:"text-xs text-gray-500",children:t.published_at?new Date(t.published_at).toISOString():""}),e.jsx("span",{className:"text-gray-300",children:"•"}),e.jsxs("span",{className:"text-xs text-gray-500",children:[u," min read"]})]}),e.jsx("h2",{className:"text-xl font-semibold text-gray-900 mb-3 hover:text-black transition-colors",children:e.jsx("a",{href:`/blog/${t.slug}`,onClick:g=>{g.preventDefault(),h(`/blog/${t.slug}`)},className:"cursor-pointer",children:t.title})}),e.jsx("p",{className:"text-gray-600 line-clamp-3 mb-4",children:t.excerpt}),e.jsxs("div",{className:"flex items-center justify-between",children:[t.author&&e.jsxs("div",{className:"flex items-center gap-3",children:[t.author.avatar?e.jsx("img",{src:t.author.avatar,alt:t.author.name,className:"w-8 h-8 rounded-full object-cover"}):e.jsx("div",{className:"w-8 h-8 rounded-full bg-gray-200 flex items-center justify-center",children:e.jsx("span",{className:"text-sm font-semibold text-gray-600",children:t.author.name.charAt(0).toUpperCase()})}),e.jsx("span",{className:"text-sm text-gray-500",children:t.author.name})]}),e.jsxs("a",{href:`/blog/${t.slug}`,onClick:g=>{g.preventDefault(),h(`/blog/${t.slug}`)},className:"flex items-center gap-2 text-sm text-gray-500 hover:text-black transition-colors cursor-pointer",children:["Read more",e.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})]})]})]})]})},fc="admin_access_token",yc="admin_access_token_expires_at_ms";function Du(t){return(t||"").trim().replace(/\/+$/,"")}function Lu(){try{return Du(Da())}catch{return""}}function Sr(){try{return localStorage.getItem(fc)||""}catch{return""}}function X0(){try{const t=localStorage.getItem(yc)||"",s=Number(t);return Number.isFinite(s)?s:0}catch{return 0}}function yi(){try{localStorage.removeItem(fc),localStorage.removeItem(yc)}catch{}}function zu(t=Date.now()){const s=Sr(),a=X0();return!s||!a?!0:t>=a-3e3}function $u(){try{window.location.href="/admin"}catch{}}function Q0(){if(zu())throw yi(),$u(),new Error("Admin session expired")}async function Z0(t){const s=Du(t.apiBaseUrl),a=(t.username||"").trim(),n=(t.password||"").trim();if(!s)throw new Error("API base URL is required");if(!a)throw new Error("Username is required");if(!n)throw new Error("Password is required");const o=await Cn.post(`${s}/api/admin/auth/login`,{username:a,password:n},{timeout:1e4}),i=String(o?.data?.access_token||""),l=Number(o?.data?.expires_in||0);if(!i)throw new Error("Missing access token from server");if(!Number.isFinite(l)||l<=0)throw new Error("Invalid token TTL from server");const c=Date.now()+l*1e3;
22try{localStorage.setItem(fc,i),localStorage.setItem(yc,String(c))}catch{}return{apiBaseUrl:s,accessToken:i,expiresAtMs:c}}class ef{constructor(){this.baseUrl="/blog"}normalizePost(s){const a=s?.featuredImage??s?.featured_image??void 0,n=s?.readTime??s?.read_time??void 0,o=s?.seoTitle??s?.seo_title??void 0,i=s?.seoDescription??s?.seo_description??void 0;return{...s,featuredImage:a,readTime:n,seoTitle:o,seoDescription:i}}async getPosts(s={}){const a=new URLSearchParams;s.page&&a.append("page",s.page.toString()),s.limit&&a.append("limit",s.limit.toString()),s.category&&a.append("category",s.category),s.tag&&a.append("tag",s.tag),s.status&&a.append("status",s.status);const n=a.toString(),o=`${this.baseUrl}/posts${n?`?${n}`:""}`,i=await ot(o);return{...i,posts:(i.posts||[]).map(l=>this.normalizePost(l))}}async getPost(s){const a=await ot(`${this.baseUrl}/posts/${s}`);return{...a,post:this.normalizePost(a.post)}}async searchPosts(s){const a=new URLSearchParams;a.append("q",s.q),s.limit&&a.append("limit",s.limit.toString());const n=await ot(`${this.baseUrl}/search?${a.toString()}`);return{...n,posts:(n.posts||[]).map(o=>this.normalizePost(o))}}async getCategories(){return ot(`${this.baseUrl}/categories`)}async getSitemapData(){return ot(`${this.baseUrl}/sitemap`)}}const bi=new ef;class tf{constructor(){this.baseUrl="/api/admin/blog"}formatErrorDetail(s){return Array.isArray(s)?s.map(n=>{const o=Array.isArray(n?.loc)?n.loc.filter(Boolean).join("."):"",i=typeof n?.msg=="string"?n.msg:typeof n=="string"?n:JSON.stringify(n);return o?`${o}: ${i}`:i}).filter(Boolean).join(`
23`)||"Request validation failed":typeof s=="string"?s:s&&typeof s=="object"?JSON.stringify(s):String(s||"Request failed")}buildRequestError(s){const a=s?.response?.data?.detail??s?.response?.data?.message??s?.message??"Request failed",n=this.formatErrorDetail(a),o=new Error(n);return o.raw=s,o}async request(s,a,n){const o=Sr();if(!o)throw new Error("Admin access token not found");const l=`${Da()}${a}`,c={method:s,url:l,headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"}};n&&(s==="PUT"||s==="POST")&&(c.data=n);try{return(await Cn(c)).data}catch(d){throw this.buildRequestError(d)}}async uploadCoverSingle(s,a){const n=Sr();if(!n)throw new Error("Admin access token not found");const i=`${Da()}${this.baseUrl}/covers_upload`,l=new FormData;l.append("files",s);try{return(await Cn.post(i,l,{headers:{Authorization:`Bearer ${n}`},onUploadProgress:d=>{try{if(!a)return;const m=d.total||0,h=d.loaded||0;if(!m)return;const p=Math.max(0,Math.min(100,Math.round(h/m*100)));a(p)}catch{}}})).data}catch(c){throw this.buildRequestError(c)}}async listPosts(s={}){const a=new URLSearchParams;s.page&&a.append("page",s.page.toString()),s.limit&&a.append("limit",s.limit.toString()),s.status&&a.append("status",s.status),s.category&&a.append("category",s.category),s.tag&&a.append("tag",s.tag),s.q&&a.append("q",s.q);const n=a.toString(),o=`${this.baseUrl}/posts${n?`?${n}`:""}`;return this.request("GET",o)}async createPost(s){return this.request("POST",`${this.baseUrl}/posts/create`,s)}async batchCreatePosts(s){return this.request("POST",`${this.baseUrl}/posts/batch_create`,s)}async getPostDetail(s){return this.request("GET",`${this.baseUrl}/posts/${s}`)}async publishPost(s){return this.request("PUT",`${this.baseUrl}/posts/${s}/publish`)}async unpublishPost(s){return this.request("PUT",`${this.baseUrl}/posts/${s}/unpublish`)}async deletePost(s){return this.request("DELETE",`${this.baseUrl}/posts/${s}`)}async batchPublishPosts(s){return this.request("PUT",`${this.baseUrl}/posts/batch_publish`,{post_ids:s})}async batchUnpublishPosts(s){return this.request("PUT",`${this.baseUrl}/posts/batch_unpublish`,{post_ids:s})}async batchDeletePosts(s){return this.request("POST",`${this.baseUrl}/posts/batch_delete`,{post_ids:s})}async listCovers(){return this.request("GET",`${this.baseUrl}/covers`)}async uploadCovers(s,a){if(!s||s.length===0)throw new Error("No files provided");if(s.length===1)return this.uploadCoverSingle(s[0],a);const n=8,o=new Array(s.length);let i=0,l=0;const c=()=>{if(!a)return;const h=Math.max(0,Math.min(100,Math.round(l/s.length*100)));a(h)},d=async()=>{for(;;){const h=i;if(i+=1,h>=s.length)return;try{const f=((await this.uploadCoverSingle(s[h])).uploaded||[])[0];f?o[h]=f:o[h]={id:"",url:"",error:"Upload failed"}}catch(p){o[h]={id:"",url:"",error:p?.message||"Upload failed"}}finally{l+=1,c()}}},m=Math.min(n,s.length);return await Promise.all(new Array(m).fill(0).map(()=>d())),a&&a(100),{success:!0,uploaded:o}}async deleteCover(s){return this.request("DELETE",`${this.baseUrl}/covers/${s}`)}}const Fs=new tf,sf=()=>{const[t,s]=r.useState([]),[a,n]=r.useState(!0),[o,i]=r.useState(""),[l,c]=r.useState("all"),[d,m]=r.useState(["all"]),[h,p]=r.useState(null);r.useEffect(()=>{b(),y()},[]);const f=u=>{window.history.pushState({},"",u),window.dispatchEvent(new PopStateEvent("popstate"))},b=async()=>{try{n(!0),p(null);const u={page:1,limit:50,status:"published"},g=await bi.getPosts(u);g.success?s(g.posts||[]):p("Failed to load blog posts")}catch(u){console.error("Failed to fetch blog posts:",u),p("Failed to load blog posts")}finally{n(!1)}},y=async()=>{try{const u=await bi.getCategories();if(u.success){const g=["all",...u.categories.map(w=>w.name).filter(w=>w!=null&&w.trim()!=="")];m(g)}}catch(u){console.error("Failed to fetch categories:",u)}},x=t.filter(u=>{const g=u.title.toLowerCase().includes(o.toLowerCase())||u.excerpt.toLowerCase().includes(o.toLowerCase()),w=l==="all"||u.category===l;return g&&w});return e.jsx(ni,{children:e.jsxs("div",{className:"max-w-4xl mx-auto px-6 py-12",children:[e.jsxs("div",{className:"text-center mb-16",children:[e.jsx("h1",{className:"text-4xl font-bold text-gray-900 mb-4",children:"Rankgale.ai Blog"}),e.jsx("p",{className:"text-lg text-gray-600 max-w-2xl mx-auto",children:"Insights, tutorials, and updates about AI-powered advertising automation"})]}),e.jsx("div",{className:"mb-12",children:e.jsxs("div",{className:"flex flex-col md:flex-row gap-4 items-center justify-between",children:[e.jsx("div",{className:"relative flex-1 max-w-md",children:e.jsx("input",{type:"text",placeholder:"Search posts...",value:o,onChange:u=>i(u.target.value),className:"w-full px-4 py-2 border border-gray-300 rounded-none bg-white text-gray-900 placeholder-gray-500 focus:outline-none focus:border-black transition-colors"})}),e.jsx("div",{className:"flex gap-2",children:d.map(u=>e.jsx("button",{onClick:()=>c(u),className:`px-4 py-2 text-sm font-medium transition-colors ${l===u?"bg-black text-white":"bg-white text-gray-600 border border-gray-300 hover:border-black hover:text-black"}`,children:u&&u.charAt(0).toUpperCase()+u.slice(1)},u))})]})}),h&&e.jsx("div",{className:"mb-8 p-4 bg-red-50 border border-red-200 rounded-md",children:e.jsxs("div",{className:"flex",children:[e.jsx("div",{className:"flex-shrink-0",children:e.jsx("svg",{className:"h-5 w-5 text-red-400",viewBox:"0 0 20 20",fill:"currentColor",children:e.jsx("path",{fillRule:"evenodd",d:"M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z",clipRule:"evenodd"})})}),e.jsxs("div",{className:"ml-3",children:[e.jsx("h3",{className:"text-sm font-medium text-red-800",children:"Error loading blog posts"}),e.jsx("div",{className:"mt-2 text-sm text-red-700",children:e.jsx("p",{children:h})}),e.jsx("div",{className:"mt-4",children:e.jsx("button",{onClick:b,className:"bg-red-100 px-3 py-2 rounded-md text-sm font-medium text-red-800 hover:bg-red-200 transition-colors",children:"Try again"})})]})]})}),a?e.jsx("div",{className:"grid gap-8 md:grid-cols-2",children:[...Array(4)].map((u,g)=>e.jsxs("div",{className:"animate-pulse",children:[e.jsx("div",{className:"bg-gray-200 h-48 mb-4"}),e.jsx("div",{className:"bg-gray-200 h-4 mb-2"}),e.jsx("div",{className:"bg-gray-200 h-4 w-3/4 mb-4"}),e.jsx("div",{className:"bg-gray-200 h-3 w-1/2"})]},g))}):e.jsx("div",{className:"grid gap-8 md:grid-cols-2",children:x.map(u=>e.jsxs("div",{onClick:()=>f(`/blog/${u.slug}`),className:"group block bg-white border border-gray-300 hover:border-black transition-all duration-200 hover:shadow-lg cursor-pointer",children:[u.featuredImage&&e.jsx("div",{className:"aspect-video overflow-hidden",children:e.jsx("img",{src:u.featuredImage,alt:u.title,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-200"})}),e.jsxs("div",{className:"p-6",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx("span",{className:"text-xs font-medium text-gray-500 uppercase tracking-wider",children:u.category}),e.jsx("span",{className:"text-gray-300",children:"•"}),e.jsx("time",{className:"text-xs text-gray-500",children:u.published_at?new Date(u.published_at).toLocaleDateString():""})]}),e.jsx("h2",{className:"text-xl font-semibold text-gray-900 mb-3 group-hover:text-black transition-colors",children:u.title}),e.jsx("p",{className:"text-gray-600 line-clamp-3 mb-4",children:u.excerpt}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-gray-500",children:[e.jsx("span",{children:"Read more"}),e.jsx("svg",{className:"w-4 h-4 transform group-hover:translate-x-1 transition-transform",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})]})]})]},u.id))}),!a&&x.length===0&&e.jsx("div",{className:"text-center py-12",children:e.jsx("p",{className:"text-gray-500 text-lg",children:"No posts found matching your criteria."})})]})})},af=({slug:t})=>{const s=t||window.location.pathname.replace("/blog/",""),[a,n]=r.useState(null),[o,i]=r.useState([]),[l,c]=r.useState(!0),[d,m]=r.useState(null);r.useEffect(()=>{s&&p(s)},[s]);const h=b=>{window.history.pushState({},"",b),window.dispatchEvent(new PopStateEvent("popstate"))},p=async b=>{try{c(!0),m(null),i([]);const y=await bi.getPost(b);if(y.success){const x=y.post;n(x),f(x)}else m("Post not found")}catch(y){console.error("Failed to fetch blog post:",y),m("Failed to load post")}finally{c(!1)}},f=async b=>{try{const y=await bi.getPosts({page:1,limit:50,status:"published"});if(!y.success)return;const x=(y.posts||[]).filter(w=>w.slug!==b.slug),u=b.category?x.filter(w=>w.category===b.category):[],g=[];for(const w of u){if(g.length>=3)break;g.push(w)}if(g.length<3)for(const w of x){if(g.length>=3)break;g.some(_=>_.id===w.id)||g.push(w)}i(g.slice(0,3))}catch(y){console.warn("Failed to fetch related posts:",y)}};return l?e.jsx(ni,{children:e.jsx("div",{className:"max-w-4xl mx-auto px-6 py-12",children:e.jsxs("div",{className:"animate-pulse",children:[e.jsx("div",{className:"h-4 bg-gray-200 w-1/4 mb-4"}),e.jsx("div",{className:"h-12 bg-gray-200 mb-6"}),e.jsx("div",{className:"h-6 bg-gray-200 mb-8"}),e.jsx("div",{className:"h-64 bg-gray-200 mb-12"}),e.jsx("div",{className:"space-y-4",children:[...Array(6)].map((b,y)=>e.jsx("div",{className:"h-4 bg-gray-200"},y))})]})})}):d||!a?e.jsx(ni,{children:e.jsxs("div",{className:"max-w-4xl mx-auto px-6 py-12 text-center",children:[e.jsx("h1",{className:"text-2xl font-bold text-gray-900 mb-4",children:d||"Post not found"}),e.jsx("p",{className:"text-gray-600 mb-8",children:"The blog post you're looking for doesn't exist or has been removed."}),e.jsx("a",{href:"/blog",onClick:b=>{b.preventDefault(),h("/blog")},className:"inline-flex items-center gap-2 px-6 py-3 bg-black text-white hover:bg-gray-800 transition-colors cursor-pointer",children:"Back to Blog"})]})}):e.jsx(ni,{children:e.jsx(J0,{post:a,isFullPost:!0,relatedPosts:o})})},be=v.forwardRef(({className:t="",variant:s="default",size:a="md",noPadding:n=!1,...o},i)=>{const l="inline-flex items-center cursor-pointer rounded-md justify-center font-medium transition-colors disabled:opacity-60 disabled:cursor-not-allowed",c={default:"bg-slate-900 text-white hover:bg-slate-800",outline:"border border-slate-300 hover:bg-slate-100",ghost:"hover:bg-slate-100",muted:"bg-slate-100 text-slate-600 hover:bg-slate-200"},d={xs:p=>`h-7 ${p?"":"px-2"} text-xs`,sm:p=>`h-8 ${p?"":"px-3"} text-sm`,md:p=>`h-9 ${p?"":"px-4"} text-sm`,lg:p=>`h-10 ${p?"":"px-5"} text-base`},h=(d[a]||d.md)(n);return e.jsx("button",{ref:i,className:`${l} ${c[s]} ${h} ${t}`,...o})});be.displayName="Button";const bt=({className:t="",...s})=>e.jsx("input",{className:`h-9 w-full rounded-md border border-slate-300 bg-white px-3 text-sm outline-none focus:ring-2 focus:ring-slate-400 ${t}`,...s}),Js=v.forwardRef(({className:t="",...s},a)=>e.jsx("textarea",{ref:a,className:`w-full rounded-md border border-slate-300 bg-white p-3 text-sm outline-none focus:ring-2 focus:ring-slate-400 ${t}`,...s}));Js.displayName="Textarea";function kn(...t){return t.filter(Boolean).join(" ")}function Fu(t){return t==="sm"?"px-5 py-3":t==="lg"?"px-7 py-7":"px-6 py-4"}function wi(t,s){const a=t==="light"?"border-slate-100":"border-slate-200";return s==="t"?`border-t ${a}`:`border-b ${a}`}const Ou=v.createContext(null);function Ht({open:t,onOpenChange:s,children:a}){return e.jsx(Ou.Provider,{value:{open:t,onOpenChange:s},children:a})}const qt=({className:t="",closeOnOutside:s=!0,children:a,...n})=>{const o=v.useContext(Ou);if(!o?.open)return null;const l=/max-w-/.test(t)?"":"max-w-lg",c=e.jsxs("div",{className:"fixed inset-0 flex items-center justify-center",style:{zIndex:1e3},"aria-modal":!0,role:"dialog",onMouseDown:d=>d.stopPropagation(),onClick:d=>d.stopPropagation(),children:[e.jsx("div",{className:"absolute inset-0 bg-black/40",onMouseDown:d=>d.stopPropagation(),onClick:d=>{d.stopPropagation(),s&&o.onOpenChange(!1)}}),e.jsx("div",{className:`relative w-[95%] ${l} rounded-2xl bg-white p-4 shadow-xl ${t}`,style:{zIndex:1001},onMouseDown:d=>d.stopPropagation(),onClick:d=>d.stopPropagation(),...n,children:a})]});return typeof document>"u"?c:Ha.createPortal(c,document.body)},Zt=({className:t="",variant:s="inset",density:a="md",divider:n=!1,dividerTone:o="default",align:i="start",spacing:l="sm",...c})=>
23{const m=kn("flex flex-col",l==="none"?"":l==="lg"?"gap-3":l==="md"?"gap-2":"gap-1.5",i==="center"?"text-center items-center":"",s==="inset"&&!n?"mb-2":"",s==="inset"&&n?kn(wi(o,"b"),"pb-3"):"",s==="full"?kn("flex-shrink-0 bg-white",Fu(a),n?wi(o,"b"):""):"");return e.jsx("div",{className:kn(m,t),...c})},Yt=({className:t="",...s})=>e.jsx("h2",{className:`text-lg font-semibold ${t}`,...s}),Ds=({className:t="",...s})=>e.jsx("div",{className:`text-sm text-slate-600 ${t}`,...s}),Ns=({className:t="",variant:s="inset",density:a="md",divider:n=!1,dividerTone:o="default",layout:i="actions",spacing:l="md",...c})=>{const m=kn(i==="split"?"flex flex-col gap-2 items-stretch sm:flex-row sm:items-center sm:justify-between":"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",s==="inset"&&!n?l==="sm"?"mt-2":"mt-4":"",s==="inset"&&n?kn(wi(o,"t"),"pt-4"):"",s==="full"?kn("flex-shrink-0 bg-white",Fu(a),n?wi(o,"t"):""):"");return e.jsx("div",{className:kn(m,t),...c})},Bu=v.createContext(null);function nf({apiBaseUrl:t,username:s,password:a,connecting:n,error:o,onChangeUsername:i,onChangePassword:l,onConnect:c}){return e.jsx("div",{className:"flex items-center justify-center min-h-screen bg-gray-50",children:e.jsxs("div",{className:"bg-white p-8 rounded-lg shadow-md w-[420px]",children:[e.jsxs("div",{className:"flex items-center justify-center gap-2 mb-2",children:[e.jsx(nc,{className:"h-6 w-6 text-gray-700"}),e.jsx("h1",{className:"text-2xl font-bold text-gray-800",children:"Admin Console"})]}),e.jsx("p",{className:"text-sm text-gray-500 text-center mb-6",children:"Configure API endpoint and authenticate"}),e.jsx("div",{className:"mb-4",children:e.jsxs("div",{className:"text-xs text-gray-500 text-center font-mono",children:["API: ",t||"<not configured>"]})}),e.jsxs("div",{className:"mb-6",children:[e.jsx("label",{className:"block text-gray-700 text-sm font-bold mb-2",children:"Username"}),e.jsx(bt,{type:"text",value:s,onChange:d=>i(d.target.value),placeholder:"admin",className:"mb-3"}),e.jsx("label",{className:"block text-gray-700 text-sm font-bold mb-2",children:"Admin Password"}),e.jsx(bt,{type:"password",value:a,onChange:d=>l(d.target.value),placeholder:"Enter admin password",onKeyDown:d=>{d.key==="Enter"&&c()}})]}),e.jsx(be,{onClick:c,disabled:n,className:"w-full",children:n?e.jsxs(e.Fragment,{children:[e.jsx(He,{className:"mr-2 h-4 w-4 animate-spin"}),"Connecting..."]}):"Connect"}),o?e.jsx("p",{className:"text-red-500 text-sm mt-2 text-center",children:o}):null]})})}function rf({children:t}){const s=Lu(),[a,n]=v.useState("admin"),[o,i]=v.useState(""),[l,c]=v.useState(()=>Sr()),[d,m]=v.useState(!1),[h,p]=v.useState(!1),[f,b]=v.useState("");v.useEffect(()=>{if(zu()){yi(),m(!1),c("");return}const g=Sr();m(!!g),c(g)},[]);const y=v.useCallback(async()=>{b(""),p(!0);try{const g=await Z0({apiBaseUrl:s,username:a,password:o});c(g.accessToken),m(!0)}catch(g){const w=g?.response?.data?.detail||g?.message||"Failed to verify admin password";m(!1),b(String(w))}finally{p(!1)}},[s,a,o]),x=v.useCallback(()=>{m(!1),b(""),yi(),c("")},[]),u=v.useMemo(()=>({apiBaseUrl:(s||"").trim().replace(/\/+$/,""),username:a,password:o,accessToken:l,connected:d,connecting:h,error:f,setUsername:n,setPassword:i,connect:y,disconnect:x}),[s,a,o,l,d,h,f,y,x]);return e.jsx(Bu.Provider,{value:u,children:t})}function Fi(){const t=v.useContext(Bu);if(!t)throw new Error("useAdminAuth must be used within AdminAuthProvider");return t}function of({children:t}){const s=Fi();return s.connected?e.jsx(e.Fragment,{children:t}):e.jsx(nf,{apiBaseUrl:s.apiBaseUrl,username:s.username,password:s.password,connecting:s.connecting,error:s.error,onChangeUsername:s.setUsername,onChangePassword:s.setPassword,onConnect:()=>s.connect()})}let On=null;function bc(t){const s=(t||Lu()||"").trim().replace(/\/+$/,"");return s?(On&&(On.defaults.baseURL||"")===s||(On=Cn.create({baseURL:s,timeout:6e5}),On.interceptors.request.use(a=>(Q0(),a.headers=a.headers||{},a.headers.Authorization=`Bearer ${Sr()}`,a.data instanceof FormData||(a.headers["Content-Type"]="application/json"),a),a=>Promise.reject(a)),On.interceptors.response.use(a=>a,a=>(a.response?.status===401&&(yi(),$u()),Promise.reject(a)))),On):Cn.create({baseURL:"",timeout:6e5})}async function ca(t,s,a,n){return(await bc(n).get(t,{params:s,...a})).data}async function Yn(t,s,a,n){return(await bc(n).post(t,s,a)).data}async function lf(t,s,a){return(await bc(a).delete(t,s)).data}const ji=({value:t,max:s=100,title:a,showPercentage:n=!0,showValue:o=!1,valueLabel:i,className:l=""})=>{const c=Math.min(Math.max(t/s*100,0),100),d=Math.round(c);return e.jsxs("div",{className:l,children:[a&&e.jsx("div",{className:"mb-2 font-semibold text-slate-900",children:a}),e.jsxs("div",{className:"relative h-4 w-full overflow-hidden rounded border border-slate-900 bg-slate-200",children:[e.jsx("div",{className:"absolute inset-y-0 left-0 flex items-center justify-center bg-slate-900 transition-all duration-300",style:{width:`${c}%`},children:n&&c>10&&e.jsxs("span",{className:"text-xs font-medium text-white",children:[d,"%"]})}),n&&c<=10&&e.jsxs("span",{className:"absolute inset-y-0 left-2 flex items-center text-xs font-medium text-slate-900",children:[d,"%"]})]}),(o||i)&&e.jsx("div",{className:"mt-2 text-sm text-slate-600",children:i||`${t} of ${s}`})]})},cf={BASE_URL:"/",DEV:!1,MODE:"production",PROD:!0,SSR:!1},Ml="seo:auth_scope_changed",Rl="seo:auth_scope_user_id";let ri=null;function wc(t){const s=String(t||"").trim();return s||null}function df(t){try{if(typeof window>"u")return;window.dispatchEvent(new CustomEvent(Ml,{detail:t}))}catch{}}function mf(){const t=["seo:selected_market","seo:selected_markets","seo:selected_market:anonymous","seo:selected_markets:anonymous"];for(const s of t)try{localStorage.removeItem(s)}catch{}}function uf(t){const s=String(t||"").trim().replace(/-/g,"+").replace(/_/g,"/"),a=s.length%4,n=a===0?s:s+"=".repeat(4-a);return atob(n)}function Uu(t){try{return JSON.parse(t)}catch{return null}}function xf(t){try{const s=String(t||"").split(".");if(s.length!==3)return null;const a=uf(s[1]);return Uu(a)}catch{return null}}function hf(t){const s=String(t||"").trim();if(!s)return null;if(s.includes(".")&&s.split(".").length===3)return s;const a=Uu(s);if(!a)return null;
23if(typeof a=="string"){const n=a.trim();return n.includes(".")&&n.split(".").length===3?n:null}if(a&&typeof a=="object"){for(const o of Object.values(a))if(o&&typeof o=="object"&&o.token){const i=String(o.token||"").trim();if(i.includes(".")&&i.split(".").length===3)return i}const n=a.token;if(n){const o=String(n||"").trim();if(o.includes(".")&&o.split(".").length===3)return o}}return null}function pf(){try{const t=cf?.VITE_LOGTO_APP_ID;if(!t)return null;const s=`logto:${t}:accessToken`,a=localStorage.getItem(s);return a?hf(a):null}catch{return null}}function gf(){const t=pf();if(!t)return null;const s=xf(t);return(s?String(s.sub||"").trim():"")||null}function jc(){if(ri)return ri;try{const t=localStorage.getItem(Rl),s=wc(t);return s&&(ri=s),s}catch{return null}}function pd(t){const s=wc(t);if(jc()!==s){ri=s;try{s?(localStorage.setItem(Rl,s),mf()):localStorage.removeItem(Rl)}catch{}df(s)}}function ff(){return!!jc()}function yf(t){try{if(typeof window>"u")return()=>{};const s=a=>{try{t(wc(a.detail))}catch(n){console.warn("⚠️ subscribeAuthScopeChanged handler failed:",n)}};return window.addEventListener(Ml,s),()=>window.removeEventListener(Ml,s)}catch(s){return console.warn("⚠️ subscribeAuthScopeChanged setup failed:",s),()=>{}}}function mr(){try{const t=jc();if(t)return t;const s=gf();return s||"anonymous"}catch{return"anonymous"}}function Ku(){return`seo:selected_market:${mr()}`}const Dl="seo:selected_market_changed";function gd(t,s){return t===s?!0:!t||!s?!1:String(t.location_id||"")===String(s.location_id||"")&&t.location_code===s.location_code&&t.language_code===s.language_code}function fd(t){try{if(typeof window>"u")return;window.dispatchEvent(new CustomEvent(Dl,{detail:t}))}catch{}}function Oi(t){try{if(typeof window>"u")return()=>{};const s=a=>{try{t(a.detail??null)}catch(n){console.warn("⚠️ subscribeSelectedMarketChanged handler failed:",n)}};return window.addEventListener(Dl,s),()=>window.removeEventListener(Dl,s)}catch(s){return console.warn("⚠️ subscribeSelectedMarketChanged setup failed:",s),()=>{}}}function ea(){try{const t=Ku(),s=localStorage.getItem(t);if(!s)return null;const a=JSON.parse(s);return typeof a.location_code!="number"||typeof a.language_code!="string"||!a.language_code.trim()?null:{location_id:typeof a.location_id=="string"&&a.location_id.trim()?a.location_id.trim():void 0,location_code:a.location_code,language_code:a.language_code.trim()}}catch{return null}}function tr(t,s){try{const a=Ku(),n=ea();if(!t){localStorage.removeItem(a),s?.emit&&!gd(n,null)&&fd(null);return}if(localStorage.setItem(a,JSON.stringify({location_id:t.location_id,location_code:t.location_code,language_code:t.language_code})),s?.emit){const o=ea();gd(n,o)||fd(o)}}catch{}}function Gu(){return`seo:selected_markets:${mr()}`}const Ll="seo:selected_markets_changed";function Wu(t){return String(t||"").trim()}function bf(t){const s=String(t.location_id||"").trim(),a=Wu(t.language_code),n=t.location_code;return s?{location_id:s,location_code:Number(n),language_code:a}:typeof n!="number"||!a?null:{location_code:Number(n),language_code:a}}function zl(t){const s=String(t.location_id||"").trim();return s?`id:${s}`:`code:${Number(t.location_code)}/${Wu(t.language_code)}`}function Vu(t){const s=[],a=new Set;for(const n of t||[]){const o=bf(n);if(!o)continue;const i=zl(o);a.has(i)||(a.add(i),s.push(o))}return s}function wf(t,s){if(t===s)return!0;if(t.length!==s.length)return!1;for(let a=0;a<t.length;a++)if(zl(t[a])!==zl(s[a]))return!1;return!0}function jf(t){try{if(typeof window>"u")return;window.dispatchEvent(new CustomEvent(Ll,{detail:t}))}catch{}}function So(t){try{if(typeof window>"u")return()=>{};const s=a=>{try{const n=a;t(Array.isArray(n.detail)?n.detail:[])}catch(n){console.warn("⚠️ subscribeSelectedMarketsChanged handler failed:",n)}};return window.addEventListener(Ll,s),()=>window.removeEventListener(Ll,s)}catch(s){return console.warn("⚠️ subscribeSelectedMarketsChanged setup failed:",s),()=>{}}}function Fr(){try{const t=Gu(),s=localStorage.getItem(t);if(!s)return[];const a=JSON.parse(s);return Array.isArray(a)?Vu(a):[]}catch{return[]}}function tn(t,s){try{const a=Gu(),n=Vu(t||[]),o=Fr();localStorage.setItem(a,JSON.stringify(n)),s?.emit&&!wf(o,n)&&jf(n)}catch{}}function yd(t){return String(t||"").trim()}function vf(){const t=Fr();return t.length>0?t[0]:ea()}function ra(t){const s=String(t?.location_id||"").trim();if(s)return{location_id:s};if(t?.location_code!==void 0||t?.language_code!==void 0){const c=t?.location_code,d=yd(t?.language_code);
23if(c===void 0!=!d)throw new Error("location_code and language_code must be provided together");if(c===void 0)throw new Error("location_id or (location_code + language_code) is required");return{location_code:c,language_code:d}}const n=vf(),o=String(n?.location_id||"").trim();if(o)return{location_id:o};const i=n?.location_code,l=yd(n?.language_code);if(i===void 0!=!l)throw new Error("location_code and language_code must be provided together");if(i===void 0)throw new Error("location_id or (location_code + language_code) is required");return{location_code:i,language_code:l}}function vc(t){return!(t instanceof zr)||t.errorInfo?.statusCode!==400?!1:String(t.message||"").toLowerCase().includes("invalid location_id")}function Nc(){try{const t=ea();if(!t?.location_id)return;tr({location_code:t.location_code,language_code:t.language_code},{emit:!0})}catch{}}const Eo=async()=>await ot("/domain_seo/competitors/keywords_limit"),Ao=async t=>await Je("/domain_seo/competitors/keywords_limit",{competitor_ranked_keywords_limit:t}),kc=async()=>await ot("/domain_seo/workflow_counts"),Or=async(t,s)=>{const a=ra({location_code:t,language_code:s});try{return await ot("/domain_seo/overview",a)}catch(n){if(vc(n)&&a?.location_id&&t===void 0&&s===void 0){const o=ea();if(o){Nc();const i=ra({location_code:o.location_code,language_code:o.language_code});return await ot("/domain_seo/overview",i)}}throw n}},Hu=async t=>await Je("/domain_seo/overview_batch",t),qu=async(t,s,a,n,o)=>{const i={};let l;if(o)l=o;else{const c=ra({location_code:t,language_code:s});Object.assign(i,c)}i.limit=n;try{return await Je("/domain_seo/own_keywords",l||{},{params:Object.keys(i).length>0?i:void 0})}catch(c){if(vc(c)&&i?.location_id&&t===void 0&&s===void 0&&!o){const d=ea();if(d){Nc();const m=ra({location_code:d.location_code,language_code:d.language_code});return m.limit=n,await Je("/domain_seo/own_keywords",{},{params:m})}}throw c}},Tn=async(t,s)=>{const a=ra({location_code:t,language_code:s});try{return await ot("/domain_seo/competitors",a)}catch(n){if(vc(n)&&a?.location_id&&t===void 0&&s===void 0){const o=ea();if(o){Nc();const i=ra({location_code:o.location_code,language_code:o.language_code});return await ot("/domain_seo/competitors",i)}}throw n}},wo=async(t,s)=>await Je("/domain_seo/competitors_batch",t,void 0),$l=async(t,s,a,n)=>{const o=ra({location_code:s,language_code:a}),i={competitor_domain:t,...o};return await ot("/domain_seo/competitors/detail",i)},vi=async(t,s,a)=>{const n={competitor_domain:t};return a?.includeMyRank!==void 0&&(n.include_my_rank=a.includeMyRank),a?.limit!==void 0&&(n.limit=a.limit),await Je("/domain_seo/competitors/detail_batch",s,{params:n})},Fl=async t=>{const s={};return t.urls&&(s.urls=t.urls),t.discoverCount&&(s.discover_count=t.discoverCount),await Je("/domain_seo/competitors/add",s)},_c=async t=>await ot("/domain_seo/competitors/sync_task_status",{task_id:t}),Yu=async(t,s,a,n,o)=>{const i=ra({location_code:s,language_code:a}),l={competitor_domain:t,...i};return l.limit=n,await ot("/domain_seo/competitors/keywords",l)},sr=async()=>{try{const[t,s,a]=await Promise.all([Bt(()=>Promise.resolve().then(()=>B0),void 0).then(o=>o.getMyCompanyInfo()).catch(()=>null),Or().catch(()=>null),Tn().catch(()=>null)]);return s?{company:{name:t?.company?.name||null,about:t?.company?.about||null,url:t?.company?.url||s.domain,keywords:t?.company?.extracted_keywords||s.top_keywords.slice(0,10).map(o=>o.keyword)},seo_overview:s,competitors:a}:null}catch(t){return console.error("Failed to get saved analysis:",t),null}},Cc=async(t,s,a)=>{const o={...ra({location_code:s,language_code:a})};return t&&(o.competitor_domain=t),await ot("/domain_seo/merged_keywords",o)},La=async()=>await ot("/domain_seo/markets"),Sc=async t=>await Je("/domain_seo/markets",{markets:t.markets,primary_market:t.primary_market??null}),Ju=async()=>await ot("/domain_seo/track_locations"),Xu=async t=>await Je("/domain_seo/track_locations",t),Qu=async t=>await Je("/domain_seo/track_locations/batch",t),Zu=async t=>await Ca(`/domain_seo/track_locations/${encodeURIComponent(t)}`),ex=async t=>await Ca(`/domain_seo/competitors/${encodeURIComponent(t)}`),Er=async(t,s=!1,a,n=!0,o=!0,i=!1)=>{const l=ra(),c={domains:t,sync_rank_overview:n,sync_ranked_keywords:o,force_sync_keywords:s,...l};return a!==void 0&&(c.keywords_limit=a),i&&(c.include_self=!0),await Je("/domain_seo/competitors/batch_sync",c)},Nf=Object.freeze(Object.defineProperty({__proto__:null,addCompetitors:Fl,batchAddTrackLocations:Qu,createTrackLocation:Xu,deleteCompetitor:ex,deleteTrackLocation:Zu,getCompetitorDetail:$l,getCompetitorDetailBatch:vi,getCompetitorKeywords:Yu,getCompetitorRankedKeywordsLimit:Eo,getCompetitorsSyncTaskStatus:_c,getDomainCompetitors:Tn,getDomainCompetitorsBatch:wo,getDomainOverview:Or,getDomainOverviewBatch:Hu,getMergedKeywords:Cc,getOwnKeywords:qu,getSavedAnalysisResult:sr,getTrackMarkets:La,getWorkflowCounts:kc,listTrackLocations:Ju,syncCompetitorsBatch:Er,updateCompetitorRankedKeywordsLimit:Ao,updateTrackMarkets:Sc},Symbol.toStringTag,{value:"Module"})),va=[{location_code:2008,location_name:"Albania",country_iso_code:"AL",location_type:"Country",languages:[{language_name:"Albanian",language_code:"sq"}]},{location_code:2012,location_name:"Algeria",country_iso_code:"DZ",location_type:"Country",languages:[{language_name:"French",language_code:"fr"},{language_name:"Arabic",language_code:"ar"}]},{location_code:2024,location_name:"Angola",country_iso_code:"AO",location_type:"Country",languages:[{language_name:"Portuguese",language_code:"pt"}]},{location_code:2031,location_name:"Azerbaijan",country_iso_code:"AZ",location_type:"Country",languages:[{language_name:"Azeri",language_code:"az"}]},{location_code:2032,location_name:"Argentina",country_iso_code:"AR",location_type:"Country",languages:[{language_name:"Spanish",language_code:"es"}]},{location_code:2036,location_name:"Australia",country_iso_code:"AU",location_type:"Country",languages:[{language_name:"English",language_code:"en"}]},{location_code:2040,location_name:"Austria",country_iso_code:"AT",location_type:"Country",languages:[{language_name:"German",language_code:"de"}]},{location_code:2048,location_name:"Bahrain",country_iso_code:"BH",location_type:"Country",languages:[{language_name:"Arabic",language_code:"ar"}]},{location_code:2050,location_name:"Bangladesh",country_iso_code:"BD",location_type:"Country",languages:[{language_name:"Bengali",language_code:"bn"}]},{location_code:2051,location_name:"Armenia",country_iso_code:"AM",location_type:"Country",languages:[{language_name:"Armenian",language_code:"hy"}]},{location_code:2056,location_name:"Belgium",country_iso_code:"BE",location_type:"Country",languages:[{language_name:"French",language_code:"fr"},{language_name:"Dutch",language_code:"nl"},{language_name:"German",language_code:"de"}]},{location_code:2068,location_name:"Bolivia",country_iso_code:"BO",location_type:"Country",languages:[{language_name:"Spanish",language_code:"es"}]},{location_code:2070,location_name:"Bosnia and Herzegovina",country_iso_code:"BA",location_type:"Country",languages:[{language_name:"Bosnian",language_code:"bs"}]},{location_code:2076,location_name:"Brazil",country_iso_code:"BR",location_type:"Country",languages:[{language_name:"Portuguese",language_code:"pt"}]},{location_code:2100,location_name:"Bulgaria",country_iso_code:"BG",location_type:"Country",languages:[{language_name:"Bulgarian",language_code:"bg"}]},{location_code:2104,location_name:"Myanmar (Burma)",country_iso_code:"MM",location_type:"Country",languages:[{language_name:"English",language_code:"en"}]},{location_code:2116,location_name:"Cambodia",country_iso_code:"KH",location_type:"Country",languages:[{language_name:"English",language_code:"en"}]},{location_code:2120,location_name:"Cameroon",country_iso_code:"CM",location_type:"Country",languages:[{language_name:"French",language_code:"fr"}]},{location_code:2124,location_name:"Canada",country_iso_code:"CA",location_type:"Country",languages:[{language_name:"English",language_code:"en"},{language_name:"French",language_code:"fr"}]},{location_code:2144,location_name:"Sri Lanka",country_iso_code:"LK",location_type:"Country",languages:[{language_name:"English",language_code:"en"}]},{location_code:2152,location_name:"Chile",country_iso_code:"CL",location_type:"Country",languages:[{language_name:"Spanish",language_code:"es"}]},{location_code:2158,location_name:"Taiwan",country_iso_code:"TW",location_type:"Region",languages:[{language_name:"Chinese (Traditional)",language_code:"zh-TW"}]},{location_code:2170,location_name:"Colombia",country_iso_code:"CO",location_type:"Country",languages:[{language_name:"Spanish",language_code:"es"}]},{location_code:2188,location_name:"Costa Rica",country_iso_code:"CR",location_type:"Country",languages:[{language_name:"Spanish",language_code:"es"}]},{location_code:2191,location_name:"Croatia",country_iso_code:"HR",location_type:"Country",languages:[{language_name:"Croatian",language_code:"hr"}]},{location_code:2196,location_name:"Cyprus",country_iso_code:"CY",location_type:"Country",languages:[{language_name:"Greek",language_code:"el"},{language_name:"English",language_code:"en"}]},{location_code:2203,location_name:"Czechia",country_iso_code:"CZ",location_type:"Country",languages:[{language_name:"Czech",language_code:"cs"}]},{location_code:2208,location_name:"Denmark",country_iso_code:"DK",location_type:"Country",languages:[{language_name:"Danish",language_code:"da"}]},{location_code:2218,location_name:"Ecuador",country_iso_code:"EC",location_type:"Country",languages:[{language_name:"Spanish",language_code:"es"}]},{location_code:2222,location_name:"El Salvador",country_iso_code:"SV",location_type:"Country",languages:[{language_name:"Spanish",language_code:"es"}]},{location_code:2233,location_name:"Estonia",country_iso_code:"EE",location_type:"Country",languages:[{language_name:"Estonian",language_code:"et"}]},{location_code:2246,location_name:"Finland",country_iso_code:"FI",location_type:"Country",languages:[{language_name:"Finnish",language_code:"fi"}]},{location_code:2250,location_name:"France",country_iso_code:"FR",location_type:"Country",languages:[{language_name:"French",language_code:"fr"}]},{location_code:2276,location_name:"Germany",country_iso_code:"DE",location_type:"Country",languages:[{language_name:"German",language_code:"de"}]},{location_code:2288,location_name:"Ghana",country_iso_code:"GH",location_type:"Country",languages:[{language_name:"English",language_code:"en"}]},{location_code:2300,location_name:"Greece",country_iso_code:"GR",location_type:"Country",languages:[{language_name:"Greek",language_code:"el"},{language_name:"English",language_code:"en"}]},{location_code:2320,location_name:"Guatemala",country_iso_code:"GT",location_type:"Country",languages:[{language_name:"Spanish",language_code:"es"}]},{location_code:2344,location_name:"Hong Kong",country_iso_code:"HK",location_type:"Region",languages:[{language_name:"English",language_code:"en"},{language_name:"Chinese (Traditional)",language_code:"zh-TW"}]},{location_code:2348,location_name:"Hungary",country_iso_code:"HU",location_type:"Country",languages:[{language_name:"Hungarian",language_code:"hu"}]},{location_code:2356,location_name:"India",country_iso_code:"IN",location_type:"Country",languages:[{language_name:"English",language_code:"en"},{language_name:"Hindi",language_code:"hi"}]},{location_code:2360,location_name:"Indonesia",country_iso_code:"ID",location_type:"Country",languages:[{language_name:"English",language_code:"en"},{language_name:"Indonesian",language_code:"id"}]},{location_code:2372,location_name:"Ireland",country_iso_code:"IE",location_type:"Country",languages:[{language_name:"English",language_code:"en"}]},{location_code:2376,location_name:"Israel",country_iso_code:"IL",location_type:"Country",languages:[{language_name:"Hebrew",language_code:"he"},{language_name:"Arabic",language_code:"ar"}]},{location_code:2380,location_name:"Italy",country_iso_code:"IT",location_type:"Country",languages:[{language_name:"Italian",language_code:"it"}]},{location_code:2384,location_name:"Cote d'Ivoire",country_iso_code:"CI",location_type:"Country",languages:[{language_name:"French",language_code:"fr"}]},{location_code:2392,location_name:"Japan",country_iso_code:"JP",location_type:"Country",languages:[{language_name:"Japanese",language_code:"ja"}]},{location_code:2398,location_name:"Kazakhstan",country_iso_code:"KZ",location_type:"Country",languages:[{language_name:"Russian",language_code:"ru"}]},{location_code:2400,location_name:"Jordan",country_iso_code:"JO",location_type:"Country",languages:[{language_name:"Arabic",language_code:"ar"}]},{location_code:2404,location_name:"Kenya",country_iso_code:"KE",location_type:"Country",languages:[{language_name:"English",language_code:"en"}]},{location_code:2410,location_name:"South Korea",country_iso_code:"KR",location_type:"Country",languages:[{language_name:"Korean",language_code:"ko"}]},{location_code:2428,location_name:"Latvia",country_iso_code:"LV",location_type:"Country",languages:[{language_name:"Latvian",language_code:"lv"}]},{location_code:2440,location_name:"Lithuania",country_iso_code:"LT",location_type:"Country",languages:[{language_name:"Lithuanian",language_code:"lt"}]},{location_code:2458,location_name:"Malaysia",country_iso_code:"MY",location_type:"Country",languages:[{language_name:"English",language_code:"en"},{language_name:"Malay",language_code:"ms"}]},{location_code:2470,location_name:"Malta",country_iso_code:"MT",location_type:"Country",languages:[{language_name:"English",language_code:"en"}]},{location_code:2484,location_name:"Mexico",country_iso_code:"MX",location_type:"Country",languages:[{language_name:"Spanish",language_code:"es"}]},{location_code:2492,location_name:"Monaco",country_iso_code:"MC",location_type:"Country",languages:[{language_name:"French",language_code:"fr"}]},{location_code:2498,location_name:"Moldova",country_iso_code:"MD",location_type:"Country",languages:[{language_name:"Romanian",language_code:"ro"}
23]},{location_code:2504,location_name:"Morocco",country_iso_code:"MA",location_type:"Country",languages:[{language_name:"Arabic",language_code:"ar"},{language_name:"French",language_code:"fr"}]},{location_code:2528,location_name:"Netherlands",country_iso_code:"NL",location_type:"Country",languages:[{language_name:"Dutch",language_code:"nl"}]},{location_code:2554,location_name:"New Zealand",country_iso_code:"NZ",location_type:"Country",languages:[{language_name:"English",language_code:"en"}]},{location_code:2558,location_name:"Nicaragua",country_iso_code:"NI",location_type:"Country",languages:[{language_name:"Spanish",language_code:"es"}]},{location_code:2566,location_name:"Nigeria",country_iso_code:"NG",location_type:"Country",languages:[{language_name:"English",language_code:"en"}]},{location_code:2578,location_name:"Norway",country_iso_code:"NO",location_type:"Country",languages:[{language_name:"Norwegian (Bokmål)",language_code:"nb"}]},{location_code:2586,location_name:"Pakistan",country_iso_code:"PK",location_type:"Country",languages:[{language_name:"English",language_code:"en"},{language_name:"Urdu",language_code:"ur"}]},{location_code:2591,location_name:"Panama",country_iso_code:"PA",location_type:"Country",languages:[{language_name:"Spanish",language_code:"es"}]},{location_code:2600,location_name:"Paraguay",country_iso_code:"PY",location_type:"Country",languages:[{language_name:"Spanish",language_code:"es"}]},{location_code:2604,location_name:"Peru",country_iso_code:"PE",location_type:"Country",languages:[{language_name:"Spanish",language_code:"es"}]},{location_code:2608,location_name:"Philippines",country_iso_code:"PH",location_type:"Country",languages:[{language_name:"English",language_code:"en"},{language_name:"Tagalog",language_code:"tl"}]},{location_code:2616,location_name:"Poland",country_iso_code:"PL",location_type:"Country",languages:[{language_name:"Polish",language_code:"pl"}]},{location_code:2620,location_name:"Portugal",country_iso_code:"PT",location_type:"Country",languages:[{language_name:"Portuguese",language_code:"pt"}]},{location_code:2642,location_name:"Romania",country_iso_code:"RO",location_type:"Country",languages:[{language_name:"Romanian",language_code:"ro"}]},{location_code:2682,location_name:"Saudi Arabia",country_iso_code:"SA",location_type:"Country",languages:[{language_name:"Arabic",language_code:"ar"}]},{location_code:2686,location_name:"Senegal",country_iso_code:"SN",location_type:"Country",languages:[{language_name:"French",language_code:"fr"}]},{location_code:2688,location_name:"Serbia",country_iso_code:"RS",location_type:"Country",languages:[{language_name:"Serbian",language_code:"sr"}]},{location_code:2702,location_name:"Singapore",country_iso_code:"SG",location_type:"Country",languages:[{language_name:"English",language_code:"en"},{language_name:"Chinese (Simplified)",language_code:"zh-CN"}]},{location_code:2703,location_name:"Slovakia",country_iso_code:"SK",location_type:"Country",languages:[{language_name:"Slovak",language_code:"sk"}]},{location_code:2704,location_name:"Vietnam",country_iso_code:"VN",location_type:"Country",languages:[{language_name:"English",language_code:"en"},{language_name:"Vietnamese",language_code:"vi"}]},{location_code:2705,location_name:"Slovenia",country_iso_code:"SI",location_type:"Country",languages:[{language_name:"Slovenian",language_code:"sl"}]},{location_code:2710,location_name:"South Africa",country_iso_code:"ZA",location_type:"Country",languages:[{language_name:"English",language_code:"en"}]},{location_code:2724,location_name:"Spain",country_iso_code:"ES",location_type:"Country",languages:[{language_name:"Spanish",language_code:"es"}]},{location_code:2752,location_name:"Sweden",country_iso_code:"SE",location_type:"Country",languages:[{language_name:"Swedish",language_code:"sv"}]},{location_code:2756,location_name:"Switzerland",country_iso_code:"CH",location_type:"Country",languages:[{language_name:"German",language_code:"de"},{language_name:"French",language_code:"fr"},{language_name:"Italian",language_code:"it"}]},{location_code:2764,location_name:"Thailand",country_iso_code:"TH",location_type:"Country",languages:[{language_name:"Thai",language_code:"th"}]},{location_code:2784,location_name:"United Arab Emirates",country_iso_code:"AE",location_type:"Country",languages:[{language_name:"Arabic",language_code:"ar"},{language_name:"English",language_code:"en"}]},{location_code:2788,location_name:"Tunisia",country_iso_code:"TN",location_type:"Country",languages:[{language_name:"Arabic",language_code:"ar"}]},{location_code:2792,location_name:"Turkiye",country_iso_code:"TR",location_type:"Country",languages:[{language_name:"Turkish",language_code:"tr"}]},{location_code:2804,location_name:"Ukraine",country_iso_code:"UA",location_type:"Country",languages:[{language_name:"Ukrainian",language_code:"uk"},{language_name:"Russian",language_code:"ru"}]},{location_code:2807,location_name:"North Macedonia",country_iso_code:"MK",location_type:"Country",languages:[{language_name:"Macedonian",language_code:"mk"}]},{location_code:2818,location_name:"Egypt",country_iso_code:"EG",location_type:"Country",languages:[{language_name:"Arabic",language_code:"ar"},{language_name:"English",language_code:"en"}]},{location_code:2826,location_name:"United Kingdom",country_iso_code:"GB",location_type:"Country",languages:[{language_name:"English",language_code:"en"}]},{location_code:2840,location_name:"United States",country_iso_code:"US",location_type:"Country",languages:[{language_name:"English",language_code:"en"},{language_name:"Spanish",language_code:"es"}]},{location_code:2854,location_name:"Burkina Faso",country_iso_code:"BF",location_type:"Country",languages:[{language_name:"French",language_code:"fr"}]},{location_code:2858,location_name:"Uruguay",country_iso_code:"UY",location_type:"Country",languages:[{language_name:"Spanish",language_code:"es"}]},{location_code:2862,location_name:"Venezuela",country_iso_code:"VE",location_type:"Country",languages:[{language_name:"Spanish",language_code:"es"}]}],tx=t=>va.find(s=>s.location_code===t),ro=t=>t?tx(t)?.location_name||`Location ${t}`:"Global",Ol=t=>tx(t)?.languages||[],bd=[2840,2826,2124,2036,2276,2250,2724,2380,2356,2392,2076,2484,2528,2702,2344],Ec=2840,Ac="en";function _n(t){return t.id?String(t.id):`${t.location_code}:${t.language_code}`}function Bl(t){const s=va.find(n=>n.location_code===t.location_code)?.location_name||`Location ${t.location_code}`,a=Ol(t.location_code).find(n=>n.language_code===t.language_code)?.language_name||t.language_code;return`${s} / ${a}`}
23function Ni(t){return{location_id:t.id||void 0,location_code:t.location_code,language_code:t.language_code}}function kf(){return{location_code:Ec,language_code:Ac}}function sx(t){const s=new Map;for(const a of t)s.set(_n(a),a);return Array.from(s.values())}function _f(t,s){return t.location_id&&s.id?String(t.location_id)===String(s.id):t.location_code===s.location_code&&t.language_code===s.language_code}function ax(t){const{stored:s,backendPrimary:a,markets:n}=t,o=s||(a?Ni(a):kf());return!n.length||n.some(l=>_f(o,l))?o:Ni(n[0])}function Cf({className:t,onMarketChange:s,sticky:a=!0,stickyTopOffsetPx:n=0}){const[o,i]=r.useState(!1),[l,c]=r.useState([]),[d,m]=r.useState(ea()),h=r.useMemo(()=>sx(l),[l]),p=d?_n({id:d.location_id,location_code:d.location_code,language_code:d.language_code}):"";if(r.useEffect(()=>{let y=!0;return(async()=>{i(!0);try{const x=await La();if(!y)return;const u=x?.markets||[];c(u);const g=ax({stored:d,backendPrimary:x?.primary_market||null,markets:u});m(g),tr(g)}catch{if(!y)return;c([])}finally{y&&i(!1)}})(),()=>{y=!1}},[]),h.length<=1)return null;const f=async y=>{const x=h.find(g=>_n(g)===y);if(!x)return;const u=Ni(x);m(u),tr(u,{emit:!0});try{s?.(u)}catch(g){console.warn("⚠️ MarketTabs onMarketChange handler failed:",g)}try{await Sc({markets:h.map(g=>({id:g.id||void 0,location_code:g.location_code,language_code:g.language_code,is_primary:!1})),primary_market:{id:x.id||void 0,location_code:x.location_code,language_code:x.language_code,is_primary:!0}})}catch{}},b=a?"sticky top-0 z-30 bg-slate-50/80 backdrop-blur supports-[backdrop-filter]:bg-slate-50/70":"";return e.jsx("div",{className:`${b} ${t||""}`,style:a?{top:n}:void 0,children:e.jsx("div",{className:"border border-slate-200 bg-white rounded-xl px-3 py-2",children:e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsx("div",{className:"text-[12px] font-semibold text-slate-700 flex-shrink-0",children:"Markets"}),e.jsx("div",{className:"flex-1 min-w-0 overflow-x-auto",children:e.jsx("div",{className:"flex items-center gap-2 w-max pr-1",children:h.map(y=>{const x=_n(y),u=x===p,g=Bl({location_code:y.location_code,language_code:y.language_code});return e.jsx("button",{type:"button",disabled:o,onClick:()=>f(x),className:["h-8 px-3 rounded-lg border text-[12px] whitespace-nowrap transition-colors","disabled:opacity-50 disabled:cursor-not-allowed",u?"bg-slate-900 text-white border-slate-900":"bg-white text-slate-700 border-slate-200 hover:bg-slate-50"].join(" "),title:g,"aria-current":u?"page":void 0,children:g},x)})})})]})})})}const nx=v.createContext(null),Sf={toast:t=>alert([t.title,t.description].filter(Boolean).join(" — "))};function _t(){const t=v.useContext(nx);return t||Sf}function za({children:t}){const[s,a]=v.useState([]);function n(l){a(c=>c.filter(d=>d.id!==l))}const o=v.useCallback(l=>{const c=Date.now()+Math.random();a(d=>[...d,{...l,id:c}]),setTimeout(()=>n(c),l.duration||3200)},[]),i=v.useMemo(()=>({toast:o}),[o]);return e.jsxs(nx.Provider,{value:i,children:[t,gs.createPortal(e.jsx("div",{className:"fixed bottom-6 right-6 flex flex-col gap-3",style:{zIndex:9999},children:s.map(l=>e.jsxs("div",{className:"max-w-md rounded-xl bg-white border border-slate-200 shadow-xl px-5 py-4 animate-in slide-in-from-right",children:[l.title&&e.jsx("div",{className:"font-semibold text-slate-900 mb-1",children:l.title}),l.description&&e.jsx("div",{className:"text-sm text-slate-600 leading-relaxed",children:l.description}),l.actionLabel&&l.onAction&&e.jsx("button",{onClick:()=>{l.onAction?.(),n(l.id)},className:"mt-3 w-full px-4 py-2 bg-slate-900 text-white text-sm font-medium rounded-lg hover:bg-slate-800 transition-colors",children:l.actionLabel})]},l.id))}),document.body)]})}function Ef({company:t,seoOverview:s,mode:a="input",onAnalyze:n,onRequestReAnalyze:o,isAnalyzing:i=!1,initialLocationCode:l=Ec,initialLanguageCode:c=Ac}){const[d,m]=r.useState(t?.url||""),[h,p]=r.useState(l),[f,b]=r.useState(c),y=r.useMemo(()=>Ol(h),[h]);r.useEffect(()=>{const S=Ol(h);S.length>0&&(S.some(D=>D.language_code===f)||b(S[0].language_code))},[h]),r.useEffect(()=>{t?.url&&m(t.url)},[t?.url]);const x=()=>{d.trim()&&n&&n(d.trim(),h,f)},u=S=>{S.key==="Enter"&&!i&&x()},[g,w]=r.useState(!1),_=()=>{w(!1),o&&o()},E=r.useMemo(()=>va.find(k=>k.location_code===h)?.location_name||"Unknown",[h]),N=r.useMemo(()=>y.find(k=>k.language_code===f)?.language_name||"Unknown",[y,f]);return e.jsxs("div",{className:"space-y-4",children:[a==="input"?e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsxs("label",{className:"block text-[12px] font-medium text-slate-700 mb-1.5",children:["Company Website URL ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{type:"text",value:d,onChange:S=>m(S.target.value),onKeyDown:u,placeholder:"www.example.com",className:"flex-1 px-3 py-2 text-[13px] border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 transition-colors",disabled:i}),e.jsxs("button",{onClick:x,disabled:!d.trim()||i,className:"px-4 py-2 bg-white border border-slate-200 rounded-lg text-[13px] font-medium text-slate-700 hover:bg-slate-50 disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2 transition-colors",children:[i?e.jsx(He,{size:14,className:"animate-spin"}):e.jsx(Pt,{size:14}),"Analyze"]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsxs("label",{className:"block text-[12px] font-medium text-slate-700 mb-1.5",children:[e.jsx(Jc,{className:"inline-block w-3.5 h-3.5 mr-1 -mt-0.5"}),"Target Location"]}),e.jsxs("select",{value:h,onChange:S=>p(Number(S.target.value)),disabled:i,className:"w-full h-9 px-3 rounded-lg border border-slate-200 bg-white text-[13px] focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 transition-colors disabled:opacity-50",children:[e.jsx("optgroup",{label:"Popular Locations",children:bd.map(S=>{const k=va.find(D=>D.location_code===S);return k?e.jsx("option",{value:k.location_code,children:k.location_name},k.location_code):null})}),e.jsx("optgroup",{label:"All Locations",children:va.filter(S=>!bd.includes(S.location_code)).sort((S,k)=>S.location_name.localeCompare(k.location_name)).map(S=>e.jsx("option",{value:S.location_code,children:S.location_name},S.location_code))})]})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"block text-[12px] font-medium text-slate-700 mb-1.5",children:[e.jsx(Qt,{className:"inline-block w-3.5 h-3.5 mr-1 -mt-0.5"}),"Language"]}),e.jsx("select",{value:f,onChange:S=>b(S.target.value),disabled:i,className:"w-full h-9 px-3 rounded-lg border border-slate-200 bg-white text-[13px] focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 transition-colors disabled:opacity-50",children:y.map(S=>e.jsx("option",{value:S.language_code,children:S.language_name},S.language_code))})]})]})]}):e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsx("div",{className:"border border-slate-200 rounded-lg p-3 bg-white",children:e.jsxs("div",{className:"flex items-center gap-2 text-[12px] text-slate-700",children:[e.jsx(Jc,{className:"w-3.5 h-3.5 text-slate-400"}),e.jsx("span",{className:"font-medium",children:"Target Location:"}),e.jsx("span",{className:"text-slate-600",children:E})]})}),e.jsx("div",{className:"border border-slate-200 rounded-lg p-3 bg-white",children:e.jsxs("div",{className:"flex items-center gap-2 text-[12px] text-slate-700",children:[e.jsx(Qt,{className:"w-3.5 h-3.5 text-slate-400"}),e.jsx("span",{className:"font-medium",children:"Language:"}),e.jsx("span",{className:"text-slate-600",children:N})]})})]}),t&&e.jsxs("div",{className:"border border-slate-200 rounded-lg p-4 bg-slate-50/50",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg bg-slate-100 flex items-center justify-center",children:e.jsx(an,{size:18,className:"text-slate-500"})}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-[13px] font-semibold text-slate-800",children:t.name||"Company"}),e.jsxs("a",{href:t.url,target:"_blank",rel:"noopener noreferrer",className:"text-[11px] text-slate-500 hover:text-slate-700 flex items-center gap-1",children:[t.url,e.jsx(ns,{size:10})]})]})]}),t.about&&e.jsxs("div",{className:"mb-3",children:[e.jsx("h4",{className:"text-[11px] font-semibold text-slate-700 mb-1.5",children:"About"}),e.jsx("p",{className:"text-[11px] text-slate-600 leading-relaxed",children:t.about})]})]}),e.jsx(Ht,{open:g,onOpenChange:w,children:e.jsxs(qt,{className:"sm:max-w-md",children:[e.jsxs(Zt,{children:[e.jsxs(Yt,{className:"flex items-center gap-2 text-orange-600",children:[e.jsx(Ja,{className:"w-5 h-5"}),"Re-analyze Company"]}),e.jsx(Ds,{children:"This will update your existing company analysis with fresh data. All current analysis data will be replaced."})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"p-3 bg-orange-50 border border-orange-100 rounded-md text-sm text-orange-800",children:[e.jsx("p",{className:"font-medium mb-1",children:"⚠️ Warning:"}),e.jsxs("ul",{className:"list-disc list-inside space-y-1 text-xs",children:[e.jsx("li",{children:"Current analysis data will be overwritten"}),e.jsx("li",{children:"Competitor data will be refreshed"}),e.jsx("li",{children:"This action cannot be undone"})]})]}),e.jsx("p",{className:"text-sm text-slate-600",children:"Are you sure you want to proceed with re-analysis?"})]}),e.jsxs(Ns,{children:[e.jsx(be,{variant:"outline",onClick:()=>w(!1),disabled:i,children:"Cancel"}),e.jsx(be,{onClick:_,disabled:i,className:"bg-orange-600 hover:bg-orange-700 text-white",children:i?e.jsxs(e.Fragment,{children:[e.jsx(He,{className:"mr-2 h-4 w-4 animate-spin"}),"Analyzing..."]}):"Confirm Re-analyze"})]})]})})]})}const jo=t=>t==null?"0":t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}
23K`:Math.floor(t).toLocaleString(),Af=t=>t>=30?{bg:"#f43f5e",text:"#be123c",light:"#fff1f2"}:t>=20?{bg:"#fb7185",text:"#e11d48",light:"#fff1f2"}:t>=10?{bg:"#fda4af",text:"#f43f5e",light:"#fdf2f8"}:{bg:"#fecdd3",text:"#f43f5e",light:"#fdf2f8"},Tf=3e4;function Ar(t){const{filename:s,blob:a,revokeDelayMs:n=Tf}=t;try{const o=window.URL.createObjectURL(a),i=document.createElement("a");i.href=o,i.download=s,i.target="_blank",i.rel="noopener noreferrer",i.style.display="none",document.body.appendChild(i),i.click(),i.remove(),window.setTimeout(()=>{window.URL.revokeObjectURL(o)},n)}catch(o){console.error("❌ Failed to download file:",o)}}function ar(t){const{filename:s,content:a,mimeType:n}=t,o=new Blob([a],{type:n});Ar({filename:s,blob:o})}const Pf=({summary:t,compact:s=!1,sharedLabel:a,sharedValueOverride:n,gapLabel:o,gapValueOverride:i,onAddCompetitor:l})=>{const c=s?"bg-white border border-slate-100 rounded-xl p-3 shadow-sm":"bg-white border border-slate-100 rounded-xl p-4 shadow-sm",d=s?"text-[10px] font-bold text-slate-800 uppercase tracking-wide":"text-[11px] font-bold text-slate-800 uppercase tracking-wide",m=s?"text-[20px] font-semibold text-slate-800":"text-2xl font-semibold text-slate-800",h=s?"text-[10px] text-slate-400 mt-0.5":"text-[11px] text-slate-400 mt-1",p=s?14:16;return e.jsxs("div",{className:`grid grid-cols-3 ${s?"gap-3":"gap-4"}`,children:[e.jsxs("div",{className:c,children:[e.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[e.jsx("span",{className:d,children:"Analyzed Competitors"}),e.jsx(Qs,{size:p,className:"text-slate-300"})]}),e.jsx("div",{className:m,children:t.total_competitors}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{className:h,children:"Tracked domains"}),l&&e.jsx(be,{onClick:l,variant:"ghost",size:"xs",title:"Add Competitors",children:e.jsxs("span",{className:"text-indigo-600 hover:text-indigo-700 text-xs",children:[e.jsx($t,{size:12,className:"inline-block"})," Add"]})})]})]}),e.jsxs("div",{className:c,children:[e.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[e.jsx("span",{className:d,children:a||"Shared Keywords"}),e.jsx(us,{size:p,className:"text-slate-300"})]}),e.jsx("div",{className:m,children:jo(n??t.total_shared_keywords)}),e.jsx("div",{className:h,children:"Total"})]}),e.jsxs("div",{className:c,children:[e.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[e.jsx("span",{className:d,children:o||"Keywords Gap"}),e.jsx(Di,{size:p,className:"text-slate-300"})]}),e.jsx("div",{className:m,children:jo(i??0)}),e.jsx("div",{className:h,children:"Total"})]})]})},To=v.createContext(null);function Pn({children:t,value:s,defaultValue:a,onValueChange:n,open:o,onOpenChange:i,selectionMode:l="single"}){const[c,d]=v.useState(a),[m,h]=v.useState(!1),p=r.useRef(null),f=s!==void 0,b=f?s:c,y=o!==void 0,x=y?o:m,u=w=>{f||d(w),n?.(w)},g=w=>{y||h(w),i?.(w)};return e.jsx(To.Provider,{value:{value:b,setValue:u,open:x,setOpen:g,selectionMode:l,triggerRef:p},children:t})}const In=({className:t="",children:s,disabled:a,noChevron:n,unstyled:o,asChild:i,...l})=>{const c=v.useContext(To),d=`h-9 w-full rounded-xl border border-slate-300 bg-white px-3 text-sm text-left flex items-center justify-between ${a?"bg-slate-100 text-slate-400 cursor-not-allowed":"hover:border-slate-400"}`,m=!!a,{onClick:h,...p}=l;if(i){if(!v.isValidElement(s))throw new Error("DropdownTrigger with asChild requires a single React element child.");const f=s,b=f.props?.onClick,y=l.onClick;return v.cloneElement(f,{...l,disabled:m||f.props?.disabled,ref:c.triggerRef,onClick:x=>{m||f.props?.disabled||(c.setOpen(!c.open),b?.(x),y?.(x))}})}return e.jsxs("button",{type:"button",ref:c.triggerRef,disabled:m,className:`${o?"":d} ${t}`,...p,onClick:f=>{m||(c.setOpen(!c.open),h?.(f))},children:[e.jsx("span",{className:o?"":"truncate flex-1",children:s}),!n&&!o&&e.jsx("svg",{width:"14",height:"14",viewBox:"0 0 20 20",fill:"none",className:`ml-2 ${m?"text-slate-300":"text-slate-500"}`,"aria-hidden":!0,children:e.jsx("path",{d:"M6 8l4 4 4-4",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]})},Tc=({placeholder:t="",className:s="",children:a})=>{const o=v.useContext(To)?.value??"",i=!o||o.length===0;return a!==void 0?e.jsx("span",{className:`${i?"text-slate-400":""} ${s}`,children:i?t:a}):e.jsx("span",{className:`${i?"text-slate-400":""} ${s}`,children:i?t:o})},Mn=({className:t="",align:s="left",side:a="bottom",children:n,...o})=>{const i=v.useContext(To),[l,c]=r.useState({top:0,left:0,width:0}),d=r.useRef(null),{onClick:m,...h}=o;if(r.useEffect(()=>{if(!i.open||!i.triggerRef?.current)return;const f=()=>{const b=i.triggerRef?.current;if(!b)return;const y=b.getBoundingClientRect(),x=d.current?.offsetWidth||0;let u=y.left,g=a==="bottom"?y.bottom+8:y.top-8;s==="right"?u=y.right-x:s==="center"&&(u=y.left+(y.width-x)/2);const w=8;u+x>window.innerWidth-w&&(u=window.innerWidth-x-w),u<w&&(u=w),a==="top"?(g=y.top-(d.current?.offsetHeight||0)-8,g<w&&(g=y.bottom+8)):g+(d.current?.offsetHeight||0)>window.innerHeight-w&&(g=y.top-(d.current?.offsetHeight||0)-8),c({top:g,left:u,width:y.width})};return f(),window.addEventListener("scroll",f,!0),window.addEventListener("resize",f),()=>{window.removeEventListener("scroll",f,!0),window.removeEventListener("resize",f)}},[i.open,i.triggerRef,s,a]),r.useEffect(()=>{if(!i.open)return;const f=b=>{d.current&&!d.current.contains(b.target)&&i.triggerRef?.current&&!i.triggerRef.current.contains(b.target)&&i.setOpen(!1)};return document.addEventListener("mousedown",f),()=>document.removeEventListener("mousedown",f)},[i.open,i.triggerRef]),!i.open)return null;const p=e.jsx("div",{ref:d,className:`fixed rounded-xl border border-slate-200 bg-white p-1 shadow-lg ${t}
23`,style:{top:`${l.top}px`,left:`${l.left}px`,minWidth:`${l.width}px`,zIndex:1e4},...h,onClick:f=>{f.stopPropagation(),m?.(f)},children:n});return Ha.createPortal(p,document.body)},js=({className:t="",value:s,children:a,...n})=>{const o=v.useContext(To),i=o.selectionMode==="single"&&o.value===s,{onClick:l,...c}=n;return e.jsx("button",{className:`block w-full rounded-md px-2 py-1.5 text-left hover:bg-slate-100 ${i?"bg-slate-100":""} ${t}`,...c,onClick:d=>{d.stopPropagation(),o.selectionMode==="single"&&o.setValue(s),o.setOpen(!1),l?.(d)},children:a})},Kt=({checked:t=!1,onCheckedChange:s,disabled:a=!1,className:n="",onClick:o,...i})=>{const[l,c]=v.useState(t);v.useEffect(()=>{c(t)},[t]);const d=m=>{if(o?.(m),m.stopPropagation(),a)return;const h=l!==!0;c(h),s?.(h)};return e.jsxs("button",{type:"button",role:"checkbox","aria-checked":l==="indeterminate"?"mixed":l,disabled:a,onClick:d,className:`
24        h-4 w-4 rounded border-2 flex items-center justify-center transition-colors
25        ${l===!0||l==="indeterminate"?"bg-blue-600 border-blue-600 !text-white":"border-slate-300 bg-white hover:border-slate-400"}
26        ${a?"opacity-50 cursor-not-allowed":"cursor-pointer"}
27        ${n}
28      `,...i,children:[l===!0&&e.jsx(wt,{size:12,strokeWidth:3,color:"currentColor"}),l==="indeterminate"&&e.jsx(Ps,{size:12,strokeWidth:3,color:"currentColor"})]})};function If({items:t,selectedIds:s,onToggle:a,onManage:n,onRemoveMarket:o}){const[i,l]=v.useState(!1),[c,d]=v.useState(null),[m,h]=v.useState(null),p=t.filter(x=>s.has(x.id||`${x.location_code}-${x.language_code}`)),f=p.length;v.useEffect(()=>{i||(d(null),h(null))},[i]);const b=v.useCallback((x,u)=>u&&f<=1&&s.has(x),[f,s]),y=()=>{if(f===0)return"Select Market";const x=p.map(_=>`${ro(_.location_code)}/${_.language_code.toUpperCase()}`);if(f===1)return x[0];const u=3,g=p.slice(0,u).map(_=>{const E=ro(_.location_code);return`${E.split(" ")[0]||E}/${_.language_code.toUpperCase()}`}),w=f>u?" ...":"";return`${g.join("  ")}${w}`};return e.jsxs(Pn,{open:i,onOpenChange:l,children:[e.jsx(In,{asChild:!0,children:e.jsxs("div",{className:`flex items-center justify-between gap-2 px-3 py-1.5 transition-all group flex-shrink-0 cursor-pointer select-none outline-none
29            bg-white border border-blue-400 rounded-lg shadow-sm hover:border-blue-500 hover:shadow-md transition-all ${i?"ring-2 ring-blue-100 border-blue-300 bg-blue-50":""}`,role:"button",tabIndex:0,children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0 overflow-hidden",children:[e.jsx(fi,{className:"w-4 h-4 text-blue-700"}),e.jsx("span",{className:"font-semibold text-slate-700 text-[12px] truncate",children:y()})]}),e.jsx(Gs,{size:14,className:`text-slate-400 ml-1 flex-shrink-0 transition-transform duration-200 ${i?"rotate-180 text-slate-600":""}`})]})}),e.jsxs(Mn,{className:"w-64 p-0 overflow-hidden",align:"left",children:[e.jsxs("div",{className:"px-3 py-2 bg-slate-50 border-b border-slate-100 flex items-center justify-between",children:[e.jsx("span",{className:"text-[10px] font-bold text-slate-400 uppercase tracking-wider",children:"Toggle Markets"}),e.jsxs("span",{className:"text-[10px] font-medium text-blue-600 bg-blue-50 px-1.5 py-0.5 rounded border border-blue-100",children:[f," Active"]})]}),e.jsx("div",{className:"max-h-[300px] overflow-y-auto py-1",children:t.map(x=>{const u=x.id||`${x.location_code}-${x.language_code}`,g=s.has(u),w=b(u,g),_=t.length<=1,E=c===u,N=m===u;return e.jsxs("div",{className:`flex items-center gap-3 px-3 py-2 hover:bg-slate-50 ${w?"cursor-not-allowed opacity-60":"cursor-pointer"}`,onClick:()=>{w||a(u,!g)},children:[e.jsx(Kt,{checked:g,disabled:w,onCheckedChange:S=>{w||a(u,S)},id:`chk-${u}`}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-sm font-medium text-slate-700 truncate",children:ro(x.location_code)}),e.jsx("div",{className:"text-xs text-slate-500",children:x.language_code.toUpperCase()})]}),e.jsx("div",{className:"flex items-center gap-1 flex-shrink-0",children:E?e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",className:"h-7 w-7 inline-flex items-center justify-center rounded-md text-slate-400 hover:text-slate-700 hover:bg-slate-100 disabled:opacity-60 disabled:cursor-not-allowed",onClick:S=>{S.stopPropagation(),d(null)},disabled:N,"aria-label":"Cancel delete",children:e.jsx(mt,{size:14})}),e.jsx("button",{type:"button",className:"h-7 w-7 inline-flex items-center justify-center rounded-md text-slate-400 hover:text-red-600 hover:bg-red-50 disabled:opacity-60 disabled:cursor-not-allowed",onClick:async S=>{if(S.stopPropagation(),!(_||N)){h(u);try{await o(x)}finally{h(null),d(null)}}},disabled:_||N,"aria-label":"Confirm delete",children:N?e.jsx("span",{className:"animate-spin h-3 w-3 border-2 border-slate-400 border-t-transparent roun
29ded-full"}):e.jsx(wt,{size:14})})]}):e.jsx("button",{type:"button",className:"h-7 w-7 inline-flex items-center justify-center rounded-md text-slate-300 hover:text-red-600 hover:bg-red-50 disabled:opacity-60 disabled:cursor-not-allowed",onClick:S=>{S.stopPropagation(),!_&&d(u)},disabled:_,"aria-label":"Delete market",children:e.jsx(es,{size:14})})})]},u)})}),e.jsx("div",{className:"p-2 border-t border-slate-100 bg-slate-50/50",children:e.jsxs(be,{variant:"ghost",size:"sm",className:"w-full justify-start text-blue-600 hover:text-blue-700 hover:bg-blue-50 gap-2 h-8",onClick:x=>{x.stopPropagation(),l(!1),n()},children:[e.jsx($t,{size:14}),"Manage / Add Markets"]})})]})]})}const Gt=({className:t="",...s})=>e.jsx("label",{className:`mb-1 block text-sm font-medium text-slate-700 ${t}`,...s});function Mf({open:t,onOpenChange:s,managedMarkets:a,onAddMarket:n,onRemoveMarket:o,onSyncStarted:i,onBatchAdded:l}){const{toast:c}=_t(),[d,m]=r.useState(""),[h,p]=r.useState(null),[f,b]=r.useState(null),[y,x]=r.useState(new Set),[u,g]=r.useState(!1),[w,_]=r.useState({rankOverview:!0,competitors:!1,trackedKeywords:!1});v.useEffect(()=>{t&&(x(new Set),b(null))},[t]),v.useEffect(()=>{if(!f)return;a.some($=>`${$.id||""}:${$.location_code}:${$.language_code}`===f)||b(null)},[f,a]);const E=r.useMemo(()=>{const L=d.toLowerCase().trim();return L?va.filter($=>$.location_name.toLowerCase().includes(L)):va},[d]),N=(L,$)=>a.some(H=>H.location_code===L&&H.language_code===$),S=(L,$)=>{const H=`${L.location_code}-${$.language_code}`;x(K=>{const X=new Set(K);return X.has(H)?X.delete(H):X.add(H),X})},k=async()=>{if(y.size!==0){g(!0);try{const L=Array.from(y).map(H=>{const[K,X]=H.split("-");return{location_code:Number(K),language_code:X,is_primary:!1}});if(w.rankOverview||w.competitors||w.trackedKeywords){const{creditEstimateService:H}=await Bt(async()=>{const{creditEstimateService:C}=await Promise.resolve().then(()=>Ya);return{creditEstimateService:C}},void 0),{validateCreditBalance:K}=await Bt(async()=>{const{validateCreditBalance:C}=await Promise.resolve().then(()=>ua);return{validateCreditBalance:C}},void 0),X=a.length,V=L.length,P=await H.estimateCredits({scenario:"domainseo_sync_new_markets",params:{markets_count:X+V,added_markets_count:V,sync_rank_overview:w.rankOverview,sync_competitors:w.competitors,sync_tracked_keywords:w.trackedKeywords}});if(!await K({estimatedRange:P?{min:P.estimated_min_credits,max:P.estimated_max_credits}:null,requiredMinimumBalance:P?.required_minimum_balance??null,toast:c})){g(!1);return}}const $=await Qu({markets:L,sync_rank_overview:w.rankOverview,sync_competitors:w.competitors,sync_tracked_keywords:w.trackedKeywords});try{l?.({markets:Array.isArray($?.markets)?$.markets:[],requested:L.map(H=>({location_code:H.location_code,language_code:H.language_code})),taskId:$?.task_id??null})}catch(H){console.warn("⚠️ onBatchAdded callback failed:",H)}$.task_id&&i&&i($.task_id),x(new Set),s(!1)}catch(L){console.error("❌ Failed to add markets:",L)}finally{g(!1)}}},D=async L=>{const $=`remove-${L.id||L.location_code}`;if(!h){p($);try{await o(L)}finally{p(null)}}},F=(L,$)=>va.find(K=>K.location_code===L)?.languages.find(K=>K.language_code===$)?.language_name||$,R=r.useMemo(()=>{if(y.size===0)return 0;let L=0;return w.rankOverview&&(L+=200*y.size),w.competitors&&(L+=1500*y.size),w.trackedKeywords&&(L+=100*y.size),L},[y.size,w]);return e.jsx(Ht,{open:t,onOpenChange:s,children:e.jsxs(qt,{className:"max-w-5xl p-0 overflow-hidden max-h-[80vh] flex flex-col gap-0",children:[e.jsxs(Zt,{variant:"full",divider:!0,dividerTone:"light",children:[e.jsx(Yt,{className:"text-lg font-semibold text-slate-900",children:"Manage Market Coverage"}),e.jsx("div",{className:"text-sm text-slate-500",children:"Configure which regions and languages you want to track."})]}),e.jsxs("div",{className:"flex flex-1 min-h-0 overflow-hidden",children:[e.jsxs("div",{className:"w-1/4 border-r border-slate-100 flex flex-col bg-slate-50/50 min-h-0",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-slate-100 bg-white flex-shrink-0",children:[e.jsx("div",{className:"text-xs font-semibold text-slate-500 uppercase tracking-wider",children:"Your Coverage"}),e.jsxs("div",{className:"text-sm text-slate-400 mt-0.5",children:[a.length," Existing",y.size>0&&` + ${y.size} New`]})]}),e.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:e.jsxs("div",{className:"p-2 space-y-1",children:[Array.from(y).map(L=>{const[$,H]=L.split("-"),K=ro(Number($)),X=F(Number($),H);return e.jsxs("div",{className:"group flex items-center justify-between px-3 py-2 rounded-md bg-blue-50 border border-blue-200 shadow-sm mb-1",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-medium text-sm text-blue-900 truncate",children:K}),e.jsx("span",{className:"text-[10px] bg-blue-200 text-blue-700 px-1.5 py-0.5 rounded font-medium",children:"NEW"})]}),e.jsx("div",{className:"text-xs text-blue-700 truncate",children:X})]}),e.jsx(be,{variant:"ghost",size:"xs",className:"h-7 w-7 p-0 text-blue-400 hover:text-blue-700",onClick:()=>{const[V,P]=L.split("-");S({location_code:Number(V)},{language_code:P})},"aria-label":"Remove new market",children:e.jsx(mt,{size:14})})]},L)}),a.length===0&&y.size===0&&e.jsx("div",{className:"p-4 text-center text-sm text-slate-400",children:"No markets selected."}),a.map((L,$)=>{const H=ro(L.location_code),K=F(L.location_code,L.language_code),X=h===`remove-${L.id||L.location_code}`,V=`${L.id||""}:${L.location_code}:${L.language_code}`,P=a.length<=1,A=f===V;return e.jsxs("div",{className:"group flex items-center justify-between px-3 py-2 rounded-md hover:bg-white hover:shadow-sm border border-transparent hover:border-slate-200 transition-all bg-white shadow-sm mb-1",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-medium text-sm text-slate-900 truncate",children:H}),e.jsx("div",{className:"text-xs text-slate-500 truncate",children:K})]}),A?e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(be,{variant:"ghost",size:"xs",className:"h-7 w-7 p-0 text-slate-400 hover:text-slate-700",disabled:X,onClick:()=>b(null),"aria-label":"Cancel delete",children:e.jsx(mt,{size:14})}),e.jsx(be,{variant:"ghost",size:"xs",className:"h-7 w-7 p-0 text-slate-400 hover:text-red-600",disabled:X||P,onClick:async()=>{await D(L),b(null)},"aria-label":"Confirm delete",children:X?e.jsx("span",{className:"animate-spin h-3 w-3 border-2 border-slate-400 border-t-transparent roun
29ded-full"}):e.jsx(wt,{size:14})})]}):e.jsx(be,{variant:"ghost",size:"xs",className:"h-7 w-7 p-0 text-slate-400 hover:text-red-600",disabled:X||P,onClick:()=>{P||b(V)},"aria-label":"Delete market",children:X?e.jsx("span",{className:"animate-spin h-3 w-3 border-2 border-slate-400 border-t-transparent rounded-full"}):e.jsx(es,{size:14})})]},L.id||`${L.location_code}-${$}`)})]})}),e.jsxs("div",{className:"p-4 border-t border-slate-200 bg-white",children:[e.jsx("div",{className:"text-[11px] font-semibold text-slate-500 uppercase tracking-wider mb-3",children:"Automatic Refresh"}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Kt,{id:"opt-rank",checked:w.rankOverview,disabled:!0,className:"mt-0.5"}),e.jsxs("div",{className:"grid gap-0.5",children:[e.jsx(Gt,{htmlFor:"opt-rank",className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:"Main Domain Overview"}),e.jsx("p",{className:"text-[11px] text-slate-500",children:"Includes ranked keywords & traffic"})]})]}),e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Kt,{id:"opt-comp",checked:w.competitors,onCheckedChange:L=>_($=>({...$,competitors:!!L})),className:"mt-0.5"}),e.jsxs("div",{className:"grid gap-0.5",children:[e.jsx(Gt,{htmlFor:"opt-comp",className:"text-sm font-medium leading-none cursor-pointer",children:"Competitors Overview"}),e.jsx("p",{className:"text-[11px] text-slate-500",children:"Traffic & keywords for all competitors"})]})]}),e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Kt,{id:"opt-track",checked:w.trackedKeywords,onCheckedChange:L=>_($=>({...$,trackedKeywords:!!L})),className:"mt-0.5"}),e.jsxs("div",{className:"grid gap-0.5",children:[e.jsx(Gt,{htmlFor:"opt-track",className:"text-sm font-medium leading-none cursor-pointer",children:"Tracked Keywords"}),e.jsx("p",{className:"text-[11px] text-slate-500",children:"Check rankings for tracked keywords"})]})]})]})]})]}),e.jsxs("div",{className:"flex-1 flex flex-col bg-white min-h-0",children:[e.jsx("div",{className:"px-4 py-3 border-b border-slate-100 flex-shrink-0",children:e.jsxs("div",{className:"relative",children:[e.jsx(Pt,{className:"absolute left-3 top-1/2 -translate-y-1/2 text-slate-400",size:16}),e.jsx(bt,{placeholder:"Search countries or languages...",className:"pl-9 bg-slate-50 border-slate-200 focus:bg-white",value:d,onChange:L=>m(L.target.value)})]})}),e.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto p-4",children:[e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-3",children:E.map(L=>L.languages.map($=>{if(N(L.location_code,$.language_code))return null;const K=`${L.location_code}-${$.language_code}`,X=y.has(K);return e.jsxs("button",{onClick:()=>S(L,$),disabled:u,className:`flex items-start gap-3 p-3 rounded-lg border transition-all text-left group relative ${X?"bg-blue-50 border-blue-200 shadow-sm ring-1 ring-blue-500/20":"bg-white border-slate-200 hover:border-blue-300 hover:bg-slate-50"}`,children:[X&&e.jsx("div",{className:"absolute top-2 right-2 text-blue-600",children:e.jsx(wt,{size:14,strokeWidth:3})}),e.jsx("div",{className:`flex-shrink-0 w-8 h-8 rounded-full flex items-center justify-center text-lg transition-colors ${X?"bg-blue-100 text-blue-600":"bg-slate-100 text-slate-500 group-hover:bg-blue-50 group-hover:text-blue-500"}`,children:e.jsx(fi,{size:16})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:`font-medium text-sm transition-colors ${X?"text-blue-900":"text-slate-900 group-hover:text-blue-700"}`,children:L.location_name}),e.jsx("div",{className:`text-xs transition-colors ${X?"text-blue-700":"text-slate-500 group-hover:text-blue-600/80"}`,children:$.language_name})]})]},K)}))}),E.length===0&&e.jsx("div",{className:"text-center py-10 text-slate-500",children:"No matching locations found."})]})]})]}),e.jsxs(Ns,{variant:"inset",density:"sm",divider:!0,dividerTone:"light",children:[e.jsx("div",{className:"flex-1 flex items-center justify-end gap-6 mr-4",children:y.size>0&&e.jsxs("div",{className:"flex items-center gap-2 text-xs text-slate-500 bg-slate-50 px-3 py-1.5 rounded-md border border-slate-200",children:[e.jsx(qr,{size:14,className:"text-blue-500"}),e.jsxs("span",{children:["Est. Credits:"," ",e.jsx("span",{className:"text-lg font-bold text-blue-600 ml-1",children:R})]})]})}),e.jsx(be,{variant:"ghost",onClick:()=>s(!1),children:"Cancel"}),e.jsx(be,{onClick:k,className:"bg-slate-900 hover:bg-slate-800 min-w-[120px]",disabled:y.size===0||u,children:u?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"animate-spin mr-2",children:"⏳"}),"Adding..."]}):`Add ${y.size} Markets`})]})]})})}const Oa="seo:new_markets_sync_task",wd=5,Rf=3,Df=600*1e3;function Lf(){const t=v.useRef(null),s=v.useRef(0),a=v.useRef(0),[n,o]=v.useState(()=>{try{const m=localStorage.getItem(Oa);if(m){const h=JSON.parse(m),p=1800*1e3;if(h.phase==="running"&&h.taskId&&Date.now()-(h.startedAtMs||0)<p)return h;localStorage.removeItem(Oa)}}catch{localStorage.removeItem(Oa)}return{phase:"idle",startedAtMs:null,etaText:null,progress:null,message:""}}),i=m=>{o(m),m.phase==="idle"?localStorage.removeItem(Oa):localStorage.setItem(Oa,JSON.stringify(m))},l=v.useCallback(()=>{t.current&&(window.clearInterval(t.current),t.current=null),i({phase:"idle",startedAtMs:null,etaText:null,progress:null,message:""})},[]),c=v.useCallback(async(m,h="1-2 min")=>{if(!m)return;t.current&&window.clearInterval(t.current);const p={phase:"running",startedAtMs:Date.now(),etaText:h,progress:{completed:0,total:100,percentage:0},message:"Starting sync...",taskId:m};i(p);const f=async()=>{const b=n;if(b.startedAtMs&&Date.now()-b.startedAtMs>Df){console.log("Task timed out after 10 minutes"),t.current&&(window.clearInterval(t.current),t.current=null),i({phase:"timeout",startedAtMs:null,etaText:null,progress:null,message:"Sync timed out. Please refresh and try again."});return}try{const y=await _c(m);if(s.current=0,y.status==="processing"){const x=Number(y.total||0),u=Number(y.progress||0),g=x>0?Math.min(100,Math.round(u/x*100)):0;if(g>=100){if(a.current+=1,console.log(`Progress at 100% count: ${a.current}`),a.current>=Rf){console.log("Task stuck at 100%, treating as completed"),t.current&&(window.clearInterval(t.current),t.current=null),a.current=0;const w={phase:"completed",startedAtMs:n.startedAtMs||Date.now(),etaText:null,progress:{completed:100,total:100,percentage:100},message:"Sync completed",taskId:m};i(w),setTimeout(()=>{l()},5e3);return}}else a.current=0;o(w=>{const _={...w,phase:"running",progress:{completed:u,total:x,percentage:g},message:y.message||y.current_step||"Syncing..."};return localStorage.setItem(Oa,JSON.stringify(_)),_});return}if(y.status==="done"){const x={...n,phase:"completed",startedAtMs:n.startedAtMs||Date.now(),etaText:null,progress:{completed:100,total:100,percentage:100},message:"Sync completed",taskId:m};i(x),t.current&&(window.clearInterval(t.current),t.current=null),setTimeout(()=>{l()},5e3);return}if(y.status==="error"||y.status==="failed"){const x={...n,phase:"error",startedAtMs:n.startedAtMs,etaText:null,progress:null,message:y.error||"Sync failed",taskId:m};i(x),t.current&&(window.clearInterval(t.current),t.current=null);return}}catch(y){if(console.warn("Polling error:",y),s.current+=1,y?.response?.status===404||y?.status===404){console.log("Task not found, resetting to idle"),t.current&&(window.clearInterval(t.current),t.current=null),s.current=0,i({phase:"idle",startedAtMs:null,etaText:null,progress:null,message:""});return}s.current>=wd&&(console.log(`Too many consecutive errors (${wd}), stopping sync`),t.current&&(window.clearInterval(t.current),t.current=null),s.current=0,i({phase:"error",startedAtMs:null,etaText:null,progress:null,message:"Sync stopped due to connection errors"}))}};await f(),t.current=window.setInterval(f,2e3)},[l]);v.useEffect(()=>{const m=localStorage.getItem(Oa);if(m)try{const h=JSON.parse(m),p=1800*1e3,f=Date.now()-(h.startedAtMs||0);h.phase==="running"&&h.taskId&&f<p?c(h.taskId,h.etaText||"1-2 min"):h.phase==="running"&&(console.log("Task too old, clearing stored state"),localStorage.removeItem(Oa))}catch{localStorage.removeItem(Oa)}return()=>{t.current&&window.clearInterval(t.current)}},[]);const d=v.useCallback(()=>{console.log("User dismissed sync panel"),t.current&&(window.clearInterval(t.current),t.current=null),s.current=0,a.current=0,localStorage.removeItem(Oa),o({phase:"idle",startedAtMs:null,etaText:null,progress:null,message:""})},[]);return{panel:n,startTask:c,resetToIdle:l,dismiss:d}}const sl=t=>String(Math.max(0,Math.floor(t))).padStart(2,"0"),zf=t=>{const s=Math.max(0,Math.floor(t)),a=Math.floor(s/3600),n=Math.floor(s%3600/60),o=s%60;return a>0?`${a}:${sl(n)}:${sl(o)}`:`${n}:${sl(o)}`};function $f(t){const[s,a]=v.useState(()=>Date.now());if(v.useEffect(()=>{if(t.state.phase!=="running")return;const p=window.setInterval(()=>a(Date.now()),1e3);return()=>window.clearInterval(p)},[t.state.phase]),t.state.phase==="idle")return null;const n=t.state.startedAtMs||s,o=(s-n)/1e3,i=zf(o),l=t.state.etaText||"1-2m",d=t.state.progress?.percentage??0,m=t.state.phase==="running"?e.jsx(kt,{className:"w-3.5 h-3.5 text-blue-500 animate-spin"}):t.state.phase==="completed"?e.jsx(Rs,{className:"w-3.5 h-3.5 text-emerald-600"}):e.jsx(Ja,{className:"w-3.5 h-3.5 text-amber-600"}),h=t.state.phase==="running"?"Syncing new markets...":t.state.phase==="completed"?"Sync completed":"Sync finished";return e.jsxs("div",{className:"flex items-center gap-3 bg-slate-50 border border-slate-200 rounded-md px-2 py-1 shadow-sm h-8 ml-2",children:[e.jsxs("div",{className:"flex items-center gap-1.5 min-w-[120px]",children:[m,e.jsx("div",{className:"min-w-0 flex flex-col justify-center",children:e.jsx("div",{className:"text-[10px] font-semibold text-slate-800 leading-tight truncate max-w-[150px]",children:h})})]}),t.state.phase==="running"&&e.jsx("div",{className:"w-[80px] bg-slate-200 rounded-full h-1.5 overflow-hidden",children:e.jsx("div",{className:"h-full bg-blue-600 transition-all duration-300 ease-out rounded-full",style:{width:`${d}%`}})}),e.jsxs("div",{className:"flex items-center gap-2 text-[9px] text-slate-500 flex-shrink-0",children:[t.state.phase==="running"&&e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"whitespace-nowrap hidden sm:inline",children:["Est. ",e.jsx("span",{className:"font-medium text-slate-700",children:l})]}),e.jsxs("span",{className:"whitespace-nowrap",children:[d,"%"]}),e.jsxs("span",{className:"flex items-center gap-1 whitespace-nowrap",children:[e.jsx(Ra,{className:"w-3 h-3 text-slate-400"}),i]})]}),t.state.phase!=="running"&&e.jsx("span",{className:"whitespace-nowrap",children:t.state.message})]}),t.onDismiss&&e.jsx("button",{onClick:t.onDismiss,className:"ml-1 p-0.5 rounded hover:bg-slate-200 text-slate-400 hover:text-slate-600 transition-colors",title:"Dismiss",children:e.jsx(mt,{className:"w-3.5 h-3.5"})})]})}const Ul="seo:markets_ready_changed",Kl=new Map;function Ff(t){try{if(typeof window>"u")return;window.dispatchEvent(new CustomEvent(Ul,{detail:t}))}catch{}}function Tr(){try{const t=mr();return Kl.get(t)===!0}catch{return!1}}function Jr(t){const s=mr(),a=Kl.get(s)===!0,n=!!t;a!==n&&(Kl.set(s,n),Ff({ready:n,scope_key:s}))}function Of(){Jr(!1)}function Pc(t){try{if(typeof window>"u")return()=>{};const s=a=>{try{const o=a.detail;if(!o)return;t(o)}catch(n){console.warn("⚠️ subscribeMarketsReadyChanged handler failed:",n)}};return window.addEventListener(Ul,s),()=>window.removeEventListener(Ul,s)}catch(s){return console.warn("⚠️ subscribeMarketsReadyChanged setup failed:",s),()=>{}}}async function Pr(t){const s=Math.max(0,Number(t?.timeout_ms??15e3));return Tr()?!0:typeof window>"u"?!1:await new Promise(a=>{let n=!1;const o=mr();let i=null;const l=Pc(c=>{if(!n&&c.scope_key===o&&c.ready){n=!0;try{i!==null&&window.clearTimeout(i)}catch{}l(),a(!0)}});if(s===0){l(),a(!1);return}i=window.setTimeout(()=>{n||(n=!0,l(),a(!1))},s)})}function $o(t){return(t||[]).map(s=>({id:s.id?String(s.id):void 0,location_code:Number(s.location_code),language_code:String(s.language_code)}))}function Ia(t){return t.id||`${t.location_code}-${t.language_code}`}function al(t,s){const a=String(s.location_id||"").trim();if(a){const n=t.find(o=>String(o.id||"")===a);if(n)return n}return t.find(n=>n.location_code===Number(s.location_code)&&n.language_code===String(s.language_code))||null}function Za(t,s){const a=[];for(const n of t){const o=Ia(n);s.has(o)&&a.push({location_id:n.id,location_code:n.location_code,language_code:n.language_code})}return a}function Bf(t){return!Array.isArray(t)||t.length===0?null:t[0]||null}
29function jd(t,s){if(s.size>0)return s;const a=Bf(t);return a?new Set([Ia(a)]):s}function vd(t){return`${Number(t.location_code)}:${String(t.language_code)}`}function Uf(t,s){const a=new Set(s.map(vd));return t.filter(n=>a.has(vd({location_code:n.location_code,language_code:n.language_code})))}function Bi({className:t=""}){const{toast:s}=_t(),[a,n]=v.useState([]),[o,i]=v.useState(new Set),[l,c]=v.useState(!1),{panel:d,startTask:m,dismiss:h}=Lf(),p=v.useCallback(async()=>{Of();try{const g=await Ju(),w=$o(g?.markets||[]);if(w.length===0){n([]),Jr(!0);return}n(w);const E=Fr().map(k=>al(w,k)).filter(Boolean).map(k=>Ia(k));let N=null;if(E.length>0&&(N=new Set(E)),N&&N.size>0){i(N),tn(Za(w,N)),Jr(!0);return}const S=new Set(w.map(Ia));S.size>0&&(console.log("✅ No stored selection found, defaulting to select all markets"),i(S),tn(Za(w,S),{emit:!0})),Jr(!0)}catch(g){console.warn("⚠️ Failed to load track locations:",g),Jr(!0)}},[]);v.useEffect(()=>{if(ff()){p();return}const g=yf(w=>{if(w){p();try{g()}catch{}}});return()=>{try{g()}catch{}}},[p]);const f=v.useRef("idle");v.useEffect(()=>{const g=d.phase;f.current==="running"&&g==="completed"&&(console.log("✅ Sync task completed, reloading markets and refreshing page"),p().then(()=>{setTimeout(()=>{window.location.reload()},500)})),f.current=g},[d.phase,p]),v.useEffect(()=>So(g=>{if(!a.length)return;const w=(g||[]).map(E=>al(a,E)).filter(Boolean).map(E=>Ia(E)),_=jd(a,new Set(w));i(_),w.length||tn(Za(a,_),{emit:!0})}),[a]);const b=v.useCallback((g,w)=>{i(_=>{if(!w&&_.size===1&&_.has(g))return _;const E=new Set(_);return w?E.add(g):E.delete(g),tn(Za(a,E),{emit:!0}),E})},[a]),y=v.useCallback(async(g,w)=>{const _=a.find(E=>E.location_code===g&&E.language_code===w);if(_){const E=Ia(_);i(N=>{const S=new Set(N);return S.add(E),tn(Za(a,S),{emit:!0}),S});return}try{const E=await Xu({location_code:g,language_code:w,is_primary:!1}),N=$o(E?.markets||[]);n(N);const S=N.find(k=>k.location_code===g&&k.language_code===w);if(S){const k=Ia(S);i(D=>{const F=new Set(D);return F.add(k),tn(Za(N,F),{emit:!0}),F})}}catch(E){throw console.error("❌ Failed to add market:",E),E}},[a]),x=v.useCallback(async g=>{const w=g.id?String(g.id):"";if(w)try{const _=await Zu(w),E=$o(_?.markets||[]);n(E);const N=Ia(g);i(S=>{const k=new Set(S);if(k.delete(N),k.size===0&&E.length>0){const D=E[0];k.add(Ia(D))}return tn(Za(E,k),{emit:!0}),k}),s({title:"Market removed",description:"The market has been removed."})}catch(_){console.error("❌ Failed to remove market:",_),s({title:"Error",description:_?.message||"Failed to remove market"})}},[a,s]),u=v.useCallback(g=>{try{const w=$o(g?.markets||[]);if(!w.length)return;i(_=>{const N=(Za(a,_)||[]).map(R=>al(w,R)).filter(Boolean).map(R=>Ia(R)),k=Uf(w,g?.requested||[]).map(Ia),D=new Set([...N,...k]),F=jd(w,D);return tn(Za(w,F),{emit:!0}),F}),n(w)}catch(w){console.warn("⚠️ Failed to apply batch added markets:",w)}},[a]);return a.length===0&&!o.size?null:e.jsxs("div",{className:t,children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(If,{items:a,selectedIds:o,onToggle:b,onManage:()=>c(!0),onRemoveMarket:x}),e.jsxs("div",{className:"flex items-center gap-2 px-1",children:[e.jsxs("span",{className:"relative flex h-2 w-2",children:[e.jsx("span",{className:"animate-ping absolute inline-flex h-full w-full rounded-full bg-blue-400 opacity-75"}),e.jsx("span",{className:"relative inline-flex rounded-full h-2 w-2 bg-blue-500"})]}),e.jsxs("span",{className:"text-[10px] font-bold text-slate-500 uppercase tracking-wide whitespace-nowrap",children:[o.size,"/",a.length," Markets Live"]})]}),e.jsx($f,{state:d,onDismiss:h})]}),e.jsx(Mf,{open:l,onOpenChange:c,managedMarkets:a,onAddMarket:y,onRemoveMarket:x,onSyncStarted:g=>m(g),onBatchAdded:u})]})}const Kf=({isOpen:t,onClose:s,competitors:a,selectedCompetitorIds:n,onToggleCompetitor:o,onSelectAllCompetitors:i,onDeselectAllCompetitors:l,numericFilters:c,onNumericFiltersChange:d,onExport:m,exportDisabled:h=!1})=>{const[p,f]=r.useState("markets");if(!t)return null;const b=n.length===a.length,y=(g,w,_)=>{const E=_===""?null:parseFloat(_);_!==""&&(isNaN(E)||E<0)||d({...c,[g]:{...c[g],[w]:E}})},x=g=>{d({...c,[g]:{min:null,max:null}})},u=g=>g.min!==null||g.max!==null;return e.jsx("div",{className:"fixed inset-0 z-[70] bg-black/40 backdrop-blur-sm",onClick:s,children:e.jsxs("div",{className:"absolute left-0 right-0 bottom-0 max-h-[80vh] bg-white rounded-t-2xl shadow-2xl flex flex-col animate-in slide-in-from-bottom duration-300",onClick:g=>g.stopPropagation(),children:[e.jsx("div",{className:"flex justify-center pt-3 pb-1 shrink-0",children:e.jsx("div",{className:"w-10 h-1 bg-slate-300 rounded-full"})}),e.jsxs("div",{className:"flex items-center justify-between px-5 py-2 border-b border-slate-100 shrink-0",children:[e.jsx("span",{className:"text-base font-semibold text-slate-900",children:"Settings"}),e.jsx("button",{onClick:s,className:"flex items-center justify-center w-8 h-8 text-slate-400 hover:text-slate-600 hover:bg-slate-100 rounded-full transition-colors",children:e.jsx(mt,{size:18})})]}),e.jsxs("div",{className:"flex border-b border-slate-100 shrink-0",children:[e.jsx("button",{onClick:()=>f("markets"),className:Lt("flex-1 py-3 text-sm font-medium transition-colors",p==="markets"?"text-indigo-600 border-b-2 border-indigo-600":"text-slate-500"),children:"Markets"}),e.jsx("button",{onClick:()=>f("competitors"),className:Lt("flex-1 py-3 text-sm font-medium transition-colors",p==="competitors"?"text-indigo-600 border-b-2 border-indigo-600":"text-slate-500"),children:"Competitors"}),e.jsx("button",{onClick:()=>f("filters"),className:Lt("flex-1 py-3 text-sm font-medium transition-colors",p==="filters"?"text-indigo-600 border-b-2 border-indigo-600":"text-slate-500"),children:"Filters"})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto overscroll-contain",children:[p==="markets"&&e.jsxs("div",{className:"p-4",children:[e.jsx("div",{className:"text-xs text-slate-500 mb-2",children:"Markets"}),e.jsx("div",{className:"overflow-x-auto",children:e.jsx(Bi,{})})]}),p==="competitors"&&e.jsxs("div",{className:"py-2",children:[e.jsxs("div",{className:"flex items-center justify-between px-4 py-2 border-b border-slate-100",children:[e.jsxs("span",{className:"text-xs text-slate-500",children:[n.length,"/",a.length," selected"]}),e.jsx("button",{onClick:b?l:i,className:"text-xs text-indigo-600 font-medium",children:b?"Deselect All":"Select All"})]}),a.map(g=>{const w=n.includes(g.id);return e.jsxs("button",{onClick:()=>o(g.id),className:"w-full flex items-center gap-3 px-4 py-3 hover:bg-slate-50 transition-colors",children:[e.jsx("div",{className:Lt("w-5 h-5 rounded border flex items-center justify-center flex-shrink-0",w?"bg-slate-800 border-slate-800":"border-gray-300"),children:w&&e.jsx(wt,{size:12,className:"text-white",strokeWidth:3})}),e.jsx("span",{className:"w-2.5 h-2.5 rounded-full flex-shrink-0",style:{backgroundColor:g.color}}),e.jsx("span",{className:"text-sm text-slate-700 truncate",children:g.domain})]},g.id)})]}),p==="filters"&&e.jsxs("div",{className:"p-4 space-y-5",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm font-medium text-slate-700",children:"Volume"}),u(c.volume)&&e.jsx("button",{onClick:()=>x("volume"),className:"text-xs text-indigo-600",children:"Clear"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("input",{type:"number",min:"0",placeholder:"Min",value:c.volume.min??"",onChange:g=>y("volume","min",g.target.value),className:"flex-1 px-3 py-2 text-sm border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-indigo-500"}),e.jsx("span",{className:"text-slate-400",children:"-"}),e.jsx("input",{type:"number",min:"0",placeholder:"Max",value:c.volume.max??"",onChange:g=>y("volume","max",g.target.value),className:"flex-1 px-3 py-2 text-sm border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-indigo-500"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm font-medium text-slate-700",children:"My Rank"}
29),u(c.myRank)&&e.jsx("button",{onClick:()=>x("myRank"),className:"text-xs text-indigo-600",children:"Clear"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"text-sm text-slate-500",children:"Rank before"}),e.jsx("input",{type:"number",min:"1",placeholder:"e.g. 10",value:c.myRank.max??"",onChange:g=>y("myRank","max",g.target.value),className:"flex-1 px-3 py-2 text-sm border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-indigo-500"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm font-medium text-slate-700",children:"Competitor Rank"}),u(c.competitorRank)&&e.jsx("button",{onClick:()=>x("competitorRank"),className:"text-xs text-indigo-600",children:"Clear"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"text-sm text-slate-500",children:"Rank before"}),e.jsx("input",{type:"number",min:"1",placeholder:"e.g. 10",value:c.competitorRank.max??"",onChange:g=>y("competitorRank","max",g.target.value),className:"flex-1 px-3 py-2 text-sm border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-indigo-500"})]})]})]})]}),e.jsx("div",{className:"shrink-0 border-t border-slate-100 p-4 pb-safe",children:e.jsxs("button",{onClick:()=>{m(),s()},disabled:h,className:"w-full flex items-center justify-center gap-2 py-3 bg-slate-100 hover:bg-slate-200 text-slate-700 rounded-xl font-medium transition-colors disabled:opacity-50 disabled:cursor-not-allowed",children:[e.jsx(Vs,{size:18}),e.jsx("span",{children:"Export to CSV"})]})})]})})},Po=v.createContext(null);function nr({children:t,value:s,defaultValue:a,onValueChange:n,size:o="md",as:i="span",className:l="",...c}){const[d,m]=v.useState(a),[h,p]=v.useState(!1),f=r.useRef(null),b=s!==void 0,y=b?s:d,x=u=>{b||m(u),n?.(u)};return e.jsx(Po.Provider,{value:{value:y,setValue:x,open:h,setOpen:p,triggerRef:f,size:o},children:e.jsx(i,{className:`inline-block ${l}`,...c,children:t})})}const rr=({className:t="",children:s,showIcon:a=!0,...n})=>{const o=v.useContext(Po),i={sm:"h-8 px-2 text-xs",md:"h-9 px-3 text-sm"},l=o.size==="sm"?"12":"14",c=t.includes("bg-transparent")||t.includes("border-0");return e.jsxs("button",{ref:o.triggerRef,className:`w-full rounded-md border border-slate-300 bg-white text-left flex items-center justify-between hover:border-slate-400 shadow-sm ${i[o.size]} ${t}`,onClick:d=>{o.setOpen(!o.open),n.onClick?.(d)},...n,children:[c?s:e.jsx("span",{className:"truncate flex-1",children:s}),a&&!c&&e.jsx("svg",{width:l,height:l,viewBox:"0 0 20 20",fill:"none",className:"ml-2 text-slate-500 flex-shrink-0","aria-hidden":!0,children:e.jsx("path",{d:"M6 8l4 4 4-4",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]})},Ui=({placeholder:t="",className:s=""})=>{const n=v.useContext(Po)?.value??"",o=!n||n.length===0;return e.jsx("span",{className:`${o?"text-slate-400":""} ${s}`,children:o?t:n})},or=({className:t="",align:s="left",side:a="bottom",children:n,...o})=>{const i=v.useContext(Po),[l,c]=r.useState({top:0,left:0,width:0}),d=r.useRef(null);if(r.useEffect(()=>{if(!i.open||!i.triggerRef?.current)return;const h=()=>{const p=i.triggerRef?.current;if(!p)return;const f=p.getBoundingClientRect(),b=d.current?.offsetWidth||f.width;let y=f.left,x=a==="bottom"?f.bottom+8:f.top-8;s==="right"?y=f.right-b:s==="center"&&(y=f.left+(f.width-b)/2);const u=8;y+b>window.innerWidth-u&&(y=window.innerWidth-b-u),y<u&&(y=u),a==="top"?(x=f.top-(d.current?.offsetHeight||0)-8,x<u&&(x=f.bottom+8)):x+(d.current?.offsetHeight||0)>window.innerHeight-u&&(x=f.top-(d.current?.offsetHeight||0)-8),c({top:x,left:y,width:f.width})};return h(),window.addEventListener("scroll",h,!0),window.addEventListener("resize",h),()=>{window.removeEventListener("scroll",h,!0),window.removeEventListener("resize",h)}},[i.open,i.triggerRef,s,a]),r.useEffect(()=>{if(!i.open)return;const h=p=>{d.current&&!d.current.contains(p.target)&&i.triggerRef?.current&&!i.triggerRef.current.contains(p.target)&&i.setOpen(!1)};return document.addEventListener("mousedown",h),()=>document.removeEventListener("mousedown",h)},[i.open,i.triggerRef]),!i.open)return null;const m=e.jsx("div",{ref:d,className:`fixed rounded-xl border border-slate-200 bg-white p-1 shadow-lg ${t}
29`,style:{top:`${l.top}px`,left:`${l.left}px`,minWidth:`${l.width}px`,zIndex:1002},...o,children:n});return Ha.createPortal(m,document.body)},_s=({className:t="",value:s,children:a,...n})=>{const o=v.useContext(Po),i={sm:"px-2 py-1 text-xs",md:"px-2 py-1.5 text-sm"};return e.jsx("button",{className:`block w-full rounded-md text-left hover:bg-slate-100 ${i[o.size]} ${t}`,onClick:l=>{o.setValue(s),o.setOpen(!1),n.onClick?.(l)},...n,children:a})},Gf=({className:t="",size:s=14})=>e.jsx(cn,{size:s,className:t,strokeWidth:1.5,"aria-hidden":"true"}),Wf=({className:t="",size:s=14})=>e.jsx(Qn,{size:s,className:t,strokeWidth:1.5,"aria-hidden":"true"});function xn({page:t,pageSize:s,total:a,onPageChange:n,onPageSizeChange:o,minPageSize:i=1,maxPageSize:l=200,className:c="",displayFormat:d="total",pageSizeOptions:m,variant:h="slate",onPageSizeChangeWithReset:p}){const f=Math.max(1,Math.ceil(a/s)),b=a===0?0:(t-1)*s+1,y=Math.min(t*s,a),x=()=>{n(Math.max(1,t-1))},u=()=>{n(t*s<a?t+1:t)},g=F=>{const R=parseInt(F,10);if(!isNaN(R)){const L=Math.max(i,Math.min(l,R));p?(p(L),n(1)):o(L)}},w=()=>{if(m)return m.filter(L=>L>=i&&L<=l);const F=[10,20,50,100,200,500,1e3],R=[];return F.forEach(L=>{L>=i&&L<=l&&R.push(L)}),!R.includes(s)&&s>=i&&s<=l&&R.push(s),R.sort((L,$)=>L-$)},_=h==="gray"?"bg-gray-50":"bg-slate-50",E=h==="gray"?"text-gray-500":"text-slate-600",N=h==="gray"?"text-gray-700":"text-slate-600",S=h==="gray"?"text-gray-900":"text-slate-600",k=h==="gray"?"border-gray-300":"border-slate-300",D=h==="gray"?"hover:bg-gray-50":"hover:bg-slate-50";return e.jsxs("div",{className:`flex flex-col sm:flex-row items-center justify-between gap-2 sm:gap-4 ${_} px-3 sm:px-6 py-2 sm:py-3 ${c}`,children:[e.jsx("div",{className:`text-xs sm:text-sm ${E}`,children:d==="range"?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"hidden sm:inline",children:"Showing "}),e.jsx("span",{className:`font-medium ${S}`,children:b}),e.jsx("span",{className:"hidden sm:inline",children:" to "}),e.jsx("span",{className:"sm:hidden",children:"-"}),e.jsx("span",{className:`font-medium ${S}`,children:y}),e.jsx("span",{className:"hidden sm:inline",children:" of "}),e.jsx("span",{className:"sm:hidden",children:"/"}),e.jsx("span",{className:`font-medium ${S}`,children:a}),e.jsx("span",{className:"hidden sm:inline",children:" results"})]}):e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"hidden sm:inline",children:"total "}),e.jsx("span",{className:`font-medium ${S}`,children:a})," ","results"]})}),e.jsxs("div",{className:"flex items-center gap-3 sm:gap-6",children:[e.jsxs("div",{className:"flex items-center gap-1.5 sm:gap-2",children:[e.jsx("span",{className:`${E} text-[10px] sm:text-xs uppercase font-medium whitespace-nowrap hidden sm:inline`,children:"Rows per page"}),e.jsx("div",{className:"w-16 sm:w-20 relative",children:e.jsxs(nr,{value:String(s),onValueChange:g,children:[e.jsx(rr,{className:`h-7 sm:h-8 text-xs sm:text-sm ${k}`,children:e.jsx(Ui,{})}),e.jsx(or,{children:w().map(F=>e.jsx(_s,{value:String(F),children:F},F))})]})})]}),e.jsxs("div",{className:"flex items-center gap-1.5 sm:gap-2",children:[e.jsxs("button",{onClick:x,disabled:t<=1,className:`w-7 h-7 sm:w-8 sm:h-8 flex items-center justify-center rounded-md border ${k} bg-white ${E} ${D} disabled:bg-gray-100 disabled:opacity-50 disabled:cursor-not-allowed transition-colors`,"aria-label":"Previous page",children:[e.jsx("span",{className:"sr-only",children:"Previous"}),e.jsx(Gf,{})]}),e.jsxs("div",{className:`text-xs sm:text-sm font-medium ${N} min-w-[50px] sm:min-w-[60px] text-center`,children:[t," / ",f]}),e.jsxs("button",{onClick:u,disabled:t>=f||f===0,className:`w-7 h-7 sm:w-8 sm:h-8 flex items-center justify-center rounded-md border ${k} bg-white ${E} ${D} disabled:bg-gray-100 disabled:opacity-50 disabled:cursor-not-allowed transition-colors`,"aria-label":"Next page",children:[e.jsx("span",{className:"sr-only",children:"Next"}),e.jsx(Wf,{})]})]})]})]})}const Vf=new Set(["co","com","org","net","gov","edu"]);function Ki(t){return(t||"").toLowerCase()}function Hf(t){const s=Ki(t).split(".").map(n=>
29n.trim()).filter(Boolean);if(s.length===0)return"";if(s.length===1)return s[0];const a=s[s.length-2]||"";return Vf.has(a)&&s.length>=3&&s[s.length-3]||a}function qf(t){const s=Ki(t).trim();if(!s)return"";const a=s.replace(/^https?:\/\//,"").replace(/\/.*$/,"").replace(/:\d+$/,"");return a.startsWith("www.")?a.slice(4):a}function Yf(t){const s=Ki(t).replace(/[^a-z0-9_-]+/g," ").trim();if(!s)return[];const a=new Set,n=s.split(/\s+/g).flatMap(i=>i.split(/[_-]+/g)).map(i=>i.trim()).filter(Boolean);n.forEach(i=>{i.length>=3&&a.add(i)});const o=n.join("");return o.length>=3&&a.add(o),Array.from(a)}function Jf(t){const s=Ki(t).replace(/[^a-z0-9]+/g," ").trim();return s?new Set(s.split(/\s+/g).map(a=>a.trim()).filter(Boolean)):new Set}function nl(t,s){if(!t||s.length===0)return!1;const a=Jf(t);return a.size===0?!1:s.some(n=>a.has(n))}function rl(t){return Array.from(new Set(t.map(s=>(s||"").trim()).filter(s=>s.length>0)))}function Nd(t){return t==null}class rx{constructor(s){this.rows=s.rows||[],this.userDomain=s.userDomain,this.competitorDomains=s.competitorDomains||[]}compute(){const s=this.buildBrandTokens(),a=this.buildCompetitorBrandTokens(),n=rl(this.rows.filter(l=>nl(l.keyword,a)).map(l=>l.keyword)),o=rl(this.rows.filter(l=>!nl(l.keyword,s)).filter(l=>Nd(l.myRank)).filter(l=>this.hasAnyCompetitorRank(l)).map(l=>l.keyword)),i=rl(this.rows.filter(l=>!nl(l.keyword,s)).filter(l=>!Nd(l.myRank)).filter(l=>this.hasCompetitorOutranking(l)).map(l=>l.keyword));return{competitorBrandKeywords:n,nonBrandCompetitorHasYouDont:o,nonBrandCompetitorOutranksYou:i,brandTokens:s}}buildBrandTokens(){const s=new Set;return this.domainToBrandTokens(this.userDomain).forEach(n=>s.add(n)),this.competitorDomains.flatMap(n=>this.domainToBrandTokens(n)).forEach(n=>s.add(n)),Array.from(s)}buildCompetitorBrandTokens(){const s=new Set;return this.competitorDomains.flatMap(a=>this.domainToBrandTokens(a)).forEach(a=>s.add(a)),Array.from(s)}domainToBrandTokens(s){const a=qf(s||"");if(!a)return[];const n=Hf(a);return Yf(n)}hasAnyCompetitorRank(s){return Object.values(s.competitorRanks||{}).some(a=>a!=null)}hasCompetitorOutranking(s){if(s.myRank===null||s.myRank===void 0)return!1;const a=s.myRank;return Object.values(s.competitorRanks||{}).some(n=>n==null?!1:n<a)}}function kd(t){return(t||"").trim()}function Xf(t){return!t.applySnapshotFreshnessGate||!t.snapshotDate?!0:t.isSnapshotFresh(t.snapshotDate)}function Qf(t,s){return s==null?!1:t==null?!0:s<t}class _d{constructor(s){this.myTopKeywords=s.myTopKeywords||[],this.competitorKeywordsData=s.competitorKeywordsData||{},this.selectedCompetitorIds=s.selectedCompetitorIds||[],this.applySnapshotFreshnessGate=s.applySnapshotFreshnessGate,this.isSnapshotFresh=s.isSnapshotFresh}build(){const s=new Map;return this.myTopKeywords.forEach(a=>{const n=kd(a.keyword);if(!n)return;const o=s.get(n);if(o){o.myRank===null&&a.rank!=null&&(o.myRank=a.rank??null),!o.myLandingPage&&a.landing_page&&(o.myLandingPage=a.landing_page),o.volume===null&&a.search_volume!==null&&(o.volume=a.search_volume);return}s.set(n,{id:n,keyword:n,volume:a.search_volume,difficulty:null,myRank:a.rank??null,myLandingPage:a.landing_page??null,competitorRanks:{},competitorLandingPages:{}})}),this.selectedCompetitorIds.forEach(a=>{(this.competitorKeywordsData[a]||[]).forEach(o=>{const i=kd(o.keyword);if(!i)return;const l=Xf({snapshotDate:o.snapshot_date,applySnapshotFreshnessGate:this.applySnapshotFreshnessGate,isSnapshotFresh:this.isSnapshotFresh}),c=s.get(i);if(c){if(l){const d=c.competitorRanks[a]??null,m=o.rank??null;Qf(d,m)&&(c.competitorRanks[a]=m,c.competitorLandingPages[a]=o.landing_page??null)}l&&c.myRank===null&&o.my_rank!=null&&(c.myRank=o.my_rank??null),
29c.volume===null&&o.search_volume!==null&&(c.volume=o.search_volume),c.difficulty===null&&o.keyword_difficulty!==null&&(c.difficulty=o.keyword_difficulty);return}s.set(i,{id:i,keyword:i,volume:o.search_volume,difficulty:o.keyword_difficulty,myRank:l?o.my_rank??null:null,myLandingPage:null,competitorRanks:{[a]:l?o.rank??null:null},competitorLandingPages:{[a]:l?o.landing_page??null:null}})})}),Array.from(s.values())}}function ox(t){return String(t||"").trim()}function Gl(t){const s=String(t.location_id||"").trim(),a=ox(t.language_code),n=t.location_code;return s?{location_id:s,location_code:Number(n),language_code:a}:typeof n!="number"||!a?null:{location_code:Number(n),language_code:a}}function ma(){const t=Fr().map(Gl).filter(Boolean);if(t.length>0)return t;const s=ea();return s?[Gl(s)].filter(Boolean):[]}function $a(t){const s=(t||[]).map(Gl).filter(Boolean),a=s.map(n=>String(n.location_id||"").trim()).filter(Boolean);return a.length===s.length&&a.length>0?{location_ids:a}:{markets:s.map(n=>({location_code:Number(n.location_code),language_code:ox(n.language_code)}))}}const Cd=["#ef4444","#f97316","#3b82f6","#8b5cf6","#10b981","#ec4899","#eab308","#06b6d4"],Sd=t=>{if(!t)return!1;try{const s=new Date(t);if(isNaN(s.getTime()))return!1;const a=new Date;a.setHours(23,59,59,999);const n=new Date(a);n.setDate(a.getDate()-6),n.setHours(0,0,0,0);const o=new Date(s);return o.setHours(0,0,0,0),o>=n&&o<=a}catch(s){return console.warn("⚠️ Failed to parse snapshot_date:",t,s),!1}},Zf=t=>t==null?"-":t>=1e6?(t/1e6).toFixed(1)+"M":t>=1e3?(t/1e3).toFixed(1)+"K":t.toString(),ey=t=>t==null?"-":`#${t}`,ty=(t,s)=>s===null?"winning":t===null?s!==null?"losing":"neutral":t<s?"winning":t>s?"losing":"neutral";function ix(t){const s=String(t||"").trim();return s?/^https?:\/\//i.test(s)?s:`https://${s}`:""}const sy=({myRank:t,compRank:s,landingPage:a})=>{const n=ty(t,s);if(s===null)return e.jsx("span",{className:"text-gray-400 font-mono text-xs",children:"-"});let o="flex items-center justify-center flex-1 px-2 py-1 rounded-md text-xs font-medium transition-colors";n==="losing"?o+=" bg-red-50 text-red-700 border border-red-100":n==="winning"?o+=" bg-emerald-50 text-emerald-700 border border-emerald-100":o+=" bg-gray-50 text-gray-600";const i=a?ix(a):"";return e.jsxs("div",{className:"flex items-center gap-1.5 w-full",children:[e.jsx("div",{className:o,children:e.jsxs("span",{className:"font-mono",children:["#",s]})}),i?e.jsxs("a",{href:i,target:"_blank",rel:"noopener noreferrer",onClick:l=>l.stopPropagation(),className:"text-slate-400 hover:text-blue-600 flex-shrink-0",title:"Open landing page",children:[e.jsx("span",{className:"sr-only",children:"Open landing page"}),e.jsx(ns,{className:"w-3 h-3"})]}):e.jsx("span",{className:"w-3 h-3 flex-shrink-0"})]})},ay=({rank:t,landingPage:s})=>{const a=s?ix(s):"";return e.jsxs("div",{className:"flex items-center justify-between gap-1.5",children:[e.jsx("div",{className:Lt("inline-flex items-center justify-center min-w-[2rem] px-1.5 py-0.5 rounded font-bold text-xs",t!==null&&t<=3?"bg-indigo-600 text-white shadow-sm":t!==null&&t<=10?"bg-indigo-100 text-indigo-700":"text-gray-500 bg-gray-100"),children:ey(t)}),a?e.jsxs("a",{href:a,target:"_blank",rel:"noopener noreferrer",onClick:n=>n.stopPropagation(),className:"text-slate-400 hover:text-blue-600 flex-shrink-0",title:"Open landing page",children:[e.jsx("span",{className:"sr-only",children:"Open landing page"}),e.jsx(ns,{className:"w-3 h-3"})]}):e.jsx("span",{className:"w-3 h-3"})]})},ny=({competitors:t,selectedIds:s,onToggle:a,onSelectAll:n,onDeselectAll:o,numericFilters:i,onNumericFiltersChange:l})=>{const[c,d]=r.useState(!1),m=r.useRef(null);r.useEffect(()=>{const x=u=>{m.current&&!m.current.contains(u.target)&&d(!1)};return document.addEventListener("mousedown",x),()=>document.removeEventListener("mousedown",x)},[]);const h=s.length===t.length,p=(x,u,g)=>{const w=g===""?null:parseFloat(g);g!==""&&(isNaN(w)||w<0)||l({...i,[x]:{...i[x],[u]:w}})},f=x=>{l(x==="myRank"||x==="competitorRank"?{...i,[x]:{min:null,max:null}}:{...i,[x]:{min:null,max:null}})},b=x=>x.min!==null||x.max!==null,y=x=>x.max!==null;return e.jsxs("div",{className:"relative",ref:m,children:[e.jsxs("button",{onClick:()=>d(!c),className:"flex items-center justify-center gap-1.5 w-10 h-10 sm:w-auto 
29sm:h-auto sm:px-3 sm:py-2 text-sm font-medium text-gray-500 sm:text-gray-600 bg-gray-50 sm:bg-white border border-gray-200 rounded-xl sm:rounded-md hover:bg-gray-100 sm:hover:bg-gray-50 hover:text-gray-700 sm:hover:text-gray-800 transition-colors",title:"Filter Settings",children:[e.jsx(ci,{className:"w-4 h-4 sm:w-3.5 sm:h-3.5"}),e.jsx("span",{className:"hidden sm:inline",children:"Filters"}),e.jsxs("span",{className:"hidden sm:inline text-xs text-gray-400",children:[s.length,"/",t.length]})]}),c&&e.jsx("div",{className:"absolute right-0 top-full mt-1 w-[calc(100vw-2rem)] sm:w-[600px] max-w-[600px] bg-white border border-gray-200 rounded-lg shadow-xl z-[9999] max-h-[410px] overflow-hidden flex flex-col",children:e.jsxs("div",{className:"flex flex-1 min-h-0 overflow-hidden",children:[e.jsxs("div",{className:"w-1/2 border-r border-gray-200 flex flex-col min-h-0",children:[e.jsx("div",{className:"px-3 py-2 border-b border-gray-100 flex-shrink-0",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-xs font-medium text-gray-500",children:"Competitors"}),e.jsx("button",{onClick:h?o:n,className:"text-xs text-blue-600 hover:text-blue-700",children:h?"Deselect All":"Select All"})]})}),e.jsx("div",{className:"flex-1 overflow-y-auto py-1 min-h-0",children:t.map(x=>{const u=s.includes(x.id);return e.jsxs("button",{onClick:()=>a(x.id),className:"w-full flex items-center gap-2 px-3 py-2 text-sm hover:bg-gray-50 transition-colors",children:[e.jsx("div",{className:Lt("w-4 h-4 rounded border flex items-center justify-center flex-shrink-0",u?"bg-slate-800 border-slate-800":"border-gray-300"),children:u&&e.jsx(wt,{size:10,className:"text-white",strokeWidth:3})}),e.jsx("span",{className:"w-2 h-2 rounded-full flex-shrink-0",style:{backgroundColor:x.color}}),e.jsx("span",{className:"text-gray-700 truncate",children:x.domain})]},x.id)})})]}),e.jsxs("div",{className:"w-1/2 flex flex-col min-h-0",children:[e.jsx("div",{className:"px-3 py-2 border-b border-gray-100 flex-shrink-0",children:e.jsx("span",{className:"text-xs font-medium text-gray-500",children:"Numeric Filters"})}),e.jsxs("div",{className:"flex-1 overflow-y-auto px-3 py-3 space-y-4 min-h-0",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-xs font-medium text-gray-500",children:"Volume"}),b(i.volume)&&e.jsx("button",{onClick:()=>f("volume"),className:"text-xs text-blue-600 hover:text-blue-700",children:"Clear"})]}),e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx("input",{type:"number",min:"0",placeholder:"Min",value:i.volume.min??"",onChange:x=>p("volume","min",x.target.value),className:"flex-1 min-w-0 max-w-[120px] px-2 py-1.5 text-xs border border-gray-200 rounded focus:outline-none focus:ring-1 focus:ring-indigo-500"}),e.jsx("span",{className:"text-xs text-gray-400 flex-shrink-0",children:"-"}),e.jsx("input",{type:"number",min:"0",placeholder:"Max",value:i.volume.max??"",onChange:x=>p("volume","max",x.target.value),className:"flex-1 min-w-0 max-w-[120px] px-2 py-1.5 text-xs border border-gray-200 rounded focus:outline-none focus:ring-1 focus:ring-indigo-500"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-xs font-medium text-gray-500",children:"My Rank"}),y(i.myRank)&&e.jsx("button",{onClick:()=>f("myRank"),className:"text-xs text-blue-600 hover:text-blue-700",children:"Clear"})]}),e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx("span",{className:"text-xs text-gray-500 flex-shrink-0",children:"Rank before"}),e.jsx("input",{type:"number",min:"1",placeholder:"e.g. 10",value:i.myRank.max??"",onChange:x=>p("myRank","max",x.target.value),className:"flex-1 min-w-0 max-w-[120px] px-2 py-1.5 text-xs border border-gray-200 rounded focus:outline-none focus:ring-1 focus:ring-indigo-500"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-xs font-medium text-gray-500",children:"Competitor Rank"}),y(i.competitorRank)&&e.jsx("button",{onClick:()=>f("competitorRank"),className:"text-xs text-blue-600 hover:text-blue-700",children:"Clear"})]}),e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx("span",{className:"text-xs text-gray-500 flex-shrink-0",children:"Rank before"}),e.jsx("input",{type:"number",min:"1",placeholder:"e.g. 10",value:i.competitorRank.max??"",onChange:x=>p("competitorRank","max",x.target.value),className:"flex-1 min-w-0 max-w-[120px] px-2 py-1.5 text-xs border border-gray-200 rounded focus:outline-none focus:ring-1 focus:ring-indigo-500"})]})]})]})]})]})})]})},Ed=({disabled:t,competitorDomains:s,userDomain:a,rows:n,opportunityFilterKeys:o,onOpportunityFilterKeysChange:i,selectedKeywords:l,onSelectedKeywordsChange:c,highlighted:d=!1})=>{const[m,h]=r.useState(!1),p=r.useRef(null);r.useEffect(()=>{const E=N=>{p.current&&!p.current.contains(N.target)&&h(!1)};return document.addEventListener("mousedown",E),()=>document.removeEventListener("mousedown",E)},[]);const f=r.useMemo(()=>{try{return new rx({rows:n,userDomain:a,competitorDomains:s}).compute()}catch(E){return console.error("❌ Failed to compute keyword opportunities:",E),{competitorBrandKeywords:[],nonBrandCompet
29itorHasYouDont:[],nonBrandCompetitorOutranksYou:[],brandTokens:[]}}},[n,a,s]),b=r.useMemo(()=>({competitor_brand:f.competitorBrandKeywords.length,nonbrand_competitor_has_you_dont:f.nonBrandCompetitorHasYouDont.length,nonbrand_competitor_outranks_you:f.nonBrandCompetitorOutranksYou.length}),[f]),y=E=>E==="competitor_brand"?f.competitorBrandKeywords:E==="nonbrand_competitor_has_you_dont"?f.nonBrandCompetitorHasYouDont:f.nonBrandCompetitorOutranksYou,x=(E,N)=>Array.from(new Set([...E||[],...N||[]])),u=(E,N)=>{const S=new Set((N||[]).map(k=>(k||"").trim()));return(E||[]).filter(k=>!S.has((k||"").trim()))},g=E=>{if(!E||E.length===0)return!1;const N=new Set((l||[]).map(D=>(D||"").trim())),S=E.length,k=E.reduce((D,F)=>N.has((F||"").trim())?D+1:D,0);return k===0?!1:k===S?!0:"indeterminate"},w=E=>{if(t||!c)return;const N=y(E);if(g(N)===!0){i(o.filter(k=>k!==E)),c(u(l||[],N));return}o.includes(E)||i([...o,E]),c(x(l||[],N))},_=b.competitor_brand+b.nonbrand_competitor_has_you_dont+b.nonbrand_competitor_outranks_you;return e.jsxs("div",{className:"relative",ref:p,children:[e.jsxs("button",{onClick:()=>h(!m),disabled:t,className:Lt("flex items-center justify-center gap-1.5 w-10 h-10 sm:w-auto sm:h-auto sm:px-3 sm:py-2 text-sm font-medium rounded-xl sm:rounded-md transition-colors disabled:opacity-40 disabled:cursor-not-allowed",d?"text-indigo-600 bg-indigo-50 border border-indigo-200 hover:bg-indigo-100":"text-gray-500 sm:text-gray-600 bg-gray-50 sm:bg-white border border-gray-200 hover:bg-gray-100 sm:hover:bg-gray-50 hover:text-gray-700 sm:hover:text-gray-800"),title:"Quick Select","data-onboarding":"keywords-gap-quick-select",children:[e.jsx(Ks,{className:Lt("w-4 h-4 sm:w-3.5 sm:h-3.5",d?"text-indigo-500":"")}),e.jsx("span",{className:"hidden sm:inline",children:"Quick Select"}),e.jsx("span",{className:Lt("hidden sm:inline text-xs px-1.5 py-0.5 rounded-full",d?"bg-indigo-100 text-indigo-700":"text-gray-400"),children:_})]}),m&&e.jsxs("div",{className:"absolute right-0 top-full mt-1 w-[calc(100vw-2rem)] sm:w-[400px] max-w-[400px] bg-white border border-gray-200 rounded-lg shadow-lg z-[9999]",children:[e.jsx("div",{className:"px-3 py-2 border-b border-gray-100",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-xs font-medium text-gray-500",children:"Quick select"}),e.jsxs("span",{className:"text-xs text-gray-400",children:[l.length," selected"]})]})}),e.jsxs("div",{className:"py-2",children:[e.jsx("div",{onClick:()=>{b.competitor_brand>0&&w("competitor_brand")},className:`w-full text-left px-3 py-2 transition-colors ${b.competitor_brand===0?"opacity-50 cursor-not-allowed":"hover:bg-gray-50 cursor-pointer"}`,children:e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx("div",{onClick:E=>E.stopPropagation(),children:e.jsx(Kt,{checked:g(f.competitorBrandKeywords),onCheckedChange:()=>w("competitor_brand"),disabled:b.competitor_brand===0,"aria-label":"Toggle competitor brand keywords"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-sm font-medium text-gray-800",children:"Competitor brand keywords"}),e.jsx("div",{className:"text-xs text-gray-500",children:"Keywords containing competitor brand tokens"})]})]}),e.jsx("span",{className:"text-xs font-mono text-gray-500",children:b.competitor_brand})]})}),e.jsx("div",{onClick:()=>{b.nonbrand_competitor_has_you_dont>0&&w("nonbrand_competitor_has_you_dont")},"data-opportunity-button":"nonbrand_gaps",className:`w-full text-left px-3 py-2 transition-colors ${b.nonbrand_competitor_has_you_dont===0?"opacity-50 cursor-not-allowed":"hover:bg-gray-50 cursor-pointer"}`,children:e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx("div",{onClick:E=>E.stopPropagation(),children:e.jsx(Kt,{checked:g(f.nonBrandCompetitorHasYouDont),onCheckedChange:()=>w("nonbrand_competitor_has_you_dont"),disabled:b.nonbrand_competitor_has_you_dont===0,"aria-label":"Toggle non-brand gaps"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-sm font-medium text-gray-800",children:"Non-brand gaps (they rank, you don't)"}),e.jsx("div",{className:"text-xs text-gray-500",children:"Competitors have rank, you have no rank"})]})]}),e.jsx("span",{className:"text-xs font-mono text-gray-500",children:b.nonbrand_competitor_has_you_dont})]})}),e.jsx("div",{onClick:()=>{b.nonbrand_competitor_outranks_you>0&&w("nonbrand_competitor_outranks_you")},className:`w-full text-left px-3 py-2 transition-colors ${b.nonbrand_competitor_outranks_you===0?"opacity-50 cursor-not-allowed":"hover:bg-gray-50 cursor-pointer"}`,children:e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx("div",{onClick:E=>E.stopPropagation(),children:e.jsx(Kt,{checked:g(f.nonBrandCompet
29itorOutranksYou),onCheckedChange:()=>w("nonbrand_competitor_outranks_you"),disabled:b.nonbrand_competitor_outranks_you===0,"aria-label":"Toggle non-brand threats"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-sm font-medium text-gray-800",children:"Non-brand threats (they outrank you)"}),e.jsx("div",{className:"text-xs text-gray-500",children:"Competitors rank higher than you"})]})]}),e.jsx("span",{className:"text-xs font-mono text-gray-500",children:b.nonbrand_competitor_outranks_you})]})})]})]})]})},ry=`
30  .custom-scrollbar::-webkit-scrollbar {
31    height: 10px;
32    width: 10px;
33  }
34  .custom-scrollbar::-webkit-scrollbar-track {
35    background: #f1f5f9;
36    border-radius: 4px;
37  }
38  .custom-scrollbar::-webkit-scrollbar-thumb {
39    background: #cbd5e1;
40    border-radius: 4px;
41  }
42  .custom-scrollbar::-webkit-scrollbar-thumb:hover {
43    background: #94a3b8;
44  }
45`,Gi=({competitors:t,userDomain:s,selectedKeywords:a=[],onSelectedKeywordsChange:n,hiddenCompetitorsCount:o=0,dataRefreshKey:i,showOpportunities:l=!0,showSelectionActions:c=!0,enableRowSelection:d=!0,targetKeywords:m=[],onTargetKeywordsChange:h,referralCode:p,lastRefreshDate:f,onRefresh:b,isRefreshing:y=!1})=>{const[x,u]=r.useState([]),[g,w]=r.useState(0),[_,E]=r.useState(!1),[N,S]=r.useState({key:"volume",direction:"desc"}),[k,D]=r.useState(""),[F,R]=r.useState([]),[L,$]=r.useState({volume:{min:null,max:null},myRank:{min:null,max:null},competitorRank:{min:null,max:null}}),[H,K]=r.useState(1),[X,V]=r.useState(100),[P,A]=r.useState(!1),[C,I]=r.useState({}),[j,q]=r.useState([]),[T,M]=r.useState(!1),Z=r.useRef(!1),B=r.useRef(null),[ae,de]=r.useState(!1),[fe,se]=r.useState(!1),[z,U]=r.useState(50),[Q,me]=r.useState(!1),le=50,[O,ne]=r.useState({keyword:160,volume:80,myRank:100}),[ge,ze]=r.useState(null),Ke=r.useCallback((te,G)=>{te.preventDefault(),te.stopPropagation();const pe="touches"in te?te.touches[0].clientX:te.clientX,ce=O[G]||100;ze({column:G,startX:pe,startWidth:ce})},[O]);r.useEffect(()=>{if(!ge)return;const te=pe=>{const Y=("touches"in pe?pe.touches[0].clientX:pe.clientX)-ge.startX,xe=Math.max(60,Math.min(400,ge.startWidth+Y));ne(Ee=>({...Ee,[ge.column]:xe}))},G=()=>{ze(null)};return document.addEventListener("mousemove",te),document.addEventListener("mouseup",G),document.addEventListener("touchmove",te),document.addEventListener("touchend",G),()=>{document.removeEventListener("mousemove",te),document.removeEventListener("mouseup",G),document.removeEventListener("touchmove",te),document.removeEventListener("touchend",G)}},[ge]),r.useEffect(()=>{const te=()=>me(window.innerWidth<640);return te(),window.addEventListener("resize",te),()=>window.removeEventListener("resize",te)},[]),r.useEffect(()=>{const te=pe=>{de(pe.detail)},G=()=>{b&&b()};return window.addEventListener("mobile-filter-toggle",te),window.addEventListener("mobile-refresh-click",G),()=>{window.removeEventListener("mobile-filter-toggle",te),window.removeEventListener("mobile-refresh-click",G)}},[b]);const ie=v.useCallback(()=>{const te=ma();return te.length===0?{markets:[],mode:"none"}:te.length===1?{markets:te,mode:"single",single:te[0]}:{markets:te,mode:"batch"}},[]),ve=v.useCallback(()=>{I({}),q([]),M(!1)},[]);r.useEffect(()=>{i!=null&&ve()},[i,ve]),r.useEffect(()=>{const te=()=>w(ce=>ce+1),G=Oi(()=>te()),pe=So(()=>te());return()=>{G(),pe()}},[]),r.useEffect(()=>{ve()},[g,ve]);const we=r.useMemo(()=>t.map((te,G)=>({id:te.competitor,domain:te.competitor,color:Cd[G%Cd.length]})),[t]),Pe=r.useMemo(()=>we.filter(te=>x.includes(te.id)),[we,x]),Ae=r.useMemo(()=>Pe.map(te=>te.id),[Pe]);r.useEffect(()=>{we.length>0&&x.length===0&&u(we.map(te=>te.id))},[we]),r.useEffect(()=>{!Z.current&&Pe.length>0&&N.key==="volume"&&N.direction==="desc"&&(S({key:Pe[0].id,direction:"asc"}),Z.current=!0)},[Pe,N]);const ye=()=>{u(we.map(te=>te.id))},Te=()=>{u([])};r.useEffect(()=>{(async()=>{if(!T){if(p)try{console.log(`🔗 [KeywordGapTable] Fetching own keywords via referral API for code: ${p}`);const G=await k0(p);q(G.top_keywords||[]),M(!0);return}catch(G){console.error("❌ Failed to fetch own keywords via referral API:",G),q([]),M(!0);return}try{let G=ie();if(G.mode==="none"||G.markets.length===0){if(!await Pr({timeout_ms:5e3})){console.warn("⚠️ Markets not ready; skip fetching own keywords.");return}if(G=ie(),G.mode==="none"||G.markets.length===0){console.warn("⚠️ Still no markets after wait; skip fetching own keywords.");return}}const pe=$a(G.markets),ce=await qu(void 0,void 0,void 0,0,pe);q(ce.top_keywords||[]),M(!0)}catch(G){console.error("❌ Failed to fetch my top keywords:",G),M(!0)}}})()},[T,ie,g,p]),r.useEffect(()=>{(async()=>
45{if(x.length===0)return;const G=x.filter(pe=>!C[pe]);if(G.length!==0)try{if(A(!0),p)try{console.log(`🔗 [KeywordGapTable] Fetching competitor keywords via referral API for code: ${p}`,G);const xe=await N0(p,G),Ee=G.map(Ne=>({id:Ne,competitorKeywords:xe.competitors[Ne]||[]}));I(Ne=>{const Ce={...Ne};return Ee.forEach(De=>{Ce[De.id]=De.competitorKeywords}),Ce}),A(!1);return}catch(xe){console.error("❌ Failed to fetch competitor keywords via referral API:",xe),A(!1);return}let pe=ie();if(pe.mode==="none"||pe.markets.length===0){if(!await Pr({timeout_ms:5e3})){console.warn("⚠️ Markets not ready; skip fetching keyword gap data."),A(!1);return}if(pe=ie(),pe.mode==="none"||pe.markets.length===0){console.warn("⚠️ Still no markets after wait; skip fetching competitor keywords."),A(!1);return}}const ce=$a(pe.markets),Y=await Promise.all(G.map(async xe=>{const Ee=await vi(xe,ce,{includeMyRank:!1}).then(Ne=>({keywords:Ne.aggregated?.keywords_data||[]})).catch(Ne=>(console.error(`❌ Failed to fetch competitor keywords batch for ${xe}:`,Ne),{keywords:[]}));return{id:xe,competitorKeywords:Ee.keywords||[]}}));I(xe=>{const Ee={...xe};return Y.forEach(Ne=>{Ee[Ne.id]=Ne.competitorKeywords}),Ee})}catch(pe){console.error("❌ fetchAllKeywordsData: error",pe)}finally{A(!1)}})()},[x,C,ie,g,p]),r.useEffect(()=>{K(1)},[k,N,x,F,L]),r.useEffect(()=>{const te=B.current;te&&(te.scrollTop=0)},[H,X]);const Ie=te=>{u(G=>G.includes(te)?G.filter(pe=>pe!==te):[...G,te])},Oe=te=>{S(G=>({key:te,direction:G.key===te&&G.direction==="desc"?"asc":"desc"}))},J=te=>{n&&(a.includes(te)?n(a.filter(G=>G!==te)):n([...a,te]))},re=()=>{if(!n)return;const te=(H-1)*X,G=H*X,pe=W.slice(te,G).map(Y=>Y.keyword);if(pe.every(Y=>a.includes(Y))){const Y=a.filter(xe=>!pe.includes(xe));n(Y)}else{const Y=Array.from(new Set([...a,...pe]));n(Y)}},Se=()=>{if(!n)return;const te=W.map(pe=>pe.keyword);te.length>2e3&&!window.confirm(`This will select ${te.length} keywords. Continue?`)||n(te)},je=()=>{n&&(R([]),n([]))},he=()=>{const te=Y=>Y.myRank!==null?"ranked":Object.values(Y.competitorRanks).some(Ee=>Ee!=null)?"competitor":"unknown",G=["Keyword","Source","Volume",s||"You (Me)"];Pe.forEach(Y=>{G.push(Y.domain)});const pe=W.map(Y=>{const xe=[`"${Y.keyword.replace(/"/g,'""')}"`,te(Y),Y.volume??"",Y.myRank!==null&&Y.myRank!==void 0?`#${Y.myRank}`:""];return Pe.forEach(Ee=>{const Ne=Y.competitorRanks[Ee.id];xe.push(Ne!=null?`#${Ne}`:"")}),xe.join(",")}),ce=[G.join(","),...pe].join(`
46`);ar({filename:`keyword-gap-${new Date().toISOString().split("T")[0]}.csv`,content:ce,mimeType:"text/csv;charset=utf-8;"})},Re=v.useCallback(te=>{let G=[...te||[]];if(k){const pe=k.toLowerCase();G=G.filter(ce=>ce.keyword.toLowerCase().includes(pe))}return G=G.filter(pe=>{if((L.volume.min!==null||L.volume.max!==null)&&(pe.volume===null||L.volume.min!==null&&pe.volume<L.volume.min||L.volume.max!==null&&pe.volume>L.volume.max)||L.myRank.max!==null&&(pe.myRank===null||pe.myRank>L.myRank.max))return!1;if(L.competitorRank.max!==null){const ce=x.map(xe=>pe.competitorRanks[xe]).filter(xe=>xe!=null);if(ce.length===0||!ce.some(xe=>xe<=L.competitorRank.max))return!1}return!0}),G.sort((pe,ce)=>{const Y=N.direction==="asc"?1:-1;if(N.key==="volume"){const Ne=pe.volume||0,Ce=ce.volume||0;
46return Ne!==Ce?(Ne-Ce)*Y:pe.keyword.localeCompare(ce.keyword)}if(N.key==="myRank"){const Ne=pe.myRank===null?999999:pe.myRank,Ce=ce.myRank===null?999999:ce.myRank;return Ne!==Ce?(Ne-Ce)*Y:pe.keyword.localeCompare(ce.keyword)}const xe=N.key,Ee=[xe,...Ae.filter(Ne=>Ne!==xe)];for(const Ne of Ee){const Ce=pe.competitorRanks[Ne]??null,De=ce.competitorRanks[Ne]??null,Ge=Ce===null?999999:Ce,ee=De===null?999999:De;if(Ge!==ee)return(Ge-ee)*Y}return pe.keyword.localeCompare(ce.keyword)}),G},[Ae,L,k,x,N]),Me=r.useMemo(()=>new _d({myTopKeywords:j,competitorKeywordsData:C,selectedCompetitorIds:x,applySnapshotFreshnessGate:!0,isSnapshotFresh:Sd}).build(),[j,C,x]),Ze=r.useMemo(()=>new _d({myTopKeywords:j,competitorKeywordsData:C,selectedCompetitorIds:x,applySnapshotFreshnessGate:!1,isSnapshotFresh:Sd}).build(),[j,C,x]),Be=r.useMemo(()=>Re(Me),[Re,Me]),et=r.useMemo(()=>Re(Ze),[Re,Ze]),$e=r.useMemo(()=>{if(F.length===0)return Be;try{const G=new rx({rows:et,userDomain:s,competitorDomains:Pe.map(Y=>Y.domain)}).compute(),pe=new Set,ce=Y=>{(Y||[]).forEach(xe=>pe.add((xe||"").trim()))};return F.forEach(Y=>{Y==="competitor_brand"&&ce(G.competitorBrandKeywords),Y==="nonbrand_competitor_has_you_dont"&&ce(G.nonBrandCompetitorHasYouDont),Y==="nonbrand_competitor_outranks_you"&&ce(G.nonBrandCompetitorOutranksYou)}),pe.size===0?[]:Be.filter(Y=>pe.has((Y.keyword||"").trim()))}catch(te){return console.error("❌ Failed to apply opportunity filter:",te),Be}},[Be,et,F,s,Pe]),W=r.useMemo(()=>{if(!_||m.length===0)return $e;const te=new Set(m.map(G=>G.trim().toLowerCase()));return $e.filter(G=>te.has(G.keyword.trim().toLowerCase()))},[$e,_,m]);r.useMemo(()=>{const te=new Set(m.map(G=>G.trim().toLowerCase()));return G=>te.has(G.trim().toLowerCase())},[m]),Math.ceil(W.length/X);const ke=W.slice((H-1)*X,H*X),qe=r.useMemo(()=>W.slice(0,z),[W,z]),Qe=z<W.length,ct=r.useCallback(()=>{if(!B.current||!Qe)return;const{scrollTop:te,scrollHeight:G,clientHeight:pe}=B.current;G-te-pe<200&&U(ce=>Math.min(ce+le,W.length))},[Qe,W.length]);r.useEffect(()=>{U(50)},[k,N,x,F,L]);const pt=ke.length>0&&ke.every(te=>a.includes(te.keyword)),At=qe.length>0&&qe.every(te=>a.includes(te.keyword));return e.jsxs(e.Fragment,{children:[e.jsx("style",{children:ry}),e.jsx(Kf,{isOpen:fe,onClose:()=>se(!1),competitors:we,selectedCompetitorIds:x,onToggleCompetitor:Ie,onSelectAllCompetitors:ye,onDeselectAllCompetitors:Te,numericFilters:L,onNumericFiltersChange:$,onExport:he,exportDisabled:W.length===0}),e.jsxs("div",{className:"sm:bg-white sm:rounded-xl sm:shadow-sm sm:border sm:border-gray-200 flex flex-col h-full min-h-0 overflow-hidden relative bg-white",children:[e.jsxs("header",{className:"flex-shrink-0 sm:border-b sm:border-gray-200 bg-white",children:[e.jsx("div",{className:Lt("sm:hidden overflow-hidden transition-all duration-300 ease-in-out bg-gray-50",ae?"max-h-60 opacity-100 border-b border-gray-200":"max-h-0 opacity-0"),children:e.jsxs("div",{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Pt,{className:"absolute left-3 top-2.5 w-4 h-4 text-gray-400"}),e.jsx("input",{type:"text",placeholder:"Search keywords...",className:"w-full pl-9 pr-4 py-2 bg-white border border-gray-200 rounded-lg text-sm focus:outline-none focus:border-blue-500 focus:ring-1 focus:ring-blue-500",value:k,onChange:te=>D(te.target.value)})]}),e.jsxs("div",{className:"flex gap-2 overflow-x-auto pb-1",style:{scrollbarWidth:"none"},children:[l&&e.jsx(Ed,{disabled:!n||W.length===0,competitorDomains:Pe.map(te=>te.domain),userDomain:s,rows:et,opportunityFilterKeys:F,onOpportunityFilterKeysChange:R,selectedKeywords:a,onSelectedKeywordsChange:n,highlighted:!0}),e.jsxs("button",{onClick:()=>se(!0),className:"px-3 py-1.5 bg-white border border-gray-200 rounded-full text-xs font-medium text-gray-600 whitespace-nowrap flex items-center gap-1.5 hover:bg-gray-50 active:bg-gray-100 transition-colors",children:[e.jsx(ci,{className:"w-3.5 h-3.5"}),"Filters"]})]})]})}),e.jsxs("div",{className:"hidden sm:flex items-center justify-between gap-4 p-4",children:[e.jsxs("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[e.jsxs("div",{className:"relative w-64",children:[e.jsx("input",{type:"text",placeholder:"Search keywords...",className:"w-full pl-9 pr-3 py-2 bg-slate-100 border-none rounded-md text-sm focus:ring-2 focus:ring-indigo-500 transition-all",value:k,onChange:te=>D(te.target.value)}),e.jsx(Pt,{className:"absolute left-3 top-2.5 text-slate-400 w-4 h-4"})]}),P&&e.jsx(He,{className:"w-4 h-4 animate-spin text-slate-400"}),l&&e.jsx(Ed,{disabled:!n||W.length===0,competitorDomains:Pe.map(te=>te.domain),userDomain:s,rows:et,opportunityFilterKeys:F,onOpportunityFilterKeysChange:R,selectedKeywords:a,onSelectedKeywordsChange:n,highlighted:!0})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[c&&d&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{onClick:Se,disabled:!n||W.length===0,className:"flex items-center gap-1.5 px-3 py-2 text-sm font-medium text-gray-600 bg-white border border-gray-200 rounded-md hover:bg-gray-50 hover:text-gray-800 transition-colors disabled:opacity-50 disabled:cursor-not-allowed",title:"Select all filtered results",children:[e.jsx(wt,{className:"w-3.5 h-3.5"}),"Select all"]}),e.jsxs("button",{onClick:je,disabled:!n||a.length===0,className:"flex items-center gap-1.5 px-3 py-2 text-sm font-medium text-gray-600 bg-white border border-gray-200 rounded-md hover:bg-gray-50 hover:text-gray-800 transition-colors disabled:opacity-50 disabled:cursor-not-allowed",title:"Clear selection",children:[e.jsx(Ps,{className:"w-3.5 h-3.5"}),"Clear"]})]}),e.jsx(ny,{competitors:we,selectedIds:x,onToggle:Ie,onSelectAll:ye,onDeselectAll:Te,numericFilters:L,onNumericFiltersChange:$}),e.jsxs("button",{onClick:he,disabled:W.length===0,className:"flex items-center gap-1.5 px-3 py-2 text-sm font-medium text-gray-600 bg-white border border-gray-200 rounded-md hover:bg-gray-50 hover:text-gray-800 transition-colors disabled:opacity-50 disabled:cursor-not-allowed",title:"Export to CSV",children:[e.jsx(Vs,{className:"w-3.5 h-3.5"}),"Export"]})]})]})]}),e.jsxs("div",{ref:B,onScroll:Q?ct:void 0,className:Lt("flex-1 min-h-0 overflow-auto custom-scrollbar relative pb-28 sm:pb-0 bg-white",ge&&"select-none cursor-col-resize"),children:[e.jsxs("table",{className:"w-full border-collapse text-left min-w-max",style:{tableLayout:"fixed"},children:[e.jsx("thead",{className:"bg-gray-50 border-b border-gray-200 sticky top-0 z-30 text-xs font-semibold text-gray-500 uppercase tracking-wider shadow-[0_1px_2px_rgba(0,0,0,0.05)]",children:e.jsxs("tr",{children:[d&&e.jsx("th",{className:"sticky left-0 top-0 bg-gray-50 w-[40px] min-w-[40px] px-2 py-2 border-r border-gray-200 border-b z-20",children:e.jsx("div",{className:"flex items-center justify-center",children:e.jsx(Kt,{checked:Q?At:pt,onCheckedChange:Q?()=>{if(!n)return;const te=qe.map(G=>G.keyword);if(At){const G=a.filter(pe=>!te.includes(pe));n(G)}else{const G=Array.from(new Set([...a,...te]));n(G)}}:re,"aria-label":"Select all"})})}),e.jsxs("th",{className:"sticky bg-gray-50 px-3 py-2 border-b border-gray-200 shadow-[4px_0_8px_-4px_rgba(0,0,0,0.1)] z-10 relative group/resize",style:{left:d?40:0,width:O.keyword,minWidth:O.keyword},children:["Keyword",e.jsx("div",{className:"absolute right-0 top-0 bottom-0 w-1 cursor-col-resize hover:bg-blue-400 active:bg-blue-500 opacity-0 group-hover/resize:opacity-100 transition-opacity",onMouseDown:te=>Ke(te,"keyword"),onTouchStart:te=>Ke(te,"keyword")})]}),e.jsxs("th",{className:"px-2 py-2 cursor-pointer hover:text-indigo-600 border-b border-gray-200 relative group/resize",style:{width:O.volume,minWidth:O.volume},onClick:()=>Oe("volume"),children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"sm:hidden",children:"Vol"}),e.jsx("span",{className:"hidden sm:inline",children:"Volume"}),N.key==="volume"&&(N.direction==="desc"?e.jsx(Ws,{size:12}):e.jsx(Is,{size:12}))]}),e.jsx("div",{className:"absolute right-0 top-0 bottom-0 w-1 cursor-col-resize hover:bg-blue-400 active:bg-blue-500 opacity-0 group-hover/resize:opacity-100 transition-opacity",onMouseDown:te=>{te.stopPropagation(),Ke(te,"volume")},onTouchStart:te=>{te.stopPropagation(),Ke(te,"volume")}})]}),e.jsxs("th",{className:"bg-indigo-50 px-2 py-2 font-semibold text-xs tracking-wider text-indigo-700 cursor-pointer hover:bg-indigo-100 transition-colors border-r border-gray-200 border-b relative group/resize",style:{width:O.myRank,minWidth:O.myRank},onClick:()=>Oe("myRank"),children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"truncate max-w-[60px] sm:max-w-[100px]",title:s||"You",children:s||"You"}),N.key==="myRank"&&(N.direction==="asc"?e.jsx(Ws,{size:12}):e.jsx(Is,{size:12}))]}),e.jsx("div",{className:"absolute right-0 top-0 bottom-0 w-1 cursor-col-resize hover:bg-blue-400 active:bg-blue-500 opacity-0 group-hover/resize:opacity-100 transition-opacity",onMouseDown:te=>{te.stopPropagation(),Ke(te,"myRank")},onTouchStart:te=>{te.stopPropagation(),Ke(te,"myRank")}})]}),Pe.length===0&&o===0?e.jsx("th",{className:"px-3 py-2 text-xs text-gray-400 font-normal italic border-b border-gray-200",children:"Select competitors to compare..."}):Pe.map(te=>e.jsxs("th",{className:"px-2 py-1.5 bg-white cursor-pointer transition-colors hover:bg-gray-50 group border-r border-gray-100 border-b border-gray-200 relative group/resize",style:{width:O[te.id]||120,minWidth:O[te.id]||120},onClick:()=>Oe(te.id),children:[e.jsxs("div",{className:"flex items-center justify-between gap-1",children:[e.jsxs("div",{className:"flex items-center gap-1.5 min-w-0",children:[e.jsx("span",{className:"w-2 h-2 rounded-full flex-shrink-0",style:{backgroundColor:te.color}}),e.jsx("span",{className:"text-xs font-semibold text-gray-700 truncate",children:te.domain})]}),e.jsx("span",{className:"text-gray-300 group-hover:text-gray-500 transition-colors flex-shrink-0",children:N.key===te.id?N.direction==="asc"?e.jsx(Ws,{size:12}):e.jsx(Is,{size:12}):e.jsx(dn,{size:12,className:"opacity-0 group-hover:opacity-100"})})]}),e.jsx("div",{className:"absolute right-0 top-0 bottom-0 w-1 cursor-col-resize hover:bg-blue-400 active:bg-blue-500 opacity-0 group-hover/resize:opacity-100 transition-opacity",onMouseDown:G=>{G.stopPropagation(),Ke(G,te.id)},onTouchStart:G=>{G.stopPropagation(),Ke(G,te.id)}})]},te.id)),o>0&&e.jsxs(e.Fragment,{children:[e.jsx("th",{className:"w-[120px] min-w-[120px] sm:w-[140px] px-2 py-1.5 bg-white border-r border-gray-100 opacity-50 select-none border-b border-gray-200",children:e.jsx("div",{className:"h-3 bg-gray-100 rounded w-20"})}),e.jsx("th",{className:"w-[120px] min-w-[120px] sm:w-[140px] px-2 py-1.5 bg-white border-r border-gray-100 opacity-50 select-none border-b border-gray-200",children:e.jsx("div",{className:"h-3 bg-gray-100 rounded w-24"})}),e.jsx("th",{className:"w-[120px] min-w-[120px] sm:w-[140px] px-2 py-1.5 bg-white border-r border-gray-100 opacity-50 select-none border-b border-gray-200",children:e.jsx("div",{className:"h-3 bg-gray-100 rounded w-16"})})]})]})}),e.jsxs("tbody",{className:"divide-y divide-gray-100 border-b border-gray-200",children:[(Q?qe:ke).map(te=>{const G=a.includes(te.keyword);return e.jsxs("tr",{className:Lt("transition-colors group",G?"bg-blue-50/50":"bg-white hover:bg-gray-50/50"),children:[d&&e.jsx("td",{className:"sticky left-0 bg-white group-hover:bg-gray-50 px-2 py-2 border-r border-gray-100 z-10",style:{backgroundColor:G?"rgb(239 246 255 / 0.5)":void 0},children:e.jsx("div",{className:"flex items-center justify-center",children:e.jsx(Kt,{checked:G,onCheckedChange:()=>J(te.keyword)})})}),e.jsx("td",{className:"sticky bg-white group-hover:bg-gray-50 px-3 py-2 shadow-[4px_0_8px_-4px_rgba(0,0,0,0.05)] border-r border-gray-100 z-10",style:{left:d?40:0,backgroundColor:G?"rgb(239 246 255 / 0.5)":void 0,width:O.keyword,minWidth:O.keyword,maxWidth:O.keyword},children:e.jsx("div",{className:"font-medium text-xs text-gray-900 truncate",children:te.keyword})}),e.jsx("td",{className:"px-2 py-2 text-xs text-gray-600 border-r border-gray-100",style:{width:O.volume,minWidth:O.volume},children:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Sn,{className:"w-3 h-3 text-gray-400"}),Zf(te.volume)]})}),e.jsx("td",{className:"bg-indigo-50 group-hover:bg-indigo-100 px-2 py-2 border-r border-gray-200",style:{width:O.myRank,minWidth:O.myRank},children:e.jsx(ay,{rank:te.myRank,landingPage:te.myLandingPage})}),Pe.length===0&&o===0?e.jsx("td",{className:"px-3 py-4 text-center text-gray-400 bg-gray-50/50",children:e.jsxs("div",{className:"flex flex-col items-center gap-1.5",children:[e.jsx(Ss,{className:"w-4 h-4 opacity-50"}),e.jsx("span",{className:"text-xs",children:"Select a competitor"})]})}):Pe.map(pe=>e.jsx("td",{className:"px-2 py-2 border-r border-gray-100",style:{width:O[pe.id]||120,minWidth:O[pe.id]||120},children:e.jsx(sy,{myRank:te.myRank,compRank:te.competitorRanks[pe.id]??null,landingPage:te.competitorLandingPages[pe.id]??null})},pe.id)),o>0&&e.jsxs(e.Fragment,{children:[e.jsx("td",{className:"px-2 py-2 border-r border-gray-100 opacity-30 select-none blur-[2px]",children:e.jsxs("div",{className:"flex items-center justify-between w-full px-2 py-1 rounded-md bg-gray-50 text-gray-400",children:[e.jsx("span",{className:"text-xs",children:"#--"}),e.jsx(Ps,{className:"w-3 h-3"})]})}),e.jsx("td",{className:"px-2 py-2 border-r border-gray-100 opacity-30 select-none blur-[2px]",children:e.jsxs("div",{className:"flex items-center justify-between w-full px-2 py-1 rounded-md bg-gray-50 text-gray-400",children:[e.jsx("span",{className:"text-xs",children:"#--"}),e.jsx(Ps,{className:"w-3 h-3"})]})}),e.jsx("td",{className:"px-2 py-2 border-r border-gray-100 opacity-30 select-none blur-[2px]",children:e.jsxs("div",{className:"flex items-center justify-between w-full px-2 py-1 rounded-md bg-gray-50 text-gray-400",children:[e.jsx("span",{className:"text-xs",children:"#--"}),e.jsx(Ps,{className:"w-3 h-3"})]})})]})]},te.id)}),W.length===0&&!P&&e.jsx("tr",{children:e.jsx("td",{colSpan:4+Pe.length+(o>0?3:0),className:"px-4 py-8 text-center text-gray-500 text-xs",children:k?`No keywords foun
46d matching "${k}"`:x.length===0&&o===0?"Select competitors to see keyword gaps":"No keyword data found. Try refreshing competitor data."})})]})]}),Q&&Qe&&e.jsxs("div",{className:"flex items-center justify-center py-4 text-gray-400",children:[e.jsx(He,{className:"w-5 h-5 animate-spin mr-2"}),e.jsx("span",{className:"text-sm",children:"Loading more..."})]}),Q&&!Qe&&W.length>0&&e.jsxs("div",{className:"text-center py-4 text-gray-400 text-sm",children:[W.length," keywords total"]}),Q&&e.jsx("div",{className:"h-20"}),o>0&&e.jsx("div",{className:"fixed inset-y-0 flex items-center justify-center bg-white/60 backdrop-blur-[1px] border-l border-slate-100 pointer-events-auto",style:{right:0}})]}),e.jsx("div",{className:"hidden sm:block flex-shrink-0 border-t border-gray-200",children:e.jsx(xn,{page:H,pageSize:X,total:W.length,onPageChange:K,onPageSizeChange:V,onPageSizeChangeWithReset:te=>{V(te),K(1)},pageSizeOptions:[10,20,50,100,200],variant:"gray",className:"rounded-none border-0"})})]})]})},ol=t=>t==null?"-":t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:t.toLocaleString(),lx=({competitors:t,userDomain:s,onDeleteCompetitor:a,onRefreshCompetitor:n,onCompetitorClick:o,className:i="",refreshingDomain:l,refreshingDomains:c})=>{const d=t,m=[s?.keywords||0,...d.map(u=>u.keywords||0)],h=[s?.traffic||0,...d.map(u=>u.est_traffic||0)],p=Math.max(...m,1),f=Math.max(...h,1);if(d.length===0&&!s)return e.jsx("div",{className:"text-xs text-slate-400 text-center py-8",children:"No competitors analyzed"});const b=u=>{if(!u)return"-";try{return new Date(u).toLocaleDateString("en-US",{year:"numeric",month:"short",day:"numeric"})}catch{return"-"}},y=[...s?[{isUser:!0,domain:s.domain,keywords:s.keywords||0,rankedKeywords:0,traffic:s.traffic||0,sharedKeywords:0,overlap:1,lastSyncedAt:null,originalItem:null}]:[],...d.map(u=>({isUser:!1,domain:u.competitor,keywords:u.keywords||0,rankedKeywords:u.ranked_keywords_count||0,traffic:u.est_traffic||0,sharedKeywords:u.shared_keywords||0,overlap:u.overlap||0,lastSyncedAt:u.last_synced_at||null,originalItem:u}))],x=!!(a||n||o);return e.jsx("div",{className:`overflow-x-auto ${i}`,children:e.jsxs("div",{className:"min-w-[800px]",children:[e.jsxs("div",{className:"sticky top-0 z-10 grid grid-cols-[minmax(0,1fr)_minmax(0,1fr)_minmax(0,1fr)_minmax(0,1fr)_130px] gap-3 px-3 py-3 bg-slate-100 border border-slate-200 rounded-t-lg text-[11px] text-slate-700 font-bold uppercase tracking-wider shadow-sm",children:[e.jsx("div",{children:"Domain"}),e.jsx("div",{children:"Keywords"}),e.jsx("div",{children:"Overlap Keywords"}),e.jsx("div",{children:"Est. Traffic"}),e.jsx("div",{className:"text-center",children:"Last Refresh"})]}),e.jsx("div",{children:y.map((u,g)=>{const w=p>0?u.keywords/p*100:0,_=Math.min(u.overlap*100,100),E=f>0?u.traffic/f*100:0,N=l===u.domain||c?.has(u.domain);return e.jsxs("div",{className:`group px-3 relative grid grid-cols-[minmax(0,1fr)_minmax(0,1fr)_minmax(0,1fr)_minmax(0,1fr)_130px] gap-3 h-12 items-center ${u.isUser?"bg-slate-50 border-x border-slate-100":`hover:bg-slate-50 transition-colors border-t border-x border-slate-100 ${o?"cursor-pointer":""}`} ${g===y.length-1?"rounded-b-lg border-b":""}`,onClick:()=>{o&&!u.isUser&&u.originalItem&&o(u.originalItem)},children:[e.jsx("div",{className:"flex items-center gap-2 min-w-0",children:e.jsxs("div",{className:`flex items-center gap-2 min-w-0 ${o&&!u.isUser?"group-hover:text-blue-600 transition-colors":""}`,children:[e.jsx("span",{className:`text-[11px] truncate ${u.isUser?"text-slate-800 font-semibold":"text-slate-700 font-medium"}`,title:u.domain,children:u.domain}),u.isUser&&e.jsx("span",{className:"text-[9px] bg-slate-800 text-white px-1.5 py-0.5 rounded font-medium flex-shrink-0",children:"YOU"})]})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:`flex-1 rounded h-2.5 overflow-hidden ${u.isUser?"bg-slate-200":"bg-slate-100"}`,children:e.jsx("div",{className:`h-full rounded ${u.isUser?"bg-slate-800":"bg-slate-400"}`,style:{width:`${w}%`}})}),e.jsx("span",{className:`text-[11px] w-12 text-right ${u.isUser?"text-slate-800 font-semibold":"text-slate-600 font-medium"}`,children:ol(u.keywords)})]}),e.jsx("div",{className:"flex items-center gap-2",children:u.isUser?e.jsx("div",{className:"flex-1"}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"flex-1 bg-red-50 rounded h-2.5 overflow-hidden",children:e.jsx("div",{className:"h-full bg-red-300 rounded",style:{width:`${_}%`}})}),e.jsxs("span",{className:"text-[11px] text-red-500 font-medium w-20 text-right",children:[ol(u.sharedKeywords)," (",u.overlap*100<1&&u.overlap>0?"<1":(u.overlap*100).toFixed(0),"%)"]})]})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:`flex-1 rounded h-2.5 overflow-hidden ${u.isUser?"bg-slate-200":"bg-slate-100"}`,children:e.jsx("div",{className:`h-full rounded ${u.isUser?"bg-slate-800":"bg-slate-400"}`,style:{width:`${E}%`}})}),e.jsx("span",{className:`text-[11px] w-12 text-right ${u.isUser?"text-slate-800 font-semibold":"text-slate-600 font-medium"}`,children:ol(u.traffic)})]}),e.jsx("div",{className:"flex items-center justify-center",children:u.isUser?e.jsx("span",{className:"text-[11px] text-slate-400",children:"-"}):e.jsx("span",{className:"text-[11px] text-slate-600 whitespace-nowrap",children:b(u.lastSyncedAt)})}),!u.isUser&&x&&e.jsxs("div",{className:"absolute right-1 top-1/2 -translate-y-1/2 flex items-center gap-1 bg-white pl-2 opacity-0 group-hover:opacity-100 transition-opacity shadow-sm border border-slate-100 rounded-lg py-1 pr-1 z-10",children:[n&&e.jsx("button",{onClick:S=>{S.stopPropagation(),n(u.domain)},disabled:N,className:"p-1 text-slate-400 hover:text-slate-600 hover:bg-slate-100 rounded transition-colors disabled:opacity-50",title:"Refresh data",children:e.jsx(kt,{size:12,className:N?"animate-spin":""})}),a&&e.jsx("button",{onClick:S=>{S.stopPropagation(),a(u.domain)},className:"p-1 text-slate-400 hover:text-red-600 hover:bg-red-50 rounded transition-colors",title:"Delete competitor",children:e.jsx(es,{size:12})}),o&&e.jsx("button",{onClick:S=>{S.stopPropagation(),u.originalItem&&o(u.originalItem)},className:"p-1 text-slate-400 hover:text-blue-600 hover:bg-blue-50 rounded transition-colors",title:"View details",children:e.jsx(Ms,{size:12})})]})]},g)})})]})})};function oy({competitors:t,summary:s,hasActivePlan:a=!1,userDomain:n,referralCode:o}){const i=!a,l=i&&t.length>1?t.length-1:0,c=r.useMemo(()=>t.map(m=>{const h=m.ranked_keywords_count??m.keywords??0,p=Math.max(h-(m.shared_keywords||0),0),f=h>0?Math.round(p/h*100):0;return{...m,distinct_keywords:p,distinct_percent:f,last_synced_at:"last_synced_at"in m?m.last_synced_at??null:null}}),[t]),d=r.useMemo(()=>c.reduce((m,h)=>m+h.distinct_keywords,0),[c]);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(Pf,{summary:s,compact:!0,gapLabel:"Opportunity",gapValueOverride:d}),c.length>0&&e.jsxs("div",{className:"relative overflow-hidden rounded-xl mt-4",children:[e.jsx(lx,{competitors:i?c.slice(0,1):c,userDomain:typeof n=="string"?void 0:n}),l>
460&&e.jsxs("div",{className:"absolute inset-x-0 bottom-0 top-[60px] z-40 bg-white/70 backdrop-blur-[1px]",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-b from-white/60 via-white/90 to-white"}),e.jsx("div",{className:"relative h-full flex items-center justify-center px-6",children:e.jsxs("div",{className:"text-center",children:[e.jsxs("div",{className:"text-[12px] font-semibold text-slate-800",children:[l," More Competitors Hidden"]}),e.jsx("div",{className:"text-[11px] text-slate-500 mt-1",children:"Upgrade to view the full competitor list"})]})})]})]}),c.length>0&&e.jsx("div",{className:"relative overflow-hidden rounded-xl h-[800px] flex flex-col",children:e.jsx(Gi,{competitors:i?c.slice(0,1):c,userDomain:typeof n=="string"?n:n?.domain,hiddenCompetitorsCount:l,showOpportunities:!1,showSelectionActions:!1,enableRowSelection:!1,referralCode:o})})]})}function Wi({analysisResult:t,showPlanMask:s,onRequestReAnalyze:a,onContinue:n,continueText:o="Go to Homepage",showMarketTabs:i=!0,showContinueButton:l=!0,referralCode:c,customTopButton:d,customBottomButton:m}){const{toast:h}=_t(),[p,f]=r.useState(t),[b,y]=r.useState(!1);r.useEffect(()=>{f(t)},[t]);const x=r.useCallback(async()=>{try{const k=await sr();
46if(!k)throw new Error("No analysis result available for this market.");f(k),console.log("🌍 Market switched, report data refreshed")}catch(k){console.warn("⚠️ Failed to refresh report after market switch:",k),h({title:"Failed to switch market",description:k?.message||"Could not load analysis data for the selected market. Please try again."})}},[h]),u=r.useCallback(async k=>{y(!0);try{await x()}finally{y(!1)}},[x]),g=r.useMemo(()=>p?.competitors?p.competitors.details:null,[p]),w=r.useMemo(()=>{if(p?.seo_overview)return{domain:p.seo_overview.domain,keywords:p.seo_overview.kpis?.ranking_keywords||null,traffic:p.seo_overview.kpis?.organic_traffic||null}},[p]),_=()=>{a?a():jt("setup")},E=()=>{n?n():jt("keyword_research")},N=p.competitors?.location_code??p.seo_overview?.top_keywords?.[0]?.location_code??void 0,S=p.competitors?.language_code??p.seo_overview?.top_keywords?.[0]?.language_code??void 0;return e.jsxs("div",{className:"space-y-8 pb-10",children:[d&&e.jsx("div",{className:"flex justify-center pb-4",children:d}),i&&e.jsx("div",{className:"sticky top-16 z-41 bg-slate-50/80 backdrop-blur supports-[backdrop-filter]:bg-slate-50/70 py-2",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(Cf,{onMarketChange:u,sticky:!1}),b&&e.jsx("div",{className:"text-[12px] text-slate-500 text-right",children:"Updating market..."})]})}),e.jsxs("section",{className:"mb-4",children:[e.jsx("div",{className:"flex items-center justify-between mb-2",children:e.jsx("h2",{className:"text-xl font-bold text-slate-900",children:"Company Analysis"})}),e.jsx("div",{className:"bg-white border border-slate-100 rounded-xl p-4",children:e.jsx(Ef,{company:p.company,seoOverview:p.seo_overview?{kpis:p.seo_overview.kpis}:void 0,mode:"result",onRequestReAnalyze:_,isAnalyzing:!1,initialLocationCode:N,initialLanguageCode:S})})]}),p.competitors&&e.jsxs("section",{className:"mb-4",children:[e.jsx("div",{className:"flex items-center justify-between mb-2",children:e.jsx("h2",{className:"text-xl font-bold text-slate-900",children:"Competitor Analysis"})}),e.jsx("div",{className:"bg-white border border-slate-100 rounded-xl p-4",children:e.jsx(oy,{competitors:g||[],summary:p.competitors.summary,hasActivePlan:!s,userDomain:w,referralCode:c})})]}),m?e.jsx("div",{className:"flex justify-center pt-4",children:m}):l&&e.jsx("div",{className:"flex justify-end pt-4",children:e.jsxs(be,{onClick:E,className:"rounded-xl",size:"lg",children:[o,e.jsx(Ms,{className:"ml-2 h-4 w-4"})]})})]})}function iy(){const{connected:t,apiBaseUrl:s,disconnect:a}=Fi(),[n,o]=v.useState(""),[i,l]=v.useState(null),[c,d]=v.useState(""),[m,h]=v.useState(""),[p,f]=v.useState(!1),[b,y]=v.useState(""),[x,u]=v.useState(3),[g,w]=v.useState(!1),[_,E]=v.useState(null),[N,S]=v.useState(null),[k,D]=v.useState(""),[F,R]=v.useState([]),[L,$]=v.useState(1),[H,K]=v.useState(1),[X,V]=v.useState(0),[P,A]=v.useState(!1),[C,I]=v.useState(""),[j,q]=v.useState(!1),[T,M]=v.useState(""),[Z,B]=v.useState(!1),[ae,de]=v.useState(""),[fe,se]=v.useState(!1),[z,U]=v.useState(null),[Q,me]=v.useState(!1),[le,O]=v.useState(!1),[ne,ge]=v.useState(null),[ze,Ke]=v.useState(!1),[ie,ve]=v.useState(""),[we,Pe]=v.useState(""),[Ae,ye]=v.useState(!1),[Te,Ie]=v.useState(""),[Oe,J]=v.useState(null),[re,Se]=v.useState(null),je=ee=>ee?new Date(ee).toLocaleString():"N/A",he=()=>{const ee=new Date,Fe=Xe=>String(Xe).padStart(2,"0");return`${ee.getFullYear()}${Fe(ee.getMonth()+1)}${Fe(ee.getDate())}_${Fe(ee.getHours())}${Fe(ee.getMinutes())}${Fe(ee.getSeconds())}`},Re=ee=>{const Fe=ee==null?"":String(ee).replace(/\r\n/g,`
47`).replace(/\r/g,`
48`),Xe=/[",\n]/.test(Fe),yt=Fe.replace(/"/g,'""');return Xe?`"${yt}"`:yt},Me=(ee,Fe)=>{const Xe=ee.map(Re).join(","),yt=Fe.map(ut=>ut.map(Re).join(","));return[Xe,...yt].join(`\r
49`)},Ze=async()=>{const Fe=await ca("/api/admin/referral/list",{page:1,page_size:100},void 0,s),Xe=[...Fe.codes||[]],yt=Math.max(Fe.total_pages||1,1);for(let ut=2;ut<=yt;ut+=1){const It=await ca("/api/admin/referral/list",{page:ut,page_size:100},void 0,s);Xe.push(...It.codes||[])}return Xe},Be=ee=>{const Fe=["code","company_url","report_link","analysis_status","use_count","competitors_count","ranked_keywords_total","company_id","analysis_error","bulk_run_id","bulk_index","created_at"],Xe=ee.map(ut=>[ut.code,ut.company_url,ue(ut.company_url,ut.code),ut.analysis_status,ut.use_count,ut.competitors_count??"",ut.ranked_keywords_total??"",ut.company_id,ut.analysis_error,ut.bulk_run_id??"",ut.bulk_index??"",ut.created_at]),yt=Me(Fe,Xe);ar({filename:`referral_codes_${he()}.csv`,content:yt,mimeType:"text/csv;charset=utf-8;"})},et=(ee,Fe)=>{const Xe=["batch_id","index","code","company_url","report_link"],yt=ee.map(It=>[Fe,It.index??"",It.code,It.company_url,ue(It.company_url,It.code)]),ut=Me(Xe,yt);ar({filename:`referral_bulk_generated_codes_${he()}.csv`,content:ut,mimeType:"text/csv;charset=utf-8;"})},$e=ee=>{try{return(new URL(ee).hostname.replace(/^www\./i,"").split(".").filter(
49Boolean)[0]||"").toLowerCase().trim().replace(/[\s_]+/g,"-").replace(/[^a-z0-9-]/g,"").replace(/-+/g,"-").replace(/^-+|-+$/g,"")||"company"}catch{return"company"}},ue=(ee,Fe)=>{if(typeof window>"u")return"";const{protocol:Xe,host:yt}=window.location,ut=$e(ee);return`${Xe}//${yt}/geo-report/${ut}/${Fe}`},W=(ee,Fe)=>`/geo-report/${$e(ee)}/${Fe}`,ke=(ee,Fe=3,Xe=3)=>{const yt=(ee||"").trim();return yt?yt.length<=Fe+Xe+3?yt:`${yt.slice(0,Fe)}...${yt.slice(-Xe)}`:"—"},qe=async ee=>{try{await navigator.clipboard.writeText(ee)}catch(Fe){console.error("Failed to copy:",Fe)}},Qe=ee=>{switch(ee){case"pending":return"bg-amber-100 text-amber-700";case"processing":return"bg-blue-100 text-blue-700";case"completed":return"bg-green-100 text-green-700";case"failed":return"bg-red-100 text-red-700";default:return"bg-gray-100 text-gray-700"}},ct=()=>{R([]),l(null),a()},pt=v.useCallback(async()=>{if(t){A(!0),I("");try{const ee=await ca("/api/admin/referral/list",{page:L,page_size:20},void 0,s);R(ee.codes),K(ee.total_pages),V(ee.total)}catch(ee){I(`Failed to connect: ${ee.message||"Network error"}`)}finally{A(!1)}}},[t,s,L]),At=async()=>{if(t&&!(typeof window>"u")&&!j){M(""),q(!0),console.info("📤 Exporting referral codes (all pages)...");try{const ee=await Ze();Be(ee),console.info(`✅ Exported referral codes: ${ee.length}`)}catch(ee){console.error("❌ Failed to export referral codes:",ee),M(`Export failed: ${ee?.message||"Network error"}`)}finally{q(!1)}}},te=async()=>{if(typeof window>"u"||Z)return;const ee=N?.successes||[];if(!ee.length)return;const Fe=String(N?.batch_id||_||"");de(""),B(!0),console.info("📤 Exporting bulk generated codes...");try{et(ee,Fe),console.info(`✅ Exported bulk generated codes: ${ee.length}`)}catch(Xe){console.error("❌ Failed to export bulk generated codes:",Xe),de(`Export failed: ${Xe?.message||"Unexpected error"}`)}finally{B(!1)}};v.useEffect(()=>{t&&pt()},[t,L,pt]);const G=async()=>{if(!n.trim()){h("Please enter a company URL");return}f(!0),h(""),l(null),d("");try{const ee=await Yn("/api/admin/referral/generate",{company_url:n.trim()},void 0,s);l(ee.code),d(String(ee.company_url||n.trim())),o(""),pt()}catch(ee){h(`Failed to connect: ${ee.message||"Network error"}`)}finally{f(!1)}}
49,pe=ee=>ee.split(/\r?\n/).map(Fe=>Fe.trim()).filter(Boolean),ce=ee=>ee.split(/\r?\n/).map(Fe=>Fe.trim()).filter(Boolean),Y=async()=>{const ee=pe(b);if(ee.length===0){D("Please paste at least one company URL (one per line)");return}w(!0),D(""),E(null),S(null);try{const Fe=await Yn("/api/admin/referral/bulk_generate",{company_urls:ee,concurrency:x},void 0,s);E(Fe.task_id)}catch(Fe){D(Fe?.message||"Failed to start bulk generate task")}finally{w(!1)}};v.useCallback(async()=>{if(_)try{const ee=await ca(`/api/admin/referral/bulk_task/${_}/status`,void 0,void 0,s);S(ee),ee.status==="done"&&pt()}catch(ee){D(ee?.message||"Failed to load bulk task status")}},[_,s,pt]),v.useEffect(()=>{if(!_)return;let ee=null,Fe=!1;const Xe=ut=>ut==="done"||ut==="failed"||ut==="error",yt=async()=>{if(!Fe)try{const ut=await ca(`/api/admin/referral/bulk_task/${_}/status`,void 0,void 0,s);S(ut),ut.status==="done"&&pt(),Xe(ut.status)&&(Fe=!0,ee&&clearInterval(ee))}catch(ut){D(ut?.message||"Failed to load bulk task status"),Fe=!0,ee&&clearInterval(ee)}};return yt(),ee=setInterval(()=>{yt()},1500),()=>{Fe=!0,ee&&clearInterval(ee)}},[_,s,pt]);const xe=async ee=>{me(!0),se(!0),O(!1),ge(null),ve("");try{const Fe=await ca(`/api/admin/referral/status/${ee}`,void 0,void 0,s);U(Fe)}catch(Fe){console.error("Failed to load details:",Fe),se(!1)}finally{me(!1)}},Ee=async ee=>{if(!(!z||z.analysis_status!=="completed")){Ke(!0),ve(""),O(!0);try{const Fe=await ca(`/api/admin/referral/analysis/${ee}`,void 0,void 0,s);ge(Fe)}catch(Fe){ve(Fe.message||"Failed to load analysis result"),O(!1)}finally{Ke(!1)}}},Ne=async()=>{if(!z||z.analysis_status!=="completed"||Ae)return;const ee=ce(we);if(ee.length===0){Ie("Please paste at least one competitor URL (one per line)");return}ye(!0),Ie(""),J(null),Se(null),console.info("🧩 Adding competitors (admin)...");try{const Fe=await Yn("/api/admin/referral/competitors/add",{code:z.code,urls:ee},void 0,s),Xe=String(Fe.task_id||"");Xe&&J(Xe),Pe(""),Xe||await Ee(z.code)}catch(Fe){console.error("❌ Failed to add competitors:",Fe),Ie(Fe?.message||"Failed to add competitors")}finally{ye(!1)}},Ce=v.useCallback(async()=>{if(Oe)try{const ee=await ca("/api/admin/referral/competitors/sync_task_status",{task_id:Oe},void 0,s);Se(ee),ee.status==="done"&&z&&await Ee(z.code)}catch(ee){console.error("❌ Failed to load competitors sync status:",ee),Ie(ee?.message||"Failed to load competitors sync status")}},[Oe,s,z]);v.useEffect(()=>{if(!Oe)return;let ee=null,Fe=!1;const Xe=ut=>ut==="done"||ut==="failed"||ut==="error",yt=async()=>{if(!Fe)try{const ut=await ca("/api/admin/referral/competitors/sync_task_status",{task_id:Oe},void 0,s);Se(ut),Xe(ut.status)&&(Fe=!0,ee&&clearInterval(ee)),ut.status==="done"&&z&&await Ee(z.code)}catch(ut){Ie(ut?.message||"Failed to load competitors sync status"),Fe=!0,ee&&clearInterval(ee)}};return yt(),ee=setInterval(()=>{yt()},1500),()=>{Fe=!0,ee&&clearInterval(ee)}},[Oe,s,z]);const De=()=>{L>1&&$(L-1)},Ge=()=>{L<H&&$(L+1)};return t?e.jsxs("div",{className:"min-h-screen bg-gray-50",children:[e.jsx("header",{className:"bg-white shadow-sm border-b",children:e.jsxs("div",{className:"mx-auto px-4 py-4 flex justify-between items-center",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-xl font-bold text-gray-800",children:"Referral Code Admin"}),e.jsxs("p",{className:"text-xs text-gray-500 font-mono",children:["Connected to: ",s]})]}),e.jsx(be,{variant:"ghost",onClick:ct,children:"Disconnect"})]})}),e.jsxs("main",{className:"mx-auto px-4 py-6 space-y-6",children:[e.jsxs("div",{className:"bg-white rounded-lg shadow-sm border p-6",children:[e.jsx("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Generate New Referral Code"}),e.jsxs("div",{className:"flex gap-4",children:[e.jsx(bt,{type:"url",value:n,onChange:ee=>o(ee.target.value),placeholder:"Enter company URL (e.g., https://example.com)",className:"flex-1",onKeyDown:ee=>ee.key==="Enter"&&G()}),e.jsx(be,{onClick:G,disabled:p,children:p?e.jsxs(e.Fragment,{children:[e.jsx(He,{className:"mr-2 h-4 w-4 animate-spin"}),"Generating..."]}):"Generate Code"})]}),m&&e.jsx("p",{className:"text-red-500 text-sm mt-2",children:m}),i&&e.jsxs("div",{className:"mt-4 p-4 bg-green-50 rounded-md border border-green-200",children:[e.jsx("p",{className:"text-green-800 font-semibold",children:"Code Generated Successfully!"}),e.jsxs("div",{className:"flex items-center gap-3 mt-2",children:[e.jsx("span",{className:"text-2xl font-mono font-bold text-green-700",children:i}),e.jsxs(be,{variant:"ghost",size:"sm",onClick:()=>qe(i),children:[e.jsx(Ys,{className:"h-4 w-4 mr-1"}),"Copy Code"]})]}),e.jsxs("div",{className:"mt-4 pt-4 border-t border-green-200",children:[e.jsx("label",{className:"text-sm text-gray-600 block mb-2",children:"Shareable Report Link"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(bt,{readOnly:!0,value:ue(c,i),className:"flex-1 font-mono text-sm bg-white"}),e.jsxs(be,{variant:"ghost",size:"sm",onClick:()=>qe(ue(c,i)),children:[e.jsx(Ys,{className:"h-4 w-4 mr-1"}),"Copy Link"]}),e.jsx(be,{variant:"ghost",size:"sm",onClick:()=>window.open(ue(c,i),"_blank"),children:e.jsx(ns,{className:"h-4 w-4"})})]})]}),e.jsx("p",{className:"text-sm text-gray-600 mt-2",children:"Analysis is running in background. Refresh the list to check 
49status."})]})]}),e.jsxs("div",{className:"bg-white rounded-lg shadow-sm border p-6",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("h2",{className:"text-lg font-semibold text-gray-800",children:"Bulk Generate Referral Codes (Async)"}),_?e.jsxs("span",{className:"text-xs text-gray-500 font-mono",children:["Task: ",_]}):null]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-4",children:[e.jsxs("div",{className:"lg:col-span-2",children:[e.jsx("label",{className:"text-sm text-gray-600 block mb-2",children:"Company URLs (one per line)"}),e.jsx(Js,{value:b,onChange:ee=>y(ee.target.value),placeholder:`https://example.com
50https://another.com`,rows:6}),e.jsxs("p",{className:"text-xs text-gray-500 mt-2",children:["Total: ",pe(b).length]})]}),e.jsxs("div",{className:"lg:col-span-1 space-y-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-sm text-gray-600 block mb-2",children:"Concurrency"}),e.jsx(bt,{type:"number",min:1,max:10,value:x,onChange:ee=>u(Math.max(1,Math.min(10,Number(ee.target.value||3))))}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"Keep it small to avoid flooding analysis tasks."})]}),e.jsx(be,{onClick:Y,disabled:g,className:"w-full",children:g?e.jsxs(e.Fragment,{children:[e.jsx(He,{className:"mr-2 h-4 w-4 animate-spin"}),"Starting..."]}):"Start Bulk Generate"}),k?e.jsx("p",{className:"text-red-500 text-sm",children:k}):null]})]}),N?e.jsxs("div",{className:"mt-6 space-y-3",children:[e.jsx(ji,{value:N.progress,max:Math.max(N.total,1),showPercentage:!0,showValue:!0,valueLabel:`${N.progress} / ${N.total} (success: ${N.success_count}, failed: ${N.failed_count})`}),N.status!=="processing"&&N.error?e.jsx("p",{className:"text-red-600 text-sm",children:N.error}):null,N.status==="done"&&N.successes?.length?e.jsxs("div",{className:"border rounded-md overflow-hidden",children:[e.jsxs("div",{className:"px-4 py-2 bg-gray-50 text-sm font-semibold text-gray-700 flex items-center justify-between gap-3",children:[e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsxs("span",{children:["Generated Codes (",N.successes.length,")"]}),e.jsxs("span",{className:"text-xs font-normal text-gray-500 font-mono",children:["Batch: ",N.batch_id||_]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[ae?e.jsx("span",{className:"text-xs font-normal text-red-600",children:ae}):null,e.jsx(be,{variant:"outline",size:"sm",onClick:te,disabled:Z,children:Z?e.jsxs(e.Fragment,{children:[e.jsx(He,{className:"mr-2 h-4 w-4 animate-spin"}),"Exporting..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Vs,{className:"mr-2 h-4 w-4"}),"Export CSV"]})})]})]}),e.jsx("div",{className:"max-h-64 overflow-y-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-white sticky top-0 border-b",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-3 py-2 text-left text-xs font-medium text-gray-500",children:"Index"}),e.jsx("th",{className:"px-3 py-2 text-left text-xs font-medium text-gray-500",children:"Code"}),e.jsx("th",{className:"px-3 py-2 text-left text-xs font-medium text-gray-500",children:"Report Link"}),e.jsx("th",{className:"px-3 py-2 text-left text-xs font-medium text-gray-500",children:"Company URL"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-100",children:N.successes.map((ee,Fe)=>e.jsxs("tr",{className:"hover:bg-gray-50",children:[e.jsx("td",{className:"px-3 py-2 text-gray-600 font-mono text-xs",children:ee.index??Fe+1}),e.jsxs("td",{className:"px-3 py-2",children:[e.jsx("span",{className:"font-mono font-semibold text-blue-600",children:ee.code}),e.jsx("button",{onClick:()=>qe(ee.code),className:"ml-2 text-gray-400 hover:text-gray-600",title:"Copy code",children:e.jsx(Ys,{className:"h-3.5 w-3.5 inline"})})]}),e.jsx("td",{className:"px-3 py-2",children:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"font-mono text-xs text-blue-600 break-all",children:ue(ee.company_url,ee.code)}),e.jsx("button",{onClick:()=>qe(ue(ee.company_url,ee.code)),className:"text-gray-400 hover:text-gray-600",title:"Copy report link",children:e.jsx(Ys,{className:"h-3.5 w-3.5 inline"})}),e.jsx("a",{href:ue(ee.company_url,ee.code),target:"_blank",rel:"noopener noreferrer",className:"text-gray-400 hover:text-gray-600",title:"Open report link",children:e.jsx(ns,{className:"h-3.5 w-3.5 inline"})})]})}),e.jsx("td",{className:"px-3 py-2 text-gray-600 break-all",children:ee.company_url})]},Fe))})]})})]}):null,N.status==="done"&&N.failures?.length?e.jsxs("div",{className:"border rounded-md overflow-hidden",children:[e.jsxs("div",{className:"px-4 py-2 bg-red-50 text-sm font-semibold text-red-700",children:["Failed Items (",N.failures.length,")"]}),e.jsx("div",{className:"max-h-64 overflow-y-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-white sticky top-0 border-b",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-3 py-2 text-left text-xs font-medium text-gray-500",children:"Index"}),e.jsx("th",{className:"px-3 py-2 text-left text-xs font-medium text-gray-500",children:"Company URL"}),e.jsx("th",{className:"px-3 py-2 text-left text-xs font-medium text-gray-500",children:"Error"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-100",children:N.failures.map((ee,Fe)=>e.jsxs("tr",{className:"hover:bg-gray-50",children:[e.jsx("td",{className:"px-3 py-2 text-gray-600 font-mono text-xs",children:ee.index??Fe+1}),e.jsx("td",{className:"px-3 py-2 text-gray-600 break-all",children:ee.company_url}),e.jsx("td",{className:"px-3 py-2 text-red-600 break-all",children:ee.error})]},Fe))})]})})]}):null]}):null]}),e.jsxs("div",{className:"bg-white rounded-lg shadow-sm border p-6",children:[e.jsxs("div",{className:"flex justify-between items-center mb-4",children:[e.jsx("h2",{className:"text-lg font-semibold text-gray-800",children:"Referral Codes"}),e.jsxs("div",{className:"flex items-center gap-2",children:[T?e.jsx("span",{className:"text-sm text-red-600",children:T}):null,e.jsx(be,{variant:"outline",size:"sm",onClick:At,disabled:j||!t,children:j?e.jsxs(e.Fragment,{children:[e.jsx(He,{className:"mr-2 h-4 w-4 animate-spin"}),"Exporting..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Vs,{className:"mr-2 h-4 w-4"}),"Export CSV"]})}),e.jsxs(be,{variant:"ghost",size:"sm",onClick:pt,children:[e.jsx(kt,{className:`h-4 w-4 mr-2 ${P?"animate-spin":""}`}),"Refresh"]})]})]}),P&&F.length===0?e.jsxs("div",{className:"text-center py-8",children:[e.jsx(He,{className:"h-6 w-6 animate-spin mx-auto text-gray-400"}),e.jsx("p",{className:"text-gray-600 mt-2",children:"Loading codes..."})]}):C?e.jsx("div",{className:"text-red-500 text-center py-4",children:C}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-left",children:[e.jsx("thead",{className:"bg-gray-50 border-y",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-4 py-3 text-xs font-semibold text-gray-600 sticky left-0 z-20 bg-gray-50",children:"Code"}),e.jsx("th",{className:"px-4 py-3 text-xs font-semibold text-gray-600",children:"Company URL"}),e.jsx("th",{className:"px-4 py-3 text-xs font-semibold text-gray-600 ",children:"Bulk Run"}),e.jsx("th",{className:"px-4 py-3 text-xs font-semibold text-gray-600",children:"Bulk Index"}),e.jsx("th",{className:"px-4 py-3 text-xs font-semibold text-gray-600",children:"Report Link"}),e.jsx("th",{className:"px-4 py-3 text-xs font-semibold text-gray-600",children:"Analysis Status"}),e.jsx("th",{className:"px-4 py-3 text-xs font-semibold text-gray-600",children:"Report Competitors"}),e.jsx("th",{className:"px-4 py-3 text-xs font-semibold text-gray-600",children:"Ranked Keywords"}),e.jsx("th",{className:"px-4 py-3 text-xs font-semibold text-gray-600",children:"Use Count"}),e.jsx("th",{className:"px-4 py-3 text-xs font-semibold text-gray-600",children:"Created"}),e.jsx("th",{className:"px-4 py-3 text-xs font-semibold text-gray-600 sticky right-0 z-20 bg-gray-50",children:"Actions"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-100",children:F.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:11,className:"px-4 py-8 text-center text-gray-500",children:"No codes found"})}):F.map(ee=>e.jsxs("tr",{className:"hover:bg-gray-50",children:[e.jsx("td",{className:"px-4 py-3 sticky left-0 z-10 bg-white whitespace-nowrap min-w-[120px]",children:e.jsxs("div",{className:"flex items-center gap-2 flex-nowrap",children:[e.jsx("span",{className:"font-mono font-semibold text-blue-600",children:ee.code}),e.jsx("button",{onClick:()=>qe(ee.code),className:"text-gray-400 hover:text-gray-600 flex-shrink-0",title:"Copy code",children:e.jsx(Ys,{className:"h-3.5 w-3.5"})})]})}),e.jsx("td",{className:"px-4 py-3 max-w-xs truncate",title:ee.company_url,children:e.jsxs("a",{href:ee.company_url,target:"_blank",rel:"noopener noreferrer",className:"text-gray-600 hover:text-blue-600 inline-flex items-center gap-1",children:[ee.company_url.length>40?ee.company_url.slice(0,40)+"...":ee.company_url,e.jsx(ns,{className:"h-3 w-3"})]})}),e.jsx("td",{className:"px-4 py-3",children:e.jsx("span",{className:"font-mono text-xs text-gray-600",children:ke(ee.bulk_run_id)})}),e.jsx("td",{className:"px-4 py-3",children:e.jsx("span",{className:"font-mono text-xs text-gray-600",children:ee.bulk_index??"—"})}),e.jsx("td",{className:"px-4 py-3",children:e.jsxs("div",{className:"flex items-center gap-1 max-w-xs",children:[e.jsx("span",{className:"font-mono text-xs text-blue-600 truncate",title:ue(ee.company_url,ee.code),children:W(ee.company_url,ee.code)}),e.jsx("button",{onClick:()=>qe(ue(ee.company_url,ee.code)),className:"text-gray-400 hover:text-gray-600 flex-shrink-0",title:"Copy report link",children:e.jsx(Ys,{className:"h-3.5 w-3.5"})}),e.jsx("a",{href:ue(ee.company_url,ee.code),target:"_blank",rel:"noopener noreferrer",className:"text-gray-400 hover:text-gray-600 flex-shrink-0",title:"Open report link",children:e.jsx(ns,{className:"h-3.5 w-3.5"})})]})}),e.jsx("td",{className:"px-4 py-3",children:e.jsx("span",{className:`px-2 py-1 rounded text-xs font-medium ${Qe(ee.analysis_status)}`,children:ee.analysis_status})}),e.jsx("td",{className:"px-4 py-3",children:e.jsx("span",{className:"px-2 py-1 rounded text-xs font-medium bg-slate-100 text-slate-700 font-mono",children:ee.competitors_count===null||ee.competitors_count===void 0?"—":ee.competitors_count})}),e.jsx("td",{className:"px-4 py-3",children:e.jsx("span",{className:"px-2 py-1 rounded text-xs font-medium bg-slate-100 text-slate-700 font-mono",children:ee.ranked_keywords_total===null||ee.ranked_keywords_total===void 0?"—":ee.ranked_keywords_total})}),e.jsx("td",{className:"px-4 py-3",children:e.jsxs("span",{className:`px-2 py-1 rounded text-xs font-medium ${ee.use_count>0?"bg-blue-100 text-blue-700":"bg-gray-100 text-gray-500"}`,children:[ee.use_count," "]})}),e.jsx("td",{className:"px-4 py-3 text-sm text-gray-600",children:je(ee.created_at)}),e.jsx("td",{className:"px-4 py-3 sticky right-0 z-10 bg-white",children:e.jsx(be,{variant:"ghost",size:"sm",onClick:()=>xe(ee.code),children:"Details"})})]},ee.code))})]})}),e.jsxs("div",{className:"flex justify-between items-center mt-4 pt-4 border-t",children:[e.jsxs("p",{className:"text-sm text-gray-600",children:["Showing ",F.length," of ",X," codes"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(be,{variant:"outline",size:"sm",onClick:De,disabled:L<=1,children:"Previous"}),e.jsx(be,{variant:"outline",size:"sm",onClick:Ge,disabled:L>=H,children:"Next"})]})]})]})]})]}),e.jsx(Ht,{open:fe,onOpenChange:se,children:e.jsxs(qt,{className:"max-w-7xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Zt,{children:e.jsx(Yt,{children:"Code Details"})}
50),Q?e.jsxs("div",{className:"text-center py-8",children:[e.jsx(He,{className:"h-6 w-6 animate-spin mx-auto text-gray-400"}),e.jsx("p",{className:"text-gray-600 mt-2",children:"Loading details..."})]}):z?le?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("h3",{className:"text-lg font-semibold",children:"Analysis Preview"}),e.jsxs(be,{variant:"ghost",size:"sm",onClick:()=>{O(!1),ge(null)},children:[e.jsx(mt,{className:"h-4 w-4 mr-2"}),"Back to Details"]})]}),ze?e.jsxs("div",{className:"text-center py-12",children:[e.jsx(He,{className:"h-8 w-8 animate-spin mx-auto text-gray-400"}),e.jsx("p",{className:"text-gray-600 mt-2",children:"Loading analysis..."})]}):ie?e.jsxs("div",{className:"text-center py-8",children:[e.jsx("p",{className:"text-red-500",children:ie}),e.jsx(be,{variant:"outline",size:"sm",onClick:()=>Ee(z.code),className:"mt-4",children:"Retry"})]}):ne?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"bg-white border border-slate-100 rounded-xl p-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-semibold text-slate-900",children:"Add Competitors (Admin)"}),e.jsx("p",{className:"text-xs text-slate-500",children:"Paste competitor URLs (one per line). Sync runs in background."})]}),e.jsxs(be,{variant:"outline",size:"sm",onClick:Ce,disabled:!Oe,children:[e.jsx(kt,{className:"h-4 w-4 mr-2"}),"Refresh Status"]})]}),e.jsx(Js,{value:we,onChange:ee=>Pe(ee.target.value),placeholder:`https://competitor1.com
51https://competitor2.com`,rows:4}),e.jsxs("div",{className:"flex items-center justify-between gap-3 mt-3",children:[e.jsxs("p",{className:"text-xs text-slate-500",children:["Total:"," ",ce(we).length]}),e.jsx(be,{onClick:Ne,disabled:Ae,children:Ae?e.jsxs(e.Fragment,{children:[e.jsx(He,{className:"mr-2 h-4 w-4 animate-spin"}),"Adding..."]}):"Add & Sync"})]}),Te?e.jsx("p",{className:"text-red-600 text-sm mt-2",children:Te}):null,re?e.jsxs("div",{className:"mt-4 space-y-2",children:[e.jsx(ji,{value:re.progress,max:Math.max(re.total,1),showPercentage:!0,showValue:!0,valueLabel:`${re.progress} / ${re.total}`}),re.message?e.jsx("p",{className:"text-xs text-slate-500",children:re.message}):null,re.error?e.jsx("p",{className:"text-xs text-red-600",children:re.error}):null]}):null]}),e.jsx("div",{className:"bg-slate-50 border border-slate-100 rounded-xl p-4",children:e.jsx(Wi,{analysisResult:ne,showPlanMask:!1,showMarketTabs:!1,showContinueButton:!1,referralCode:z.code})})]}):null]}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"bg-gray-50 p-4 rounded-lg",children:[e.jsx("label",{className:"text-sm text-gray-500",children:"Code"}),e.jsx("p",{className:"font-mono text-2xl font-bold text-blue-600",children:z.code})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-sm text-gray-500",children:"Company URL"}),e.jsx("p",{className:"text-gray-800 break-all",children:e.jsx("a",{href:z.company_url,target:"_blank",rel:"noopener noreferrer",className:"hover:text-blue-600",children:z.company_url})})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm text-gray-500",children:"Template Company ID"}),e.jsx("p",{className:"text-gray-800 font-mono text-sm",children:z.company_id||"N/A"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm text-gray-500",children:"Analysis Status"}),e.jsx("p",{children:e.jsx("span",{className:`px-2 py-1 rounded text-xs font-medium ${Qe(z.analysis_status)}`,children:z.analysis_status})})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm text-gray-500",children:"Total Uses"}),e.jsx("p",{children:e.jsxs("span",{className:`px-2 py-1 rounded text-xs font-medium ${z.use_count>0?"bg-blue-100 text-blue-700":"bg-gray-100 text-gray-500"}`,children:[z.use_count," ",z.use_count===1?"use":"uses"]})})]}),z.analysis_error&&e.jsxs("div",{className:"col-span-2",children:[e.jsx("label",{className:"text-sm text-gray-500",children:"Analysis Error"}),e.jsx("p",{className:"text-red-600 text-sm",children:z.analysis_error})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm text-gray-500",children:"Created At"}),e.jsx("p",{className:"text-gray-800",children:je(z.created_at)})]})]}),z.usages&&z.usages.length>0&&e.jsxs("div",{children:[e.jsxs("label",{className:"text-sm text-gray-500 mb-2 block",children:["Usage History (",z.usages.length,")"]}),e.jsx("div",{className:"max-h-48 overflow-y-auto border rounded",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-gray-50 sticky top-0",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-3 py-2 text-left text-xs font-medium text-gray-500",children:"User ID"}),e.jsx("th",{className:"px-3 py-2 text-left text-xs font-medium text-gray-500",children:"Company ID"}),e.jsx("th",{className:"px-3 py-2 text-left text-xs font-medium text-gray-500",children:"Used At"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-100",children:z.usages.map((ee,Fe)=>e.jsxs("tr",{className:"hover:bg-gray-50",children:[e.jsx("td",{className:"px-3 py-2 font-mono text-xs text-gray-700",children:ee.user_id}),e.jsx("td",{className:"px-3 py-2 font-mono text-xs text-gray-500",children:ee.company_id||"N/A"}),e.jsx("td",{className:"px-3 py-2 text-xs text-gray-500",children:je(ee.created_at)})]},Fe))})]})})]}),e.jsxs("div",{className:"mt-4 pt-4 border-t",children:[e.jsx("p",{className:"text-sm text-gray-500 mb-2",children:"How to use:"}),e.jsxs("p",{className:"text-xs text-gray-600 mb-3",children:["Share this code with users. They can enter it on the Setup page after logging in."," ",e.jsx("strong",{children:"Code 
51can be reused by multiple users."})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-sm text-gray-500 block mb-2",children:"Referral Code"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(bt,{readOnly:!0,value:z.code,className:"flex-1 text-lg font-mono font-bold text-center tracking-wider bg-gray-50"}),e.jsxs(be,{onClick:()=>qe(z.code),children:[e.jsx(Ys,{className:"h-4 w-4 mr-2"}),"Copy Code"]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm text-gray-500 block mb-2",children:"Shareable Report Link"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(bt,{readOnly:!0,value:ue(z.company_url,z.code),className:"flex-1 font-mono text-sm bg-gray-50"}),e.jsxs(be,{onClick:()=>qe(ue(z.company_url,z.code)),children:[e.jsx(Ys,{className:"h-4 w-4 mr-2"}),"Copy Link"]}),e.jsx(be,{variant:"outline",onClick:()=>window.open(ue(z.company_url,z.code),"_blank"),children:e.jsx(ns,{className:"h-4 w-4"})})]})]})]})]}),z.analysis_status==="completed"&&e.jsx("div",{className:"mt-4 pt-4 border-t",children:e.jsx(be,{onClick:()=>Ee(z.code),disabled:ze,className:"w-full",variant:"outline",children:ze?e.jsxs(e.Fragment,{children:[e.jsx(He,{className:"h-4 w-4 mr-2 animate-spin"}),"Loading..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Ga,{className:"h-4 w-4 mr-2"}),"View Analysis Preview"]})})})]}):null]})})]}):null}class ly{constructor(){this.baseUrl="/open_api_keys",this.blogBaseUrl="/open_api/blog"}async generateAPIKey(s){return Je(`${this.baseUrl}/generate`,s)}async listAPIKeys(s=!1){return ot(`${this.baseUrl}/list?include_inactive=${s}`)}async updateAPIKeyLimits(s,a,n){return $r(`${this.baseUrl}/${s}/update`,{rate_limit_per_minute:a,rate_limit_per_day:n})}async deactivateAPIKey(s){return Ca(`${this.baseUrl}/${s}/deactivate`)}async deleteAPIKey(s){return Ca(`${this.baseUrl}/${s}/delete`)}async createBlogPost(s,a){return this.makeAuthenticatedRequest(`${this.blogBaseUrl}/posts/create`,"POST",a,s)}async batchCreateBlogPosts(s,a){return this.makeAuthenticatedRequest(`${this.blogBaseUrl}/posts/batch_create`,"POST",a,s)}async checkAPIStatus(s){return this.makeAuthenticatedRequest(`${this.blogBaseUrl}/posts/status`,"GET",void 0,s)}async makeAuthenticatedRequest(s,a,n,o){const i=Wg(),l=Cn.create({baseURL:i,timeout:6e5}),c={method:a,url:s,headers:{"Content-Type":"application/json"}};return o&&(c.headers.Authorization=`Bearer ${o}`),n&&(a==="POST"||a==="PUT")&&(c.data=n),(await l.request(c)).data}}const sn=new ly,Wr="blog_upload_api_keys",cy=({embedded:t=!1,adminMode:s=!1})=>{const[a,n]=r.useState([]),[o,i]=r.useState([]),[l,c]=r.useState(""),[d,m]=r.useState(""),[h,p]=r.useState(null),[f,b]=r.useState(!1),[y,x]=r.useState(!1),[u,g]=r.useState(""),[w,_]=r.useState(""),[E,N]=r.useState(""),[S,k]=r.useState("RankGale Team"),[D,F]=r.useState(""),[R,L]=r.useState(!1),[$,H]=r.useState(!0),[K,X]=r.useState(null),[V,P]=r.useState(""),[A,C]=r.useState(!1),[I,j]=r.useState(0),[q,T]=r.useState(null),[M,Z]=r.useState(null),[B,ae]=r.useState(!1),[de,fe]=r.useState(0),[se,z]=r.useState(!0),[U,Q]=r.useState([]);r.useEffect(()=>{s||(ne(),me())},[]),r.useEffect(()=>{!s&&o.length>0&&!l&&c(o[0].key)},[s,o,l]);const me=()=>{try{const J=localStorage.getItem(Wr);J&&i(JSON.parse(J))}catch(J){console.error("Failed to load saved API keys:",J)}
51},le=(J,re,Se)=>{try{const je=localStorage.getItem(Wr),he=je?JSON.parse(je):[],Re={name:J,key:re,prefix:Se,savedAt:new Date().toISOString()};he.push(Re),localStorage.setItem(Wr,JSON.stringify(he)),i(he),c(re),b(!1),p(null),ge("success","API key saved to browser storage")}catch(je){console.error("Failed to save API key:",je),ge("error","Failed to save API key to browser")}},O=J=>{try{const re=localStorage.getItem(Wr),je=(re?JSON.parse(re):[]).filter(he=>he.key!==J);localStorage.setItem(Wr,JSON.stringify(je)),i(je),l===J&&c(""),ge("success","API key removed from storage")}catch(re){console.error("Failed to delete API key:",re),ge("error","Failed to delete API key")}},ne=async()=>{try{const J=await sn.listAPIKeys();J.success&&n(J.keys.filter(re=>re.is_active))}catch{ge("error","Failed to load API keys")}},ge=(J,re)=>{Q(Se=>[...Se,{type:J,text:re}]),setTimeout(()=>{Q(Se=>Se.slice(1))},5e3)},ze=J=>{const re=J?.raw||J?.cause||null,Se=re?.response?.data?.detail??re?.response?.data?.message??J?.response?.data?.detail??J?.response?.data?.message??J?.message??J;return Array.isArray(Se)?Se.map(he=>{const Re=Array.isArray(he?.loc)?he.loc.filter(Boolean).join("."):"",Me=typeof he?.msg=="string"?he.msg:typeof he=="string"?he:JSON.stringify(he);return Re?`${Re}: ${Me}`:Me}).filter(Boolean).join("; ")||"Request validation failed":typeof Se=="string"?Se:Se&&typeof Se=="object"?JSON.stringify(Se):String(Se||"Unknown error")},Ke=async()=>{if(s){ge("error","API key management is not available in admin mode");return}if(!d.trim()){ge("error","Please enter a name for the API key");return}x(!0);try{const J=await sn.generateAPIKey({name:d,rate_limit_per_minute:60,rate_limit_per_day:1e3});J.success&&(p({key:J.api_key,prefix:J.key_info.key_prefix}),b(!0),await ne(),ge("success","API key generated successfully!"))}catch(J){ge("error",ze(J)||"Failed to generate API key")}finally{x(!1)}},ie=()=>{if(!l)return"";const J=o.find(re=>re.key===l);return J?J.key:l},ve=()=>s?"":ie(),we=async()=>{if(!u.trim()||!E.trim()){ge("error","Please fill in all required fields");return}if(!S.trim()){ge("error","Please provide an author name");return}L(!0);try{const J={title:u,slug:w||void 0,content:E,author_name:S.trim(),author_email:D.trim()||void 0,featured_image:V||void 0,auto_publish:$},re=s?await Fs.createPost(J):await sn.createBlogPost(ve(),J);re.success&&(ge("success",re.message),g(""),_(""),N(""),k("RankGale Team"),F(""),X(null),P(""),j(0))}catch(J){ge("error",ze(J)||"Failed to create blog post")}finally{L(!1)}},Pe=async()=>{if(!s){ge("error","Cover upload is only available in admin mode (requires admin token)");return}if(!K){ge("error","Please select a cover image first");return}C(!0),j(0);try{const J=await Fs.uploadCovers([K],re=>{j(re)});if(J.success){const re=(J.uploaded||[]).find(Se=>!Se.error&&Se.url);re?.url?(P(re.url),ge("success","Cover uploaded")):ge("error","Cover upload failed")}else ge("error","Cover upload failed")}catch(J){ge("error",ze(J)||"Cover upload failed")}finally{C(!1)}},Ae=J=>{const re={"¡ª":"—","¡°":'"',"¡±":'"',"¡¯":"'","¡®":"'","€":"€","¡":"•","©":"©","®":"®","™":"™","…":"…","–":"–","—":"—"};let Se=J;return Se=Se.replace(/\u0097/g,"—").replace(/\u0096/g,"–").replace(/\u0093/g,'"').replace(/\u0094/g,'"').replace(/\u0091/g,"'").replace(/\u0092/g,"'").replace(/\u0085/g,"…"),Object.entries(re).forEach(([je,he])=>{je!==he&&(Se=Se.replace(new RegExp(je.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),he))}),console.debug("🧩 After fixEncoding:",Se.substring(0,200)),Se};function ye(J){const re=new Uint8Array(J);if(re.length>=3&&re[0]===239&&re[1]===187&&re[2]===191)return new TextDecoder("utf-8").decode(re.subarray(3));if(re.length>=2&&re[0]===255&&re[1]===254)return new TextDecoder("utf-16le").decode(re.subarray(2));if(re.length>=2&&re[0]===254&&re[1]===255)return new TextDecoder("utf-16be").decode(re.subarray(2));const Se=["windows-1252","utf-8","iso-8859-1","gbk","big5"];let je="",he=Number.POSITIVE_INFINITY;for(const Re of Se)try{const Me=new TextDecoder(Re,{fatal:!1}).decode(re),Ze=(Me.match(/\uFFFD/g)||[]).length;Ze<he&&(he=Ze,je=Me)}catch{}return je||new TextDecoder("utf-8").decode(re)}const Te=J=>{const re=Ae(J);if(!re.trim())return[];const Se=Dh.parse(re,{header:!0,skipEmptyLines:!0,transformHeader:ke=>ke.toLowerCase().trim()});Se.errors.length>0&&console.warn("CSV parse warnings:",Se.errors);const je=Se.data;if(je.length===0)return[];const he=Se.meta.fields||[],Re=ke=>he.find(Qe=>Qe===ke.toLowerCase())||null,Me=(ke,qe)=>!qe||!(qe in ke)?"":ke[qe]?.trim()||"",Ze=Re("title"),Be=Re("content"),et=Re("slug"),$e=Re("author_name"),ue=Re("author_email");
51if(!Ze)throw new Error('CSV 必须包含 "title" 列');if(!Be)throw new Error('CSV 必须包含 "content" 列');const W=[];for(const ke of je){const qe=Me(ke,Ze),Qe=Me(ke,Be),ct=Me(ke,et),pt=Me(ke,$e),At=Me(ke,ue);qe&&Qe&&W.push({title:qe,slug:ct||void 0,content:Qe,author_name:(pt||"RankGale Team").trim(),author_email:At||void 0,auto_publish:se})}return W},Ie=async()=>{if(!q){ge("error","Please select a CSV file");return}if(!s&&!ve()){ge("error","Please provide an Open API key");return}ae(!0),Z(null),fe(0);try{const J=new FileReader;J.onload=async re=>{try{let Se;if(re.target?.result instanceof ArrayBuffer){const et=re.target.result;Se=ye(et)}else Se=String(re.target?.result||"");Se=Ae(Se);const je=Te(Se);if(je.length===0){ge("error","No valid posts found in CSV file"),ae(!1);return}ge("info",`Found ${je.length} posts in CSV. Starting upload...`);const he=5,Re=[];for(let et=0;et<je.length;et+=he)Re.push(je.slice(et,et+he));let Me=0,Ze=0;const Be=[];for(const[et,$e]of Re.entries()){try{const ue=s?await Fs.batchCreatePosts({posts:$e,auto_publish:se}):await sn.batchCreateBlogPosts(ve(),{posts:$e,auto_publish:se});Me+=ue.created_count,Ze+=ue.failed_count,ue.failed_posts&&ue.failed_posts.length>0&&ue.failed_posts.forEach(W=>{Be.push(`${W.title}: ${W.error}`)}),fe((et+1)/Re.length*100)}catch(ue){const W=ze(ue)||"Unknown error";Be.push(`Batch ${et+1} failed: ${W}`),console.error(`❌ Batch ${et+1} error:`,ue),Ze+=$e.length}et<Re.length-1&&await new Promise(ue=>setTimeout(ue,1e3))}Z({total:je.length,completed:Me,failed:Ze,errors:Be}),Ze===0?ge("success",`Successfully created all ${Me} blog posts!`):ge("error",`Created ${Me} posts, ${Ze} failed`)}catch(Se){ge("error",ze(Se)||"Failed to parse CSV file")}finally{ae(!1)}},J.readAsArrayBuffer(q)}catch(J){ge("error",ze(J)||"Failed to read file"),ae(!1)}},Oe=J=>{navigator.clipboard.writeText(J),ge("success","Copied to clipboard!")};return e.jsxs("div",{className:t?"h-full bg-slate-50":"min-h-screen bg-gray-50",children:[!t&&e.jsx("div",{className:"bg-white border-b border-gray-200",children:e.jsxs("div",{className:"max-w-7xl mx-auto px-6 py-6",children:[e.jsx("h1",{className:"text-3xl font-bold text-gray-900",children:"Blog Upload - Open API"}),e.jsx("p",{className:"mt-2 text-gray-600",children:"Manage API keys and create blog posts"})]})}),U.length>0&&e.jsx("div",{className:"fixed top-4 right-4 z-50 space-y-2",children:U.map((J,re)=>e.jsx("div",{className:`px-4 py-3 rounded-md shadow-lg ${J.type==="success"?"bg-green-50 text-green-800 border border-green-200":J.type==="error"?"bg-red-50 text-red-800 border border-red-200":"bg-blue-50 text-blue-800 border border-blue-200"} whitespace-pre-line break-words max-w-[520px]`,children:J.text},re))}),e.jsxs("div",{className:t?"px-6 py-6":"max-w-7xl mx-auto px-6 py-8",children:[t&&e.jsxs("div",{className:"mb-5",children:[e.jsx("div",{className:"text-lg font-semibold text-slate-900",children:"Blog Upload"}),e.jsx("div",{className:"text-sm text-slate-600",children:"Manage API keys and create blog posts via Open API"})]}),s?null:e.jsxs("div",{className:"bg-white rounded-lg shadow-sm border border-gray-200 p-6 mb-6",children:[e.jsx("h2",{className:"text-xl font-semibold text-gray-900 mb-4",children:"API Key Management"}),e.jsxs("div",{className:"mb-6 pb-6 border-b border-gray-200",children:[e.jsx("h3",{className:"text-sm font-medium text-gray-700 mb-3",children:"Generate New API Key"}),e.jsxs("div",{className:"flex gap-3",children:[e.jsx("input",{type:"text",placeholder:"Enter key name...",value:d,onChange:J=>m(J.target.value),className:"flex-1 px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 placeholder:text-gray-400"}),e.jsx(be,{onClick:Ke,disabled:y,children:y?"Generating...":"Generate"})]}),f&&h&&e.jsxs("div",{className:"mt-4 p-4 bg-yellow-50 border border-yellow-200 rounded-md",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("span",{className:"text-sm font-medium text-yellow-800",children:"Save this key now - you won't see it again!"}),e.jsx("button",{onClick:()=>Oe(h.key),className:"text-sm text-yellow-800 hover:text-yellow-900 underline",children:"Copy"})]}),e.jsx("div",{className:"bg-white p-3 rounded border border-yellow-300 font-mono text-sm text-gray-900 break-all",children:h.key}),e.jsx("button",{onClick:()=>
51le(d,h.key,h.prefix),className:"mt-3 w-full px-4 py-2 bg-yellow-600 text-white rounded-md hover:bg-yellow-700 transition-colors",children:"Save to Browser Storage"})]})]}),o.length>0&&e.jsxs("div",{className:"mb-6 pb-6 border-b border-gray-200",children:[e.jsx("h3",{className:"text-sm font-medium text-gray-700 mb-3",children:"Saved API Keys"}),e.jsx("div",{className:"space-y-2",children:o.map(J=>e.jsxs("div",{className:"flex items-center justify-between p-3 bg-gray-50 border border-gray-200 rounded-md",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"text-sm font-medium text-gray-900",children:J.name}),e.jsxs("div",{className:"text-xs text-gray-500",children:[J.prefix,"..."]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(be,{variant:"outline",size:"sm",onClick:()=>c(J.key),className:l===J.key?"bg-blue-50":"",children:l===J.key?"Selected":"Select"}),e.jsx(be,{variant:"outline",size:"sm",onClick:()=>O(J.key),children:"Delete"})]})]},J.key))})]})]}),e.jsxs("div",{className:"grid md:grid-cols-2 gap-6",children:[e.jsxs("div",{className:"bg-white rounded-lg shadow-sm border border-gray-200 p-6",children:[e.jsx("h2",{className:"text-xl font-semibold text-gray-900 mb-4",children:"Create Single Blog Post"}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:["Title ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx("input",{type:"text",value:u,onChange:J=>g(J.target.value),className:"w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500",placeholder:"Enter blog post title"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Slug (optional)"}),e.jsx("input",{type:"text",value:w,onChange:J=>_(J.target.value),className:"w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500",placeholder:"Custom URL slug"})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:["Content ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx("textarea",{value:E,onChange:J=>N(J.target.value),rows:8,className:"w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 font-mono text-sm",placeholder:"Enter blog post content (Markdown supported)"})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:["Author name ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx("input",{type:"text",value:S,onChange:J=>k(J.target.value),className:"w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500",placeholder:"Enter author name"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Author email (optional)"}),e.jsx("input",{type:"email",value:D,onChange:J=>F(J.target.value),className:"w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500",placeholder:"Enter author email"})]}),s?e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Featured image (optional)"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("input",{type:"file",accept:"image/*",onChange:J=>{const re=J.target.files?.[0]||null;X(re),P(""),j(0)},className:"w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(be,{type:"button",variant:"outline",onClick:Pe,disabled:!K||A,children:A?"Uploading...":"Upload cover"}),V?e.jsx(be,{type:"button",variant:"outline",onClick:()=>{X(null),P(""),j(0)},children:"Remove"}):null]}),A?e.jsxs("div",{className:"mt-2",children:[e.jsx("div",{className:"h-2 bg-gray-200 rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full bg-blue-500 transition-all duration-300",style:{width:`${I}%`}})}),e.jsxs("div",{className:"mt-2 text-sm text-gray-600 text-center",children:[I.toFixed(0),"% complete"]})]}):null,V?e.jsxs("div",{className:"mt-2 border border-gray-200 rounded overflow-hidden bg-white",children:[e.jsx("div",{className:"aspect-video bg-gray-50",children:e.jsx("img",{src:V,alt:"Featured",className:"w-full h-full object-cover",loading:"lazy"})}),e.jsx("div",{className:"p-2 text-xs text-gray-600 break-all",children:V})]}):null]})]}):null,e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"checkbox",id:"single-auto-publish",checked:$,onChange:J=>H(J.target.checked),className:"rounded"}),e.jsx("label",{htmlFor:"single-auto-publish",className:"text-sm text-gray-700 cursor-pointer",children:"Auto publish immediately"})]}),e.jsx(be,{onClick:we,disabled:R||A||!s&&!l,className:`w-full text-white ${!s&&!l?"bg-gray-400 cursor-not-allowed":"bg-blue-600 hover:bg-blue-700"}`,children:R?"Creating...":!s&&!l?"Please select an Open API Key first":"Create Blog Post"})]})]}),e.jsxs("div",{className:"bg-white rounded-lg shadow-sm border border-gray-200 p-6",children:[e.jsx("h2",{className:"text-xl font-semibold text-gray-900 mb-4",children:"Upload CSV File"}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-2",children:"CSV File Format"}),e.jsxs("div",{className:"bg-gray-50 p-3 rounded border border-gray-200 font-mono text-xs",children:[e.jsx("div",{children:"title,slug,content,author_name,author_email"}),e.jsx("div",{className:"mt-2 text-gray-600",children:"At minimum: title and content columns required. author_name is o
51ptional (defaults to RankGale Team)"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"checkbox",id:"csv-auto-publish",checked:se,onChange:J=>z(J.target.checked),className:"rounded"}),e.jsx("label",{htmlFor:"csv-auto-publish",className:"text-sm text-gray-700 cursor-pointer",children:"Auto publish all posts immediately"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Select CSV File"}),e.jsx("input",{type:"file",accept:".csv",onChange:J=>T(J.target.files?.[0]||null),className:"w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"}),q&&e.jsxs("div",{className:"mt-2 text-sm text-gray-600",children:["Selected: ",q.name]})]}),e.jsx(be,{onClick:Ie,disabled:B||!q||!s&&!l,className:`w-full text-white ${!s&&!l?"bg-gray-400 cursor-not-allowed":"bg-blue-600 hover:bg-blue-700"}`,children:B?"Uploading...":!s&&!l?"Please select an Open API Key first":"Upload & Create Posts"}),B&&e.jsxs("div",{className:"mt-4",children:[e.jsx("div",{className:"h-2 bg-gray-200 rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full bg-blue-500 transition-all duration-300",style:{width:`${de}%`}})}),e.jsxs("div",{className:"mt-2 text-sm text-gray-600 text-center",children:[de.toFixed(0),"% complete"]})]}),M&&e.jsxs("div",{className:"mt-4 p-4 bg-gray-50 rounded border border-gray-200",children:[e.jsx("h3",{className:"text-sm font-semibold text-gray-900 mb-2",children:"Upload Summary"}),e.jsxs("div",{className:"space-y-1 text-sm",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-gray-600",children:"Total:"}),e.jsx("span",{className:"font-medium",children:M.total})]}),e.jsxs("div",{className:"flex justify-between text-green-600",children:[e.jsx("span",{children:"Created:"}),e.jsx("span",{className:"font-medium",children:M.completed})]}),e.jsxs("div",{className:"flex justify-between text-red-600",children:[e.jsx("span",{children:"Failed:"}),e.jsx("span",{className:"font-medium",children:M.failed})]})]}),M.errors.length>0&&e.jsxs("details",{className:"mt-3",children:[e.jsxs("summary",{className:"text-sm text-red-600 cursor-pointer hover:text-red-700",children:["Show Errors (",M.errors.length,")"]}),e.jsx("div",{className:"mt-2 max-h-40 overflow-y-auto space-y-1",children:M.errors.map((J,re)=>e.jsx("div",{className:"text-xs text-red-600 font-mono bg-red-50 p-2 rounded",children:J},re))})]})]})]})]})]})]})]})};function dy(t){try{const s=(t||"/").split("/").filter(Boolean);if(s[0]!=="admin")return"referral";const a=s[1]||"referral";return a==="referral"||a==="blog_upload"||a==="users"||a==="open_api_keys"||a==="blog"||a==="blog_covers"?a:"referral"}catch{return"referral"}}function jn(t,s={}){try{const a=s.replace??!1,n=t==="referral"?"/admin/referral":t==="users"?"/admin/users":t==="open_api_keys"?"/admin/open_api_keys":t==="blog_covers"?"/admin/blog_covers":t==="blog"?"/admin/blog":"/admin/blog_upload";window.location.pathname!==n&&(a?window.history.replaceState({},"",n):window.history.pushState({},"",n),window.dispatchEvent(new PopStateEvent("popstate")))}catch{}}function hr({active:t,icon:s,label:a,onClick:n}){return e.jsxs("button",{onClick:n,className:`group w-full flex items-center gap-2.5 py-2 px-3 text-[12px] transition-all relative ${t?"text-gray-900 font-medium bg-slate-50":"text-gray-500 hover:text-gray-700 hover:bg-slate-50"}`,children:[t&&e.jsx("div",{className:"absolute left-0 top-1/2 -translate-y-1/2 w-0.5 h-4 bg-gray-900 rounded-r"}),e.jsx(s,{size:13,className:`flex-shrink-0 ${t?"text-gray-700":"text-gray-400 group-hover:text-gray-500"}`}),e.jsx("span",{className:"flex-1 text-left",children:a})]})}function my({current:t}){return e.jsxs("aside",{className:"w-56 flex-none border-r border-gray-100 bg-white h-full flex flex-col shadow-lg z-10",children:[e.jsx("div",{className:"h-14 flex items-center px-4 border-b border-gray-100",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-6 h-6 bg-gray-900 rounded flex items-center justify-center",children:e.jsx(nc,{size:12,className:"text-white"})}),e.jsx("span",{className:"text-sm font-semibold text-gray-800 tracking-tight",children:"Admin"})]})}),e.jsx("nav",{className:"flex-1 overflow-y-auto py-2",children:e.jsxs("div",{className:"px-1 space-y-1",children:[e.jsx(hr,{active:t==="referral",icon:ou,label:"Referral Admin",onClick:()=>jn("referral")}),e.jsx(hr,{active:t==="users",icon:Qs,label:"Users",onClick:()=>jn("users")}),e.jsx(hr,{active:t==="blog",icon:is,label:"Blog Management",onClick:()=>jn("blog")}
51),e.jsx(hr,{active:t==="blog_covers",icon:rn,label:"Blog Cover Library",onClick:()=>jn("blog_covers")}),e.jsx(hr,{active:t==="blog_upload",icon:rc,label:"Blog Upload",onClick:()=>jn("blog_upload")}),e.jsx(hr,{active:t==="open_api_keys",icon:oc,label:"Open API Keys",onClick:()=>jn("open_api_keys")})]})})]})}function uy({current:t,children:s}){return e.jsxs("div",{className:"flex h-screen bg-slate-50",children:[e.jsx(my,{current:t}),e.jsx("main",{className:"flex-1 overflow-hidden relative flex flex-col",children:e.jsx("div",{className:"flex-1 min-h-0 overflow-auto relative",children:e.jsx("div",{className:"h-full",children:s})})})]})}async function xy(t){return ca("/api/admin/users",{q:t.q||void 0,page:t.page||1,page_size:t.page_size||20},void 0,t.apiBaseUrl)}async function hy(t){const s=(t.userId||"").trim();if(!s)throw new Error("Missing userId");return ca(`/api/admin/users/${encodeURIComponent(s)}`,void 0,void 0,t.apiBaseUrl)}async function py(t){const s=(t.userId||"").trim();if(!s)throw new Error("Missing userId");return ca(`/api/admin/users/${encodeURIComponent(s)}/credit_records`,{start_date:t.start_date||void 0,end_date:t.end_date||void 0,page:t.page||1,page_size:t.page_size||20,include_increase:typeof t.include_increase=="boolean"?t.include_increase:!0},void 0,t.apiBaseUrl)}async function cx(t){const s=(t.userId||"").trim();if(!s)throw new Error("Missing userId");const a=Number(t.amount);if(!Number.isFinite(a)||a<=0)throw new Error("Amount must be a positive number");const n=(t.reason||"").trim();if(!n)throw new Error("Reason is required");return Yn(`/api/admin/users/${encodeURIComponent(s)}/credit_grants`,{amount:a,reason:n},void 0,t.apiBaseUrl)}async function dx(t){const s=(t.userId||"").trim();if(!s)throw new Error("Missing userId");return Yn(`/api/admin/users/${encodeURIComponent(s)}/enterprise_plan`,void 0,void 0,t.apiBaseUrl)}async function mx(t){const s=(t.userId||"").trim();if(!s)throw new Error("Missing userId");return lf(`/api/admin/users/${encodeURIComponent(s)}/enterprise_plan`,void 0,t.apiBaseUrl)}function Ad(t){try{const s=(t||"/").split("/").filter(Boolean);if(s[0]!=="admin")return{userId:null};if(s[1]!=="users")return{userId:null};const a=(s[2]||"").trim();if(!a)return{userId:null};try{return{userId:decodeURIComponent(a)||null}}catch{return{userId:a||null}}}catch{return{userId:null}}}function oo(t){if(!t)return"—";try{const s=new Date(t),a=s.getUTCFullYear(),n=String(s.getUTCMonth()+1).padStart(2,"0"),o=String(s.getUTCDate()).padStart(2,"0"),i=String(s.getUTCHours()).padStart(2,"0"),l=String(s.getUTCMinutes()).padStart(2,"0"),c=String(s.getUTCSeconds()).padStart(2,"0");return`${a}-${n}-${o} ${i}:${l}:${c}`}catch{return t}}function Hn(t){return Number.isFinite(t)?Math.round(t).toLocaleString():"0"}const Ic=v.createContext(null);function ux({defaultValue:t="",value:s,onValueChange:a,className:n="",children:o}){const[i,l]=v.useState(t),c=typeof s=="string",d=c?s:i,m=h=>{c?a?.(h):l(h)};return e.jsx("div",{className:n,children:e.jsx(Ic.Provider,{value:{value:d,setValue:m},children:o})})}const xx=({className:t="",...s})=>e.jsx("div",{className:`inline-flex flex-row items-center gap-2 rounded-lg bg-slate-100 p-1 ${t}`,...s}),ki=({className:t="",value:s,children:a,...n})=>{const o=v.useContext(Ic),i=o.value===s;return e.jsx("button",{className:`rounded-md px-3 py-2 text-sm transition-colors ${i?"bg-white shadow":"hover:bg-white/60"} ${t}`,onClick:l=>{o.setValue(s),n.onClick?.(l)},...n,children:a})},_i=({className:t="",value:s,...a})=>v.useContext(Ic).value!==s?null:e.jsx("div",{className:t,...a}),wr=({className:t="",viewportClassName:s="",children:a,...n})=>e.jsx("div",{className:`relative ${t}`,...n,children:e.jsx("div",{className:`h-full w-full overflow-auto ${s}`,children:a})});function hx({open:t,onOpenChange:s,isOpen:a,onClose:n,onConfirm:o,onCancel:i,title:l,message:c,confirmText:d="Confirm",cancelText:m="Cancel",variant:h="danger",isLoading:p=!1}){if(!(typeof t=="boolean"?t:!!a))return null;const x={default:{icon:"text-slate-600",confirmButton:"bg-slate-900 hover:bg-slate-800 text-white"},danger:{icon:"text-red-600",confirmButton:"bg-red-600 hover:bg-red-700 text-white"},warning:{icon:"text-yellow-600",confirmButton:"bg-yellow-600 hover:bg-yellow-700 text-white"},info:{icon:"text-blue-600",confirmButton:"bg-blue-600 hover:bg-blue-700 text-white"}}[h||"danger"],u=()=>{p||(s&&s(!1),n&&n(),i&&i())},g=async()=>{p||!o||await o()};return e.jsxs("div",{className:"fixed inset-0 z-1002 flex items-center justify-center",children:[e.jsx("div",{className:"absolute inset-0 bg-black/20 backdrop-blur-sm",onClick:u}),e.jsxs("div",{className:"relative bg-white rounded-xl shadow-lg max-w-md w-full mx-4 border border-gray-200",children:[e.jsxs("div",{className:"flex items-start justify-between p-4 border-b border-gray-100",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ss,{className:`h-4 w-4 ${x.icon}`}),e.jsx("h3",{className:"text-[13px] font-semibold text-gray-800",children:l})]}),e.jsx("button",{onClick:u,className:"flex-shrink-0 h-6 w-6 flex items-center justify-center hover:bg-gray-100 rounded transition-colors",children:e.jsx(mt,{className:"h-3.5 w-3.5 text-gray-400"})})]}),e.jsx("div",{className:"p-4",children:e.jsx("p",{className:"text-[11px] text-gray-600 leading-relaxed",children:c})}),e.jsxs("div",{className:"flex items-center justify-end gap-2 p-4 border-t border-gray-100",children:[e.jsx("button",{onClick:u,disabled:p,className:"px-3 py-1.5 rounded-lg border border-gray-200 text-[11px] font-medium text-gray-600 hover:bg-gray-50 transition-colors disabled:opacity-50 disabled:cursor-not-allowed",children:m}),e.jsx("button",{onClick:g,disabled:p,className:`px-3 py-1.5 rounded-lg text-[11px] font-medium transition-colors disabled:opacity-50 disabled:cursor-not-allowed ${x.confirmButton}`,children:p?"Processing...":d})]})]})]})}const px=v.createContext(null);function gx({children:t}){const[s,a]=v.useState(!1),[n,o]=v.useState(null),i=v.useRef(void 0),l=v.useCallback(p=>(o(p),a(!0),new Promise(f=>{i.current=f})),[]),c=p=>{i.current&&(i.current(p),i.current=void 0)},d=p=>{!p&&s&&c(!1),a(p)},m=()=>{c(!0),a(!1)},h=()=>{c(!1),a(!1)};return e.jsxs(px.Provider,{value:{confirm:l},children:[t,n&&e.jsx(hx,{open:s,onOpenChange:d,title:n.title,message:n.message,confirmText:n.confirmText,cancelText:n.cancelText,variant:n.variant,onConfirm:m,onCancel:h})]})}function ia(){const t=v.useContext(px);if(!t){const s=a=>
51{if(typeof a=="string")return a;if(a==null)return"";try{return String(a)}catch{return""}};return{confirm:async a=>window.confirm(s(a.message))}}return t}async function gy(t){const s=(t.userId||"").trim();if(!s)throw new Error("Missing userId");const a=Number(t.percent_off);if(!Number.isFinite(a)||a<1||a>50)throw new Error("percent_off must be between 1 and 50");return(await Yn("/api/admin/discount_code/create",{user_id:s,percent_off:Math.floor(a),note:(t.note||"").trim()||void 0},void 0,t.apiBaseUrl)).data}async function fy(t){const s=(t.userId||"").trim();if(!s)throw new Error("Missing userId");return(await ca(`/api/admin/discount_code/user/${encodeURIComponent(s)}`,void 0,void 0,t.apiBaseUrl)).data||[]}async function yy(t){const s=(t.discountCodeId||"").trim();if(!s)throw new Error("Missing discountCodeId");return(await Yn(`/api/admin/discount_code/${encodeURIComponent(s)}/disable`,{reason:(t.reason||"").trim()||void 0},void 0,t.apiBaseUrl)).data}function by({open:t,onOpenChange:s,onSubmit:a,submitting:n}){const[o,i]=v.useState("100"),[l,c]=v.useState(""),[d,m]=v.useState("");v.useEffect(()=>{t||(m(""),c(""),i("100"))},[t]);const h=v.useCallback(async()=>{m("");const p=Number(o);if(!Number.isFinite(p)||p<=0){m("Amount must be a positive number.");return}const f=(l||"").trim();if(!f){m("Reason is required.");return}try{await a({amount:p,reason:f}),s(!1)}catch(b){m(String(b?.message||"Failed to grant credits."))}},[o,l,a,s]);return e.jsx(Ht,{open:t,onOpenChange:s,children:e.jsxs(qt,{className:"max-w-xl",children:[e.jsxs(Zt,{divider:!0,variant:"full",density:"md",children:[e.jsx(Yt,{children:"Grant credits"}),e.jsx(Ds,{children:"This will create a credit record and increase the user balance."})]}),e.jsxs("div",{className:"px-6 py-4 space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-slate-700 mb-1",children:"Amount"}),e.jsx(bt,{type:"number",min:1,step:1,value:o,onChange:p=>i(p.target.value),placeholder:"e.g. 500",onKeyDown:p=>{p.key==="Enter"&&h()}}),e.jsx("p",{className:"text-xs text-slate-500 mt-1",children:"Credits are stored as integer balance."})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-slate-700 mb-1",children:"Reason"}),e.jsx(bt,{value:l,onChange:p=>c(p.target.value),placeholder:"e.g. Manual grant for support case #123",onKeyDown:p=>{p.key==="Enter"&&h()}})]}),d?e.jsx("div",{className:"text-sm text-red-600",children:d}):null]}),e.jsxs(Ns,{variant:"full",divider:!0,children:[e.jsx(be,{variant:"outline",onClick:()=>s(!1),disabled:n,children:"Cancel"}),e.jsx(be,{onClick:h,disabled:n,children:n?"Granting...":"Grant"})]})]})})}async function Td(t){const s=String(t??"");if(!s)return!1;try{if(navigator?.clipboard?.writeText)return await navigator.clipboard.writeText(s),!0}catch{}try{const a=document.createElement("textarea");a.value=s,a.setAttribute("readonly","true"),a.style.position="fixed",a.style.left="-9999px",a.style.top="0",document.body.appendChild(a),a.select();const n=document.execCommand("copy");return document.body.removeChild(a),!!n}catch{return!1}}function wy(){const t=new Date,s=t.getUTCFullYear(),a=String(t.getUTCMonth()+1).padStart(2,"0"),n=String(t.getUTCDate()).padStart(2,"0"),o=`${s}-${a}-${n}`,i=new Date(Date.UTC(s,t.getUTCMonth(),t.getUTCDate()));i.setUTCDate(i.getUTCDate()-29);const l=i.getUTCFullYear(),c=String(i.getUTCMonth()+1).padStart(2,"0"),d=String(i.getUTCDate()).padStart(2,"0");return{start:`${l}-${c}-${d}`,end:o}}function jy(t){if(!t?.subscription)return"free";const s=t.subscription.plan?.plan_type||"—",a=t.subscription.status||"—",n=t.subscription.billing_interval||"—";return`${s} · ${a} · ${n}`}function vy({items:t}){return!t||t.length===0?e.jsx("div",{className:"px-6 py-10 text-sm text-slate-500",children:"No records found."}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm text-left",children:[e.jsx("thead",{className:"bg-slate-50/80 border-b border-slate-200",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-6 py-3 font-semibold text-slate-500 text-xs uppercase tracking-wider w-[180px]",children:"Timestamp (UTC)"}),e.jsx("th",{className:"px-6 py-3 font-semibold text-slate-500 text-xs uppercase tracking-wider w-[120px] text-right",children:"Amount"}),e.jsx("th",{className:"px-6 py-3 font-semibold text-slate-500 text-xs uppercase tracking-wider w-[200px] text-right",children:"Balance Flow"}),e.jsx("th",{className:"px-6 py-3 font-semibold text-slate-500 text-xs uppercase tracking-wider",children:"Description"})]})}),e.jsx("tbody",{className:"divide-y divide-slate-100 bg-white",children:t.map(s=>e.jsxs("tr",{className:"hover:bg-slate-50/80 transition-colors",children:[e.jsx("td",{className:"px-6 py-3 text-slate-600 font-medium text-xs font-mono whitespace-nowrap",children:oo(s.created_at)}),e.jsx("td",{className:"px-6 py-3 text-right font-semibold tabular-nums text-xs",children:s.is_increase?e.jsxs("span",{className:"text-green-600",children:["+",Hn(s.credit_cost)]}):e.jsxs("span",{className:"text-slate-900",children:["-",Hn(s.credit_cost)]})}),e.jsx("td",{className:"px-6 py-3 text-right tabular-nums text-xs",children:e.jsxs("div",{className:"flex items-center justify-end gap-1.5",children:[e.jsx("span",{className:"text-slate-400 line-through opacity-70",children:Hn(s.before_balance)}),e.jsx("span",{className:"text-slate-300",children:"→"}),e.jsx("span",{className:"font-bold text-slate-700",children:Hn(s.after_balance)})]})}),e.jsxs("td",{className:"px-6 py-3 text-slate-700 text-xs",children:[s.description||"—",e.jsxs("div",{className:"text-[11px] text-slate-400 mt-1",children:[s.biz_type||"—"," · ",s.source||"—"]})]})]},s.id))})]})})}function Ny(t){return t.used_at?{label:"Used",cls:"bg-emerald-50 text-emerald-700 border-emerald-200"}:t.is_disabled?{label:"Disabled",cls:"bg-slate-50 text-slate-700 border-slate-200"}:t.redeemed_at?{label:"Redeemed",cls:"bg-indigo-50 text-indigo-700 border-indigo-200"}:{label:"Issued",cls:"bg-amber-50 text-amber-800 border-amber-200"}}function ky({userId:t,open:s,onOpenChange:a,apiBaseUrl:n}){const{toast:o}=_t(),{confirm:i}=ia(),[l,c]=v.useState("credit_records"),[d,m]=v.useState(!1),[h,p]=v.useState(null),[f,b]=v.useState(!1),[y,x]=v.useState(!1),[u,g]=v.useState([]),[w,_]=v.useState(0),[E,N]=v.useState(1),[S,k]=v.useState(20),D=v.useMemo(()=>wy(),[]),[F,R]=v.useState(D.start),[L,$]=v.useState(D.end),[H,K]=v.useState(!1),[X,V]=v.useState(!1),[P,A]=v.useState(!1),[C,I]=v.useState([]),[j,q]=v.useState(!1),[T,M]=v.useState("10"),[Z,B]=v.useState(""),[ae,de]=v.useState(null),fe=v.useCallback(async()=>{m(!0);try{const ie=await hy({userId:t,apiBaseUrl:n});p(ie)}catch(ie){const ve=ya(ie);o({title:ve.type==="warning"?"Warning":"Error",description:ve.content||"Failed to load user detail."}),p(null)}finally{m(!1)}},[t,n,o]),se=v.useCallback(async()=>{A(!0);try{const ie=await fy({userId:t,apiBaseUrl:n});I(ie||[])}catch(ie){const ve=ya(ie);o({title:ve.type==="warning"?"Warning":"Error",description:ve.content||"Failed to load discount codes."}),I([])}finally{A(!1)}},[t,n,o]),z=v.useCallback(async()=>{x(!0);try{const ie=await py({userId:t,start_date:F,end_date:L,page:E,page_size:S,include_increase:!0,apiBaseUrl:n});g(ie.items||[]),_(ie.total||0)}catch(ie){const ve=ya(ie);o({title:ve.type==="warning"?"Warning":"Error",description:ve.content||"Failed to load credit records."}),g([]),_(0)}finally{x(!1)}},[t,F,L,E,S,n,o]);v.useEffect(()=>{s&&(c("credit_records"),N(1),fe(),se())},[s,t,fe]),v.useEffect(()=>{s&&z()},[s,t,F,L,E,S,z]);const U=Math.max(1,Math.ceil(w/S)),Q=v.useCallback(async ie=>{V(!0);try{await cx({userId:t,amount:ie.amount,reason:ie.reason,apiBaseUrl:n}),o({title:"Success",description:"Credits granted successfully."}),await Promise.all([fe(),z()])}catch(ve){const we=ya(ve);throw o({title:we.type==="warning"?"Warning":"Error",description:we.content||"Failed to grant credits."}),ve}finally{V(!1)}},[t,n,o,fe,z]),me=v.useCallback(async()=>
51{if(!j){q(!0);try{const ie=Number(T);await gy({userId:t,percent_off:ie,note:Z,apiBaseUrl:n}),o({title:"Success",description:"Discount code created."}),B(""),await se()}catch(ie){const ve=ya(ie);o({title:ve.type==="warning"?"Warning":"Error",description:ve.content||"Failed to create discount code."})}finally{q(!1)}}},[j,T,Z,t,n,o,se]),le=v.useCallback(async ie=>{if(!(!ie?.id||ae||!await i({title:"Disable discount code?",message:`Disable code "${ie.code}" (-${Number(ie.percent_off||0)}%) for this user?`,confirmText:"Continue",cancelText:"Cancel",variant:"warning"})||!await i({title:"Confirm disable",message:"This code will no longer be redeemable. Are you sure?",confirmText:"Disable",cancelText:"Cancel",variant:"danger"}))){de(ie.id);try{await yy({discountCodeId:ie.id,reason:"Disabled by admin",apiBaseUrl:n}),o({title:"Success",description:"Discount code disabled."}),await se()}catch(Pe){const Ae=ya(Pe);o({title:Ae.type==="warning"?"Warning":"Error",description:Ae.content||"Failed to disable discount code."})}finally{de(null)}}},[n,o,se,i,ae]),O=h?.user?.email||"—",ne=h?.user?.credits_balance??0,ge=(h?.subscription?.plan?.plan_type||"").toLowerCase()||null,ze=ge!=="enterprise"&&!f,Ke=ge==="enterprise"&&!f;return e.jsxs(e.Fragment,{children:[e.jsx(Ht,{open:s,onOpenChange:a,children:e.jsx(qt,{className:"max-w-none !absolute right-0 top-0 h-screen w-[min(1000px,95vw)] rounded-none p-0",closeOnOutside:!0,children:e.jsxs("div",{className:"h-full flex flex-col bg-white",children:[e.jsxs(Zt,{divider:!0,variant:"full",density:"md",className:"flex-row items-center justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx(Yt,{className:"truncate",children:"User"}),e.jsx("div",{className:"text-xs text-slate-500 font-mono truncate mt-0.5",children:t})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(be,{variant:"outline",size:"sm",onClick:async()=>{const ie=await Td(t);o({title:ie?"Copied":"Copy failed",description:ie?"User id copied to clipboard.":"Failed to copy. Please copy manually."})},title:"Copy user id",children:[e.jsx(Ys,{className:"h-4 w-4 mr-2"}),"Copy"]}),e.jsxs(be,{variant:"outline",size:"sm",onClick:()=>{fe(),z(),se()},disabled:d||y||P,children:[e.jsx(kt,{className:`h-4 w-4 mr-2 ${d||y||P?"animate-spin":""}`}),"Refresh"]}),e.jsxs(be,{variant:"ghost",size:"sm",onClick:()=>a(!1),children:[e.jsx(mt,{className:"h-4 w-4 mr-2"}),"Close"]})]})]}),e.jsxs("div",{className:"px-6 py-4 border-b border-slate-100 bg-slate-50/40",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-slate-500",children:"Email"}),e.jsx("div",{className:"text-sm text-slate-900 font-medium truncate",children:O})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-slate-500",children:"Plan"}),e.jsx("div",{className:"text-sm text-slate-900 font-medium truncate",children:jy(h)})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-slate-500",children:"Credits"}),e.jsx("div",{className:"text-sm text-slate-900 font-semibold tabular-nums",children:Hn(ne)})]})]}),e.jsxs("div",{className:"mt-4 flex items-center gap-2",children:[e.jsx(be,{onClick:()=>K(!0),children:"Grant credit"}),ze?e.jsx(be,{variant:"outline",disabled:f,onClick:async()=>{const ie=ge||"free",ve=!!h?.subscription;if(await i({title:"Set Enterprise plan?",message:ve?`This will immediately replace the current ${ie} subscription with an admin-managed Enterprise plan. Stripe subscriptions are canceled immediately, and existing credits stay unchanged. Continue?`:"This will create an admin-managed Enterprise plan for the user (no Stripe). Existing credits stay unchanged. Continue?",confirmText:"Set Enterprise",cancelText:"Cancel",variant:"warning"})){b(!0);try{await dx({userId:t,apiBaseUrl:n}),o({title:"Success",description:"Enterprise plan has been set."}),await fe()}catch(Pe){const Ae=ya(Pe);o({title:Ae.type==="warning"?"Warning":"Error",description:Ae.content||"Failed to set Enterprise plan."})}finally{b(!1)}}},children:h?.subscription?"Switch to Enterprise":"Set Enterprise"}):null,Ke?e.jsx(be,{variant:"outline",disabled:f,onClick:async()=>
51{if(await i({title:"Revert to no plan?",message:"This will remove the Enterprise plan and revert the user to free (no subscription). Continue?",confirmText:"Revert",cancelText:"Cancel",variant:"danger"})){b(!0);try{await mx({userId:t,apiBaseUrl:n}),o({title:"Success",description:"Enterprise plan has been removed."}),await fe()}catch(ve){const we=ya(ve);o({title:we.type==="warning"?"Warning":"Error",description:we.content||"Failed to remove Enterprise plan."})}finally{b(!1)}}},children:"Revert to Free"}):null]})]}),e.jsx("div",{className:"px-6 py-4 border-b border-slate-100",children:e.jsxs(ux,{value:l,onValueChange:c,className:"w-full",children:[e.jsxs(xx,{className:"inline-flex flex-row items-center gap-2 whitespace-nowrap",children:[e.jsx(ki,{value:"credit_records",children:"Credit records"}),e.jsx(ki,{value:"discount_codes",children:"Discount codes"})]}),e.jsxs(_i,{value:"credit_records",className:"mt-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2 mb-3",children:[e.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 bg-slate-50 rounded-lg border border-slate-100",children:[e.jsx("input",{type:"date",className:"bg-transparent text-sm text-slate-700 outline-none border-none p-0 w-[120px] focus:ring-0 cursor-pointer",value:F,onChange:ie=>{R(ie.target.value),N(1)}}),e.jsx("span",{className:"text-slate-300 mx-1",children:"→"}),e.jsx("input",{type:"date",className:"bg-transparent text-sm text-slate-700 outline-none border-none p-0 w-[120px] focus:ring-0 cursor-pointer",value:L,onChange:ie=>{$(ie.target.value),N(1)}})]}),e.jsx("div",{className:"ml-auto flex items-center gap-2",children:e.jsxs("select",{className:"h-9 rounded-md border border-slate-200 bg-white px-2 text-xs font-medium text-slate-600 outline-none focus:ring-2 focus:ring-indigo-500/20 focus:border-indigo-500 cursor-pointer hover:bg-slate-50",value:String(S),onChange:ie=>{const ve=Number(ie.target.value)||20;k(ve),N(1)},disabled:y,children:[e.jsx("option",{value:"10",children:"10 / page"}),e.jsx("option",{value:"20",children:"20 / page"}),e.jsx("option",{value:"50",children:"50 / page"}),e.jsx("option",{value:"100",children:"100 / page"})]})})]}),e.jsx("div",{className:"border border-slate-200 rounded-xl overflow-hidden",children:e.jsx(wr,{className:"h-[calc(100vh-320p
51x)]",children:y?e.jsx("div",{className:"px-6 py-10 text-sm text-slate-500",children:"Loading records..."}):e.jsx(vy,{items:u})})}),e.jsxs("div",{className:"mt-3 flex items-center justify-between",children:[e.jsxs("div",{className:"text-xs text-slate-500",children:["Page ",E," of ",U," ·"," ",w.toLocaleString()," records"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(be,{variant:"outline",size:"sm",onClick:()=>N(ie=>Math.max(1,ie-1)),disabled:y||E<=1,children:"Previous"}),e.jsx(be,{variant:"outline",size:"sm",onClick:()=>N(ie=>Math.min(U,ie+1)),disabled:y||E>=U,children:"Next"})]})]})]}),e.jsxs(_i,{value:"discount_codes",className:"mt-4",children:[e.jsxs("div",{className:"flex items-start gap-3 flex-wrap",children:[e.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 bg-slate-50 rounded-lg border border-slate-100",children:[e.jsx("div",{className:"text-xs text-slate-500 font-medium whitespace-nowrap",children:"Percent off"}),e.jsx(bt,{value:T,onChange:ie=>M(ie.target.value),className:"h-9 w-[110px]",placeholder:"1-50",inputMode:"numeric"}),e.jsx("div",{className:"text-xs text-slate-400 whitespace-nowrap",children:"(1-50)"})]}),e.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 bg-slate-50 rounded-lg border border-slate-100 min-w-[280px] flex-1",children:[e.jsx("div",{className:"text-xs text-slate-500 font-medium whitespace-nowrap",children:"Note"}),e.jsx(bt,{value:Z,onChange:ie=>B(ie.target.value),className:"h-9 flex-1",placeholder:"Optional"})]}),e.jsx("div",{className:"ml-auto flex items-center gap-2",children:e.jsx(be,{onClick:me,disabled:j,children:j?"Creating...":"Create code"})})]}),e.jsx("div",{className:"mt-4 border border-slate-200 rounded-xl overflow-hidden",children:e.jsx(wr,{className:"h-[calc(100vh-320p
51x)]",children:P?e.jsx("div",{className:"px-6 py-10 text-sm text-slate-500",children:"Loading discount codes..."}):C.length===0?e.jsx("div",{className:"px-6 py-10 text-sm text-slate-500",children:"No discount codes."}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm text-left",children:[e.jsx("thead",{className:"bg-slate-50/80 border-b border-slate-200",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-6 py-3 font-semibold text-slate-500 text-xs uppercase tracking-wider w-[170px]",children:"Code"}),e.jsx("th",{className:"px-6 py-3 font-semibold text-slate-500 text-xs uppercase tracking-wider w-[110px] text-right",children:"Percent"}),e.jsx("th",{className:"px-6 py-3 font-semibold text-slate-500 text-xs uppercase tracking-wider w-[120px]",children:"Status"}),e.jsx("th",{className:"px-6 py-3 font-semibold text-slate-500 text-xs uppercase tracking-wider w-[170px]",children:"Redeemed (UTC)"}),e.jsx("th",{className:"px-6 py-3 font-semibold text-slate-500 text-xs uppercase tracking-wider w-[170px]",children:"Used (UTC)"}),e.jsx("th",{className:"px-6 py-3 font-semibold text-slate-500 text-xs uppercase tracking-wider w-[170px]",children:"Disabled (UTC)"}),e.jsx("th",{className:"px-6 py-3 font-semibold text-slate-500 text-xs uppercase tracking-wider w-[140px] text-right",children:"Actions"})]})}),e.jsx("tbody",{className:"divide-y divide-slate-100 bg-white",children:C.map(ie=>{const ve=Ny(ie);return e.jsxs("tr",{className:"hover:bg-slate-50/80 transition-colors",children:[e.jsx("td",{className:"px-6 py-3 text-slate-700 font-mono text-xs whitespace-nowrap",children:ie.code||"—"}),e.jsxs("td",{className:"px-6 py-3 text-right font-semibold tabular-nums text-xs",children:["-",Number(ie.percent_off||0),"%"]}),e.jsx("td",{className:"px-6 py-3",children:e.jsx("span",{className:`inline-flex items-center px-2 py-0.5 rounded-full border text-[10px] font-bold whitespace-nowrap ${ve.cls}`,title:ie.disabled_reason||void 0,children:ve.label})}),e.jsx("td",{className:"px-6 py-3 text-slate-600 text-xs font-mono whitespace-nowrap",children:ie.redeemed_at?oo(ie.redeemed_at):"—"}),e.jsx("td",{className:"px-6 py-3 text-slate-600 text-xs font-mono whitespace-nowrap",children:ie.used_at?oo(ie.used_at):"—"}),e.jsx("td",{className:"px-6 py-3 text-slate-600 text-xs font-mono whitespace-nowrap",children:ie.disabled_at?oo(ie.disabled_at):"—"}),e.jsx("td",{className:"px-6 py-3 text-right",children:e.jsxs("div",{className:"inline-flex items-center gap-2 justify-end",children:[e.jsx(be,{variant:"outline",size:"sm",className:"h-9 w-9 p-0",title:"Copy code",onClick:async()=>{const we=await Td(ie.code);o({title:we?"Copied":"Copy failed",description:we?"Discount code copied to clipboard.":"Failed to copy. Please copy manually."})},children:e.jsx(Ys,{className:"h-4 w-4"})}),e.jsx(be,{variant:"outline",size:"sm",className:"h-9 w-9 p-0",title:"Disable code",onClick:()=>le(ie),disabled:ie.is_disabled||!!ie.used_at||ae===ie.id,children:e.jsx(Lh,{className:"h-4 w-4"})})]})})]},ie.id)})})]})})})})]})]})})]})})}),e.jsx(by,{open:H,onOpenChange:K,onSubmit:Q,submitting:X})]})}const Pd=[{value:"free",label:"Free",color:"bg-slate-50 text-slate-600 border-slate-200"},{value:"enterprise",label:"Enterprise",color:"bg-fuchsia-50 text-fuchsia-700 border-fuchsia-200"}];function _y(t){try{navigator.clipboard.writeText(t)}catch{}}function Cy(t={}){try{const s="/admin/users",a=t.replace??!1;window.location.pathname!==s&&(a?window.history.replaceState({},"",s):window.history.pushState({},"",s),window.dispatchEvent(new PopStateEvent("popstate")))}catch{}}function Sy(t){try{const s=(t||"").trim();if(!s)return;const a=`/admin/users/${encodeURIComponent(s)}`;window.history.pushState({},"",a),window.dispatchEvent(new PopStateEvent("popstate"))}catch{}}function Id(t){const s=(t||"").toLowerCase();return s==="enterprise"?"bg-fuchsia-50 text-fuchsia-700 border-fuchsia-200":s==="starter"?"bg-sky-50 text-sky-700 border-sky-200":s==="payg"?"bg-amber-50 text-amber-800 border-amber-200":s==="pro"?"bg-indigo-50 text-indigo-700 border-indigo-200":s==="growth"?"bg-emerald-50 text-emerald-700 border-emerald-200":"bg-slate-50 text-slate-600 border-slate-200"}function Ey(){const{connected:t}=Fi();return t?e.jsx(Ay,{}):null}function Ay(){const{apiBaseUrl:t}=Fi(),{toast:s}=_t(),[a,n]=v.useState(""),[o,i]=v.useState(1),[l]=v.useState(20),[c,d]=v.useState(!1),[m,h]=v.useState(""),[p,f]=v.useState([]),[b,y]=v.useState(0),[x,u]=v.useState(()=>Ad(window.location.pathname).userId),[g,w]=v.useState(!1),[_,E]=v.useState(null),[N,S]=v.useState(""),[k,D]=v.useState(""),[F,R]=v.useState(""),[L,$]=v.useState(!1),[H,K]=v.useState(!1);v.useEffect(()=>{const I=()=>{u(Ad(window.location.pathname).userId)};return window.addEventListener("popstate",I),()=>window.removeEventListener("popstate",I)},[]);const X=Math.max(1,Math.ceil(b/l)),V=v.useCallback(async()=>{d(!0),h("");try{const I=await xy({q:a.trim()||void 0,page:o,page_size:l,apiBaseUrl:t});f(I.items||[]),y(I.total||0)}catch(I){const j=ya(I);h(j.content||"Failed to load users."),s({title:j.type==="warning"?"Warning":"Error",description:j.content||"Failed to load users."}),f([]),y(0)}finally{d(!1)}},[a,o,l,t,s]);v.useEffect(()=>{V()},[V]);const P=I=>{const j=(I.plan_type||"free").toLowerCase();E(I),S(j==="enterprise"||j==="free"?j:"enterprise"),D(""),R(""),w(!0)},A=async()=>
51{if(!_||L)return;const I=Number(k);if(!Number.isFinite(I)||I<=0){s({title:"Error",description:"Amount must be a positive number"});return}if(!F.trim()){s({title:"Error",description:"Reason is required"});return}$(!0);try{await cx({userId:_.user_id,amount:I,reason:F.trim(),apiBaseUrl:t}),s({title:"Success",description:`Granted ${I.toLocaleString()} credits`}),D(""),R(""),V()}catch(j){const q=ya(j);s({title:"Error",description:q.content||"Failed to grant credits"})}finally{$(!1)}},C=async()=>{if(!_||H)return;const I=(_.plan_type||"free").toLowerCase();if(N!=="enterprise"&&!(N==="free"&&I==="enterprise")){s({title:"Error",description:"Invalid plan selected"});return}if(N===I){s({title:"Info",description:"No change - same plan selected"});return}K(!0);try{N==="enterprise"?(await dx({userId:_.user_id,apiBaseUrl:t}),s({title:"Success",description:"Plan set to Enterprise"})):(await mx({userId:_.user_id,apiBaseUrl:t}),s({title:"Success",description:"Plan cleared to Free"})),w(!1),V()}catch(q){const T=ya(q);s({title:"Error",description:T.content||"Failed to set plan"})}finally{K(!1)}};return e.jsxs("div",{className:"min-h-screen bg-gray-50",children:[e.jsx("header",{className:"bg-white shadow-sm border-b",children:e.jsxs("div",{className:"max-w-7xl mx-auto px-4 py-4 flex justify-between items-center",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-xl font-bold text-gray-800",children:"Users"}),e.jsxs("p",{className:"text-xs text-gray-500 font-mono",children:["Connected to: ",t]})]}),e.jsxs(be,{variant:"ghost",size:"sm",onClick:()=>V(),disabled:c,children:[e.jsx(kt,{className:`h-4 w-4 mr-2 ${c?"animate-spin":""}`}),"Refresh"]})]})}),e.jsxs("main",{className:"max-w-7xl mx-auto px-4 py-6 space-y-4",children:[e.jsxs("div",{className:"bg-white rounded-lg shadow-sm border p-4 flex items-center gap-3",children:[e.jsx(bt,{value:a,onChange:I=>n(I.target.value),placeholder:"Search by user id or email",onKeyDown:I=>{I.key==="Enter"&&(i(1),V())}}),e.jsx(be,{variant:"outline",onClick:()=>{i(1),V()},disabled:c,children:"Search"})]}),e.jsxs("div",{className:"bg-white rounded-lg shadow-sm border p-0 overflow-hidden",children:[m?e.jsx("div",{className:"p-4 text-sm text-red-600",children:m}):null,e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-left",children:[e.jsx("thead",{className:"bg-gray-50 border-y",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-4 py-3 text-xs font-semibold text-gray-600",children:"User ID"}),e.jsx("th",{className:"px-4 py-3 text-xs font-semibold text-gray-600",children:"Username"}),e.jsx("th",{className:"px-4 py-3 text-xs font-semibold text-gray-600",children:"Email"}),e.jsx("th",{className:"px-4 py-3 text-xs font-semibold text-gray-600",children:"Plan"}),e.jsx("th",{className:"px-4 py-3 text-xs font-semibold text-gray-600 text-right",children:"Credits"}),e.jsx("th",{className:"px-4 py-3 text-xs font-semibold text-gray-600",children:"Created"}),e.jsx("th",{className:"px-4 py-3 text-xs font-semibold text-gray-600",children:"Actions"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-100",children:c&&p.length===0?e.jsx("tr",{children:e.jsx("td",{className:"px-4 py-10 text-center text-gray-500",colSpan:7,children:"Loading users..."})}):p.length===0?e.jsx("tr",{children:e.jsx("td",{className:"px-4 py-10 text-center text-gray-500",colSpan:7,children:"No users found"})}):p.map(I=>e.jsxs("tr",{className:"hover:bg-gray-50",children:[e.jsx("td",{className:"px-4 py-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-mono text-xs text-gray-700",children:I.user_id}),e.jsx("button",{className:"text-gray-400 hover:text-gray-600",title:"Copy",onClick:()=>_y(I.user_id),children:e.jsx(Ys,{className:"h-3.5 w-3.5"})})]})}),e.jsx("td",{className:"px-4 py-3 text-sm text-gray-700",children:I.username||"—"}),e.jsx("td",{className:"px-4 py-3 text-sm text-gray-700",children:I.email||"—"}),e.jsx("td",{className:"px-4 py-3",children:e.jsx("button",{onClick:()=>P(I),className:"text-left hover:opacity-80 transition-opacity cursor-pointer",title:"Click to manage plan & credits",children:e.jsx("span",{className:`inline-flex items-center px-2 py-1 rounded text-xs font-medium border ${Id(I.plan_type)}`,children:(I.plan_type||"free").toLowerCase()})})}),e.jsx("td",{className:"px-4 py-3 text-sm text-gray-700 text-right tabular-nums",children:Hn(I.credits_balance||0)}),e.jsx("td",{className:"px-4 py-3 text-sm text-gray-600",children:oo(I.created_at)}),e.jsx("td",{className:"px-4 py-3",children:e.jsx(be,{variant:"ghost",size:"sm",onClick:()=>
51Sy(I.user_id),children:"View"})})]},I.user_id))})]})}),e.jsxs("div",{className:"flex justify-between items-center px-4 py-3 border-t bg-white",children:[e.jsxs("div",{className:"text-sm text-gray-600",children:["Showing ",p.length," of ",b," users"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(be,{variant:"outline",size:"sm",onClick:()=>i(I=>Math.max(1,I-1)),disabled:c||o<=1,children:"Previous"}),e.jsxs("div",{className:"text-xs text-gray-500",children:["Page ",o," / ",X]}),e.jsx(be,{variant:"outline",size:"sm",onClick:()=>i(I=>Math.min(X,I+1)),disabled:c||o>=X,children:"Next"})]})]})]})]}),e.jsx(ky,{apiBaseUrl:t,userId:x||"",open:!!x,onOpenChange:I=>{I||Cy()}}),e.jsx(Ht,{open:g,onOpenChange:w,children:e.jsxs(qt,{className:"max-w-md",children:[e.jsx(Zt,{children:e.jsx(Yt,{children:"Manage Plan & Credits"})}),_&&e.jsx("div",{className:"space-y-6",children:(()=>{const q=(_.plan_type||"free").toLowerCase()==="enterprise"?Pd:Pd.filter(T=>T.value!=="free");return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"p-3 bg-gray-50 rounded-lg border",children:[e.jsxs("div",{className:"text-sm text-gray-600",children:[e.jsx("span",{className:"font-medium",children:"User:"})," ",_.email||_.username||_.user_id]}),e.jsxs("div",{className:"text-sm text-gray-600 mt-1",children:[e.jsx("span",{className:"font-medium",children:"Current Plan:"})," ",e.jsx("span",{className:`inline-flex items-center px-2 py-0.5 rounded text-xs font-medium border ${Id(_.plan_type)}`,children:(_.plan_type||"free").toLowerCase()})]}),e.jsxs("div",{className:"text-sm text-gray-600 mt-1",children:[e.jsx("span",{className:"font-medium",children:"Credits:"})," ",Hn(_.credits_balance||0)]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs(Gt,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(zh,{className:"h-4 w-4 text-amber-500"}),"Change Plan"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(nr,{value:N,onValueChange:S,children:[e.jsx(rr,{className:"flex-1",children:e.jsx(Ui,{placeholder:"Select plan"})}),e.jsx(or,{children:q.map(T=>e.jsx(_s,{value:T.value,children:e.jsx("span",{className:`inline-flex items-center px-2 py-0.5 rounded text-xs font-medium border ${T.color}`,children:T.label})},T.value))})]}),e.jsx(be,{onClick:C,disabled:H||!N||N===(_.plan_type||"free").toLowerCase(),className:"bg-amber-600 hover:bg-amber-700",children:H?"Saving...":"Save"})]}),e.jsx("p",{className:"text-xs text-gray-500",children:"Switching a non-free user to Enterprise will immediately close the current active subscription and replace it with an admin-managed Enterprise plan. Revert to Free is only available from Enterprise."})]}),e.jsxs("div",{className:"space-y-3 pt-3 border-t",children:[e.jsxs(Gt,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(vs,{className:"h-4 w-4 text-emerald-500"}),"Add Credits"]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(Gt,{className:"text-xs text-gray-500",children:"Amount"}),e.jsx(bt,{type:"number",placeholder:"e.g. 10000",value:k,onChange:T=>D(T.target.value),min:1})]}),e.jsxs("div",{children:[e.jsx(Gt,{className:"text-xs text-gray-500",children:"Reason"}),e.jsx(bt,{placeholder:"e.g. Promo bonus",value:F,onChange:T=>R(T.target.value)})]})]}),e.jsx(be,{onClick:A,disabled:L||!k||!F.trim(),className:"w-full bg-emerald-600 hover:bg-emerald-700",children:L?"Granting...":"Grant Credits"})]})]})})()})]})})]})}function Ty(){const[t,s]=r.useState([]),[a,n]=r.useState(!1),[o,i]=r.useState([]),[l,c]=r.useState(!1),[d,m]=r.useState(""),[h,p]=r.useState(60),[f,b]=r.useState(1e3),[y,x]=r.useState(!1),[u,g]=r.useState(null),[w,_]=r.useState(!1),[E,N]=r.useState(null),[S,k]=r.useState(null),[D,F]=r.useState(null);r.useEffect(()=>{L()},[l]);const R=(A,C)=>{i(I=>[...I,{type:A,text:C}]),setTimeout(()=>{i(I=>I.slice(1))},5e3)},L=async()=>{n(!0);try{const A=await sn.listAPIKeys(l);A.success?s(A.keys):R("error","Failed to load API keys")}catch(A){R("error",A.response?.data?.detail||"Failed to load API keys")}finally{n(!1)}},$=async()=>{if(!d.trim()){R("error","Please enter a name for the API key");return}x(!0);try{const A={name:d,rate_limit_per_minute:h,rate_limit_per_day:f},C=await sn.generateAPIKey(A);C.success&&(g({key:C.api_key,prefix:C.key_info.key_prefix}),_(!0),m(""),await L(),R("success","API key generated successfully!"))}catch(A){R("error",A.response?.data?.detail||"Failed to generate API key")}finally{x(!1)}},H=async A=>{try{(await sn.updateAPIKeyLimits(A,S??void 0,D??void 0)).success&&(R("success","API key limits updated successfully"),N(null),k(null),F(null),await L())}catch(C){R("error",C.response?.data?.detail||"Failed to update API key limits")}},K=async A=>
51{if(confirm("Are you sure you want to deactivate this API key?"))try{(await sn.deactivateAPIKey(A)).success&&(R("success","API key deactivated successfully"),await L())}catch(C){R("error",C.response?.data?.detail||"Failed to deactivate API key")}},X=async A=>{if(confirm("Are you sure you want to permanently delete this API key? This action cannot be undone."))try{(await sn.deleteAPIKey(A)).success&&(R("success","API key deleted successfully"),await L())}catch(C){R("error",C.response?.data?.detail||"Failed to delete API key")}},V=A=>{navigator.clipboard.writeText(A),R("success","Copied to clipboard!")},P=A=>{if(!A)return"—";try{return new Date(A).toLocaleString()}catch{return A}};return e.jsx("div",{className:"h-full bg-slate-50",children:e.jsxs("div",{className:"px-6 py-6",children:[e.jsxs("div",{className:"mb-5",children:[e.jsx("div",{className:"text-lg font-semibold text-slate-900",children:"Open API Keys Management"}),e.jsx("div",{className:"text-sm text-slate-600",children:"Generate and manage Open API keys for blog creation"})]}),o.length>0&&e.jsx("div",{className:"fixed top-4 right-4 z-50 space-y-2",children:o.map((A,C)=>e.jsx("div",{className:`px-4 py-3 rounded-md shadow-lg ${A.type==="success"?"bg-green-50 text-green-800 border border-green-200":A.type==="error"?"bg-red-50 text-red-800 border border-red-200":"bg-blue-50 text-blue-800 border border-blue-200"}`,children:A.text},C))}),e.jsxs("div",{className:"bg-white rounded-lg shadow-sm border border-gray-200 p-6 mb-6",children:[e.jsxs("h2",{className:"text-xl font-semibold text-gray-900 mb-4 flex items-center gap-2",children:[e.jsx(oc,{size:20}),"Generate New API Key"]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:["Key Name ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(bt,{type:"text",placeholder:"Enter key name...",value:d,onChange:A=>m(A.target.value),className:"w-full"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Rate Limit (per minute)"}),e.jsx(bt,{type:"number",min:1,max:1e3,value:h,onChange:A=>p(parseInt(A.target.value)||60),className:"w-full"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Rate Limit (per day)"}),e.jsx(bt,{type:"number",min:1,max:1e5,value:f,onChange:A=>b(parseInt(A.target.value)||1e3),className:"w-full"})]})]}),e.jsx(be,{onClick:$,disabled:y||!d.trim(),className:"w-full",children:y?"Generating...":"Generate API Key"}),w&&u&&e.jsxs("div",{className:"mt-4 p-4 bg-yellow-50 border border-yellow-200 rounded-md",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("span",{className:"text-sm font-medium text-yellow-800",children:"⚠️ Save this key now - you won't see it again!"}),e.jsxs("button",{onClick:()=>V(u.key),className:"text-sm text-yellow-800 hover:text-yellow-900 underline flex items-center gap-1",children:[e.jsx(Ys,{size:14}),"Copy"]})]}),e.jsx("div",{className:"bg-white p-3 rounded border border-yellow-300 font-mono text-sm text-gray-900 break-all",children:u.key}),e.jsxs("div",{className:"mt-2 text-xs text-gray-600",children:["Prefix: ",u.prefix,"..."]})]})]})]}),e.jsxs("div",{className:"bg-white rounded-lg shadow-sm border border-gray-200 p-6",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("h2",{className:"text-xl font-semibold text-gray-900",children:"API Keys List"}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("label",{className:"flex items-center gap-2 text-sm text-gray-700",children:[e.jsx("input",{type:"checkbox",checked:l,onChange:A=>c(A.target.checked),className:"rounded"}),"Include inactive"]}),e.jsxs(be,{variant:"outline",size:"sm",onClick:L,disabled:a,children:[e.jsx(kt,{className:`h-4 w-4 mr-2 ${a?"animate-spin":""}`}),"Refresh"]})]})]}),a&&t.length===0?e.jsx("div",{className:"text-center py-10 text-gray-500",children:"Loading API keys..."}):t.length===0?e.jsx("div",{className:"text-center py-10 text-gray-500",children:"No API keys found"}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-left",children:[e.jsx("thead",{className:"bg-gray-50 border-y",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-4 py-3 text-xs font-semibold text-gray-600",children:"Name"}),e.jsx("th",{className:"px-4 py-3 text-xs font-semibold text-gray-600",children:"Key Prefix"}),e.jsx("th",{className:"px-4 py-3 text-xs font-semibold text-gray-600",children:"Rate Limits"}),e.jsx("th",{className:"px-4 py-3 text-xs font-semibold text-gray-600",children:"Usage"}),e.jsx("th",{className:"px-4 py-3 text-xs font-semibold text-gray-600",children:"Status"}),e.jsx("th",{className:"px-4 py-3 text-xs font-semibold text-gray-600",children:"Created"}),e.jsx("th",{className:"px-4 py-3 text-xs font-semibold text-gray-600",children:"Last Used"}),e.jsx("th",{className:"px-4 py-3 text-xs font-semibold text-gray-600",children:"Actions"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-100",children:t.map(A=>e.jsxs("tr",{className:"hover:bg-gray-50",children:[e.jsx("td",{className:"px-4 py-3",children:e.jsx("div",{className:"text-sm font-medium text-gray-900",children:A.name})}),e.jsx("td",{className:"px-4 py-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"font-mono text-xs text-gray-700",children:[A.key_prefix,"..."]}),e.jsx("button",{onClick:()=>V(A.key_prefix),className:"text-gray-400 hover:text-gray-600",title:"Copy prefix",children:e.jsx(Ys,{size:14})})]})}),e.jsx("td",{className:"px-4 py-3",children:E===A.id?e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(bt,{type:"number",min:1,max:1e3,value:S??A.rate_limit_per_minute,onChange:C=>
51k(parseInt(C.target.value)||null),className:"w-20 text-xs",placeholder:"Min"}),e.jsx("span",{className:"text-xs text-gray-500",children:"/min"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(bt,{type:"number",min:1,max:1e5,value:D??A.rate_limit_per_day,onChange:C=>F(parseInt(C.target.value)||null),className:"w-20 text-xs",placeholder:"Day"}),e.jsx("span",{className:"text-xs text-gray-500",children:"/day"})]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(be,{size:"sm",variant:"outline",onClick:()=>H(A.id),className:"text-xs h-6",children:"Save"}),e.jsx(be,{size:"sm",variant:"ghost",onClick:()=>{N(null),k(null),F(null)},className:"text-xs h-6",children:"Cancel"})]})]}):e.jsxs("div",{className:"text-xs text-gray-600",children:[e.jsxs("div",{children:[A.rate_limit_per_minute," /min"]}),e.jsxs("div",{children:[A.rate_limit_per_day," /day"]}),e.jsx("button",{onClick:()=>{N(A.id),k(A.rate_limit_per_minute),F(A.rate_limit_per_day)},className:"text-blue-600 hover:text-blue-700 mt-1",children:"Edit"})]})}),e.jsx("td",{className:"px-4 py-3",children:e.jsxs("div",{className:"text-xs text-gray-600",children:[A.total_requests||0," requests"]})}),e.jsx("td",{className:"px-4 py-3",children:e.jsx("span",{className:`inline-flex items-center px-2 py-1 rounded text-xs font-medium ${A.is_active?"bg-green-50 text-green-700 border border-green-200":"bg-gray-50 text-gray-600 border border-gray-200"}`,children:A.is_active?"Active":"Inactive"})}),e.jsx("td",{className:"px-4 py-3 text-xs text-gray-600",children:P(A.created_at)}),e.jsx("td",{className:"px-4 py-3 text-xs text-gray-600",children:P(A.last_used_at)}),e.jsx("td",{className:"px-4 py-3",children:e.jsxs("div",{className:"flex items-center gap-1",children:[A.is_active?e.jsx(be,{size:"sm",variant:"ghost",onClick:()=>K(A.id),className:"text-xs h-7",title:"Deactivate",children:e.jsx($h,{size:14})}):e.jsx(be,{size:"sm",variant:"ghost",onClick:()=>H(A.id),className:"text-xs h-7",title:"Reactivate (update to activate)",children:e.jsx(Fh,{size:14})}),e.jsx(be,{size:"sm",variant:"ghost",onClick:()=>X(A.id),className:"text-xs h-7 text-red-600 hover:text-red-700",title:"Delete",children:e.jsx(es,{size:14})})]})})]},A.id))})]})})]})]})})}function Py(){const[t,s]=r.useState([]),[a,n]=r.useState(!1),[o,i]=r.useState([]),[l,c]=r.useState(null),[d,m]=r.useState(!1),[h,p]=r.useState(new Set),[f,b]=r.useState(!1),[y,x]=r.useState(1),[u]=r.useState(20),[g,w]=r.useState(""),[_,E]=r.useState("");r.useEffect(()=>{S()},[y,g]),r.useEffect(()=>{p(new Set)},[t]);const N=(C,I)=>{i(j=>[...j,{type:C,text:I}]),setTimeout(()=>{i(j=>j.slice(1))},5e3)},S=async()=>{n(!0);try{const C={page:y,limit:u,status:g||void 0,q:_||void 0},I=await Fs.listPosts(C);s(I.posts)}catch(C){N("error",C.message||"Failed to load blog posts")}finally{n(!1)}},k=()=>{x(1),S()},D=async C=>{try{const I=await Fs.getPostDetail(C.id);c(I),m(!0)}catch(I){N("error",I.message||"Failed to load post detail")}},F=async C=>{if(confirm("Are you sure you want to publish this blog post?"))try{if(await Fs.publishPost(C),N("success","Blog post published successfully"),await S(),l?.id===C){const I=await Fs.getPostDetail(C);c(I)}}catch(I){N("error",I.message||"Failed to publish blog post")}},R=async C=>{if(confirm("Are you sure you want to unpublish this blog post?"))try{if(await Fs.unpublishPost(C),N("success","Blog post unpublished successfully"),await S(),l?.id===C){const I=await Fs.getPostDetail(C);c(I)}}catch(I){N("error",I.message||"Failed to unpublish blog post")}},L=async C=>{if(confirm("Are you sure you want to permanently delete this blog post? This action cannot be undone."))try{await Fs.deletePost(C),N("success","Blog post deleted successfully"),l?.id===C&&(m(!1),c(null)),await S()}catch(I){N("error",I.message||"Failed to delete blog post")}},$=C=>{p(I=>{const j=new Set(I);return j.has(C)?j.delete(C):j.add(C),j})},H=()=>{h.size===t.length?p(new Set):p(new Set(t.map(C=>C.id)))},K=async()=>{if(h.size===0){N("error","Please select at least one blog post");return}if(confirm(`Are you sure you want to publish ${h.size} blog post(s)?`)){b(!0);try{const C=Array.from(h),I=await Fs.batchPublishPosts(C);N("success",`Published ${I.processed_count} post(s), ${I.failed_count} failed`),I.failed_ids.length>0&&N("error",`Failed IDs: ${I.failed_ids.join(", ")}`),p(new Set),await S()}catch(C){N("error",C.message||"Failed to batch publish posts")}finally{b(!1)}}},X=async()=>
51{if(h.size===0){N("error","Please select at least one blog post");return}if(confirm(`Are you sure you want to unpublish ${h.size} blog post(s)?`)){b(!0);try{const C=Array.from(h),I=await Fs.batchUnpublishPosts(C);N("success",`Unpublished ${I.processed_count} post(s), ${I.failed_count} failed`),I.failed_ids.length>0&&N("error",`Failed IDs: ${I.failed_ids.join(", ")}`),p(new Set),await S()}catch(C){N("error",C.message||"Failed to batch unpublish posts")}finally{b(!1)}}},V=async()=>{if(h.size===0){N("error","Please select at least one blog post");return}if(confirm(`Are you sure you want to permanently delete ${h.size} blog post(s)? This action cannot be undone.`)){b(!0);try{const C=Array.from(h),I=await Fs.batchDeletePosts(C);N("success",`Deleted ${I.processed_count} post(s), ${I.failed_count} failed`),I.failed_ids.length>0&&N("error",`Failed IDs: ${I.failed_ids.join(", ")}`),p(new Set),l&&C.includes(l.id)&&(m(!1),c(null)),await S()}catch(C){N("error",C.message||"Failed to batch delete posts")}finally{b(!1)}}},P=C=>{if(!C)return"—";try{return new Date(C).toLocaleString()}catch{return"—"}},A=C=>{switch(C){case"published":return"bg-green-50 text-green-700 border-green-200";case"draft":return"bg-yellow-50 text-yellow-700 border-yellow-200";case"archived":return"bg-gray-50 text-gray-600 border-gray-200";default:return"bg-gray-50 text-gray-600 border-gray-200"}};return d&&l?e.jsx("div",{className:"h-full bg-slate-50",children:e.jsxs("div",{className:"px-6 py-6",children:[e.jsxs("div",{className:"mb-5 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-lg font-semibold text-slate-900",children:"Blog Post Detail"}),e.jsx("div",{className:"text-sm text-slate-600",children:"View and manage blog post details"})]}),e.jsx(be,{variant:"outline",onClick:()=>m(!1),children:"Back to List"})]}),o.length>0&&e.jsx("div",{className:"fixed top-4 right-4 z-50 space-y-2",children:o.map((C,I)=>e.jsx("div",{className:`px-4 py-3 rounded-md shadow-lg ${C.type==="success"?"bg-green-50 text-green-800 border border-green-200":C.type==="error"?"bg-red-50 text-red-800 border border-red-200":"bg-blue-50 text-blue-800 border border-blue-200"}`,children:C.text},I))}),e.jsxs("div",{className:"bg-white rounded-lg shadow-sm border border-gray-200 p-6",children:[e.jsxs("div",{className:"mb-6 flex items-start justify-between",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx("h1",{className:"text-2xl font-bold text-gray-900 mb-2",children:l.title}),e.jsxs("div",{className:"flex items-center gap-4 text-sm text-gray-600",children:[e.jsx("span",{className:`inline-flex items-center px-2 py-1 rounded text-xs font-medium border ${A(l.status)}`,children:l.status}),l.category&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Lr,{size:14}),l.category]}),l.read_time&&e.jsxs("span",{children:[l.read_time," min read"]})]})]}),e.jsxs("div",{className:"flex gap-2",children:[l.status==="draft"?e.jsxs(be,{size:"sm",onClick:()=>F(l.id),className:"bg-green-600 hover:bg-green-700",children:[e.jsx(Ga,{size:14,className:"mr-2"}),"Publish"]}):l.status==="published"?e.jsxs(be,{size:"sm",variant:"outline",onClick:()=>R(l.id),children:[e.jsx(Qi,{size:14,className:"mr-2"}),"Unpublish"]}):null,e.jsxs(be,{size:"sm",variant:"outline",onClick:()=>L(l.id),className:"text-red-600 hover:text-red-700",children:[e.jsx(es,{size:14,className:"mr-2"}),"Delete"]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Slug"}),e.jsx("div",{className:"text-sm text-gray-900 font-mono bg-gray-50 p-2 rounded border",children:l.slug})]}),l.excerpt&&e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Excerpt"}),e.jsx("div",{className:"text-sm text-gray-900 bg-gray-50 p-3 rounded border",children:l.excerpt})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Content"}),e.jsx("div",{className:"text-sm text-gray-900 bg-gray-50 p-4 rounded border max-h-96 overflow-y-auto whitespace-pre-wrap",children:l.content||"—"})]}),l.tags&&l.tags.length>0&&e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Tags"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:l.tags.map((C,I)=>e.jsx("span",{className:"px-2 py-1 bg-blue-50 text-blue-700 rounded text-xs",children:C},I))})]}),l.author&&e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Author"}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-gray-900",children:[e.jsx(Oh,{size:14}),e.jsx("span",{children:l.author.name}),l.author.email&&e.jsxs("span",{className:"text-gray-500",children:["(",l.author.email,")"]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Created At"}),e.jsxs("div",{className:"text-sm text-gray-600 flex items-center gap-1",children:[e.jsx(ka,{size:14}),P(l.created_at)]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Updated At"}),e.jsxs("div",{className:"text-sm text-gray-600 flex items-center gap-1",children:[e.jsx(ka,{size:14}),P(l.updated_at)]})]}),l.published_at&&e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Published At"}),e.jsxs("div",{className:"text-sm text-gray-600 flex items-center gap-1",children:[e.jsx(ka,{size:14}),P(l.published_at)]})]})]}),l.seo_title&&e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"geo/aeo Title"}),e.jsx("div",{className:"text-sm text-gray-900 bg-gray-50 p-2 rounded border",children:l.seo_title})]}),l.seo_description&&e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"geo/aeo Description"}),e.jsx("div",{className:"text-sm text-gray-900 bg-gray-50 p-2 rounded border",children:l.seo_description})]})]})]})]})}):e.jsx("div",{className:"h-full bg-slate-50",children:e.jsxs("div",{className:"px-6 py-6",children:[e.jsxs("div",{className:"mb-5",children:[e.jsx("div",{className:"text-lg font-semibold text-slate-900",children:"Blog Management"}),e.jsx("div",{className:"text-sm text-slate-600",children:"View and manage blog posts"})]}),o.length>0&&e.jsx("div",{className:"fixed top-4 right-4 z-50 space-y-2",children:o.map((C,I)=>e.jsx("div",{className:`px-4 py-3 rounded-md shadow-lg ${C.type==="success"?"bg-green-50 text-green-800 border border-green-200":C.type==="error"?"bg-red-50 text-red-800 border border-red-200":"bg-blue-50 text-blue-800 border border-blue-200"}`,children:C.text},I))}),e.jsx("div",{className:"bg-white rounded-lg shadow-sm border border-gray-200 p-4 mb-6",children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"flex-1",children:e.jsxs("div",{className:"relative",children:[e.jsx(Pt,{size:16,className:"absolute left-3 top-1/2 -translate-y-1/2 text-gray-400"}),e.jsx(bt,{type:"text",placeholder:"Search by title or excerpt...",value:_,onCh
51ange:C=>E(C.target.value),onKeyDown:C=>{C.key==="Enter"&&k()},className:"pl-10"})]})}),e.jsxs("select",{value:g,onChange:C=>{w(C.target.value),x(1)},className:"px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 text-sm",children:[e.jsx("option",{value:"",children:"All Status"}),e.jsx("option",{value:"published",children:"Published"}),e.jsx("option",{value:"draft",children:"Draft"}),e.jsx("option",{value:"archived",children:"Archived"})]}),e.jsxs(be,{onClick:k,variant:"outline",size:"sm",children:[e.jsx(Pt,{size:14,className:"mr-2"}),"Search"]}),e.jsxs(be,{variant:"outline",size:"sm",onClick:S,disabled:a,children:[e.jsx(kt,{className:`h-4 w-4 mr-2 ${a?"animate-spin":""}`}),"Refresh"]})]})}),h.size>0&&e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-4 mb-6 flex items-center justify-between",children:[e.jsxs("div",{className:"text-sm text-blue-900 font-medium",children:[h.size," post(s) selected"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(be,{size:"sm",onClick:K,disabled:f,className:"bg-green-600 hover:bg-green-700",children:[e.jsx(Ga,{size:14,className:"mr-2"}),"Batch Publish"]}),e.jsxs(be,{size:"sm",variant:"outline",onClick:X,disabled:f,children:[e.jsx(Qi,{size:14,className:"mr-2"}),"Batch Unpublish"]}),e.jsxs(be,{size:"sm",variant:"outline",onClick:V,disabled:f,className:"text-red-600 hover:text-red-700",children:[e.jsx(es,{size:14,className:"mr-2"}),"Batch Delete"]}),e.jsx(be,{size:"sm",variant:"ghost",onClick:()=>p(new Set),disabled:f,children:"Clear Selection"})]})]}),e.jsxs("div",{className:"bg-white rounded-lg shadow-sm border border-gray-200",children:[a&&t.length===0?e.jsx("div",{className:"text-center py-10 text-gray-500",children:"Loading blog posts..."}):t.length===0?e.jsx("div",{className:"text-center py-10 text-gray-500",children:"No blog posts found"}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-left",children:[e.jsx("thead",{className:"bg-gray-50 border-y",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-4 py-3 text-xs font-semibold text-gray-600 w-12",children:e.jsx("input",{type:"checkbox",checked:h.size===t.length&&t.length>0,onChange:H,className:"rounded"})}),e.jsx("th",{className:"px-4 py-3 text-xs font-semibold text-gray-600",children:"Title"}),e.jsx("th",{className:"px-4 py-3 text-xs font-semibold text-gray-600",children:"Status"}),e.jsx("th",{className:"px-4 py-3 text-xs font-semibold text-gray-600",children:"Category"}),e.jsx("th",{className:"px-4 py-3 text-xs font-semibold text-gray-600",children:"Author"}),e.jsx("th",{className:"px-4 py-3 text-xs font-semibold text-gray-600",children:"Published"}),e.jsx("th",{className:"px-4 py-3 text-xs font-semibold text-gray-600",children:"Created"}),e.jsx("th",{className:"px-4 py-3 text-xs font-semibold text-gray-600",children:"Actions"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-100",children:t.map(C=>e.jsxs("tr",{className:`hover:bg-gray-50 ${h.has(C.id)?"bg-blue-50":""}`,children:[e.jsx("td",{className:"px-4 py-3",children:e.jsx("input",{type:"checkbox",checked:h.has(C.id),onChange:()=>$(C.id),className:"rounded"})}),e.jsxs("td",{className:"px-4 py-3",children:[e.jsx("div",{className:"text-sm font-medium text-gray-900",children:C.title}),e.jsx("div",{className:"text-xs text-gray-500 font-mono",children:C.slug})]}),e.jsx("td",{className:"px-4 py-3",children:e.jsx("span",{className:`inline-flex items-center px-2 py-1 rounded text-xs font-medium border ${A(C.status)}`,children:C.status})}),e.jsx("td",{className:"px-4 py-3 text-xs text-gray-600",children:C.category||"—"}),e.jsx("td",{className:"px-4 py-3 text-xs text-gray-600",children:C.author?.name||"—"}),e.jsx("td",{className:"px-4 py-3 text-xs text-gray-600",children:P(C.published_at)}),e.jsx("td",{className:"px-4 py-3 text-xs text-gray-600",children:P(C.
51created_at)}),e.jsx("td",{className:"px-4 py-3",children:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(be,{size:"sm",variant:"ghost",onClick:()=>D(C),className:"text-xs h-7",title:"View Detail",children:e.jsx(is,{size:14})}),C.status==="draft"?e.jsx(be,{size:"sm",variant:"ghost",onClick:()=>F(C.id),className:"text-xs h-7 text-green-600 hover:text-green-700",title:"Publish",children:e.jsx(Ga,{size:14})}):C.status==="published"?e.jsx(be,{size:"sm",variant:"ghost",onClick:()=>R(C.id),className:"text-xs h-7 text-yellow-600 hover:text-yellow-700",title:"Unpublish",children:e.jsx(Qi,{size:14})}):null,e.jsx(be,{size:"sm",variant:"ghost",onClick:()=>L(C.id),className:"text-xs h-7 text-red-600 hover:text-red-700",title:"Delete",children:e.jsx(es,{size:14})})]})})]},C.id))})]})}),t.length>0&&e.jsxs("div",{className:"px-4 py-3 border-t border-gray-200 flex items-center justify-between",children:[e.jsxs("div",{className:"text-sm text-gray-600",children:["Page ",y]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(be,{size:"sm",variant:"outline",onClick:()=>x(C=>Math.max(1,C-1)),disabled:y===1||a,children:"Previous"}),e.jsx(be,{size:"sm",variant:"outline",onClick:()=>x(C=>C+1),disabled:a,children:"Next"})]})]})]})]})})}function Iy(){const[t,s]=r.useState([]),[a,n]=r.useState([]),[o,i]=r.useState(!1),[l,c]=r.useState(0),[d,m]=r.useState([]),[h,p]=r.useState(null),f=(w,_)=>{m(E=>[...E,{type:w,text:_}]),window.setTimeout(()=>{m(E=>E.slice(1))},4500)},b=async()=>{try{const w=await Fs.listCovers();w.success&&s(w.covers||[])}catch(w){f("error",w.message||"Failed to load cover library")}};r.useEffect(()=>{b()},[]);const y=r.useMemo(()=>a.map(w=>({name:w.name,size:w.size})),[a]),x=w=>{w&&n(Array.from(w))},u=async()=>{if(a.length===0){f("error","Please select at least one cover image");return}i(!0),c(0);try{const w=await Fs.uploadCovers(a,_=>{c(_)});if(w.success){const _=(w.uploaded||[]).filter(N=>N.error),E=(w.uploaded||[]).filter(N=>!N.error&&N.url).length;f("success",`Uploaded ${E} cover image(s)`),_.length>0&&f("error",`Failed ${_.length} image(s)`),n([]),await b()}}catch(w){f("error",w.message||"Failed to upload cover images")}finally{i(!1)}},g=async w=>{if(window.confirm("Delete this cover image?")){p(w);try{(await Fs.deleteCover(w))?.success?(f("success","Cover deleted"),await b()):f("error","Failed to delete cover")}catch(E){f("error",E.message||"Failed to delete cover")}finally{p(null)}}};return e.jsxs("div",{className:"p-6 space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-xl font-semibold text-gray-900",children:"Blog Cover Library"}),e.jsx("p",{className:"text-sm text-gray-600",children:"Upload and manage blog cover images."})]}),e.jsx(be,{onClick:()=>{b()},variant:"outline",children:"Refresh"})]}),d.length>0?e.jsx("div",{className:"space-y-2",children:d.map((w,_)=>e.jsx("div",{className:["text-sm px-3 py-2 rounded border",w.type==="success"?"bg-green-50 border-green-200 text-green-800":w.type==="error"?"bg-red-50 border-red-200 text-red-800":"bg-blue-50 border-blue-200 text-blue-800"].join(" "),children:w.text},_))}):null,e.jsxs("div",{className:"bg-white rounded-lg border border-gray-200 p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{className:"font-medium text-gray-900",children:"Upload Covers"}),e.jsx("div",{className:"text-xs text-gray-500",children:"multi-select"})]}),e.jsx(bt,{type:"file",accept:"image/*",multiple:!0,onChange:w=>x(w.target.files)}),y.length>0?e.jsxs("div",{className:"text-xs text-gray-600",children:["Selected ",y.length," file(s)"]}):null,o?e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between text-xs text-gray-600",children:[e.jsx("span",{children:"Uploading…"}),e.jsxs("span",{children:[l,"%"]})]}),e.jsx("div",{className:"w-full h-2 bg-gray-100 rounded",children:e.jsx("div",{className:"h-2 bg-gray-900 rounded",style:{width:`${l}%`}})})]}):null,e.jsxs("div",{className:"flex gap-2",children:[e.jsx(be,{onClick:()=>{u()},disabled:o||a.length===0,children:o?"Uploading...":"Upload"}),e.jsx(be,{variant:"outline",onClick:()=>n([]),disabled:o||a.length===0,children:"Clear"})]})]}),e.jsxs("div",{className:"bg-white rounded-lg border border-gray-200 p-4",children:[e.jsx("div",{className:"flex items-center justify-between mb-4",children:e.jsxs("div",{className:"font-medium text-gray-900",children:["Covers (",t.length,")"]})}),t.length===0?e.jsx("div",{className:"text-sm text-gray-500",children:"No covers uploaded."}):e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4",children:t.map(w=>e.jsxs("div",{className:"border border-gray-200 rounded overflow-hidden bg-white",children:[e.jsx("div",{className:"aspect-video bg-gray-50",children:e.jsx("img",{src:w.url,alt:w.id,className:"w-full h-full object-cover",loading:"lazy"})}),e.jsxs("div",{className:"p-2 flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-xs text-gray-600 truncate",children:w.id}),"blob_key"in w?e.jsx("div",{className:"text-[11px] text-gray-400 truncate",children:w.blob_key}):null]}),e.jsx(be,{variant:"outline",disabled:o||h===w.id,onClick:()=>{g(w.id)},children:h===w.id?"Deleting...":"Delete"})]})]},w.id))})]})]})}function il(){const[t,s]=v.useState(()=>({pathname:window.location.pathname}));v.useEffect(()=>{const n=()=>{s({pathname:window.location.pathname})};
51return window.addEventListener("popstate",n),()=>window.removeEventListener("popstate",n)},[]),v.useEffect(()=>{const n=t.pathname;(n==="/admin"||n==="/admin/")&&jn("referral",{replace:!0})},[t.pathname]);const a=dy(t.pathname);return v.useEffect(()=>{const n=t.pathname,o=n==="/admin/referral"||n==="/admin/blog_upload"||n==="/admin/users"||n==="/admin/open_api_keys"||n==="/admin/blog"||n==="/admin/blog_covers"||n.startsWith("/admin/users/");n.startsWith("/admin/")&&!o&&jn(a,{replace:!0})},[t.pathname,a]),e.jsx(za,{children:e.jsx(rf,{children:e.jsx(uy,{current:a,children:e.jsx(of,{children:a==="referral"?e.jsx(iy,{}):a==="users"?e.jsx(Ey,{}):a==="open_api_keys"?e.jsx(Ty,{}):a==="blog_covers"?e.jsx(Iy,{}):a==="blog"?e.jsx(Py,{}):e.jsx(cy,{embedded:!0,adminMode:!0})})})})})}class Cs{static{this.inFlight=null}static{this.cache=null}static invalidate(){Cs.cache=null}static async getAccountCached(s){const a=s?.ttlMs??1e4,n=s?.force??!1,o=Date.now();return!n&&Cs.cache&&Cs.cache.expiresAt>o?Cs.cache.value:(Cs.inFlight||(Cs.inFlight=(async()=>{try{const i=await y0();return Cs.cache={value:i,expiresAt:o+a},i}finally{Cs.inFlight=null}})()),Cs.inFlight)}}function vo(t){if(!t.price_usd||t.price_usd<=0||!t.yearly_price_usd)return 0;const s=t.price_usd*12;return t.yearly_price_usd>=s?0:Math.round((1-t.yearly_price_usd/s)*100)}async function fx(){return(await ot("/subscription/plans")).data}async function Xa(){return(await ot("/subscription/current")).data}async function Ci(t,s,a="monthly",n){return(await Je("/subscription/checkout",{plan_type:t,coupon_id:s,billing_interval:a,return_to:n})).data}async function My(t=!0){return(await Je("/subscription/cancel",{at_period_end:t})).data}async function Ry(){return(await Je("/subscription/reactivate")).data}async function Dy(){return(await Je("/subscription/portal")).data}async function Ly(){return(await ot("/subscription/payg_packages")).data}async function Mc(t,s){return(await Je("/subscription/payg_checkout",{package_code:t,return_to:s})).data}const Md="discount_code_suppress_until_ms";function zy(t=Date.now()){try{const s=sessionStorage.getItem(Md)||"",a=Number(s);return!Number.isFinite(a)||a<=0?!1:t>=a?(sessionStorage.removeItem(Md),!1):!0}catch{return!1}}async function yx(){return zy()?null:(await ot("/discount_code/current")).data}async function $y(t){const s=String(t||"").trim();if(!s)throw new Error("Discount code is required.");return(await Je("/discount_code/redeem",{code:s})).data}const Rc="post_sign_out_redirect_v1",Fy=["/promotion/","/geo-report/"];function Oy(t){return Fy.some(s=>t.startsWith(s))}function By(){try{return sessionStorage.getItem(Rc)}catch{return null}}function Uy(t){try{sessionStorage.setItem(Rc,t)}catch{}}function Ky(){try{sessionStorage.removeItem(Rc)}catch{}}function Rd(){try{const t=`${window.location.pathname}${window.location.search}${window.location.hash}`;return Oy(t)?t:"/"}catch{return"/"}}const Dd={free:{label:"Free",bgColor:"bg-slate-700",textColor:"text-white"},starter:{label:"Starter",bgColor:"bg-blue-100",textColor:"text-blue-600"},growth:{label:"Growth",bgColor:"bg-emerald-100",textColor:"text-emerald-600"},pro:{label:"Pro",bgColor:"bg-violet-100",textColor:"text-violet-600"},enterprise:{label:"Enterprise",bgColor:"bg-amber-100",textColor:"text-amber-600"}},Dc=({dropdownPosition:t="above"})=>{const[s,a]=r.useState(!0),[n,o]=r.useState(!1),[i,l]=r.useState(null),[c,d]=r.useState(null),[m,h]=r.useState(!1),[p,f]=r.useState(!1),[b,y]=r.useState(""),[x,u]=r.useState(!1),g=r.useRef(null),{confirm:w}=ia(),{toast:_}=_t();if(r.useEffect(()=>{(async()=>{try{const $=await rs.isAuthenticated();if(o($),!$){const H=By();if(H){Ky();try{if(`${window.location.pathname}${window.location.search}${window.location.hash}`!==H){window.location.href=H;return}}catch{}}}if($){try{const H=await Cs.getAccountCached({ttlMs:1e4});l({id:H.user_id,email:H.email||null,name:H.username||null})}catch{try{const H=await wu();l({id:H.id,email:H.email,name:H.name})}catch{}}try{const H=await Xa();d(H)}catch{}}}finally{a(!1)}})()},[]),r.useEffect(()=>{const $=H=>{g.current&&!g.current.contains(H.target)&&h(!1)};return m&&document.addEventListener("mousedown",$),()=>{document.removeEventListener("mousedown",$)}},[m]),s)return e.jsx("div",{className:"text-sm text-slate-500","aria-busy":!0,children:"Loading..."});if(!n)return e.jsx(be,{size:"sm",className:"rounded-2xl",onClick:()=>An(),children:"Sign in"});const E=async $=>{if($.preventDefault(),$.stopPropagation(),h(!1),!!await w({title:"Sign out",message:"Are you sure you want to sign out?",confirmText:"Sign out",cancelText:"Cancel"}))try{const K=Rd();Uy(K),await Zp(),window.location.href=K}
51catch(K){console.error("❌ [UserMenu] Sign out error:",K),window.location.href=Rd()}},N=$=>{$.preventDefault(),$.stopPropagation(),h(!1),y(""),f(!0)},S=async()=>{if(!x){u(!0);try{const $=await $y(b);_({title:"Discount code applied",description:`Applied -${$.percent_off}% to your next purchase.`}),f(!1),y("");try{window.dispatchEvent(new Event("discount_code_updated"))}catch{}}catch($){_({title:"Invalid discount code",description:$?.message||"Failed to redeem discount code."})}finally{u(!1)}}},k=i?.name||i?.email?.split("@")[0]||"User",D=i?.email||i?.name||"",F=k.split(" ").map($=>$[0]).join("").toUpperCase().slice(0,2),R=c?.plan?.plan_type?.toLowerCase()||"free",L=Dd[R]||Dd.free;return e.jsxs("div",{className:"relative bg-white",ref:g,children:[e.jsxs("button",{onClick:()=>h(!m),className:"w-full flex items-center gap-3 px-3 py-2.5 hover:bg-gray-100 rounded-lg transition-colors cursor-pointer",children:[e.jsxs("div",{className:"relative flex-shrink-0",children:[e.jsx("div",{className:"w-9 h-9 bg-gray-200 rounded-full flex items-center justify-center text-gray-600 text-sm font-medium",children:F}),e.jsx("div",{className:`absolute -top-1 -right-1 px-1 py-px text-[9px] font-semibold rounded ${L.bgColor} ${L.textColor} border border-white shadow-sm`,title:`${L.label} Plan`,children:L.label})]}),e.jsxs("div",{className:"min-w-0 flex-1 text-left",children:[e.jsx("div",{className:"text-sm font-medium text-gray-900 truncate",title:k,children:k}),D?e.jsx("div",{className:"text-xs text-gray-500 truncate",title:D,children:D}):null]}),e.jsx("div",{className:"flex-shrink-0 text-gray-400",children:e.jsx(En,{className:"h-4 w-4"})})]}),m&&e.jsxs("div",{className:`absolute left-0 right-0 bg-white border border-gray-200 rounded-lg shadow-lg py-1 z-50 ${t==="below"?"top-full mt-1":"bottom-full mb-1"}`,onClick:$=>$.stopPropagation(),children:[e.jsxs("button",{onClick:N,className:"w-full flex items-center gap-2 px-3 py-2 text-sm text-gray-700 hover:bg-gray-100 transition-colors",children:[e.jsx(Lr,{className:"h-4 w-4 text-gray-400"}),e.jsx("span",{children:"Discount code"})]}),e.jsxs("button",{onClick:E,className:"w-full flex items-center gap-2 px-3 py-2 text-sm text-red-600 hover:bg-gray-100 transition-colors ",children:[e.jsx(Bh,{className:"h-4 w-4"}),e.jsx("span",{children:"Sign out"})]})]}),e.jsx(Ht,{open:p,onOpenChange:f,children:e.jsxs(qt,{children:[e.jsx(Zt,{children:e.jsx(Yt,{children:"Redeem discount code"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"text-sm text-slate-600",children:"Enter the code provided to you. Your discount applies to your next purchase only."}),e.jsx(bt,{value:b,onChange:$=>y($.target.value),placeholder:"Enter code",autoFocus:!0}),e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[e.jsx(be,{variant:"outline",onClick:()=>f(!1),disabled:x,children:"Cancel"}),e.jsx(be,{onClick:S,disabled:x,children:x?"Applying...":"Apply"})]})]})]})})]})};function Wl({messages:t,intervalMs:s=3e3,typeSpeed:a=25,eraseSpeed:n=15,pauseAfterType:o=1200,className:i=""}){const[l,c]=r.useState(0),[d,m]=r.useState(""),[h,p]=r.useState("typing"),f=r.useRef(null),b=t[l]||"",y=r.useCallback(()=>{m(g=>g.length<b.length?b.slice(0,g.length+1):g)},[b]),x=r.useCallback(()=>{m(g=>g.length>0?g.slice(0,-1):g)},[]);r.useEffect(()=>{if(!t.length)return;let g;switch(h){case"typing":if(d.length<b.length){const w=b[d.length],E=/[\s]/.test(w)?a*.4:a+Math.random()*10;g=setTimeout(y,E)}else g=setTimeout(()=>p("pause"),50);break;case"pause":g=setTimeout(()=>p("erasing"),o);break;case"erasing":d.length>0?g=setTimeout(x,n):g=setTimeout(()=>p("wait"),100);break;case"wait":c(w=>(w+1)%t.length),p("typing");break}return()=>clearTimeout(g)},[h,d,b,t.length,a,n,o,y,x]),r.useEffect(()=>{c(0),m(""),p("typing")},[t]);const u=t.reduce((g,w)=>g.length>w.length?g:w,"");return e.jsxs("div",{ref:f,className:`relative ${i}`,children:[e.jsx("span",{className:"invisible whitespace-pre-wrap","aria-hidden":"true",children:u}),e.jsxs("span",{className:"absolute inset-0 whitespace-pre-wrap",children:[d,e.jsx("span",{className:"inline-block w-0.5 h-[1em] bg-current ml-0.5 align-text-bottom animate-pulse",style:{opacity:h==="pause"?0:1}})]})]})}function Gy({text:t,speed:s=30,onComplete:a,className:n=""}){const[o,i]=r.useState(""),l=r.useRef(!1);return r.useEffect(()=>{i(""),l.current=!1},[t]),r.useEffect(()=>{if(t){if(o.length<t.length){const c=t[o.length],m=/[\s.,!?;:]/.test(c)?s*.5:s+Math.random()*10,h=setTimeout(()=>{i(t.slice(0,o.length+1))},m);return()=>clearTimeout(h)}l.current||(l.current=!0,a?.())}},[o,s,t,a]),e.jsxs("span",{className:n,children:[o,o.length<t.length&&e.jsx("span",{className:"inline-block w-0.5 h-[1em] bg-current ml-0.5 align-text-bottom animate-pulse"})]})}function Wy({message:t,messages:s,onComplete:a,durationMs:n}){const[o,i]=r.useState(!0),l=r.useMemo(()=>s&&s.length>0?s:t?[t]:["Loading..."],[t,s]);return r.useEffect(()=>{if(!n||n<=0)return;const c=setTimeout(()=>{i(!1),a()},n);return()=>clearTimeout(c)},[n,a]),o?e.jsx("div",{className:"fixed left-56 top-14 right-0 bottom-0 bg-white z-40 flex items-center justify-center",children:e.jsx("div",{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-3 text-xl text-slate-900 font-medium",children:[e.jsx(He,{size:24,className:"animate-spin text-slate-400"}),e.jsx(Wl,{messages:l,typeSpeed:35,eraseSpeed:20,pauseAfterType:1500})]})})}):null}const Ld=[{id:"website",label:"Website",icon:Qt},{id:"company_profile",label:"Company Profile",icon:is},{id:"competitors",label:"Competitors",icon:Qs},{id:"ai_visibility",label:"AI Visibility",icon:Na},{id:"keywords",label:"Keywords",icon:qa},{id:"complete",label:"Complete",icon:wt}];function Vy({currentStep:t,completedSteps:s,onStepClick:a,canNavigateToStep:n}){const o=Ld.findIndex(i=>i.id===t);return e.jsx("div",{className:"w-56 border-r border-slate-200/60 flex flex-col bg-slate-50/30",children:e.jsx("div",{className:"flex-1 overflow-y-auto py-6 px-3",children:e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"absolute left-[10px] top-3 bottom-3 w-[2px] bg-slate-200 rounded-full"}),e.jsx("div",{className:"space-y-1",children:Ld.map((i,l)=>{const c=s.has(i.id),d=i.id===t,m=l<o,h=n(i.id)&&(m||c||d);return e.jsxs("button",{onClick:()=>h&&a(i.id),disabled:!h,className:Lt("pl-1.5 w-full flex items-center gap-4 py-2 pr-3 rounded-lg transition-all text-left group",d&&"bg-slate-100/80",h&&!d&&"hover:bg-slate-50 cursor-pointer",!h&&"cursor-not-allowed opacity-70"),children:[e.jsx("div",{className:"relative z-10 flex-shrink-0",children:e.jsx("div",{className:Lt("w-3 h-3 rounded-full border-2 transition-all flex items-center justify-center",c&&"bg-emerald-500 border-emerald-500",d&&!c&&"bg-slate-800 border-slate-800 scale-110",!d&&!c&&"bg-white border-slate-300 group-hover:border-slate-400"),children:c&&e.jsx(wt,{size:8,strokeWidth:3,className:"text-white"})})}),e.jsx("span",{className:Lt("text-[11px] transition-all truncate",d&&"font-medium text-slate-900",!d&&"text-slate-600 group-hover:text-slate-800"),children:i.label})]},i.id)})})]})})})}const xs=({className:t="",...s})=>e.jsx("div",{className:`rounded-lg border shadow-sm border-slate-200 bg-white ${t}`,...s}),Bs=({className:t="",...s})=>e.jsx("div",{className:`p-4 ${t}`,...s}),Xs=({className:t="",...s})=>e.jsx("h3",{className:`text-lg font-semibold ${t}`,...s}),Br=({className:t="",...s})=>e.jsx("p",{className:`text-sm text-slate-500 ${t}`,...s}),fs=({className:t="",...s})=>e.jsx("div",{className:`p-4 pt-0 ${t}`,...s});function Hy(t){return`${t.location_code}:${t.language_code}`}function qy({url:t,onUrlChange:s,market:a,onMarketChange:n,onContinue:o,loading:i,readonly:l=!1}){const[c,d]=r.useState(""),m=r.useMemo(()=>{const y=c.toLowerCase().trim();return y?va.filter(x=>x.location_name.toLowerCase().includes(y)):va},[c]),h=(y,x)=>va.find(g=>g.location_code===y)?.languages.find(g=>g.language_code===x)?.language_name||x,p=r.useMemo(()=>({locationName:va.find(x=>x.location_code===a.location_code)?.location_name||String(a.location_code),languageName:h(a.location_code,a.language_code)}),[a.language_code,a.location_code]),f=!!t.trim()&&!!a,b=!l&&!i;return e.jsx("div",{className:"flex flex-col items-center justify-center min-h-full py-12",children:e.jsxs("div",{className:"w-full max-w-2xl mx-auto 
51space-y-6",children:[e.jsxs("div",{className:"text-center space-y-4",children:[e.jsx("div",{className:"flex justify-center",children:e.jsx("div",{className:"h-16 w-16 rounded-full bg-slate-100 flex items-center justify-center",children:e.jsx(an,{className:"h-8 w-8 text-slate-600"})})}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold text-slate-900",children:"Welcome to Rankgale!"}),e.jsx("p",{className:"text-slate-600 mt-2",children:"Enter your company URL to get started with geo/aeo analysis"})]})]}),e.jsx(xs,{children:e.jsxs(fs,{className:"pt-6 space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-slate-700 mb-2",children:"Company URL"}),e.jsx(bt,{type:"url",placeholder:"https://example.com",value:t,onChange:y=>s(y.target.value),onKeyDown:y=>{y.key==="Enter"&&b&&f&&o()},disabled:!b})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("label",{className:"block text-sm font-medium text-slate-700 mb-2",children:"Target Market"}),e.jsx("p",{className:"text-xs text-slate-600",children:"Select one location + language for setup."})]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:e.jsxs("div",{className:"inline-flex items-center gap-1.5 px-3 py-1.5 bg-slate-100 text-slate-800 rounded-full text-sm",children:[e.jsx(fi,{size:16,className:"flex-shrink-0"}),e.jsx("span",{className:"font-medium",children:p.locationName}),e.jsxs("span",{className:"text-slate-500",children:["(",p.languageName,")"]})]},Hy(a))}),e.jsxs("div",{className:"relative",children:[e.jsx(Pt,{className:"absolute left-3 top-1/2 -translate-y-1/2 text-slate-400",size:16}),e.jsx(bt,{placeholder:"Search locations...",value:c,onChange:y=>d(y.target.value),className:"pl-9",disabled:!b})]}),e.jsx("div",{className:"max-h-48 overflow-y-auto border border-slate-200 rounded-lg",children:e.jsx("div",{className:"divide-y divide-slate-100",children:m.slice(0,16).map(y=>e.jsx("div",{className:"p-2",children:e.jsx("div",{className:"flex flex-wrap gap-1.5",children:y.languages.map(x=>{const u=a.location_code===y.location_code&&a.language_code===x.language_code;return e.jsxs("button",{onClick:()=>n({location_code:y.location_code,language_code:x.language_code}),disabled:!b,className:Lt("inline-flex items-center gap-1.5 px-2.5 py-1.5 rounded-md text-xs transition-all",u?"bg-slate-800 text-white":"bg-slate-50 text-slate-700 hover:bg-slate-100"),children:[e.jsx(fi,{size:14}),e.jsx("span",{children:y.location_name}),y.languages.length>1&&e.jsxs("span",{className:"text-slate-400",children:["(",x.language_name,")"]}),u&&e.jsx(wt,{size:12})]},`${y.location_code}-${x.language_code}`)})})},y.location_code))})})]}),e.jsx(be,{onClick:o,disabled:!f||!b,className:"w-full",children:i?e.jsxs(e.Fragment,{children:[e.jsx(He,{size:16,className:"mr-2 animate-spin"}),"Analyzing..."]}):"Continue"})]})})]})})}const Yy={location_code:Ec,language_code:Ac};function Jy({companyAbout:t,onCompanyAboutChange:s,onBack:a,onContinue:n,readonly:o=!1}){const l=t.length>2e3,c=!!t.trim()&&!l;return e.jsx("div",{className:"flex flex-col items-center justify-center min-h-full py-12 px-8",children:e.jsxs("div",{className:"w-full max-w-3xl space-y-6",children:[e.jsxs("div",{className:"text-center space-y-2",children:[e.jsx("h2",{className:"text-2xl font-semibold text-slate-900",children:"Refine Your Company Profile"}),e.jsx("p",{className:"text-slate-600 text-sm",children:"Review and edit the company description. This helps improve analysis accuracy."})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(Js,{value:t,onChange:d=>s(d.target.value),placeholder:"Enter your company description...",className:"min-h-[280px] resize-none text-sm leading-relaxed bg-white border-slate-200 focus:border-slate-400 focus:ring-slate-400",maxLength:2e3,disabled:o}),e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsxs("span",{className:Lt("text-slate-500",t.length>2e3*.9&&"text-amber-600",t.length>=2e3&&"text-red-600"),children:[t.length,"/",2e3," characters"]}),o&&e.jsx("span",{className:"text-slate-500",children:"Read-only"})]})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3 pt-4",children:[e.jsxs(be,{variant:"outline",onClick:a,children:[e.jsx(un,{size:14,className:"mr-2"}),"Back"]}),e.jsxs(be,{onClick:n,disabled:!c,children:["Continue",e.jsx(Ms,{size:14,className:"ml-2"})]})]})]})})}function Xy(t){const s=String(t||"").trim();if(!s)return"";try{return new URL(/^https?:\/\//i.test(s)?s:`https://${s}`).hostname.replace(/^www\./,"")}catch{return s.replace(/^https?:\/\//i,"").replace(/^www\./i,"")}}function Qy({candidates:t,visibleCount:s,selectedDomains:a,maxSelected:n=10,onToggleSelect:o,onLoadMore:i,onBack:l,onContinue:c,onAddManual:d,readonly:m=!1}){const[h,p]=r.useState(m||a.length>0),[f,b]=r.useState(!1),[y,x]=r.useState("");r.useEffect(()=>{if(m){p(!0);return}a.length>0&&p(!0)},[m,a.length]);const u=r.useMemo(()=>new Set(a.map(N=>N.toLowerCase().trim())),[a]),g=a.length<n,w=r.useMemo(()=>(t||[]).slice(0,Math.max(0,s)),[t,s]),_=!m&&w.length<(t||[]).length,E=()=>{const N=Xy(y);if(N){if(u.has(N.toLowerCase())){x(""),b(!1);return}d(N),x(""),b(!1)}};return e.jsx("div",{className:"h-full flex flex-col py-8 px-8",children:e.jsxs("div",{className:"max-w-7xl mx-auto w-full flex-1 flex flex-col min-h-0",children:[e.jsx("div",{className:"mb-6 min-h-[60
51px]",children:e.jsx("h2",{className:"text-2xl font-semibold text-slate-900",children:m?"Competitors":e.jsx(Gy,{text:"Please select competitors (up to 10):",speed:40,onComplete:()=>p(!0)})})}),h&&e.jsxs("div",{className:"flex-1 min-h-0 flex flex-col gap-6",children:[a.length>0&&e.jsxs("div",{children:[e.jsxs("p",{className:"text-sm text-slate-500 mb-3",children:["Selected competitors (",a.length,"/",n,")"]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:a.map(N=>e.jsxs("div",{className:"inline-flex items-center gap-2 px-3 py-1.5 bg-slate-900 text-white rounded-full text-sm",children:[e.jsx("span",{children:N}),!m&&e.jsx("button",{onClick:()=>o(N),className:"hover:bg-slate-800 rounded-full p-0.5 transition-colors","aria-label":"Remove competitor",children:e.jsx(mt,{size:12})})]},N))})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-slate-500 mb-3",children:"Suggestions"}),e.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[w.map(N=>N.domain).filter(N=>N&&!u.has(N.toLowerCase().trim())).map(N=>{const S=m||!g;return e.jsx("button",{onClick:()=>o(N),disabled:S,className:Lt("inline-flex items-center gap-2 px-3 py-1.5 rounded-full text-sm transition-all",S?"cursor-not-allowed opacity-60 bg-slate-100 text-slate-500":"bg-slate-100 text-slate-700 hover:bg-slate-200"),"aria-label":"Add competitor",children:e.jsx("span",{children:N})},N)}),_&&e.jsxs("button",{onClick:i,className:"px-3 py-1.5 rounded-full text-sm font-medium bg-slate-100 text-slate-700 hover:bg-slate-200 transition-all border-2 border-dashed border-slate-300",children:[e.jsx($t,{size:14,className:"inline-block mr-1"}),"Add more (AI)"]}),w.length===0&&e.jsx("div",{className:"text-sm text-slate-500",children:"No competitors found."})]})]}),e.jsxs("div",{className:"mt-auto pt-6 border-t border-slate-200 flex items-center justify-between gap-3",children:[e.jsxs(be,{variant:"outline",onClick:l,children:[e.jsx(un,{size:14,className:"mr-2"}),"Back"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[!m&&e.jsx(e.Fragment,{children:f?e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx(bt,{value:y,onChange:N=>x(N.target.value),placeholder:"Enter competitor URL (e.g., competitor.com)",className:"w-[320px]",autoFocus:!0,onKeyDown:N=>{N.key==="Enter"&&E(),N.key==="Escape"&&(b(!1),x(""))}}),e.jsx(be,{onClick:E,size:"sm",children:"Add"}),e.jsx(be,{variant:"ghost",onClick:()=>{b(!1),x("")},size:"sm",children:"Cancel"})]}):e.jsxs(be,{variant:"outline",onClick:()=>b(!0),className:"text-slate-600",children:[e.jsx($t,{size:14,className:"mr-2"}),"Add Competitor Manually"]})}),e.jsxs(be,{onClick:c,disabled:!m&&a.length===0,className:"bg-slate-800 hover:bg-slate-700",children:["Continue",e.jsx(Ms,{size:14,className:"ml-2"})]})]})]})]})]})})}const Zy=({size:t=16,className:s=""})=>e.jsx("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"currentColor",className:s,children:e.jsx("path",{d:"M22.282 9.821a5.985 5.985 0 0 0-.516-4.91 6.046 6.046 0 0 0-6.51-2.9A6.065 6.065 0 0 0 4.981 4.18a5.985 5.985 0 0 0-3.998 2.9 6.046 6.046 0 0 0 .743 7.097 5.98 5.98 0 0 0 .51 4.911 6.051 6.051 0 0 0 6.515 2.9A5.985 5.985 0 0 0 13.26 24a6.056 6.056 0 0 0 5.772-4.206 5.99 5.99 0 0 0 3.997-2.9 6.056 6.056 0 0 0-.747-7.073zM13.26 22.43a4.476 4.476 0 0 1-2.876-1.04l.141-.081 4.779-2.758a.795.795 0 0 0 .392-.681v-6.737l2.02 1.168a.071.071 0 0 1 .038.052v5.583a4.504 4.504 0 0 1-4.494 4.494zM3.6 18.304a4.47 4.47 0 0 1-.535-3.014l.142.085 4.783 2.759a.771.771 0 0 0 .78 0l5.843-3.369v2.332a.08.08 0 0 1-.033.062L9.74 19.95a4.5 4.5 0 0 1-6.14-1.646zM2.34 7.896a4.485 4.485 0 0 1 2.366-1.973V11.6a.766.766 0 0 0 .388.676l5.815 3.355-2.02 1.168a.076.076 0 0 1-.071 0l-4.83-2.786A4.504 4.504 0 0 1 2.34 7.896zm16.597 3.855l-5.833-3.387L15.119 7.2a.076.076 0 0 1 .071 0l4.83 2.791a4.494 4.494 0 0 1-.676 8.105v-5.678a.79.79 0 0 0-.407-.667zm2.01-3.023l-.141-.085-4.774-2.782a.776.776 0 0 0-.785 0L9.409 9.23V6.897a.066.066 0 0 1 .028-.061l4.83-2.787a4.5 4.5 0 0 1 6.68 4.66zm-12.64 4.135l-2.02-1.164a.08.08 0 0 1-.038-.057V6.075a4.5 4.5 0 0 1 7.375-3.453l-.142.08L8.704 5.46a.795.795 0 0 0-.393.681zm1.097-2.365l2.602-1.5 2.607 1.5v2.999l-2.597 1.5-2.607-1.5z"})}),eb=({size:t=16,className:s=""})=>e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",className:s,children:[e.jsx("path",{d:"M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z",fill:"#4285F4"}),e.jsx("path",{d:"M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z",fill:"#34A853"}),e.jsx("path",{d:"M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z",fill:"#FBBC05"}),e.jsx("path",{d:"M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z",fill:"#EA4335"})]}),tb=({size:t=16,className:s=""})=>e.jsx("img",{src:"/claude-logo.svg",alt:"Claude",width:t,height:t,className:s});function zd(t,s=16){const a=String(t||"").toLowerCase();return a==="openai"||a==="chatgpt"?e.jsx(Zy,{size:s,className:"text-slate-700"}):a==="google"||a==="gemini"?e.jsx(eb,{size:s}):a==="anthropic"||a==="claude"?e.jsx(tb,{size:s}):null}function $d(t){try{return new URL(t).hostname}catch{const s=t.match(/^https?:\/\/([^/]+)/);return s?s[1]:t}}
51function sb(t){return isFinite(t)?Math.max(0,Math.min(100,Math.round(t))):0}function Fd({percentage:t,label:s,subLabel:a,tone:n="you"}){const l=2*Math.PI*40,c=sb(t),d=l-c/100*l,m=n==="competitor"?"text-slate-400":"text-slate-600";return e.jsxs("div",{className:"flex flex-col items-center",children:[e.jsxs("div",{className:"relative",style:{width:96,height:96},children:[e.jsxs("svg",{className:"transform -rotate-90",width:96,height:96,children:[e.jsx("circle",{cx:96/2,cy:96/2,r:40,stroke:"currentColor",strokeWidth:"8",fill:"none",className:"text-slate-200"}),e.jsx("circle",{cx:96/2,cy:96/2,r:40,stroke:"currentColor",strokeWidth:"8",fill:"none",strokeDasharray:l,strokeDashoffset:d,className:m,strokeLinecap:"round",style:{transition:"stroke-dashoffset 0.5s ease"}})]}),e.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:e.jsxs("span",{className:"text-xl font-semibold text-slate-900",children:[c,"%"]})})]}),e.jsx("span",{className:"text-sm text-slate-700 mt-2 font-medium",children:s}),a&&e.jsx("span",{className:"text-xs text-slate-500 mt-0.5",children:a})]})}function ab({prompts:t,selectedPromptIds:s,maxSelected:a=3,readonly:n=!1,onGeneratePrompts:o,generatingPrompts:i=!1,insightsText:l,resultsByPromptId:c,onTogglePrompt:d,onUpdatePromptText:m,runStatus:h,runProgress:p,onBack:f,onRun:b,onContinue:y,mainDomain:x=""}){const[u,g]=r.useState(null),[w,_]=r.useState(null),[E,N]=r.useState(""),[S,k]=r.useState({}),D=r.useMemo(()=>["Building questions your customers are asking...","Generating prompts for multiple AI providers...","Tailoring prompts to your market and competitors...","Almost ready..."],[]),F=r.useMemo(()=>["Connecting to search providers...","Analyzing competitor visibility...","Calculating your share of voice...","Finalizing results..."],[]),R=r.useMemo(()=>new Set(s.map(P=>P.trim())),[s]),L=s.length<a,$=!!(c&&Object.keys(c).length>0),H=(t||[]).length>0,K=h==="RUNNING",X=P=>{const A=String(P||"").toLowerCase();return A==="openai"?"ChatGPT":A==="google"?"Gemini":A==="anthropic"?"Claude":P||"Provider"},V=P=>{const A=Math.max(1,P.length),C=P.filter(Z=>Z.mentioned).length,I=Math.round(C/A*100),j={};P.forEach(Z=>{const B=Z.competitors_mentioned||{};Object.entries(B).forEach(([ae,de])=>{de&&(j[ae]=(j[ae]||0)+1)})});let q=null,T=0;Object.entries(j).forEach(([Z,B])=>{B>T&&(T=B,q=Z)});const M=Math.round(T/A*100);return{youRate:I,competitorRate:M,bestCompetitorDomain:q}};return e.jsx("div",{className:"h-full flex flex-col",children:e.jsxs("div",{className:"max-w-7xl mx-auto w-full flex flex-col h-full py-8 px-8",children:[e.jsxs("div",{className:"flex-shrink-0 mb-4",children:[e.jsx("h2",{className:"text-2xl font-semibold text-slate-900",children:$?"AI visibility results":"Select prompts to analyze AI visibility"}),e.jsx("p",{className:"text-sm text-slate-600 mt-1",children:$?"Review results by prompt and provider.":`Select up to ${a} prompts`})]}),e.jsx("div",{className:"flex-1 min-h-0 flex flex-col relative",children:i?e.jsx("div",{className:"flex-1 flex items-center justify-center",children:e.jsxs("div",{className:"max-w-md w-full rounded-xl border border-slate-200 bg-white p-6 shadow-sm",children:[e.jsxs("div",{className:"flex items-center gap-3 text-lg font-semibold text-slate-900",children:[e.jsx(He,{size:20,className:"animate-spin text-slate-500"}),e.jsx("span",{children:"Generating prompts..."})]}),e.jsx("div",{className:"text-sm text-slate-600 mt-3",children:e.jsx(Wl,{messages:D,typeSpeed:35,eraseSpeed:20,pauseAfterType:1500})})]})}):K&&!$?e.jsx("div",{className:"flex-1 flex items-center justify-center",children:e.jsxs("div",{className:"max-w-2xl w-full rounded-xl border border-slate-200 bg-white p-6 shadow-sm",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-3 text-lg font-semibold text-slate-900",children:[e.jsx(He,{size:20,className:"animate-spin text-slate-500"}),e.jsx("span",{children:"Analyzing AI visibility..."})]}),e.jsxs("div",{className:"text-sm font-semibold text-slate-700",children:["(",p?.finished_prompts??0,"/",p?.total_prompts??s.length,")"]})]}),e.jsx("div",{className:"text-sm text-slate-600 mt-3",children:e.jsx(Wl,{messages:F,typeSpeed:35,eraseSpeed:20,pauseAfterType:1500})}),e.jsx("div",{className:"mt-4 space-y-3",children:(s||[]).map(P=>{const A=t.find(q=>q.id===P),C=p?.by_prompt?.[P],I=Number(C?.completed_models||0)+Number(C?.failed_models||0),j=Number(C?.total_models||3)||3;return e.jsxs("div",{className:"rounded-lg border border-slate-200 bg-slate-50 p-3",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsx("div",{className:"text-sm font-medium text-slate-900 flex-1",children:A?.text||C?.prompt||P}),e.jsxs("div",{className:"text-sm font-semibold text-slate-700",children:[I,"/",j]})]}),e.jsx("div",{className:"mt-2 flex flex-wrap gap-2",children:(C?.providers||[]).map((q,T)=>{const M=String(q?.status||"").toUpperCase(),Z=String(q?.provider||""),B=X(Z),ae=M==="DONE"||M==="COMPLETED"||M==="FAILED",de=!ae,fe=zd(Z,14);return e.jsxs("span",{className:Lt("inline-flex items-center gap-1.5 px-2 py-0.5 rounded-full text-xs font-medium border",ae?"bg-white border-slate-200 text-slate-700":"bg-white border-slate-200 text-slate-500"),children:[fe&&e.jsx("span",{className:"flex-shrink-0",children:fe}
51),de&&e.jsx(He,{size:10,className:"animate-spin flex-shrink-0"}),ae&&e.jsx(wt,{size:10,className:"text-emerald-600 flex-shrink-0",strokeWidth:3}),B]},`${P}-${B}-${T}`)})})]},P)})})]})}):$?e.jsxs("div",{className:"mt-0 pt-0 flex-1 overflow-auto",children:[l&&e.jsxs("div",{className:"mb-5",children:[e.jsx("div",{className:"text-xs font-medium text-slate-500 uppercase tracking-widest mb-2",children:"Insights"}),e.jsx("div",{className:"text-lg font-semibold text-slate-900 leading-snug",children:l})]}),e.jsx("div",{className:"space-y-4",children:(s||[]).map(P=>{const A=t.find(M=>M.id===P),C=(c||{})[P]||[],I=x||"Your domain",{youRate:j,competitorRate:q,bestCompetitorDomain:T}=V(C);return e.jsxs("div",{className:"bg-white rounded-lg border border-slate-200 p-6",children:[e.jsx("div",{className:"mb-4 pb-4 border-b border-slate-200",children:e.jsxs("p",{className:"text-sm text-slate-700 font-medium",children:['"',A?.text||P,'"']})}),e.jsxs("div",{className:"flex items-start gap-8",children:[e.jsxs("div",{className:"flex items-center gap-8 shrink-0",children:[e.jsx(Fd,{percentage:q,label:"Competitor",subLabel:T||void 0,tone:"competitor"}),e.jsx(Fd,{percentage:j,label:"You",subLabel:I,tone:"you"})]}),e.jsx("div",{className:"flex-1 space-y-3",children:C.length===0?e.jsx("div",{className:"text-sm text-slate-500",children:"No results yet."}):C.map((M,Z)=>{const B=`${P}:${M.provider}:${Z}`,ae=S[P]===B;return e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg border border-slate-200 hover:bg-slate-50 cursor-pointer transition-colors",onClick:()=>k(de=>({...de,[P]:ae?null:B})),children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[zd(M.provider,18),e.jsx("span",{className:"font-medium text-slate-900",children:M.provider})]}),M.mentioned?e.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium bg-emerald-100 text-emerald-700",children:[e.jsx(wt,{size:12,strokeWidth:3}),"Mentioned"]}):e.jsx("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium bg-slate-200 text-slate-500",children:"Not mentioned"})]}),e.jsx(Gs,{size:16,className:Lt("text-slate-400 transition-transform",ae&&"rotate-180")})]}),ae&&e.jsx("div",{className:"mt-2 rounded-lg border border-slate-200 bg-white p-4 max-h-[600px] overflow-y-auto",children:M.response?e.jsxs("div",{className:"grid grid-cols-5 gap-6",children:[e.jsx("div",{className:"col-span-3 min-w-0",children:e.jsx("div",{className:`prose prose-sm prose-slate max-w-none
52                                            prose-p:text-slate-700 prose-p:leading-relaxed prose-p:mb-2
53                                            prose-headings:text-slate-800 prose-headings:font-semibold
54                                            prose-strong:text-slate-800 prose-strong:font-semibold
55                                            prose-ul:my-2 prose-ol:my-2 prose-li:my-0.5
56                                          `,children:e.jsx(Wn,{remarkPlugins:[Vn],children:M.response})})}),e.jsxs("div",{className:"col-span-2 border-l border-slate-200 pl-4",children:[e.jsxs("p",{className:"text-[10px] uppercase tracking-wide text-slate-400 font-medium mb-3 sticky top-0 bg-white py-1",children:["AI Citations"," ",(M.citations||[]).length>0?`(${(M.citations||[]).length})`:""]}),(M.citations||[]).length>0?e.jsx("div",{className:"grid grid-cols-1 gap-2",children:(M.citations||[]).map((de,fe)=>{const se=(de.title||de.url||"").toLowerCase(),z=x&&se.includes(x.toLowerCase());return e.jsx("a",{href:de.url,target:"_blank",rel:"noopener noreferrer",className:`block p-2.5 rounded-lg border transition-colors group ${z?"border-emerald-300 bg-emerald-50 hover:bg-emerald-100 hover:border-emerald-400":"border-slate-200 bg-slate-50/50 hover:bg-slate-100 hover:border-slate-300"}`,children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(ns,{size:12,className:`mt-0.5 flex-shrink-0 ${z?"text-emerald-500":"text-slate-400 group-hover:text-indigo-500"}`}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:`text-xs font-medium line-clamp-2 ${z?"text-emerald-700":"text-slate-700 group-hover:text-indigo-600"}`,children:de.title||$d(de.url)}),e.jsx("p",{className:`text-[10px] truncate mt-0.5 ${z?"text-emerald-500":"text-slate-400"}`,children:$d(de.url)})]})]})},fe)})}):e.jsx("p",{className:"text-xs text-slate-400",children:"No citations available"})]})]}):e.jsx("div",{className:"text-sm text-slate-400 py-2",children:"No response data available yet"})})]},B)})})]})]},P)})})]}):e.jsxs("div",{className:"flex-1 min-h-0 overflow-auto space-y-3",children:[!H&&e.jsx("div",{className:"text-sm text-slate-500",children:"Preparing prompts..."}),(t||[]).map(P=>{const A=R.has(P.id),C=n||!A&&!L,I=w===P.id;return e.jsx("div",{role:"button",tabIndex:C?-1:0,"aria-disabled":C,onClick:()=>{C||I||d(P.id)},onKeyDown:j=>{C||I||(j.key==="Enter"||j.key===" ")&&(j.preventDefault(),d(P.id))},className:Lt("w-full text-left rounded-lg border p-4 transition-all  cursor-pointer",C?"opacity-60 cursor-not-allowed":"hover:bg-slate-50",A?"border-blue-500 bg-blue-50/40":"border-slate-200 bg-white"),children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:Lt("mt-1 w-6 h-6 rounded-full border flex items-center justify-center flex-shrink-0",A?"bg-blue-600 border-blue-600":"border-slate-300"),children:A&&e.jsx(wt,{size:14,className:"text-white",strokeWidth:3})}),e.jsx("div",{className:"flex-1 min-w-0",children:I?e.jsxs("div",{onClick:j=>j.stopPropagation(),children:[e.jsx(Js,{value:E,disabled:n,onChange:j=>N(j.target.value),className:Lt("min-h-[44px] resize-none",n?"bg-slate-50 text-slate-700":"bg-white"),autoFocus:!0,onBlur:()=>{n||(m(P.id,E),_(null),N(""))}}),e.jsxs("div",{className:"mt-2 flex items-center justify-end gap-2",children:[e.jsx(be,{type:"button",variant:"outline",className:"h-8 px-2",onMouseDown:j=>j.preventDefault(),onClick:j=>{j.stopPropagation(),_(null),N("")},children:"Cancel"}),e.jsx(be,{type:"button",className:"h-8 px-3 bg-slate-800 hover:bg-slate-700",onMouseDown:j=>j.preventDefault(),onClick:j=>{j.stopPropagation(),m(P.id,E),_(null),N("")},children:"Save"})]})]}):e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"text-sm font-medium text-slate-900 whitespace-pre-wrap break-words",children:P.text}),!n&&e.jsx("button",{type:"button",className:Lt("flex-shrink-0 w-8 h-8 rounded-md hover:bg-slate-100 flex items-center justify-center",C&&"opacity-60 cursor-not-allowed"),"aria-label":"Edit prompt",disabled:C,onClick:j=>{j.stopPropagation(),!C&&(_(P.id),N(P.text))},children:e.jsx(Ua,{size:14,className:"text-slate-600"})})]})})]})},P.id)})]})}),e.jsxs("div",{className:"flex-shrink-0 mt-6 pt-6 border-t border-slate-200 flex items-center justify-between gap-3",children:[e.jsxs(be,{variant:"outline",onClick:f,children:[e.jsx(un,{size:14,className:"mr-2"}),"Back"]}),$?e.jsxs(be,{onClick:y,className:"bg-slate-800 hover:bg-slate-700",children:["Continue",e.jsx(Ms,{size:14,className:"ml-2"})]}):e.jsxs(be,{onClick:b,disabled:s.length===0||n||i||K,className:"bg-slate-800 hover:bg-slate-700",children:["Run",e.jsx(Ms,{size:14,className:"ml-2"})]})]})]})})}function nb(t){return t==null?"-":t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:String(t)}function rb(t){return t===null?"text-slate-400":t<=10?"text-emerald-600":t<=30?"text-sky-600":t<=50?"text-amber-600":"text-slate-400"}function ob(t,s){if(t===null)return!1;let a=null;for(const n of Object.values(s))n!==null&&(a===null||n<a)&&(a=n);return a===null?!0:t<=a}function Od(t){const s=t.competitor_ranks||{};let a=0;for(const n of Object.values(s))n!=null&&(a+=1);return a}function ib(t,s){const a=Od(t),n=Od(s);if(a!==n)return n-a;const o=t.search_volume??0,i=s.search_volume??0;if(o!==i)return i-o;const l=t.you_rank_group??Number.POSITIVE_INFINITY,c=s.you_rank_group??Number.POSITIVE_INFINITY;if(l!==c)return c-l;const d=String(t.keyword||"").toLowerCase(),m=String(s.keyword||"").toLowerCase();return d<m?-1:d>m?1:0}function lb({rows:t,onBack:s,onContinue:a,readonly:n=!1}){const i=r.useMemo(()=>{const d=[...t||[]];return d.sort(ib),d},[t]),l=r.useMemo(()=>i.slice(0,10),[i]),c=Math.max(0,i.length-10);return e.jsx("div",{className:"flex flex-col h-full py-8 px-8",children:e.jsxs("div",{className:"flex flex-col h-full max-w-7xl mx-auto w-full",children:[e.jsxs("div",{className:"text-center flex-shrink-0 mb-6",children:[e.jsx("h1",{className:"text-2xl font-semibold text-slate-900",children:"Keywords Re
56search"}),e.jsx("p",{className:"mt-2 text-slate-500",children:"Keywords are sorted by search volume (high to low)."}),i.length>10&&e.jsxs("p",{className:"mt-1 text-xs text-slate-500",children:["Showing top ",10,". ",i.length-10," ","more hidden."]})]}),e.jsx("div",{className:"flex-1 min-h-0 bg-white border border-slate-200 rounded-xl overflow-hidden",children:e.jsx("div",{className:"h-full overflow-auto",children:e.jsxs("table",{className:"w-full min-w-[760px]",children:[e.jsx("thead",{className:"bg-slate-50 border-b border-slate-200 sticky top-0 z-10",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left px-4 py-3 text-xs font-semibold text-slate-600",children:"Keyword"}),e.jsx("th",{className:"text-right px-4 py-3 text-xs font-semibold text-slate-600 w-[140px]",children:"Volume"}),e.jsx("th",{className:"text-center px-4 py-3 text-xs font-semibold text-slate-600 w-[120px]",children:"Your Rank"}),e.jsx("th",{className:"text-left px-4 py-3 text-xs font-semibold text-slate-600",children:"Competitors ranks"})]})}),e.jsxs("tbody",{className:"divide-y divide-slate-100",children:[l.map(d=>{const m=Object.entries(d.competitor_ranks||{}).map(([h,p])=>({domain:h,rank:p}
56)).sort((h,p)=>{const f=h.rank??999999,b=p.rank??999999;return f-b});return e.jsxs("tr",{className:"hover:bg-slate-50",children:[e.jsx("td",{className:"px-4 py-3",children:e.jsx("div",{className:"text-sm font-medium text-slate-900",children:d.keyword})}),e.jsx("td",{className:"px-4 py-3 text-right",children:e.jsxs("div",{className:"inline-flex items-center gap-1 text-sm text-slate-700",children:[e.jsx(Sn,{className:"w-4 h-4 text-slate-400"}),nb(d.search_volume)]})}),e.jsx("td",{className:"px-4 py-3 text-center",children:(()=>{const h=ob(d.you_rank_group,d.competitor_ranks||{});return e.jsx("span",{className:Lt("inline-flex items-center justify-center px-2.5 py-1 rounded-md text-xs font-mono border font-semibold",d.you_rank_group!=null?h?"bg-emerald-50 border-emerald-200 text-emerald-700":"bg-red-50 border-red-200 text-red-700":"bg-slate-50 border-slate-200 text-slate-400"),children:d.you_rank_group!=null?`#${d.you_rank_group}`:"-"})})()}),e.jsx("td",{className:"px-4 py-3",children:e.jsxs("div",{className:"flex flex-wrap gap-2",children:[m.map(h=>e.jsxs("span",{className:"inline-flex items-center gap-1.5 px-2.5 py-1 rounded-md text-xs border bg-white border-slate-200",children:[e.jsx("span",{className:"font-medium text-slate-700",children:h.domain}),e.jsx("span",{className:Lt("font-mono font-semibold",rb(h.rank)),children:h.rank!=null?`#${h.rank}`:"-"})]},h.domain)),m.length===0&&e.jsx("span",{className:"text-sm text-slate-500",children:"No competitor ranks"})]})})]},d.keyword)}),l.length>0&&c>0&&e.jsx("tr",{children:e.jsxs("td",{colSpan:4,className:"px-4 py-3 text-center text-xs text-slate-500 bg-slate-50",children:["Has ",c," more keywords."]})}),l.length===0&&e.jsx("tr",{children:e.jsx("td",{colSpan:4,className:"px-4 py-10 text-center text-sm text-slate-500",children:"No keywords yet."})})]})]})})}),e.jsxs("div",{className:"flex items-center justify-between gap-3 pt-6 flex-shrink-0",children:[e.jsxs(be,{variant:"outline",onClick:s,children:[e.jsx(un,{size:14,className:"mr-2"}),"Back"]}),e.jsxs(be,{onClick:a,children:["Continue",e.jsx(Ms,{size:14,className:"ml-2"})]})]})]})})}function cb({headline:t,subline:s,body:a,onBack:n,onStartWinning:o,initStatus:i,initProgress:l,initError:c,onRetryInit:d}){const m=String(i||"").toUpperCase(),h=m==="RUNNING",p=m==="COMPLETED",f=m==="FAILED",b=m==="WAITING_FOR_PAYMENT",y=!!d&&f,x=l?.scans_done??0,u=l?.scans_total??0;return e.jsx("div",{className:"flex flex-col min-h-full px-4 justify-center",children:e.jsxs("div",{className:"max-w-4xl mx-auto w-full space-y-6",children:[e.jsxs("div",{className:"bg-white rounded-2xl border border-slate-200 p-10",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-xs font-medium text-slate-500 uppercase tracking-widest",children:"Competitive Analysis"}),e.jsx("h1",{className:"text-3xl font-normal text-slate-900",children:t}),s&&e.jsx("p",{className:"text-sm text-slate-500",children:s})]}),e.jsx("div",{className:"border-t border-slate-200 my-8 w-1/2"}),e.jsx("p",{className:"text-base text-slate-700 leading-relaxed",children:a}),(h||f||p)&&e.jsxs("div",{className:"mt-8 border-t border-slate-200 pt-6",children:[e.jsx("div",{className:"text-sm font-medium text-slate-900",children:h?"Initializing your workspace...":p?"Initialization completed.":"Initialization failed."}),h&&e.jsxs("div",{className:"mt-2 text-sm text-slate-600",children:["Progress: ",x,"/",u," scans finished"]}),f&&c&&e.jsx("div",{className:"mt-2 text-sm text-rose-600",children:String(c)}),y&&e.jsx("div",{className:"mt-4",children:e.jsx(be,{variant:"outline",onClick:d,children:"Retry initialization"})})]})]}),e.jsxs("div",{className:"flex flex-col items-center justify-center pt-6",children:[h||p?e.jsx(be,{disabled:!0,className:"bg-slate-900 hover:bg-slate-800 text-white px-12 py-4 text-sm font-medium tracking-widest uppercase rounded-none",children:p?"Ready":"Initializing..."}):e.jsx(be,{onClick:o,className:"bg-slate-900 hover:bg-slate-800 text-white px-12 py-4 text-sm font-medium tracking-widest uppercase rounded-none",children:"Start Winning"}),e.jsx("button",{onClick:n,className:"text-xs text-slate-400 hover:text-slate-600 transition-colors mt-6",children:"Back to analysis"})]})]})})}const ss={getState:async()=>await ot("/setup/state"),start:async t=>await Je("/setup/start",t),confirmCompanyProfile:async t=>await Je("/setup/company_profile_confirm",{about:t}),discoverCompetitors:async(t=30)=>await Je(`/setup/competitors_discover?limit=${encodeURIComponent(String(t))}`,{},{timeout:6e5}),discoverCompetitorsStart:async(t=30)=>await Je(`/setup/competitors_discover_start?limit=${encodeURIComponent(String(t))}`,{}),discoverCompetitorsStatus:async()=>await ot("/setup/competitors_discover_status"),confirmCompetitors:async t=>await Je("/setup/competitors_confirm",{selected_domains:t}),getAiVisibilityPrompts:async(t=5)=>await ot(`/setup/ai_visibility_prompts?count=${encodeURIComponent(String(t))}`),runAiVisibility:async(t,s)=>await Je("/setup/ai_visibility_run",{selected_prompt_ids:t,prompts:s}),saveAiVisibilitySelection:async(t,s)=>await Je("/setup/ai_visibility_select",{selected_prompt_ids:t,prompts:s}),getAiVisibilityResults:async()=>await ot("/setup/ai_visibility_results"),generateKeywords:async(t=200)=>await Je(`/setup/keywords_generate?limit_per_competitor=${encodeURIComponent(String(t))}`,{}),complete:async()=>await Je("/setup/complete",{}),initStart:async()=>await Je("/setup/init_start",{}),getInitStatus:async()=>await ot("/setup/init_status")},db="/app/subscription/checkout?plan_type=growth&billing_interval=monthly&return_to=/app/setup";function mb(t,s,a){return Math.max(s,Math.min(a,t))}function bx(){const{toast:t}=_t(),[s,a]=r.useState("website"),[n,o]=r.useState(new Set),[i,l]=r.useState(new Set),[c,d]=r.useState(null),[m,h]=r.useState(null),[p,f]=r.useState(!1),[b,y]=r.useState(""),[x,u]=r.useState(Yy),[g,w]=r.useState(""),[_,E]=r.useState(""),[N,S]=r.useState([]),[k,D]=r.useState(10),[F,R]=r.useState([]),[L,$]=r.useState([]),[H,K]=r.useState(!1),[X,V]=r.useState([]),P=r.useRef([]),[A,C]=r.useState(null),[I,j]=r.useState(null),[q,T]=r.useState(null),[M,Z]=r.useState(null),[B,ae]=r.useState({}),[de,fe]=r.useState(null),[se,z]=r.useState("IDLE"),U=r.useRef(!1),Q=r.useRef(!1),[me,le]=r.useState([]),O=r.useRef(!1),[ne,ge]=r.useState(null),[ze,Ke]=r.useState(null),[ie,ve]=r.useState(null),[we,Pe]=r.useState(null),Ae=r.useRef(0),ye=r.useMemo(()=>({website_to_company_profile:"Analyzing your website structure...",company_profile_to_competitors:"Finding competitors...",competitors_to_ai_visibility:"Generating AI prompts...",ai_visibility_to_keywords:"Analyzing keyword gaps...",keywords_to_complete:"Finalizing your analysis..."}),[]),Te=r.useMemo(()=>
56{if(!b.trim())return"";try{return new URL(/^https?:\/\//i.test(b)?b:`https://${b}`).hostname.replace(/^www\./,"").toLowerCase()}catch{return b.replace(/^https?:\/\//i,"").replace(/^www\./i,"").toLowerCase()}},[b]),Ie=r.useMemo(()=>({website_to_company_profile:["Analyzing your website structure...","Discovering key pages and topics...","Extracting company signals from your site...","Organizing findings into a company profile..."],company_profile_to_competitors:["Finding competitors...","Scanning similar domains in your category...","Shortlisting the best matches..."],competitors_to_ai_visibility:["Generating AI prompts...","Building questions your customers are asking...","Preparing prompt sets for multiple AI providers...","Almost ready..."],ai_visibility_to_keywords:["Analyzing keyword gaps...","Cross-checking competitor rankings...","Estimating search demand...","Building your opportunity list..."],keywords_to_complete:["Finalizing your analysis...","Summarizing key opportunities...","Preparing your next steps...","Almost done..."],discover_competitors:["Finding competitors...","Checking category similarity...","Estimating competitive overlap...","Ranking the best candidates..."],run_ai_visibility:["Running AI visibility scan...","Querying AI providers...","Measuring mention rate vs competitors...","Aggregating results..."]}),[]),Oe=r.useCallback(te=>{const G=Ie[te],pe=G&&G.length>0?G:[ye[te]??te];d(te),h(pe)},[Ie,ye]),J=r.useCallback(()=>{d(null),h(null)},[]),re=r.useCallback(te=>i.has(te),[i]),Se=r.useCallback(te=>te===s?!0:n.has(te),[n,s]),je=te=>a(te),he=r.useCallback(te=>{const G=new Set,pe=new Set;["website","company_profile","competitors","ai_visibility","keywords","complete"].forEach(ce=>{const Y=te?.[ce];Y&&String(Y.status).toUpperCase()==="COMPLETED"&&G.add(ce),Y&&Y.locked&&pe.add(ce)}),o(G),l(pe)},[]);r.useEffect(()=>{let te=!1;return(async()=>{try{const G=await ss.getState();if(te)return;if(G?.has_session&&G.session){const pe=G.steps||{};he(pe);const ce=pe.website?.payload_json;ce?.url&&y(String(ce.url)),ce?.market?.location_code&&ce?.market?.language_code&&u({location_code:Number(ce.market.location_code),language_code:String(ce.market.language_code)}),ce?.company?.name&&w(String(ce.company.name)),ce?.company?.about&&E(String(ce.company.about));const Y=pe.competitors?.payload_json;if(Array.isArray(Y?.candidates)){const Ge=Y.candidates.map(ee=>({domain:String(ee.domain)}));if(S(Ge),!Array.isArray(Y?.selected_domains)||Y.selected_domains.length===0){const ee=Ge.map(Fe=>String(Fe.domain||"").trim()).filter(Boolean).slice(0,10);ee.length>0&&R(ee)}}Array.isArray(Y?.selected_domains)&&R(Y.selected_domains.map(Ge=>String(Ge)));const xe=pe.ai_visibility?.payload_json;Array.isArray(xe?.prompts)&&$(xe.prompts.map(Ge=>({id:String(Ge.id),text:String(Ge.text)}))),Array.isArray(xe?.selected_prompt_ids)&&V(xe.selected_prompt_ids.map(Ge=>String(Ge)));const Ee=xe?.results;if(Ee?.by_prompt){const Ge={};Object.entries(Ee.by_prompt).forEach(([ee,Fe])=>{const Xe=Fe?.providers||[];Ge[ee]=Xe.map(yt=>({provider:yt.provider||"ChatGPT",mentioned:!!yt.you_mentioned,position:null,response:String(yt.answer||""),citations:Array.isArray(yt.sources)?yt.sources.map(ut=>({title:String(ut.title||ut.url),url:String(ut.url)})):[],competitors_mentioned:yt.competitors_mentioned||{}}))}),ae(Ge),C(Ee.insight||""),j(Ee.comparison?.best_competitor_domain||null),T(Ee.comparison?.best_competitor_rate??0),Z(Ee.comparison?.worst_you_rate??0)}const Ne=pe.keywords?.payload_json;Array.isArray(Ne?.rows)&&le(Ne.rows.map(Ge=>({keyword:String(Ge.keyword),search_volume:Ge.search_volume??null,you_rank_group:Ge.you_rank_group??null,competitor_ranks:Ge.competitor_ranks||{}})));const Ce=pe.complete?.payload_json;Ce?.headline&&Ce?.body&&ge({headline:String(Ce.headline),subline:String(Ce.subline||""),body:String(Ce.body)});const De=G.session.current_step||"website";a(De)}}catch{}})(),()=>{te=!0}},[he]);const Re=async()=>{if(!b.trim()){t({title:"Missing URL",description:"Please enter your company URL."});return}f(!0),Oe("website_to_company_profile");try{const te=await ss.start({url:b,market:x}),G=te.company?.about||"",pe=te.company?.name||"";E(String(G)),w(String(pe));const ce=await ss.getState();he(ce.steps),a("company_profile")}catch(te){t({title:"Failed to analyze website",description:String(te?.message||te||"Unknown error")})}finally{f(!1),J()}},Me=async()=>{Oe("company_profile_to_competitors");try{await ss.confirmCompanyProfile(_);const te=await ss.getState();he(te.steps),a("competitors")}catch(te){t({title:"Failed to save company profile",description:String(te?.message||te||"Unknown error")})}finally{J()}},Ze=te=>{re("competitors")||R(G=>{const pe=new Set(G.map(Y=>Y.toLowerCase().trim())),ce=te.toLowerCase().trim();return pe.has(ce)?G.filter(Y=>Y.toLowerCase().trim()!==ce):G.length>=10?G:[...G,te]})},Be=async()=>
56{if(F.length===0){if(re("competitors")){a("ai_visibility");return}t({title:"No competitors selected",description:"Please select at least one competitor."});return}Oe("competitors_to_ai_visibility");try{re("competitors")||await ss.confirmCompetitors(F);const te=await ss.getState();he(te.steps),a("ai_visibility")}catch(te){t({title:"Failed to save competitors",description:String(te?.message||te||"Unknown error")})}finally{J()}},et=te=>{if(re("ai_visibility"))return;let G=[];V(pe=>{const ce=new Set(pe);if(ce.has(te))ce.delete(te);else{if(ce.size>=3)return pe;ce.add(te)}return G=Array.from(ce),P.current=G,G}),(async()=>{try{await ss.saveAiVisibilitySelection(G)}catch(pe){t({title:"Failed to save prompt selection",description:String(pe?.message||pe||"Unknown error")})}})()},$e=r.useCallback((te,G)=>{re("ai_visibility")||($(pe=>pe.map(ce=>ce.id===te?{...ce,text:G}:ce)),(async()=>{try{await ss.saveAiVisibilitySelection(X,[{id:te,text:G}])}catch(pe){t({title:"Failed to save prompt",description:String(pe?.message||pe||"Unknown error")})}})())},[re,X,t]),ue=async()=>{if(Q.current)return;const te=P.current.length?P.current:X;if(te.length===0||re("ai_visibility"))return;Q.current=!0;let G=null;const pe=ce=>{const Y={};Object.entries(ce.by_prompt||{}).forEach(([xe,Ee])=>{const Ne=Ee?.providers||[];Y[xe]=Ne.map(Ce=>({provider:Ce.provider||"ChatGPT",mentioned:!!Ce.you_mentioned,position:null,response:String(Ce.answer||""),citations:Array.isArray(Ce.sources)?Ce.sources.map(De=>({title:String(De.title||De.url),url:String(De.url)})):[],competitors_mentioned:Ce.competitors_mentioned||{}}))}),ae(Y),C(ce.insight||""),j(ce.comparison?.best_competitor_domain||null),T(ce.comparison?.best_competitor_rate??0),Z(ce.comparison?.worst_you_rate??0)};try{z("RUNNING"),fe(null);const ce=L.filter(Ne=>te.includes(Ne.id)).map(Ne=>({id:Ne.id,text:Ne.text})),Y=await ss.runAiVisibility(te,ce),xe=await ss.getState();if(he(xe.steps),Y?.results){pe(Y.results),z("IDLE"),fe(null),t({title:"AI visibility updated",description:"Results are ready."});return}const Ee=async()=>{try{const Ne=await ss.getAiVisibilityResults();if(Ne.status==="NOT_STARTED"){z("IDLE"),fe(null),t({title:"AI visibility not started",description:"Please click Run to start the scan."});return}if(Ne.status==="FAILED"){z("IDLE"),fe(null),t({title:"AI visibility scan failed",description:String(Ne?.error||"Unknown error")});return}if(Ne.status==="COMPLETED"&&Ne.results){pe(Ne.results);const Ce=await ss.getState();he(Ce.steps),z("IDLE"),fe(null),t({title:"AI visibility updated",description:"Results are ready."});return}Ne.status==="RUNNING"&&(z("RUNNING"),fe(Ne.progress||null)),G=setTimeout(Ee,2e3)}catch(Ne){if(String(Ne?.message||"").includes("AI visibility scans not started")){z("IDLE"),fe(null),t({title:"AI visibility not started",description:"Please click Run to start the scan."});return}G=setTimeout(Ee,2e3)}};Ee()}catch(ce){t({title:"AI visibility scan failed",description:String(ce?.message||ce||"Unknown error")}),z("IDLE"),fe(null),G&&clearTimeout(G)}finally{Q.current=!1}},W=async()=>{a("keywords")},ke=async()=>{Oe("keywords_to_complete");try{const te=await ss.complete();ge({headline:te.summary.headline,subline:te.summary.subline,body:te.summary.body});const G=await ss.getState();he(G.steps),a("complete")}catch(te){t({title:"Failed to finalize setup",description:String(te?.message||te||"Unknown error")})}finally{J()}},qe=()=>{window.location.href=db},Qe=r.useCallback(async()=>{try{const te=await ss.initStart();Ke(te.status||null),ve(null);const G=String(te.status||"").toUpperCase();return G==="FAILED"&&ve("Failed to start initialization."),G||"PENDING"}catch(te){return Ke("FAILED"),ve(String(te?.message||te||"Unknown error")),"FAILED"}},[]),ct=r.useCallback(async()=>{try{const te=await ss.getInitStatus(),G=String(te.status||"").toUpperCase();if(Ke(pe=>{const ce=String(pe||"").toUpperCase(),Y=te.status||null,xe=String(Y||"").toUpperCase();return(xe==="PENDING"||xe==="NOT_STARTED")&&(ce==="WAITING_FOR_PAYMENT"||ce==="NOT_READY")?pe:Y}),Pe(te.progress||null),ve(te.error?String(te.error):null),G==="COMPLETED"&&s==="complete")try{const pe=await Xa();pe&&pe.status==="active"&&(window.location.href="/app")}
56catch(pe){console.warn("⚠️ Failed to check subscription status:",pe)}return G}catch(te){return Ke("FAILED"),ve(String(te?.message||te||"Unknown error")),"FAILED"}},[s]);r.useEffect(()=>{let te=!1;if(s==="competitors")return(async()=>{try{if(N.length===0){Oe("discover_competitors");const ce=Date.now(),Y=async()=>(await new Promise(Ce=>window.setTimeout(Ce,1500)),await ss.discoverCompetitorsStatus()),xe=await ss.discoverCompetitorsStart(30);if(te)return;let Ee=[],Ne=String(xe?.status||"").toUpperCase();if(Ne==="COMPLETED"){const Ce=xe.candidates||[];Ee=Ce,S(Ce)}else{if(Ne==="FAILED")throw new Error(String(xe?.error||"Failed to discover competitors."));for(;!te;){if(Date.now()-ce>18e4)throw new Error("Timed out while waiting for competitor discovery.");const Ce=await Y();if(te)return;if(Ne=String(Ce?.status||"").toUpperCase(),Ne==="COMPLETED"){const De=Ce.candidates||[];Ee=De,S(De);break}if(Ne==="FAILED")throw new Error(String(Ce?.error||"Failed to discover competitors."))}}if(F.length===0){const Ce=(Ee||[]).map(De=>String(De?.domain||"").trim()).filter(Boolean).slice(0,10);Ce.length>0&&R(Ce)}}const G=await ss.getState();if(te)return;he(G.steps);const pe=G.steps?.competitors?.payload_json?.selected_domains;Array.isArray(pe)&&pe.length>0&&R(pe.map(ce=>String(ce)))}catch(G){t({title:"Failed to load competitors",description:String(G?.message||G||"Unknown error")})}finally{J()}})(),()=>{te=!0}},[he,N.length,s,F.length,Oe,J,t]),r.useEffect(()=>{let te=!1;if(s==="ai_visibility")return(async()=>{try{if(te||U.current||re("ai_visibility")||Object.keys(B||{}).length>0||(L||[]).length>0)return;U.current=!0,K(!0);try{const pe=await ss.getAiVisibilityPrompts(5);if(te)return;$(pe.prompts||[]);const ce=await ss.getState();if(te)return;he(ce.steps)}catch(pe){t({title:"Failed to generate prompts",description:String(pe?.message||pe||"Unknown error")})}finally{K(!1)}}finally{J()}})(),()=>{te=!0}},[s,re,J,he,t]);const pt=async()=>{if(!re("ai_visibility")){K(!0);try{const te=await ss.getAiVisibilityPrompts(5);$(te.prompts||[]);const G=await ss.getState();he(G.steps)}catch(te){t({title:"Failed to generate prompts",description:String(te?.message||te||"Unknown error")})}finally{K(!1)}}};r.useEffect(()=>{let te=!1;if(s==="keywords")return(async()=>{try{if(me.length>0||O.current)return;O.current=!0,Oe("ai_visibility_to_keywords");try{const Y=(await ss.getState())?.steps?.competitors?.payload_json?.selected_domains;if(!(Array.isArray(Y)&&Y.length>0)){const Ee=(F||[]).map(Ne=>String(Ne||"").trim()).filter(Boolean);if(Ee.length>0)await ss.confirmCompetitors(Ee);else{t({title:"Competitors missing",description:"Please go back and select competitors."});return}}}catch{}const G=await ss.generateKeywords(200);if(te)return;le((G.rows||[]).map(ce=>({keyword:ce.keyword,search_volume:ce.search_volume,you_rank_group:ce.you_rank_group??null,competitor_ranks:ce.competitor_ranks||{}})));const pe=await ss.getState();if(te)return;he(pe.steps)}catch(G){t({title:"Failed to load keywords",description:String(G?.message||G||"Unknown error")})}finally{O.current=!1,J()}})(),()=>{te=!0,O.current=!1}},[he,s,me.length,F,Oe,J,t]);const At=()=>{switch(s){case"website":return e.jsx(qy,{url:b,onUrlChange:y,market:x,onMarketChange:u,onContinue:Re,loading:p,readonly:re("website")});case"company_profile":return e.jsx(Jy,{companyAbout:_,onCompanyAboutChange:E,onBack:()=>je("website"),onContinue:Me,readonly:re("company_profile")});case"competitors":return e.jsx(Qy,{candidates:N,visibleCount:k,selectedDomains:F,maxSelected:10,onToggleSelect:Ze,onLoadMore:()=>D(te=>mb(te+10,10,N.length)),onAddManual:te=>Ze(te),onBack:()=>je("company_profile"),onContinue:Be,readonly:re("competitors")});case"ai_visibility":return e.jsx(ab,{prompts:L,selectedPromptIds:X,onTogglePrompt:et,onUpdatePromptText:$e,onBack:()=>je("competitors"),onRun:ue,onContinue:W,readonly:re("ai_visibility"),onGeneratePrompts:pt,generatingPrompts:H,insightsText:A,resultsByPromptId:B,runStatus:se,runProgress:de,mainDomain:Te});case"keywords":return e.jsx(lb,{rows:me,onBack:()=>je("ai_visibility"),onContinue:ke,readonly:re("keywords")});case"complete":return e.jsx(cb,{headline:ne?.headline||"Competitive analysis is ready",subline:ne?.subline||"",body:ne?.body||"Your setup is complete.",onBack:()=>je("keywords"),onStartWinning:qe,initStatus:ze,initProgress:we,initError:ie,onRetryInit:Qe});default:return null}};return r.useEffect(()=>{let te=null,G=!1;const pe=15e3;if(s!=="complete")return;const ce=async()=>
56{if(G)return;let Y=!0;try{const xe=String(ze||"").toUpperCase();if(xe==="COMPLETED"){Y=!1,await ct();return}if(xe==="FAILED"){Y=!1;return}if(xe==="WAITING_FOR_PAYMENT"){Y=!1;return}if(!ze||["WAITING_FOR_PAYMENT","PENDING","NOT_STARTED","NOT_READY"].includes(xe)){const De=Date.now();if(De-Ae.current>=pe){Ae.current=De;const Ge=await Qe();if(String(Ge||"").toUpperCase()==="WAITING_FOR_PAYMENT"){Y=!1;return}}}const Ne=await ct(),Ce=String(Ne||"").toUpperCase();(Ce==="COMPLETED"||Ce==="FAILED")&&(Y=!1)}finally{!G&&Y&&(te=setTimeout(ce,2e3))}};return ce(),()=>{G=!0,te&&clearTimeout(te)}},[s,ze,ct,Qe]),e.jsxs("div",{className:"flex h-screen bg-slate-50",children:[m&&m.length>0&&e.jsx(Wy,{messages:m,onComplete:()=>{},durationMs:null}),e.jsxs("div",{className:"fixed top-0 left-0 right-0 h-16 bg-white border-b border-slate-200 flex items-center justify-between px-4 z-50",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(dr,{className:"w-6 h-6 rounded",alt:"Rankgale"}),e.jsx("span",{className:"text-sm font-semibold text-gray-800 tracking-tight",children:"Rankgale"})]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(Dc,{dropdownPosition:"below"})})]}),e.jsxs("div",{className:"flex flex-1 pt-16",children:[e.jsx(Vy,{currentStep:s,completedSteps:n,onStepClick:je,canNavigateToStep:Se}),e.jsx("div",{className:"flex-1 overflow-auto",children:At()})]})]})}const ub=Object.freeze(Object.defineProperty({__proto__:null,default:bx},Symbol.toStringTag,{value:"Module"}));function xb(){const{toast:t}=_t(),[s,a]=r.useState(null),[n,o]=r.useState(null),[i,l]=r.useState(!0);if(r.useEffect(()=>{let p=!0;return(async()=>{try{if(!await rs.isAuthenticated()){p&&(window.location.href="/app/landing");return}const b=await Cs.getAccountCached({ttlMs:1e4});if(!p)return;a(b);try{const y=await Xa();if(!p)return;o(y)}catch{if(!p)return;o(null)}}catch(f){console.error("Failed to load account:",f),p&&t({title:"Error",description:"Failed to load account information"})}finally{p&&l(!1)}})(),()=>{p=!1}},[]),i)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-slate-50",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-slate-900 mx-auto"}),e.jsx("p",{className:"mt-4 text-slate-600",children:"Loading..."})]})});const c=!!(s&&s.setup_company_analysis_status==="completed"),d=!!(n&&n.status==="active"),m=!!(s&&s.setup_init_status==="completed");return c&&d&&m?(window.location.href="/app",null):e.jsx(bx,{})}function hb(){return e.jsx(za,{children:e.jsx(gx,{children:e.jsx(xb,{})})})}function pb(t){return t?t.startsWith("/app/subscription/success")?"success":t.startsWith("/app/subscription/cancel")?"cancel":t.startsWith("/seo/subscription/success")?"success":t.startsWith("/seo/subscription/cancel")?"cancel":null:null}function gb(t){return!(!t||!t.startsWith("/")||t.startsWith("//")||t.includes("://"))}function fb(t){try{window.history.replaceState({},"",t),window.dispatchEvent(new PopStateEvent("popstate"))}catch{window.location.href=t}}const yb="discount_code_suppress_until_ms";function bb(t){try{const s=Date.now()+Math.max(0,Number(t)||0);sessionStorage.setItem(yb,String(s))}catch{}}function wb(){const t=pb(window.location.pathname);v.useEffect(()=>{const n=new URLSearchParams(window.location.search).get("return_to"),o=gb(n)?n:"/app/subscription";t==="success"?(console.log("✅ Stripe checkout completed, redirecting:",o),bb(9e4)):t==="cancel"?console.log("⚠️ Stripe checkout canceled, redirecting:",o):console.warn("🟡 Stripe checkout callback: unknown path, redirecting:",o),Promise.resolve().then(()=>fb(o))},[t]);const s=t==="success"?"Payment completed":t==="cancel"?"Payment canceled":"Redirecting";return e.jsx("div",{style:{minHeight:"100vh",display:"flex",alignItems:"center",justifyContent:"center",padding:16,fontFamily:"Inter, system-ui, sans-serif",background:"rgba(249, 250, 251, 1)"},children:e.jsxs("div",{style:{width:"100%",maxWidth:420,background:"#fff",border:"1px solid rgba(229, 231, 235, 1)",borderRadius:12,padding:16,color:"rgba(17, 24, 39, 1)"},children:[e.jsx("div",{style:{fontSize:14,fontWeight:600,marginBottom:6},children:s}),e.jsx("div",{style:{fontSize:12,color:"rgba(107, 114, 128, 1)"},children:"Redirecting..."})]})})}function jb(t){return!(!t||!t.startsWith("/")||t.startsWith("//")||t.includes("://"))}function vb(t){return t==="monthly"?"monthly":"yearly"}function Nb(){return new URLSearchParams(window.location.search)}function Vl(t){try{window.history.replaceState({},"",t),window.dispatchEvent(new PopStateEvent("popstate"))}catch{window.location.href=t}}function wx(t){const s=t.get("return_to");return jb(s)?s:"/app"}function kb(t){const s=t.get("plan_type");return s?s.trim().toLowerCase():null}function _b(t){const s=t.get("coupon_id");if(!s)return;const a=s.trim();return a||void 0}function Cb(t){const s=t.get("payg_code");return s?s.trim():null}async function Sb(t){const s=vb(t.get("billing_interval")),a=wx(t),n=_b(t),o=Cb(t);if(o){console.log("🧾 [checkout-bridge] Creating PAYG checkout session",{paygCode:o,returnTo:a});const c=await Mc(o,a);if("checkout_url"in c){window.location.href=c.checkout_url;return}throw new Error("Unexpected response from server.")}const i=kb(t);if(!i){console.warn("🟡 [checkout-bridge] Missing plan_type; redirecting to homepage"),Vl(a);return}console.log("🧾 [checkout-bridge] Creating subscription checkout session",{planType:i,billingInterval:s,returnTo:a,hasCoupon:!!n});const l=await Ci(i,n,s,a);if("checkout_url"in l){window.location.href=l.checkout_url;return}if("downgraded"in l){console.log("✅ [checkout-bridge] Downgrade handled without Stripe. Redirecting.",{message:l.message,returnTo:a}),Vl(a);return}throw new Error("Unexpected response from server.")}function Eb(){const[t,s]=v.useState("Redirecting to checkout...");return v.useEffect(()=>{let a=!0;return(async()=>{const n=Nb(),o=wx(n);try{if(!await rs.isAuthenticated()){console.log("🔐 [checkout-bridge] Not authenticated. Redirecting to Logto sign-in."),s("Redirecting to sign-in..."),await An();return}if(!a)return;s("Preparing Stripe checkout..."),await Sb(n)}catch(i){if(console.error("🔴 [checkout-bridge] Failed to start checkout:",i),!a)return;s("Unable to start checkout. Redirecting..."),setTimeout(()=>Vl(o),900)}})(),()=>{a=!1}},[]),e.jsx("div",{style:{minHeight:"100vh",display:"flex",alignItems:"center",justifyContent:"center",padding:16,fontFamily:"Inter, system-ui, sans-serif",background:"rgba(249, 250, 251, 1)"},children:e.jsxs("div",{style:{width:"100%",maxWidth:420,background:"#fff",border:"1px solid rgba(229, 231, 235, 1)",borderRadius:12,padding:16,color:"rgba(17, 24, 39, 1)"},children:[e.jsx("div",{style:{fontSize:14,fontWeight:600,marginBottom:6},children:"Checkout"}),e.jsx("div",{style:{fontSize:12,color:"rgba(107, 114, 128, 1)"},children:t})]})})}function Ab({className:t,size:s="md",onMarketChange:a}){const[n,o]=r.useState(!1),[i,l]=r.useState([]),[c,d]=r.useState(ea()),m=r.useMemo(()=>sx(i),[i]),h=c?_n({id:c.location_id,location_code:c.location_code,language_code:c.language_code}):"";if(r.useEffect(()=>{let y=!0;return(async()=>{o(!0);try{const x=await La();if(!y)return;const u=x?.markets||[];l(u);const g=ax({stored:c,backendPrimary:x?.primary_market||null,markets:u});d(g),tr(g)}catch{if(!y)return;l([])}finally{y&&o(!1)}})(),()=>{y=!1}},[]),!m.length)return null;const p=s==="sm"?"h-8":"h-9",f=s==="sm"?"text-[12px]":"text-[13px]",b=async y=>
56{const x=m.find(g=>_n(g)===y);if(!x)return;const u=Ni(x);d(u),tr(u,{emit:!0});try{a?.(u)}catch(g){console.warn("⚠️ MarketSwitcher onMarketChange handler failed:",g)}try{await Sc({markets:m.map(g=>({id:g.id||void 0,location_code:g.location_code,language_code:g.language_code,is_primary:!1})),primary_market:{id:x.id||void 0,location_code:x.location_code,language_code:x.language_code,is_primary:!0}})}catch{}};return e.jsx("div",{className:t,children:e.jsx("div",{className:"flex items-center gap-2 min-w-0",children:e.jsx("div",{className:"flex-1 min-w-0",children:e.jsx("select",{disabled:n,value:h,onChange:y=>b(y.target.value),className:`w-full min-w-0 truncate ${p} px-2.5 rounded-lg border border-slate-200 bg-white ${f} text-slate-700 focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 disabled:opacity-50`,title:c?Bl(c):"Market","aria-label":"Market",children:m.map(y=>e.jsx("option",{value:_n(y),children:Bl({location_code:y.location_code,language_code:y.language_code})},_n(y)))})})})})}function Tb(){return`${Date.now()}_${Math.random().toString(16).slice(2)}`}function Bd(t){const a=Math.abs(t).toLocaleString();return t>0?`+${a}`:`-${a}`}function Ud(t){return t>0?"text-emerald-600":t<0?"text-red-600":"text-gray-600"}function jx({variant:t="compact",show:s=!0,clickable:a=!0,onClick:n}){const[o,i]=r.useState(0),[l,c]=r.useState(!1),[d,m]=r.useState([]),h=r.useRef(0),p=r.useRef(!1),f=r.useRef([]),b=r.useMemo(()=>l?"...":o.toLocaleString(),[o,l]),y=r.useCallback(w=>{if(!Number.isFinite(w)||w===0)return;const _={id:Tb(),delta:w};
56m(N=>[...N,_].slice(-3));const E=window.setTimeout(()=>{m(N=>N.filter(S=>S.id!==_.id))},1200);f.current.push(E)},[]);if(r.useEffect(()=>{if(!s)return;p.current=!1,m([]);let w=!1;async function _(N=!1){try{if(N||c(!0),window.location.pathname.includes("/prototpye")||window.location.pathname.includes("/prototype")){if(w)return;const L=h.current;if(p.current){const $=1e3-L;y($)}else p.current=!0;h.current=1e3,i(1e3);return}const k=await Cs.getAccountCached({ttlMs:1e4}),D=Number(k.credits_balance??0);if(!Number.isFinite(D)||w)return;const F=h.current;if(p.current){const R=D-F;y(R)}else p.current=!0;h.current=D,i(D)}catch(S){const k=window.location.pathname.includes("/prototpye")||window.location.pathname.includes("/prototype");k||console.error("❌ Failed to load credits:",S),k&&!p.current&&(h.current=1e3,i(1e3),p.current=!0)}finally{!w&&!N&&c(!1)}}_(!1);const E=setInterval(()=>_(!0),1e4);return()=>{w=!0,clearInterval(E),f.current.forEach(N=>window.clearTimeout(N)),f.current=[]}},[y,s]),!s)return null;const x=()=>{n?n():a&&jt("subscription")},u=o<=20,g=d;return t==="card"?e.jsxs("button",{onClick:x,className:"relative w-full flex items-center justify-between px-3 py-2 bg-gray-50 border border-gray-100 rounded-lg hover:border-gray-200 transition-colors cursor-pointer",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(vs,{className:`h-4 w-4 ${u?"text-amber-600":"text-gray-600"}`}),e.jsx("span",{className:`text-sm ${u?"text-amber-600 font-medium":"text-gray-700"}`,children:"Credits"})]}),e.jsxs("div",{className:"relative",children:[e.jsx("span",{className:`text-sm font-semibold ${u?"text-amber-600":"text-gray-900"}`,children:b}),e.jsx("div",{className:"pointer-events-none absolute right-0 top-0 -translate-y-full",children:g.map(w=>e.jsx("div",{className:`animate-float-up-fade-out text-xs font-semibold drop-shadow-sm ${Ud(w.delta)}`,children:Bd(w.delta)},w.id))})]})]}):e.jsxs("button",{onClick:x,className:`flex items-center gap-2 px-3 py-1.5 bg-white border rounded-lg transition-colors ${a?"border-gray-200 hover:border-gray-300 cursor-pointer":"border-gray-200 cursor-default"}`,children:[e.jsx(vs,{className:`h-4 w-4 ${u?"text-amber-600":"text-gray-600"}`}),e.jsxs("div",{className:"relative",children:[e.jsx("span",{className:`text-sm font-semibold ${u?"text-amber-600":"text-gray-900"}`,children:b}),e.jsx("div",{className:"pointer-events-none absolute left-1/2 top-0 -translate-x-1/2 -translate-y-full",children:g.map(w=>e.jsx("div",{className:`animate-float-up-fade-out text-xs font-semibold drop-shadow-sm ${Ud(w.delta)}`,children:Bd(w.delta)},w.id))})]})]})}const Pb=["gmail.com","yahoo.com","hotmail.com","outlook.com","aol.com","icloud.com","mail.com","protonmail.com","yandex.com","zoho.com","gmx.com","live.com","msn.com","qq.com","163.com","sina.com"],Ib=t=>{const a=t.toLowerCase().trim().split("@")[1];return a?Pb.some(n=>a===n||a.endsWith(`.${n}`)):!1};function Kd(t,s){const a=t.toLowerCase();if(a==="enterprise")return[{label:"Credits",value:"Custom"},{label:"Competitor Analysis",value:"Unlimited"},{label:"Keywords Research",value:"Unlimited"},{label:"Page Creations",value:"Unlimited"},{label:"Page Optimizations (GEO)",value:"Unlimited"},{label:"Technical SEO QA",value:"Custom"},{label:"Crawlability & Indexation",value:"Custom"},{label:"Tracked Pages",value:"Unlimited"},{label:"Tracked Keywords",value:"Unlimited"},{label:"Tracked Prompts",value:"Unlimited"},{label:"AI Models",value:"Custom / All Models"},{label:"CMS & SEO Integrations",value:"Custom"},{label:"Knowledge Bases RAG",value:"Custom"},{label:"Content Strategy",value:"Expert-assisted"},{label:"Support",value:"Dedicated Vetted Operator"}];const n=s.toLocaleString();return a==="starter"?[{label:"Credits",value:n},{label:"Competitor Analysis",value:Nt.getFormattedLimit("competitor_analysis","starter")},{label:"Keywords Research",value:Nt.getFormattedLimit("keywords_research_per_competitor","starter")},{label:"Page Creations",value:Nt.getFormattedLimit("page_content_creations","starter")},{label:"Page Optimizations (GEO)",value:Nt.getFormattedLimit("page_optimizations_geo","starter")},{label:"Technical SEO QA",value:"10"},{label:"Crawlability & Indexation",value:"3"},{label:"Tracked Pages",value:"3"},{label:"Tracked Keywords",value:Nt.getFormattedLimit("tracked_keywords","starter")},{label:"Tracked Prompts",value:Nt.getFormattedLimit("tracked_prompts","starter")},{label:"AI Models",value:"GPT, Gemini 3, Anthropic"},{label:"CMS & SEO Integrations",value:"Basic"},{label:"Knowledge Bases RAG",value:"Standard"},{label:"Content Strategy",value:"Automated"},{label:"Support",value:"Standard"}]:a==="pro"?[{label:"Credits",value:n},{label:"Competitor Analysis",value:Nt.getFormattedLimit("competitor_analysis","pro")}
56,{label:"Keywords Research",value:Nt.getFormattedLimit("keywords_research_per_competitor","pro")},{label:"Page Creations",value:Nt.getFormattedLimit("page_content_creations","pro")},{label:"Page Optimizations (GEO)",value:Nt.getFormattedLimit("page_optimizations_geo","pro")},{label:"Technical SEO QA",value:"2,000"},{label:"Crawlability & Indexation",value:"400"},{label:"Tracked Pages",value:"400"},{label:"Tracked Keywords",value:Nt.getFormattedLimit("tracked_keywords","pro")},{label:"Tracked Prompts",value:Nt.getFormattedLimit("tracked_prompts","pro")},{label:"AI Models",value:"GPT, Gemini 3, Anthropic"},{label:"CMS & SEO Integrations",value:"Advanced"},{label:"Knowledge Bases RAG",value:"Advanced"},{label:"Content Strategy",value:"Advanced"},{label:"Support",value:"1:1 Strategic"}]:[{label:"Credits",value:n},{label:"Competitor Analysis",value:Nt.getFormattedLimit("competitor_analysis","growth")},{label:"Keywords Research",value:Nt.getFormattedLimit("keywords_research_per_competitor","growth")},{label:"Page Creations",value:Nt.getFormattedLimit("page_content_creations","growth")},{label:"Page Optimizations (GEO)",value:Nt.getFormattedLimit("page_optimizations_geo","growth")},{label:"Technical SEO QA",value:"150"},{label:"Crawlability & Indexation",value:"35"},{label:"Tracked Pages",value:"35"},{label:"Tracked Keywords",value:Nt.getFormattedLimit("tracked_keywords","growth")},{label:"Tracked Prompts",value:Nt.getFormattedLimit("tracked_prompts","growth")},{label:"AI Models",value:"GPT, Gemini 3, Anthropic"},{label:"CMS & SEO Integrations",value:"Basic"},{label:"Knowledge Bases RAG",value:"Standard"},{label:"Content Strategy",value:"Automated"},{label:"Support",value:"Standard"}]}function Mb(t,s,a=["starter","growth","pro"]){if(!s)return"Subscribe";const n=a.indexOf(s.toLowerCase()),o=a.indexOf(t.toLowerCase());return n===-1||o===-1?"Subscribe":n===o?"Current Plan":o>n?"Upgrade":"Downgrade"}function Gd({plan:t,billingInterval:s,currentPlanType:a,currentSubscription:n,discountCode:o=null,isProcessing:i=!1,onSubscribe:l,onCancelSubscription:c,onReactivateSubscription:d,onEnterpriseContact:m,onSwitchBillingInterval:h,isSwitchingBillingInterval:p=!1,maxFeatures:f,isComparison:b=!1,checkoutDisabled:y=!1,checkoutDisabledReason:x}){const u=a===t.plan_type,g=i,w=Mb(t.plan_type,a),_=vo(t),E=s==="yearly",N=t.yearly_price_usd!==null,S=t.plan_type==="enterprise",k=!!y&&!S,D=k&&x?x:void 0,R=S?null:E&&N?((se,z)=>{const U=se/12;return z.toLowerCase()==="starter"?parseFloat(U.toFixed(1)):Math.round(U)})(t.yearly_price_usd,t.plan_type):t.price_usd,L=!!o&&!S,$=o?.percent_off??0,H=1-$/100,K=L&&typeof R=="number"?R*H:null,X=L&&E&&N&&t.yearly_price_usd!==null?t.yearly_price_usd*H:null,V=t.plan_type==="pro"&&!u&&!S,P=b&&u,A=u&&!P||V?"relative rounded-2xl p-8 transition-all duration-300 flex flex-col bg-gradient-to-br from-blue-600 to-cyan-500 text-white shadow-2xl shadow-blue-500/25 z-10":"relative rounded-2xl p-8 transition-all duration-300 flex flex-col bg-white text-slate-900 border border-slate-200 hover:border-blue-200 hover:shadow-xl",C=u?"Current":t.plan_type==="pro"&&!u?"Most popular":void 0,I=u?"absolute -top-3 right-4 flex items-center gap-1 bg-blue-100 text-blue-700 text-[10px] font-bold px-2.5 py-1 rounded-full shadow-sm":C?"absolute -top-3 right-4 flex items-center gap-1 bg-amber-400 text-slate-900 text-[10px] font-bold px-2.5 py-1 rounded-full shadow-sm":"",j=(V||u)&&!P?"text-white":"text-slate-900",q=(V||u)&&!P?"text-blue-100":"text-slate-500",T=(V||u)&&!P?"bg-white/20":"bg-blue-100",M=(V||u)&&!P?"text-white":"text-blue-600",Z=w==="Downgrade",B=u&&!!n&&n.status==="active"&&!n.cancel_at_period_end&&typeof h=="function",ae=n?.billing_interval==="yearly"?"monthly":"yearly",de=!B||ae==="monthly"||N,fe=u&&!P||V?"w-full py-3 px-6 rounded-xl font-semibold text-sm transition-all duration-200 bg-white text-blue-600 hover:bg-blue-50 shadow-lg flex items-center justify-center gap-2":Z||u&&P?"w-full py-3 px-6 rounded-xl font-semibold text-sm transition-all duration-200 bg-slate-100 text-slate-600 hover:bg-slate-200 flex items-center justify-center gap-2":"w-full py-3 px-6 rounded-xl font-semibold text-sm transition-all duration-200 bg-slate-900 text-white hover:bg-slate-800 flex items-center justify-center gap-2";return e.jsxs("div",{className:A,children:[C&&e.jsxs("div",{className:I,children:[(V||u)&&!P&&C==="Most popular"&&e.jsx(Dr,{className:"w-3 h-3 fill-current"}),C]}),e.jsxs("div",{className:"mb-6",children:[e.jsx("h3",{className:`text-2xl font-display italic mb-1 ${j}`,children:t.name}),t.description&&e.jsx("p",{className:`text-sm ${q}`,children:t.description})]}),e.jsx("div",{className:"mb-6",children:S?e.jsx("span",{className:`text-4xl font-bold ${j}`,children:"Custom"}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"flex items-baseline gap-x-2 flex-wrap",children:L&&K!==null?e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:`text-4xl font-bold ${(V||u)&&!P?"text-white":"text-indigo-600"}
56`,children:["$",K%1===0?K.toLocaleString():K.toFixed(1)]}),e.jsx("span",{className:`text-sm ${q}`,children:"/mo"}),e.jsxs("span",{className:`text-lg line-through decoration-slate-400/50 ${(V||u)&&!P?"text-blue-200":"text-slate-400"}`,children:["$",R!=null?R%1===0?R.toLocaleString():R.toFixed(1):""]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:`text-4xl font-bold ${j}`,children:["$",R!=null?R%1===0?R.toLocaleString():R.toFixed(1):""]}),e.jsx("span",{className:`text-sm ml-1 ${q}`,children:"/month"})]})}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 mt-2 min-h-[24px]",children:[L&&K!==null&&e.jsxs("span",{className:`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-bold border whitespace-nowrap ${(V||u)&&!P?"bg-white/20 text-white border-white/20":"bg-indigo-50 text-indigo-700 border-indigo-100"}`,children:["Your discount -",$,"% (1st"," ",E?"yr":"mo",")"]}),E&&N&&_>0&&e.jsxs("span",{className:"inline-flex items-center px-2 py-0.5 rounded-full text-xs font-bold bg-emerald-500 text-white border border-emerald-600",children:["Save ",_,"%"]})]}),E&&N&&e.jsx("p",{className:`text-xs mt-2 ${q} opacity-80 whitespace-nowrap`,children:X!==null?e.jsxs(e.Fragment,{children:["Billed"," ",e.jsxs("span",{className:"line-through opacity-60",children:["$",t.yearly_price_usd?.toLocaleString(),"/yr"]})," ",e.jsxs("span",{className:"font-semibold",children:["$",X%1===0?X.toLocaleString():X.toFixed(1),"/yr"]})," ","(1st year)"]}):e.jsxs(e.Fragment,{children:["Billed $",t.yearly_price_usd?.toLocaleString(),"/year"]})})]})}),e.jsx("div",{className:"flex-1 mt-6",children:e.jsx("ul",{className:"space-y-3",children:(f!==void 0?Kd(t.plan_type,S?0:t.credits_per_month).slice(0,f):Kd(t.plan_type,S?0:t.credits_per_month)).map((se,z)=>e.jsxs("li",{className:"flex items-start gap-3",children:[e.jsx("div",{className:`flex-shrink-0 w-5 h-5 rounded-full flex items-center justify-center mt-0.5 ${T}`,children:e.jsx(wt,{className:`w-3 h-3 ${M}`})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("span",{className:`text-xs font-medium ${(V||u)&&!P?"text-blue-200":"text-slate-500"}`,children:[se.label,":"]}),e.jsx("span",{className:`text-sm ml-1 ${(V||u)&&!P?"text-blue-50":"text-slate-600"}`,children:se.value})]})]},z))})}),S?e.jsxs("button",{onClick:m,className:"w-full py-3 px-6 rounded-xl font-semibold text-sm transition-all duration-200 mt-8 bg-slate-900 text-white hover:bg-slate-800 flex items-center justify-center gap-2",children:[e.jsx(Wa,{size:14}),"Book a demo"]}):Z?e.jsx("button",{onClick:()=>l(t.plan_type),disabled:g||k,className:`w-full py-3 px-6 rounded-xl font-semibold text-sm transition-all duration-200 mt-8 bg-slate-100 text-slate-600 hover:bg-slate-200 flex items-center justify-center gap-2 ${g||k?"opacity-50 cursor-not-allowed":""}`,title:D,children:g?e.jsxs(e.Fragment,{children:[e.jsx(He,{size:14,className:"animate-spin"}),"Processing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Wa,{size:14}),w]})}):B&&de?e.jsx("button",{onClick:()=>h?.(ae),disabled:g||p||k,className:`${fe} mt-8 ${g||p||k?"opacity-50 cursor-not-allowed":""}`,title:D,children:g||p?e.jsxs(e.Fragment,{children:[e.jsx(He,{size:14,className:"animate-spin"}),"Processing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Ms,{size:14}),"Switch to ",ae==="yearly"?"Yearly":"Monthly",n?.billing_interval==="monthly"&&ae==="yearly"&&_>0&&e.jsxs("span",{className:"ml-2 px-1.5 py-0.5 text-[10px] font-semibold bg-emerald-500 text-white rounded-full",children:["Save ",_,"%"]})]})}):e.jsx("button",{onClick:()=>l(t.plan_type),disabled:u||g||k,className:`${fe} mt-8 ${g||k?"opacity-50 cursor-not-allowed":""}`,title:D,children:g?e.jsxs(e.Fragment,{children:[e.jsx(He,{size:14,className:"animate-spin"}),"Processing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Wa,{size:14}),w]})})]})}function Hl({open:t,onOpenChange:s,toast:a}){const[n,o]=r.useState({fullName:"",email:"",company:"",website:""}),[i,l]=r.useState(!1),[c,d]=r.useState("idle"),[m,h]=r.useState(""),p=y=>{const{name:x,value:u}=y.target;o(g=>({...g,[x]:u})),c==="error"&&(d("idle"),h(""))},f=async y=>{if(y.preventDefault(),Ib(n.email)){d("error"),h("Please use a work email address.");return}l(!0),d("idle"),h("");try{const x=n.fullName.trim().split(/\s+/),u=x[0]||"",g=x.slice(1).join(" ")||"",w=await fetch(`${Da()}/api/contact_requests`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({first_name:u,last_name:g,work_email:n.email.trim(),marketing_team_size:null,help_with:["Enterprise Plan"]})});if(!w.ok){const _=await w.json().catch(()=>({}));
56throw new Error(_.detail||"Failed to submit contact request")}d("success"),o({fullName:"",email:"",company:"",website:""}),a({title:"Success",description:"Your request has been submitted successfully. We'll be in touch soon!"}),setTimeout(()=>{s(!1),d("idle")},2e3)}catch(x){d("error"),h(x instanceof Error?x.message:"Something went wrong. Please try again.")}finally{l(!1)}},b=()=>{i||(s(!1),c!=="success"&&(o({fullName:"",email:"",company:"",website:""}),d("idle"),h("")))};return e.jsx(Ht,{open:t,onOpenChange:b,children:e.jsx(qt,{className:"max-w-md",children:c==="success"?e.jsxs("div",{className:"text-center py-8",children:[e.jsx("div",{className:"w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-4",children:e.jsx(Rs,{className:"w-8 h-8 text-green-600"})}),e.jsx(Yt,{className:"text-2xl font-semibold text-slate-900 mb-2",children:"Thank you!"}),e.jsx(Ds,{className:"text-slate-600",children:"We'll be in touch within 24 hours."})]}):e.jsxs(e.Fragment,{children:[e.jsx(Zt,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 bg-blue-100 rounded-lg flex items-center justify-center",children:e.jsx(Wa,{className:"w-5 h-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(Yt,{className:"text-lg font-semibold text-slate-900",children:"Book a Demo"}),e.jsx(Ds,{className:"text-sm text-slate-500",children:"Contact us for Enterprise plan pricing"})]})]}),e.jsx("button",{onClick:b,disabled:i,className:"text-slate-400 hover:text-slate-600 transition-colors disabled:opacity-50",children:e.jsx(mt,{size:20})})]})}),e.jsxs("form",{onSubmit:f,className:"space-y-4 mt-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-slate-700 mb-1",children:"Full Name"}),e.jsx("input",{type:"text",name:"fullName",value:n.fullName,onChange:p,required:!0,className:"w-full px-4 py-3 border border-slate-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all",placeholder:"John Doe"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-slate-700 mb-1",children:"Work Email"}),e.jsx("input",{type:"email",name:"email",value:n.email,onChange:p,required:!0,className:"w-full px-4 py-3 border border-slate-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all",placeholder:"[email protected]"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-slate-700 mb-1",children:"Company"}),e.jsx("input",{type:"text",name:"company",value:n.company,onChange:p,className:"w-full px-4 py-3 border border-slate-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all",placeholder:"Acme Inc"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-slate-700 mb-1",children:"Website"}),e.jsx("input",{type:"url",name:"website",value:n.website,onChange:p,className:"w-full px-4 py-3 border border-slate-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all",placeholder:"https://company.com"})]}),c==="error"&&e.jsx("p",{className:"text-red-600 text-sm",children:m}),e.jsx("button",{type:"submit",disabled:i,className:"w-full bg-blue-600 text-white py-4 px-6 rounded-xl font-semibold hover:bg-blue-700 transition-colors duration-200 flex items-center justify-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed",children:i?e.jsxs(e.Fragment,{children:[e.jsx(He,{size:16,className:"animate-spin"}),"Submitting..."]}):e.jsxs(e.Fragment,{children:["Get a Demo",e.jsx(Ri,{className:"w-4 h-4"})]})})]})]})})})}const Rb={payg_10:["Full access to all features","Credits never expire"],starter:[{label:"Credits",value:""},{label:"Competitor Analysis",value:Nt.getFormattedLimit("competitor_analysis","starter")},{label:"Keywords Research",value:Nt.getFormattedLimit("keywords_research_per_competitor","starter")},{label:"Page Creations",value:Nt.getFormattedLimit("page_content_creations","starter")},{label:"Page Optimizations (GEO)",value:Nt.getFormattedLimit("page_optimizations_geo","starter")},{label:"Technical SEO QA",value:"10"},{label:"Crawlability & Indexation",value:"3"},{label:"Tracked Pages",value:"3"},{label:"Tracked Keywords",value:Nt.getFormattedLimit("tracked_keywords","starter")},{label:"Tracked Prompts",value:Nt.getFormattedLimit("tracked_prompts","starter")},{label:"AI Models",value:"GPT, Gemini 3, Anthropic"},{label:"CMS & SEO Integrations",value:"Basic"},{label:"Knowledge Bases RAG",value:"Standard"},{label:"Content Strategy",value:"Automated"},{label:"Support",value:"Standard"}],growth:[{label:"Credits",value:""},{label:"Competitor Analysis",value:Nt.getFormattedLimit("competitor_analysis","growth")}
56,{label:"Keywords Research",value:Nt.getFormattedLimit("keywords_research_per_competitor","growth")},{label:"Page Creations",value:Nt.getFormattedLimit("page_content_creations","growth")},{label:"Page Optimizations (GEO)",value:Nt.getFormattedLimit("page_optimizations_geo","growth")},{label:"Technical SEO QA",value:"150"},{label:"Crawlability & Indexation",value:"35"},{label:"Tracked Pages",value:"35"},{label:"Tracked Keywords",value:Nt.getFormattedLimit("tracked_keywords","growth")},{label:"Tracked Prompts",value:Nt.getFormattedLimit("tracked_prompts","growth")},{label:"AI Models",value:"GPT, Gemini 3, Anthropic"},{label:"CMS & SEO Integrations",value:"Basic"},{label:"Knowledge Bases RAG",value:"Standard"},{label:"Content Strategy",value:"Automated"},{label:"Support",value:"Standard"}],pro:[{label:"Credits",value:""},{label:"Competitor Analysis",value:Nt.getFormattedLimit("competitor_analysis","pro")},{label:"Keywords Research",value:Nt.getFormattedLimit("keywords_research_per_competitor","pro")},{label:"Page Creations",value:Nt.getFormattedLimit("page_content_creations","pro")},{label:"Page Optimizations (GEO)",value:Nt.getFormattedLimit("page_optimizations_geo","pro")},{label:"Technical SEO QA",value:"2,000"},{label:"Crawlability & Indexation",value:"400"},{label:"Tracked Pages",value:"400"},{label:"Tracked Keywords",value:Nt.getFormattedLimit("tracked_keywords","pro")},{label:"Tracked Prompts",value:Nt.getFormattedLimit("tracked_prompts","pro")},{label:"AI Models",value:"GPT, Gemini 3, Anthropic"},{label:"CMS & SEO Integrations",value:"Advanced"},{label:"Knowledge Bases RAG",value:"Advanced"},{label:"Content Strategy",value:"Advanced"},{label:"Support",value:"1:1 Strategic"}]},Db={payg_10:{badge:"One-time",buttonText:"Buy Now",variant:"stone"},starter:{badge:"Starter",buttonText:"Get Started"},growth:{badge:"Popular",buttonText:"Get Started"},pro:{badge:"Best Value",buttonText:"Book Call",isPrimary:!0,isHighlighted:!0}};function Wd(t){return`$${t.toLocaleString()}`}function Vd(){try{return`${window.location.pathname}${window.location.search}`}catch{return}}function Lb(t){const s=Db[t.plan_type]||{buttonText:"Subscribe"},a=Rb[t.plan_type]||[],n=vo(t),o=t.yearly_price_usd?Math.round(t.yearly_price_usd/12):null,i=Array.isArray(a)&&a.length>0?a.map(l=>typeof l=="string"?l:l.label==="Credits"&&!l.value?{...l,value:t.credits_per_month.toLocaleString()}:l):[];return{id:t.plan_type,name:t.name,price:Wd(t.price_usd),priceLabel:"per month",yearlyPrice:o?Wd(o):void 0,yearlyPriceLabel:o?"per month, billed yearly":void 0,yearlyDiscountPercent:n>0?Math.round(n):void 0,credits:t.credits_per_month.toLocaleString(),creditsLabel:"Included Credits",features:i,...s}}const zb={id:"quick-start",name:"Quick Start",price:"$9.9",priceLabel:"One-time purchase",credits:"2,000",creditsLabel:"Bonus Credits",features:["Full access to all features","Credits never expire"],badge:"One-time",buttonText:"Buy Now",variant:"stone"},$b=[{id:"quick-start",packageCode:"payg_10",name:"Quick Start",amountUsd:9.9,price:"$9.9",credits:"2,000",badge:"One-time",bullets:["Credits never expire","Use for all AI features"]},{id:"payg-plus",packageCode:"payg_50",name:"Credit Pack",amountUsd:49.9,price:"$49.9",credits:"10,000",badge:"Best Value",bullets:["Credits never expire","Best for refills"]}];function Fb(t){return t?t.toLowerCase():null}function Ob(t){return!t||!Number.isFinite(t)?"—":t.toLocaleString()}function Fo(t,s){const a=s.toLowerCase();return t.find(n=>n.plan_type.toLowerCase()===a)}function Bb({option:t,loading:s,disabled:a,discountCode:n,onBuy:o}){const i=Number(t.amountUsd),l=!!n,c=n?.percent_off??0,d=1-c/100,m=l?i*d:null;return e.jsxs("div",{className:"relative rounded-xl border border-slate-200 bg-white p-4 hover:border-amber-200 hover:shadow-sm transition-all flex flex-col h-full",children:[t.badge&&e.jsx("div",{className:"absolute -top-3 right-4 bg-amber-400 text-slate-900 text-[10px] font-bold px-2.5 py-1 rounded-full shadow-sm",children:t.badge}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(vs,{size:16,className:"text-amber-600"}),e.jsx("div",{className:"text-[15px] font-semibold italic text-slate-900",children:t.name})]}),e.jsxs("div",{className:"mt-2 flex items-end gap-2",children:[e.jsxs("div",{className:"text-3xl font-bold text-slate-900 tabular-nums",children:["$",m!==null?m.toFixed(1).replace(/\.0$/,""):i.toFixed(1).replace(/\.0$/,"")]}),e.jsx("div",{className:"text-[11px] text-slate-500 mb-1",children:"one-time"}),l&&m!==null&&e.jsxs("div",{className:"ml-2 mb-1 text-[11px] text-slate-400 line-through",children:["$",i.toFixed(1).replace(/\.0$/,"")]})]}),l&&e.jsxs("div",{className:"mt-2 inline-flex items-center px-2 py-0.5 rounded-full text-[10px] font-bold border border-indigo-200 bg-indigo-50 text-indigo-700 whitespace-nowrap",children:["Your discount -",c,"% (1st purchase)"]}),e.jsx("div",{className:"mt-3 px-3 py-2 bg-amber-50 rounded-lg border border-amber-100",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-[10px] font-medium text-amber-700",children:"Bonus Credits"}),e.jsx("span",{className:"text-[12px] font-bold text-amber-800",children:t.credits})]})}),e.jsx("ul",{className:"mt-3 space-y-2",children:t.bullets.slice(0,2).map(h=>e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("div",{className:"flex-shrink-0 w-4 h-4 rounded-full flex items-center justify-center mt-0.5 bg-amber-50",children:e.jsx(wt,{className:"w-3 h-3 text-amber-700"})}),e.jsx("span",{className:"text-[11px] text-slate-600",children:h})]},h))}),e.jsx("div",{className:"mt-auto pt-4",children:e.jsxs("button",{className:`w-full h-10 px-4 roun
56ded-lg font-semibold text-[12px] leading-none transition-all flex items-center justify-center gap-2 ${s||a?"opacity-50 cursor-not-allowed bg-slate-200 text-slate-600":"bg-stone-600 text-white hover:bg-stone-700"}`,onClick:()=>o(t.packageCode),disabled:s||a,children:[s?e.jsx(He,{size:14,className:"animate-spin"}):e.jsx(vs,{size:14}),s?"Processing...":"Buy Now"]})})]})}function ll({plan:t,billingInterval:s,discountCode:a,isCurrent:n,isRecommended:o,loading:i,disabled:l,onSelect:c}){const m=t.plan_type.toLowerCase()==="enterprise",h=s==="yearly",p=t.yearly_price_usd!==null,b=m?null:h&&p?((F,R)=>{const L=F/12;return R.toLowerCase()==="starter"?parseFloat(L.toFixed(1)):Math.round(L)})(t.yearly_price_usd,t.plan_type):t.price_usd,y=vo(t),x=!!a&&!m,u=a?.percent_off??0,g=1-u/100,w=x&&typeof b=="number"?b*g:null,_=x&&h&&p&&t.yearly_price_usd!==null?t.yearly_price_usd*g:null,E=o?"relative rounded-xl border border-blue-200 bg-gradient-to-br from-blue-600 to-cyan-500 p-4 text-white shadow-sm flex flex-col h-full":n?"relative rounded-xl border border-slate-200 bg-white p-4 text-slate-900 shadow-sm flex flex-col h-full":"relative rounded-xl border border-slate-200 bg-white p-4 text-slate-900 flex flex-col h-full",N=n?"Current":o?"Recommended":void 0,S=n?"bg-blue-100 text-blue-700":"bg-amber-400 text-slate-900",k=o?"text-white":"text-slate-900",D=o?"text-blue-100":"text-slate-500";return e.jsxs("div",{className:E,children:[N&&e.jsxs("div",{className:`absolute -top-3 right-4 flex items-center gap-1 px-2.5 py-1 rounded-full shadow-sm text-[10px] font-bold ${S}`,children:[o&&e.jsx(Dr,{className:"w-3 h-3 fill-current"}),N]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Wa,{size:16,className:o?"text-white":"text-slate-600"}),e.jsx("div",{className:`text-[15px] font-semibold italic ${k}`,children:t.name})]}),e.jsx("div",{className:`mt-1 text-[11px] leading-snug ${D} line-clamp-2 min-h-[32px]`,children:t.description||""}),e.jsxs("div",{className:"mt-3",children:[e.jsx("div",{className:"flex items-end gap-2",children:m?e.jsx("div",{className:`text-2xl font-bold ${k} tabular-nums`,children:"Custom"}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:`text-3xl font-bold tabular-nums ${x&&w!==null?o?"text-white":"text-indigo-600":k}`,children:["$",(x&&w!==null?w:b)!==null&&(x&&w!==null?w:b)!==void 0?(x&&w!==null?w:b)%1===0?(x&&w!==null?w:b).toLocaleString():(x&&w!==null?w:b).toFixed(1):""]}),e.jsx("div",{className:`text-[11px] mb-1 ${D}`,children:"/mo"}),x&&w!==null&&e.jsxs("div",{className:`text-[11px] mb-1 line-through decoration-slate-400/50 ${o?"text-blue-200":"text-slate-400"}`,children:["$",b!=null?b%1===0?b.toLocaleString():b.toFixed(1):""]})]})}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 mt-2 min-h-[20px]",children:[x&&w!==null&&e.jsxs("span",{className:`inline-flex items-center px-2 py-0.5 rounded-full text-[10px] font-bold border whitespace-nowrap ${o?"bg-white/20 text-white border-white/20":"bg-indigo-50 text-indigo-700 border-indigo-100"}`,children:["Your discount -",u,"% (1st"," ",h?"yr":"mo",")"]}),h&&p&&y>0&&e.jsxs("span",{className:"inline-flex items-center px-2 py-0.5 rounded-full text-[10px] font-bold bg-emerald-500 text-white border border-emerald-600 whitespace-nowrap",children:["Save ",y,"%"]})]}),h&&p&&e.jsx("div",{className:`mt-2 text-[10px] ${D} whitespace-nowrap`,children:_!==null?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"opacity-80",children:"Billed"})," ",e.jsxs("span",{className:"line-through opacity-60",children:["$",t.yearly_price_usd?.toLocaleString(),"/yr"]})," ",e.jsxs("span",{className:"font-semibold",children:["$",_%1===0?_.toLocaleString():_.toFixed(1),"/yr"]})," ",e.jsx("span",{className:"opacity-80",children:"(1st year)"})]}):e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"opacity-80",children:"Billed"})," ",e.jsxs("span",{className:"font-semibold",children:["$",t.yearly_price_usd?.toLocaleString(),"/yr"]})]})})]}),e.jsx("div",{className:`mt-3 rounded-lg px-3 py-2 ${o?"bg-white/15 border border-white/20":"bg-slate-50 border border-slate-200"}`,children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:`text-[10px] font-medium ${o?"text-blue-100":"text-slate-500"}`,children:"Included Credits"}),e.jsx("span",{className:`text-[12px] font-bold ${o?"text-white":"text-slate-900"}
56 tabular-nums`,children:m?"Custom":Ob(t.credits_per_month)})]})}),e.jsx("div",{className:"mt-auto pt-4",children:e.jsxs("button",{className:`w-full h-10 px-4 rounded-lg font-semibold text-[12px] leading-none transition-all flex items-center justify-center gap-2 ${i||l?"opacity-50 cursor-not-allowed bg-white/80 text-slate-700":o?"bg-white text-blue-700 hover:bg-blue-50":"bg-slate-900 text-white hover:bg-slate-800"}`,onClick:()=>c(t.plan_type),disabled:i||l||n,children:[i?e.jsx(He,{size:14,className:"animate-spin"}):e.jsx(Wa,{size:14}),n?"Current Plan":o?"Upgrade":"Select Plan"]})})]})}function vx({plans:t,title:s="Get started",subtitle:a="Choose a plan to get credits and try all features",footnote:n="Content Optimization values are monthly estimates. Actual output may vary based on project complexity and content quality requirements.",billingInterval:o,onBillingIntervalChange:i,showBillingToggle:l=!0,onPlanSelect:c,stripePlanMapping:d,onCheckoutError:m,fetchFromApi:h=!0,currentPlanType:p,fetchSubscription:f=!0,maxFeatures:b}){const[y,x]=r.useState(null),[u,g]=r.useState("yearly"),[w,_]=r.useState([]),[E,N]=r.useState([]),[S,k]=r.useState({}),[D,F]=r.useState(h),[R,L]=r.useState(null),[$,H]=r.useState(null),[K,X]=r.useState(!1),{toast:V}=_t();r.useEffect(()=>{let se=!0;const z=async()=>{try{const Q=await yx();if(!se)return;H(Q)}catch(Q){if(console.warn("⚠️ [pricing-plans] Failed to load discount code:",Q),!se)return;H(null)}};z();const U=()=>{z()};return window.addEventListener("discount_code_updated",U),()=>{se=!1,window.removeEventListener("discount_code_updated",U)}},[]),r.useEffect(()=>{const se=z=>{z.persisted&&(console.log("🟢 [pricing-plans] Restored from bfcache. Resetting loading..."),x(null))};return window.addEventListener("pageshow",se),()=>window.removeEventListener("pageshow",se)},[]),r.useEffect(()=>{if(!h||t){F(!1);return}async function se(){try{const[z,U]=await Promise.all([fx(),f&&p===void 0?Xa():Promise.resolve(null)]);U&&L(U);const Q=z.filter(ne=>ne.is_active&&!["free","payg"].includes(ne.plan_type.toLowerCase()));Q.sort((ne,ge)=>ne.price_usd-ge.price_usd);const me=[],le={};p==="pro"||Q.forEach(ne=>{const ge=Lb(ne);me.push(ge),le[ge.id]={type:"subscription",code:ne.plan_type}}),me.push(zb),le["quick-start"]={type:"payg",code:"payg_10"},me.push({id:"payg-plus",name:"Credit Pack",price:"$49.9",priceLabel:"One-time purchase",credits:"10,000",creditsLabel:"Bonus Credits",features:["Full access to all features","Credits never expire"],badge:"Best Value",buttonText:"Buy Now",variant:"stone"}),le["payg-plus"]={type:"payg",code:"payg_50"},_(me),N(Q),k(le)}catch(z){console.error("🔴 Failed to load plans from API:",z),N([]),k({"quick-start":{type:"payg",code:"payg_10"},starter:{type:"subscription",code:"starter"},growth:{type:"subscription",code:"growth"},pro:{type:"subscription",code:"pro"}})}finally{F(!1)}}se()},[h,t,f,p]);const P=t||(w.length>0?w:[]);d||Object.keys(S).length>0;const A=o??u,C=i??g,I=p??R?.plan?.plan_type??null,j=Fb(I),q=Fo(E,"starter"),T=Fo(E,"growth"),M=Fo(E,"pro"),Z=Fo(E,"enterprise"),B=j==="pro"||j==="enterprise",ae=Math.max(0,...P.filter(se=>se.yearlyDiscountPercent).map(se=>se.yearlyDiscountPercent||0));async function de(se){try{x(se);const z=Vd(),U=await Mc(se,z);window.location.href=U.checkout_url}catch(z){console.error("🔴 PAYG checkout error:",z),m?.(se,z instanceof Error?z:new Error("Checkout failed"))}finally{x(null)}}async function fe(se){if(j==="enterprise"){V({title:"Disabled",description:"Self-serve plan checkout is disabled for Enterprise users."});return}try{x(se);const z=Vd(),U=await Ci(se,void 0,A,z);"checkout_url"in U?window.location.href=U.checkout_url:c?.(se)}catch(z){console.error("🔴 Subscription checkout error:",z),m?.(se,z instanceof Error?z:new Error("Checkout failed"))}finally{x(null)}}return e.jsxs("div",{id:Kb,className:"border border-slate-200 rounded-lg p-4 bg-white max-w-5xl mx-auto",children:[e.jsxs("div",{className:"text-center mb-4",children:[s&&e.jsx("h3",{className:"text-sm font-semibold text-slate-900 mb-0.5",children:s}),a&&e.jsx("p",{className:"text-[10px] text-slate-500",children:a}),$&&!B&&e.jsxs("div",{className:"mt-2 inline-flex items-center gap-2 px-3 py-1 rounded-full border border-indigo-200 bg-indigo-50 text-[10px] text-indigo-800 whitespace-nowrap",children:[e.jsx("span",{className:"font-semibold",children:"Your discount"}),e.jsx("span",{className:"opacity-80",children:"•"}),e.jsxs("span",{children:["-",$.percent_off,"% 1st"," ",A==="yearly"?"year":"month"]})]}),!B&&l&&ae>0&&e.jsx(Ub,{value:A,onChange:C,maxDiscount:ae})]}),D?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(He,{className:"h-6 w-6 animate-spin text-slate-400"})}):e.jsxs("div",{className:"space-y-5",children:[!B&&(T||M)&&e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Wa,{size:16,className:"text-slate-600"}),e.jsx("div",{className:"text-[12px] font-semibold text-slate-900",children:"Upgrade Plan"})]}),e.jsx("button",{className:"text-[10px] font-medium text-slate-600 hover:text-slate-900 underline underline-offset-2",onClick:()=>{window.location.href="/app/subscription"},children:"View pricing"})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-3",children:[q&&e.jsx(ll,{plan:q,billingInterval:A,discountCode:$,isCurrent:j==="starter",isRecommended:!1,loading:y===q.plan_type,disabled:y!==null&&y!==q.plan_type,onSelect:fe}),T&&e.jsx(ll,{plan:T,billingInterval:A,discountCode:$,isCurrent:j==="growth",isRecommended:!1,loading:y===T.plan_type,disabled:y!==null&&y!==T.plan_type,onSelect:fe}),M&&e.jsx(ll,{plan:M,billingInterval:A,discountCode:$,isCurrent:j==="pro",isRecommended:!0,loading:y===M.plan_type,disabled:y!==null&&y!==M.plan_type,onSelect:fe})]}),Z&&e.jsxs("div",{className:"mt-2 flex items-center justify-between rounded-lg border border-slate-200 bg-slate-50 px-3 py-2",children:[e.jsx("div",{className:"text-[10px] text-slate-600",children:"Need custom volume? Contact us for Enterprise."}),e.jsx("button",{className:"text-[10px] font-semibold text-slate-900 hover:text-slate-700",onClick:()=>X(!0),children:"Contact"})]})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(vs,{size:16,className:"text-amber-600"}),e.jsx("div",{className:"text-[12px] font-semibold text-slate-900",children:"Credit Refill"})]}),e.jsx("div",{className:"text-[10px] text-slate-500",children:"One-time purchase"})]}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:$b.map(se=>e.jsx(Bb,{option:se,loading:y===se.packageCode,disabled:y!==null&&y!==se.packageCode,discountCode:$,onBuy:de},se.id))})]})]}),e.jsx(Hl,{open:K,onOpenChange:X,toast:V}),n&&e.jsx("p",{className:"mt-4 text-[8px] text-slate-400 text-center px-4 leading-relaxed",children:n})]})}function Ub({value:t,onChange:s,maxDiscount:a}){return e.jsx("div",{className:"flex items-center justify-center mt-3",children:e.jsxs("div",{className:"inline-flex items-center bg-slate-100 rounded-lg p-0.5",children:[e.jsx("button",{onClick:()=>s("monthly"),className:`px-3 py-1.5 text-[11px] font-medium rounded-md transition-all ${t==="monthly"?"bg-slate-900 text-white shadow-sm":"text-slate-600 hover:text-slate-900"}`,children:"Monthly"}),e.jsxs("button",{onClick:()=>s("yearly"),className:`px-3 py-1.5 text-[11px] font-medium rounded-md transition-all flex items-center gap-1.5 ${t==="yearly"?"bg-slate-900 text-white shadow-sm":"text-slate-600 hover:text-slate-900"}`,children:["Yearly",a>0&&e.jsxs("span",{className:"px-1.5 py-0.5 text-[9px] font-semibold bg-emerald-500 text-white rounded-full",children:["Save ",a,"%"]})]})]})})}const Kb="pricing-plans-section",Gb=({open:t,onOpenChange:s})=>{const{toast:a}=_t(),n=(o,i)=>{a({title:"Error",description:i.message||"Failed to create checkout session"})};return e.jsx(Ht,{open:t,onOpenChange:s,children:e.jsxs(qt,{className:"sm:max-w-5xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Zt,{align:"center",spacing:"lg",children:e.jsx(Yt,{className:"text-xl font-semibold",children:"Choose Your Plan"})}),e.jsx("div",{className:"mt-4",children:e.jsx(vx,{title:"",subtitle:"",footnote:"",onCheckoutError:n})})]})})};function ir({borderColor:t,showMarketSwitcher:s=!0,showCredits:a=!1,customRightContent:n}){const[o,i]=r.useState(!1),l=t?"border-b":"border-b border-slate-200",c=t?{borderBottomColor:t}:void 0;return e.jsxs(e.Fragment,{children:[e.jsx("header",{className:`sticky top-0 z-40 backdrop-blur supports-[backdrop-filter]:bg-white/70 bg-white/80 ${l}`,style:c,children:e.jsx("div",{className:"mx-auto max-w-7xl px-4 sm:px-6 lg:px-8",children:e.jsxs("div",{className:"flex items-center h-16 justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(dr,{className:"h-9 w-9 rounded-2xl",alt:"RankGale"}),e.jsx("span",{className:"font-semibold tracking-tight",children:"Rankgale"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[a&&e.jsx(jx,{variant:"compact",onClick:()=>i(!0)}),s&&e.jsx(Ab,{size:"sm"}),n||e.jsx(Dc,{dropdownPosition:"below"})]})]})})}),a&&e.jsx(Gb,{open:o,onOpenChange:i})]})}function Nx({title:t="Activating referral code...",subtitle:s,progress:a}){const n=typeof a=="number"&&Number.isFinite(a)?Math.max(0,Math.min(100,a)):null;return e.jsx("div",{className:"w-full bg-white border border-slate-100 rounded-xl p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(He,{className:"h-5 w-5 animate-spin text-slate-900 mt-0.5"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"text-sm font-semibold text-slate-900",children:t}),s?e.jsx("div",{className:"text-[12px] text-slate-600 mt-1",children:s}):null,n!==null?e.jsxs("div",{className:"w-full mt-3",children:[e.jsx("div",{className:"h-2.5 bg-slate-200 rounded-full overflow-hidden mb-2 relative",children:e.jsx("div",{className:"h-full bg-indigo-500 transition-all duration-150 ease-out rounded-full",style:{width:`${n}%`}})}),e.jsxs("div",{className:"flex justify-between text-xs text-slate-500",children:[e.jsx("span",{children:"Activating..."}),e.jsxs("span",{children:[Math.round(n),"%"]})]})]}):null]})]})})}const Hd="referral_code";function Wb(){const{toast:t}=_t(),[s,a]=r.useState(!0),[n,o]=r.useState(!1),[i,l]=r.useState(!1),[c,d]=r.useState(""),[m,h]=r.useState(!1),[p,f]=r.useState(0),[b,y]=r.useState(null),x=r.useCallback(async(u,g=!1)=>{const w=u||c.trim();if(!w){y("Please enter a referral code");return}g||h(!0),y(null),f(0);const _=7e3,E=100,N=_/E;let S=0;const k=setInterval(()=>{S++;const D=Math.min(95,S/N*100);f(D)},E);try{const D=await Tl(w.toUpperCase());clearInterval(k),f(100),await new Promise(F=>setTimeout(F,500)),D.success?(localStorage.removeItem(Hd),t({title:"Success!",description:"Referral code activated. Redirecting to homepage..."}),setTimeout(()=>{jt("homepage")},1e3)):(y(D.message||"Failed to activate referral code"),h(!1))}catch(D){clearInterval(k),y(D?.message||"Failed to activate referral code"),h(!1)}},[c,t]);return r.useEffect(()=>{let u=!0;return(async()=>{try{const w=new URLSearchParams(window.location.search),_=w.get("code")||w.get("referral_code");let E=!1;try{const S=await Dn();u&&S?.company&&(E=!0,o(!0))}catch(S){S?.response?.status===404||S?.message?.includes("No active company")?u&&(E=!1,o(!1)):console.error("Failed to check existing company:",S)}try{const S=await sr();if(!u)return;if(S&&(console.log("📊 Loaded saved analysis result"),u)){window.location.href="/app/referral/report";return}}catch{console.log("No saved analysis found, checking for referral code")}let N=null;if(_){console.log("🔗 Found referral code in URL parameter, auto-activating..."),N=_.trim().toUpperCase(),w.delete("code"),w.delete("referral_code");const S=window.location.pathname+(w.toString()?`?${w.toString()}`:"");window.history.replaceState({},"",S)}else{const S=localStorage.getItem(Hd);S&&(console.log("🔑 Found referral code in localStorage, auto-activating..."),N=S)}N&&!E&&u?(l(!0),await x(N,!0),u&&l(!1)):_&&u&&d(_.trim().toUpperCase())}catch(w){console.error("Failed to load:",w),u&&(a(!1),l(!1))}finally{u&&a(!1)}})(),()=>{u=!1}},[x]),s||i?e.jsxs("div",{className:"min-h-screen bg-slate-50",children:[e.jsx(ir,{}),e.jsx("div",{className:"flex flex-col items-center justify-center py-12 px-4",children:i?e.jsx("div",{className:"w-full max-w-xl",children:e.jsx(Nx,{progress:p})}):e.jsx("div",{className:"flex items-center justify-center",children:e.jsx(He,{className:"h-8 w-8 animate-spin text-slate-900"})})})]}):e.jsxs("div",{className:"min-h-screen bg-slate-50",children:[e.jsx(ir,{}),e.jsx("div",{className:"max-w-2xl mx-auto px-4 py-8",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"text-center space-y-4",children:[e.jsx("div",{className:"flex justify-center",children:e.jsx("div",{className:"h-16 w-16 rounded-full bg-indigo-100 flex items-center justify-center",children:e.jsx(ou,{className:"h-8 w-8 text-indigo-600"})})}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold text-slate-900",children:"Activate Referral Code"}),e.jsx("p",{className:"text-slate-600 mt-2",children:"Enter your referral code to get instant geo/aeo & competitor analysis for free"})]})]}),e.jsx(xs,{children:e.jsxs(fs,{className:"pt-6 space-y-4",children:[e.jsx("div",{className:"space-y-3",children:m?e.jsxs("div",{className:"w-full py-2 space-y-2",children:[e.jsxs("div",{className:"flex justify-between text-xs text-slate-500",children:[e.jsx("span",{children:"Activating..."}),e.jsxs("span",{children:[Math.round(p),"%"]})]}),e.jsx("div",{className:"h-2 bg-slate-200 rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full bg-indigo-600 transition-all duration-100 ease-out",style:{width:`${p}%`}})})]}):e.jsxs("div",{className:"flex gap-2",children:[e.jsx(bt,{type:"text",placeholder:"Enter code (e.g., ABC12345)",value:c,onChange:u=>{d(u.target.value.toUpperCase()),y(null)},onKeyDown:u=>{u.key==="Enter"&&!m&&x()},className:"flex-1 font-mono uppercase",maxLength:16,disabled:m}),e.jsx(be,{onClick:()=>x(),disabled:m||!c.trim(),className:"bg-indigo-600 hover:bg-indigo-700",children:e.jsxs(e.Fragment,{children:[e.jsx(ac,{className:"h-4 w-4 mr-1"}),"Activate"]})})]})}),b&&e.jsxs("div",{className:"flex items-center gap-2 text-xs text-red-500",children:[e.jsx(Ss,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:b})]}),n&&e.jsxs("div",{className:"flex items-center gap-2 text-xs text-amber-600 bg-amber-50 p-2 rounded",children:[e.jsx(Ss,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"You already have a company. Referral codes can only be used for first-time analysis."})]})]})})]})})]})}function Vb(){return e.jsx(za,{children:e.jsx(Wb,{})})}function Hb(){const{toast:t}=_t(),[s,a]=r.useState(!0),[n,o]=r.useState(null);return r.useEffect(()=>{let i=!0;return(async()=>{try{const c=await sr();if(!i)return;if(c)o(c);
56else{t({title:"No analysis found",description:"Please run an analysis first."}),jt("setup");return}}catch(c){console.error("Failed to load data:",c),i&&t({title:"Error",description:"Failed to load analysis results"})}finally{i&&a(!1)}})(),()=>{i=!1}},[t]),s?e.jsxs("div",{className:"min-h-screen bg-slate-50",children:[e.jsx(ir,{showMarketSwitcher:!1,showCredits:!0}),e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(He,{className:"h-8 w-8 animate-spin text-slate-900 mb-4"})})]}):n?e.jsxs("div",{className:"min-h-screen bg-slate-50",children:[e.jsx(ir,{showMarketSwitcher:!1,showCredits:!0}),e.jsx("div",{className:"max-w-7xl mx-auto px-4 py-8",children:e.jsx(Wi,{analysisResult:n,showPlanMask:!1,continueText:"View Competitors Intelligence",onContinue:()=>jt("competitors")})})]}):null}function qb(){return e.jsx(za,{children:e.jsx(Hb,{})})}function Yb(){const{toast:t}=_t(),[s,a]=r.useState(!0),[n,o]=r.useState(null);return r.useEffect(()=>{let i=!0;return(async()=>{try{const c=await sr();if(!i)return;if(c)o(c);else{t({title:"No analysis found",description:"Please activate a referral code first."}),window.location.href="/app/referral";return}}catch(c){console.error("Failed to load data:",c),i&&t({title:"Error",description:"Failed to load analysis results"})}finally{i&&a(!1)}})(),()=>{i=!1}},[t]),s?e.jsxs("div",{className:"min-h-screen bg-slate-50",children:[e.jsx(ir,{showMarketSwitcher:!1,showCredits:!0}),e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(He,{className:"h-8 w-8 animate-spin text-slate-900 mb-4"})})]}):n?e.jsxs("div",{className:"min-h-screen bg-slate-50",children:[e.jsx(ir,{showMarketSwitcher:!1,showCredits:!0}),e.jsx("div",{className:"max-w-7xl mx-auto px-4 py-8",children:e.jsx(Wi,{analysisResult:n,showPlanMask:!1,onRequestReAnalyze:()=>{jt("setup")},continueText:"Unlock geo/aeo Potential",onContinue:()=>jt("competitors")})})]}):null}function Jb(){return e.jsx(za,{children:e.jsx(Yb,{})})}const Xb=({open:t,onOpenChange:s,currentBalance:a})=>{const{toast:n}=_t(),[o,i]=r.useState(null);r.useEffect(()=>{if(t){async function m(){try{const h=await Xa();i(h?.plan?.plan_type??null)}catch(h){console.error("Failed to load subscription:",h),i(null)}}m()}},[t]);const l=m=>{const h=e.jsxs("span",{className:"font-semibold text-amber-600",children:[a.toLocaleString()," credits"]});switch(m?.toLowerCase()){case"free":return e.jsxs(e.Fragment,{children:["You have ",h," remaining. Upgrade to a paid plan to get more credits and unlock advanced features."]});case"starter":return e.jsxs(e.Fragment,{children:["You have ",h," remaining. Upgrade to Basic/Pro plan for more credits and enhanced capabilities."]});case"growth":return e.jsxs(e.Fragment,{children:["You have ",h," remaining. Upgrade to Pro plan for more credits and enhanced capabilities."]});case"pro":return e.jsxs(e.Fragment,{children:["You have ",h," remaining. Consider upgrading to Enterprise or purchasing additional credits to continue without interruption."]});case"enterprise":return e.jsxs(e.Fragment,{children:["You have ",h," remaining. Contact your account manager to add more credits or upgrade your Enterprise plan."]});default:return e.jsxs(e.Fragment,{children:["You have ",h," remaining. Upgrade your plan to continue creating amazing content without interruption."]})}},c=()=>{s(!1),jt("subscription")},d=(m,h)=>{n({title:"Error",description:h.message||"Failed to create checkout session"})};return e.jsx(Ht,{open:t,onOpenChange:s,children:e.jsxs(qt,{className:"sm:max-w-4xl max-h-[80vh] overflow-y-auto",children:[e.jsxs(Zt,{align:"center",spacing:"lg",children:[e.jsxs("div",{className:"flex items-center justify-center gap-2",children:[e.jsx("div",{className:"mx-auto w-12 h-12 rounded-full bg-amber-100 flex items-center justify-center",children:e.jsx(vs,{className:"h-6 w-6 text-amber-600"})}),e.jsx(Yt,{className:"text-xl font-semibold",children:"Credit Refill"})]}),e.jsx("p",{className:"text-base text-slate-600",children:l(o)})]}),e.jsx("div",{className:"mt-4",children:e.jsx(vx,{title:"",subtitle:"",footnote:"",onCheckoutError:d})}),e.jsx(Ns,{className:"border-t border-gray-200",children:e.jsx("div",{className:"flex justify-end",children:e.jsxs("div",{className:"flex gap-2 pt-4",children:[e.jsx(be,{variant:"outline",className:"flex-1 flex-shrink-0",onClick:()=>s(!1),children:"Maybe Later"}),e.jsxs(be,{className:"flex-1 bg-slate-900 hover:bg-slate-800 w-[200px]",onClick:c,children:[e.jsx("span",{className:"flex-shrink-0",children:"View All"}),e.jsx(Ms,{className:"h-4 w-4 ml-2 flex-shrink-0"})]})]})})})]})})},ls=({className:t="",variant:s="default",...a})=>e.jsx("span",{className:`inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium ${s==="default"?"bg-slate-900 text-white":"bg-slate-100 text-slate-700"} ${t}`,...a});function Qb(t){const s=t?.width??500,a=t?.height??650,n=Math.max(0,Math.floor((window.screen.width-s)/2)),o=Math.max(0,Math.floor((window.screen.height-a)/2));return`scrollbars=yes,width=${s},height=${a},top=${o},left=${n}`}function kx(t,s){return new Promise((a,n)=>{try{const o=s?.name??"oauth_popup",i=Qb(s),l=window.open(t,o,i);if(!l){n(new Error("Popup blocked by the browser"));return}const c=s?.timeoutMs??300*1e3,d=window.location.origin;let m=!1;const h=()=>{m=!0,window.removeEventListener("message",p),clearInterval(f),clearTimeout(b)},p=y=>{if(y.origin!==d)return;const x=y.data;if(!(!x||x.source!=="google_oauth")){h();try{l.close()}catch{}a({code:x.code,error:x.error,success:x.success})}};window.addEventListener("message",p);const f=window.setInterval(()=>{l.closed&&!m&&(h(),a({error:"Popup closed"}))},300),b=window.setTimeout(()=>{if(!m){h();try{l.close()}catch{}a({error:"Authorization timeout"})}},c)}catch(o){n(o)}})}class bs{static{this.inFlight=null}static{this.cache=null}
56static invalidate(){bs.cache=null}static async getGoogleAuthExistsCached(s){const a=s?.ttlMs??3e4,n=s?.force??!1,o=Date.now();return!n&&bs.cache&&bs.cache.expiresAt>o?bs.cache.value:(bs.inFlight||(bs.inFlight=(async()=>{try{const i=await Nu();return bs.cache={value:i,expiresAt:o+a},i}finally{bs.inFlight=null}})()),bs.inFlight)}}function _x({visible:t,onAuthorized:s,onComplete:a}){const{toast:n}=_t(),[o,i]=r.useState("idle"),[l,c]=r.useState(""),[d,m]=r.useState(!1),[h,p]=r.useState(!0),f=r.useRef(null),b=r.useRef(!1);r.useEffect(()=>{if(!t){b.current&&(b.current=!1,a?.()),i("idle"),p(!1),m(!1),c("");return}b.current=!1,(async()=>{try{p(!0),(await bs.getGoogleAuthExistsCached({force:!0})).exists?(s?.(),i("connected")):i("idle")}catch(_){console.error("Failed to check GSC auth:",_),i("idle")}finally{p(!1)}})()},[t,s,a]);const y=r.useRef(o),x=r.useRef(d),u=r.useRef(0);r.useEffect(()=>{y.current=o,x.current=d},[o,d]),r.useEffect(()=>{if(o!=="connecting"||!d){f.current&&(clearInterval(f.current),f.current=null),u.current=0;return}u.current=0;let _=!0;const E=30,N=async()=>{if(!(!_||y.current!=="connecting"||!x.current)){if(u.current++,u.current>E){f.current&&(clearInterval(f.current),f.current=null),_&&(i("error"),c("Authorization timeout. Please try again."),m(!1),n({title:"GSC error",description:"Authorization timeout. Please try again."}));return}try{const k=await bs.getGoogleAuthExistsCached({force:!0});if(!_||y.current!=="connecting"||!x.current)return;k.exists?(f.current&&(clearInterval(f.current),f.current=null),s?.(),b.current=!0,_&&(i("connected"),c("Authorized"),m(!1),n({title:"GSC authorized",description:"Google Search Console connected successfully"}))):console.log(`[GSC Auth] Polling attempt ${u.current}: authorization not yet available`)}catch(k){console.error("Failed to poll GSC auth status:",k)}}},S=setTimeout(()=>{_&&y.current==="connecting"&&x.current&&N()},500);return f.current=setInterval(()=>{_&&y.current==="connecting"&&x.current?N():f.current&&(clearInterval(f.current),f.current=null)},1e3),()=>{_=!1,clearTimeout(S),f.current&&(clearInterval(f.current),f.current=null)}},[o,d,s,n]);async function g(){i("connecting"),c(""),m(!0);try{const _=await gc(),E=await kx(_,{name:"google_oauth",width:500,height:650});if(E.error){i("error"),c(E.error),m(!1),n({title:"GSC error",description:E.error});return}if(!E.success&&E.code)try{await pc(E.code)}catch(N){i("error"),c(N?.message||"Authorization callback failed"),m(!1),n({title:"GSC error",description:N?.message||"Authorization callback failed"})}else i("idle"),m(!1)}catch(_){i("error"),c(_?.message||"Authorization error"),m(!1),n({title:"GSC error",description:_?.message||"Authorization error"})}}if(!t||o==="connected")return null;const w=o;return e.jsx("div",{className:"absolute inset-0 z-[999] flex items-center justify-center bg-black/60 backdrop-blur-sm",children:e.jsxs(xs,{className:"w-[95%] max-w-2xl rounded-2xl shadow-2xl border-2 border-slate-200",children:[e.jsx(Bs,{className:"border-b border-slate-200",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(Xs,{className:"text-2xl font-bold flex items-center gap-2",children:[e.jsx(Sn,{className:"h-6 w-6 text-black"}),"Connect Google Search Console"]}),e.jsx(Br,{className:"mt-2 text-base",children:"Connect your GSC account to unlock powerful SEO analytics and insights"})]}),e.jsxs(ls,{variant:w==="error"?"default":"secondary",className:"text-xs",children:[w==="idle"&&"Required",w==="connecting"&&"Connecting",w==="error"&&"Error"]})]})}),e.jsxs(fs,{className:"pt-6",children:[e.jsxs("div",{className:"mb-6",children:[e.jsx("h3",{className:"text-lg font-semibold text-slate-900 mb-4",children:"What you'll get after connecting:"}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs("div",{className:"flex items-start gap-3 p-4 rounded-lg bg-slate-50 border border-slate-200",children:[e.jsx("div",{className:"mt-0.5",children:e.jsx(Sn,{className:"h-5 w-5 text-black"})}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium text-slate-900 mb-1",children:"Comprehensive Dashboard"}),e.jsx("p",{className:"text-sm text-slate-600",children:"Real-time SEO performance metrics and analytics"})]})]}),e.jsxs("div",{className:"flex items-start gap-3 p-4 rounded-lg bg-slate-50 border border-slate-200",children:[e.jsx("div",{className:"mt-0.5",children:e.jsx(Ma,{className:"h-5 w-5 text-black"})}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium text-slate-900 mb-1",children:"Enhanced Reports"}),e.jsx("p",{className:"text-sm text-slate-600",children:"Detailed SEO reports with search query data"})]})]}),e.jsxs("div",{className:"flex items-start gap-3 p-4 rounded-lg bg-slate-50 border border-slate-200",children:[e.jsx("div",{className:"mt-0.5",children:e.jsx(Pt,{className:"h-5 w-5 text-black"})}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium text-slate-900 mb-1",children:"Search Analytics"}),e.jsx("p",{className:"text-sm text-slate-600",children:"Top queries, pages, and performance insights"})]})]}),e.jsxs("div",{className:"flex items-start gap-3 p-4 rounded-lg bg-slate-50 border border-slate-200",children:[e.jsx("div",{className:"mt-0.5",children:e.jsx(is,{className:"h-5 w-5 text-black"})}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium text-slate-900 mb-1",children:"Content Optimization"}),e.jsx("p",{className:"text-sm text-slate-600",children:"Data-driven content optimization recommendations"})]})]})]})]}),h?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(He,{className:"h-6 w-6 animate-spin text-slate-400"})}):e.jsxs("div",{className:"space-y-4",children:[l&&e.jsx("div",{className:`text-sm p-3 rounded-lg ${o==="error"?"bg-red-50 text-red-700 border border-red-200":"bg-green-50 text-green-700 border border-green-200"}`,children:l}),e.jsx("div",{className:"flex gap-3",children:e.jsx(be,{className:"flex-1 rounded-xl h-12 text-base font-medium",onClick:g,disabled:o==="connecting"||d,variant:"default",children:o==="connecting"||d?e.jsxs(e.Fragment,{children:[e.jsx(He,{className:"mr-2 h-5 w-5 animate-spin"}),"Connecting..."]}):"Connect Google Search Console"})}),e.jsx("p",{className:"text-xs text-slate-500 text-center",children:"Your data is secure. We only request read-only access to your Search Console data."})]})]})]})})}const Wt={async listMetadata(t){return await ot("/table_metadata/list",t)},async fetchByIds(t){return await Je("/table_metadata/fetch_by_ids",{campaign_id:t.campaign_id,table_type:t.table_type,entity_ids:t.entity_ids})},async updateCustomData(t){return await Je("/table_metadata/update_custom_data",t)},async updateDisplayOrder(t,s,a){return await Je("/table_metadata/update_order",{campaign_id:t,table_type:s,orders:a})},async batchUpdateCustomData(t){return await Je("/table_metadata/batch_update_custom_data",t)},async batchDeleteMetadata(t){return await Je("/table_metadata/batch_delete",{campaign_id:t.campaign_id,table_type:t.table_type,entity_ids:t.entity_ids,deleted_display_orders:t.deleted_display_orders})},async batchDeleteRows(t,s,a,n){return await Je("/table_metadata/batch_delete",{campaign_id:t,table_type:s,entity_ids:a,deleted_display_orders:n})},async createViewConfig(t){return await Je("/table_metadata/view_config/create",t)},async listViewConfigs(t){return await ot("/table_metadata/view_config/list",t)},async getViewConfig(t){return await ot(`/table_metadata/view_config/${t}`,{})},async updateViewConfig(t,s){return await $r(`/table_metadata/view_config/${t}`,s)},async deleteViewConfig(t){return await Ca(`/table_metadata/view_config/${t}`,{})},async copyViewConfig(t){return await Je("/table_metadata/view_config/copy",t)},async _getAuthToken(){try{const s=await rs.getBackendAccessToken();if(s)return s}catch{}return yo()?.access_token||null},async exportCampaignAllViewsToExcel(t){const s=Da(),a=await this._getAuthToken(),n=await fetch(`${s}/table_metadata/export_excel`,{method:"POST",headers:{"Content-Type":"application/json",...a?{Authorization:`Bearer ${a}`}:{}},body:JSON.stringify({campaign_ids:[t.campaign_id]})});if(!n.ok){const c=await n.text();throw new Error(c||"Export failed")}const o=n.headers.get("Content-Disposition");let i="export.xlsx";if(o){const c=o.match(/filename="?([^";\n]+)"?/);c&&c[1]&&(i=c[1])}const l=await n.blob();Ar({filename:i,blob:l})},async exportSingleViewToExcel(t){const s=Da(),a=await this._getAuthToken(),n=await fetch(`${s}/table_metadata/export_excel_single_view`,{method:"POST",headers:{"Content-Type":"application/json",...a?{Authorization:`Bearer ${a}`}:{}},body:JSON.stringify(t)});if(!n.ok){const c=await n.text();throw new Error(c||"Export failed")}const o=n.headers.get("Content-Disposition");let i="export.xlsx";if(o){const c=o.match(/filename="?([^";\n]+)"?/);c&&c[1]&&(i=c[1])}const l=await n.blob();Ar({filename:i,blob:l})}};function Zb({onClick:t,className:s=""}){return e.jsx("button",{onClick:t,className:`fixed bottom-5 right-5 z-50 h-8 w-8 rounded-full bg-white border border-slate-200 shadow-md hover:shadow-lg hover:bg-slate-50 transition-all hover:scale-105 flex items-center justify-center ${s}`,title:"View onboarding guide","aria-label":"View onboarding guide",children:e.jsx(Hs,{className:"h-4 w-4 text-slate-600"})})}function qd({steps:t,run:s,onComplete:a,onSkip:n}){const[o,i]=r.useState(s),[l,c]=r.useState(0),[d,m]=r.useState(!1);v.useEffect(()=>{i(s),s&&(c(0),m(!1))},[s]),r.useEffect(()=>{if(!o||l!==2||d)return;console.log("[Onboarding] Step 2: Waiting for target to be ready...");let f=0;const b=50,y=setInterval(()=>{const x=document.querySelector('[data-onboarding="keywords-column-run-button"]');if(x){const u=x.getBoundingClientRect();if(u.width>0&&u.height>0){console.log("[Onboarding] Step 2 target is ready!"),clearInterval(y),m(!0);return}}f++,f>=b&&(console.warn("[Onboarding] Step 2 target not ready after max tries, proceeding anyway"),clearInterval(y),m(!0))},100);return()=>clearInterval(y)},[o,l,d]),r.useEffect(()=>{if(!o||l!==2)return;
56const f="[Onboarding][Step2]",b=typeof t[2]?.target=="string"?t[2].target:'.hot-wrapper .ht_clone_top button.table-run-btn[data-onboarding="keywords-column-run-button"]';let y,x=null;const u=_=>{try{const E=document.querySelector(b);if(!E||!document.body.contains(E))return;const N=E.getBoundingClientRect();N.width>0&&N.height>0&&(console.debug(`${f} re-validate target on ${_}`,N),c(k=>k))}catch{}},g=()=>{y&&window.clearTimeout(y),y=window.setTimeout(()=>u("resize"),120)};window.addEventListener("resize",g),window.addEventListener("orientationchange",g);const w=document.querySelector(".hot-wrapper .ht_clone_top thead");return w&&(x=new MutationObserver(()=>u("mutation")),x.observe(w,{childList:!0,subtree:!0})),u("effect-mount"),()=>{window.removeEventListener("resize",g),window.removeEventListener("orientationchange",g),x&&x.disconnect(),y&&window.clearTimeout(y)}},[o,l,t]),r.useEffect(()=>{if(o&&(console.log(`[Onboarding] Step index changed to: ${l}, target:`,t[l]?.target),l===1)){const f=t[l];if(typeof f?.target=="string"&&f.target.includes("keyword-cell-first")){document.querySelectorAll('[data-onboarding="keyword-cell-first"]').forEach(u=>{u.removeAttribute("data-onboarding")});const y=()=>{const u=document.querySelectorAll('[data-onboarding="keyword-cell-generate-button"]');for(const g of Array.from(u))if(g instanceof HTMLElement)try{const w=g.getBoundingClientRect();if(w.width>0&&w.height>0&&w.top>=0){let E=g.closest("td");if(!E){let N=g.parentElement;for(;N&&N!==document.body;){if(N.tagName==="TD"||N.classList.contains("htCore")){E=N;break}N=N.parentElement}}if(E&&E instanceof HTMLElement&&document.body.contains(E)){const N=E.closest("tr");if(N&&!N.querySelector("th"))return E.setAttribute("data-onboarding","keyword-cell-first"),console.log("[Onboarding] Marked first cell:",E),E}}}catch{continue}return null};let x=y();if(!x){let u=0;const g=20,w=setInterval(()=>{u++,x=y(),(x||u>=g)&&(clearInterval(w),x?console.log("[Onboarding] Successfully marked first cell after retries"):console.warn("[Onboarding] Failed to find and mark first cell after max retries"))},100);return()=>{clearInterval(w)}}}}},[l,o,t]),r.useEffect(()=>{if(!o||l<0||l>=t.length)return;const f=t[l];if(!f||f.target==="body"||l===2)return;let b=null;if(typeof f.target=="function")try{const A=f.target();A&&A instanceof HTMLElement&&document.body.contains(A)&&typeof A.getBoundingClientRect=="function"?b=A:console.warn("[Onboarding] Function target returned invalid element:",A)}catch(A){console.warn("[Onboarding] Error calling function target:",A)}else if(typeof f.target=="string")if(f.target.includes("keyword-cell-first")){const A=document.querySelector(f.target);A&&A instanceof HTMLElement&&document.body.contains(A)&&typeof A.getBoundingClientRect=="function"&&(b=A)}else if(f.target.includes("keyword-cell-generate-button")){const A=document.querySelectorAll('[data-onboarding="keyword-cell-generate-button"]');for(const C of Array.from(A))if(C instanceof HTMLElement)try{const I=C.getBoundingClientRect();if(I.width>0&&I.height>0&&I.top>=0){const q=C.closest("td");if(q&&q instanceof HTMLElement&&typeof q.getBoundingClientRect=="function"){const T=q.closest("tr");if(T&&!T.querySelector("th")){b=q;break}}}}catch{continue}}else{const A=document.querySelector(f.target);A&&A instanceof HTMLElement&&document.body.contains(A)&&typeof A.getBoundingClientRect=="function"&&(b=A)}if(!b||!b.parentNode||!document.body.contains(b)){console.warn("[Onboarding] Target element is invalid or not in DOM:",b);return}if(typeof b.getBoundingClientRect!="function"){console.warn("[Onboarding] Target element does not have getBoundingClientRect method:",b);return}let y=null;const x=A=>{const C=A.getBoundingClientRect();return{x:C.left+C.width/2,y:C.top+C.height/2,width:C.width,height:C.height}},u=()=>{y&&clearTimeout(y),y=setTimeout(()=>{const A=document.querySelector('[class*="react-joyride__tooltip"]'),C=document.querySelector('[class*="react-joyride__floater"]');if(!A||!C||!f)return;let I=null;if(typeof f.target=="function")try{const se=f.target();se&&se instanceof HTMLElement&&document.body.contains(se)&&typeof se.getBoundingClientRect=="function"&&(I=se)}catch(se){console.warn("[Onboarding] Error getting function target in repositionTooltip:",se)}else if(typeof f.target=="string"){const se=document.querySelector(f.target);se&&se instanceof HTMLElement&&document.body.contains(se)&&typeof se.getBoundingClientRect=="function"&&(I=se)}if(!I){console.warn("[Onboarding] Could not find target element in repositionTooltip:",f.target);return}const j=A.getBoundingClientRect(),q=I.getBoundingClientRect(),T=j.left+j.width/2,M=j.top+j.height/2,Z=q.left+q.width/2,B=q.top+q.height/2,ae=Math.abs(T-Z),de=Math.abs(M-B);if(j.left<50&&j.top<50||ae>300||de>300){console.log("[Onboarding] Detected wrong tooltip position, fixing:",{tooltipPos:{left:j.left,top:j.top},targetPos:{x:Z,y:B},distance:{x:ae,y:de}}),q.width,q.height;const se=f.placement||"top";let z=0,U=0;const Q=f.offset||10,me=typeof f.target=="string"&&f.target.includes("keywords-column-run-button");se==="top"||se==="top-start"||se==="top-end"?(se==="top-start"&&me?z=q.left:se==="top-end"&&me?z=q.right-j.width:z=q.left+q.width/2-j.width/2,U=q.top-j.height-Q):se==="bottom"||se==="bottom-start"||se==="bottom-end"?(se==="bottom-start"&&me?z=q.left:se==="bottom-end"&&me?z=q.right-j.width:z=q.left+q.width/2-j.width/2,U=q.bottom+Q):se==="left"||se==="left-start"||se==="left-end"?(z=q.left-j.width-Q,se==="left-start"&&me?U=q.top:se==="left-end"&&me?U=q.bottom-j.height:U=q.top+q.height/2-j.height/2):se==="right"||se==="right-start"||se==="right-end"?(z=q.right+Q,se==="right-start"&&me?U=q.top:se==="right-end"&&me?U=q.bottom-j.height:U=q.top+q.height/2-j.height/2):(z=q.left+q.width/2-j.width/2,U=q.top-j.height-Q),z=Math.max(8,Math.min(z,window.innerWidth-j.width-8)),U=Math.max(8,Math.min(U,window.innerHeight-j.height-8)),C.style.position="fixed",C.style.left=`${z}px`,C.style.top=`${U}px`,C.style.transform="none",C.style.zIndex="10001",C.style.margin="0"}else q.width,q.height},50)};x(b);const g=new ResizeObserver(()=>{u()}),w=new MutationObserver(()=>{u()}),_=A=>{const C=[];let I=A.parentElement;for(;I&&I!==document.body;){const j=window.getComputedStyle(I),q=j.overflow||j.overflowY||j.overflowX;(q==="auto"||q==="scroll"||q==="overlay")&&C.push(I),I=I.parentElement}return C},E=()=>{u()},N=_(b);
56N.forEach(A=>{A.addEventListener("scroll",E,!0)}),g.observe(b),w.observe(document.body,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["style","class"]}),window.addEventListener("scroll",E,!0),window.addEventListener("resize",E);let S=null,k=null,D=!1,F=0;const R=200,L=()=>{if(D)return;const A=Date.now();if(A-F<R)return;const C=document.querySelector('[class*="react-joyride__tooltip"], [class*="react-joyride"] [role="tooltip"]');if(!C||!f)return;let I=document.querySelector('[class*="react-joyride__floater"]');if(!I){let le=C.parentElement;for(;le&&le!==document.body;){const O=window.getComputedStyle(le);if(O.position==="fixed"||O.position==="absolute"){I=le;break}le=le.parentElement}I||(I=C)}const j=b.getBoundingClientRect(),q=C.getBoundingClientRect(),T=j.top>=0&&j.left>=0&&j.bottom<=window.innerHeight&&j.right<=window.innerWidth,M=Math.max(0,j.top),Z=Math.max(0,j.left),B=Math.min(window.innerHeight,j.bottom),ae=Math.min(window.innerWidth,j.right),de=(Z+ae)/2,fe=(M+B)/2,se=q.left+q.width/2,z=q.top+q.height/2,U=Math.abs(se-de),Q=Math.abs(z-fe),me=q.left<50&&q.top<50||U>300||Q>300||!T;if(k){const le=q.left,O=q.top,ne=10;if(Math.abs(le-k.left)<ne&&Math.abs(O-k.top)<ne&&!me)return}if(me){D=!0,F=A;const le=f.placement||"top";let O=0,ne=0;const ge=typeof f.target=="string"&&f.target.includes("keywords-column-run-button"),ze=Math.max(0,j.top),Ke=Math.max(0,j.left),ie=Math.min(window.innerHeight,j.bottom),ve=Math.min(window.innerWidth,j.right),we=ve-Ke,Pe=ie-ze,Ae=Ke+we/2,ye=ze+Pe/2;le==="top"||le==="top-start"||le==="top-end"?(le==="top-start"&&ge?O=Ke:le==="top-end"&&ge?O=ve-q.width:O=Ae-q.width/2,ne=ze-q.height-10):le==="bottom"||le==="bottom-start"||le==="bottom-end"?(le==="bottom-start"&&ge?O=Ke:le==="bottom-end"&&ge?O=ve-q.width:O=Ae-q.width/2,ne=ie+10):le==="left"||le==="left-start"||le==="left-end"?(O=Ke-q.width-10,le==="left-start"&&ge?ne=ze:le==="left-end"&&ge?ne=ie-q.height:ne=ye-q.height/2):le==="right"||le==="right-start"||le==="right-end"?(O=ve+15,le==="right-start"&&ge?ne=ze:le==="right-end"&&ge?ne=ie-q.height:ne=ye-q.height/2):(O=Ae-q.width/2,ne=ze-q.height-10),O=Math.max(8,Math.min(O,window.innerWidth-q.width-8)),ne=Math.max(8,Math.min(ne,window.innerHeight-q.height-8)),(!k||Math.abs(k.left-O)>5||Math.abs(k.top-ne)>5)&&(k={left:O,top:ne},K(I,O,ne),requestAnimationFrame(()=>{requestAnimationFrame(()=>{I.style.setProperty("position","fixed","important"),I.style.setProperty("left",`${O}px`,"important"),I.style.setProperty("top",`${ne}px`,"important"),I.style.setProperty("transform","none","important"),I.style.setProperty("z-index","10001","important"),I.style.setProperty("margin","0","important"),I.style.setProperty("right","auto","important"),I.style.setProperty("bottom","auto","important"),C!==I&&(C.style.setProperty("position","relative","important"),C.style.setProperty("left","0","important"),C.style.setProperty("top","0","important"),C.style.setProperty("transform","none","important"),C.style.setProperty("margin","0","important"))})}),console.log("[Onboarding] Fixed wrong position:",{old:{left:q.left,top:q.top},new:{left:O,top:ne},targetRect:{left:j.left,top:j.top,right:j.right,bottom:j.bottom,width:j.width,height:j.height},targetVisible:{top:ze,left:Ke,bottom:ie,right:ve,centerX:Ae,centerY:ye},floater:I.tagName,tooltip:C.tagName,placement:le})),setTimeout(()=>{D=!1},100)}};S=setInterval(L,100);let $=null,H=null;const K=(A,C,I)=>{if(H)return;const j=A.style.setProperty.bind(A.style);H=(q,T,M)=>{if(["left","top","transform","position"].includes(q.toLowerCase())){if(q.toLowerCase()==="left"&&T!==`${C}px`&&T!=="auto"){console.log("[Onboarding] Blocked left change:",T,"expected:",`${C}px`);return}if(q.toLowerCase()==="top"&&T!==`${I}px`&&T!=="auto"){console.log("[Onboarding] Blocked top change:",T,"expected:",`${I}px`);return}if(q.toLowerCase()==="transform"&&T!=="none"&&T!==""){console.log("[Onboarding] Blocked transform change:",T);return}if(q.toLowerCase()==="position"&&T!=="fixed"){console.log("[Onboarding] Blocked position change:",T);return}}return j(q,T,M)},A.style.setProperty=H},X=new MutationObserver(A=>{A.some(I=>{if(I.type==="attributes"&&I.attributeName==="style"){const j=I.target,q=window.getComputedStyle(j);if(k){const T=parseFloat(q.left)||0,M=parseFloat(q.top)||0;if(Math.abs(T-k.left)>5||Math.abs(M-k.top)>5)return!0}}return!1})&&!D&&($&&clearTimeout($),$=setTimeout(()=>{D||L()},50))}),V=()=>{const A=document.querySelector('[class*="react-joyride__floater"]');A&&X.observe(A,{attributes:!0,attributeFilter:["style","class"],childList:!1,subtree:!1})};V();const P=setInterval(()=>{V()},200);return()=>
56{if(y&&clearTimeout(y),S&&clearInterval(S),P&&clearInterval(P),$&&clearTimeout($),X.disconnect(),g.disconnect(),w.disconnect(),N.forEach(A=>{A.removeEventListener("scroll",E,!0)}),window.removeEventListener("scroll",E,!0),window.removeEventListener("resize",E),H){const A=document.querySelector('[class*="react-joyride__floater"]');if(A&&A.style.setProperty===H)try{const C=Object.getPrototypeOf(A.style).setProperty;C&&(A.style.setProperty=C)}catch{}}k=null,D=!1}},[o,l,t]),r.useEffect(()=>{if(!o||l!==1)return;let f=!1;const b=()=>{document.querySelector('[data-onboarding="campaign-modal"]')&&!f&&(f=!0,setTimeout(()=>{c(2)},300))};b();const y=setInterval(b,100);return()=>{clearInterval(y),f=!1}},[o,l]),r.useEffect(()=>{if(!o||l!==2)return;let f=!1;const b=()=>{const x=document.querySelector('[data-onboarding="campaign-card"]'),u=document.querySelector('[data-onboarding="campaign-view-button"]');(x||u)&&!f&&(f=!0,setTimeout(()=>{c(3)},500))};b();const y=setInterval(b,200);return()=>{clearInterval(y),f=!1}},[o,l]),r.useEffect(()=>{if(!o||l!==3)return;let f=!1;const b=y=>{const x=y.target,u=x.closest('[data-onboarding="campaign-card"]'),g=x.closest('[data-onboarding="campaign-view-button"]');(u||g)&&!f&&(f=!0,setTimeout(()=>{c(4)},300))};return document.addEventListener("click",b,!0),()=>{document.removeEventListener("click",b,!0),f=!1}},[o,l]),r.useEffect(()=>{if(!o||l!==1)return;const f=t[l];if(!(l===1&&(typeof f?.target=="function"||typeof f?.target=="string"&&f.target.includes("keyword-cell"))))return;let y=!1;const x=w=>{w.stopPropagation(),y||(y=!0,setTimeout(()=>{c(2)},2e3))},u=()=>{let w=document.querySelectorAll('[data-onboarding="keyword-cell-generate-button-first"]');return w.length===0&&(w=document.querySelectorAll('[data-onboarding="keyword-cell-generate-button"]')),w.forEach(_=>{try{const E=_.getBoundingClientRect();E.width>0&&E.height>0&&E.top>=0&&(_.removeEventListener("click",x),_.addEventListener("click",x,!0))}catch{}}),w.length};u();const g=setInterval(()=>{u()},500);return()=>{clearInterval(g),document.querySelectorAll('[data-onboarding="keyword-cell-generate-button"]').forEach(_=>{_.removeEventListener("click",x,!0)}),y=!1}},[o,l,t]),r.useEffect(()=>{if(!o||l!==2)return;t[l];let f=!1;const b=u=>{const g=u.target;(g.classList.contains("table-run-btn")||g.closest(".table-run-btn"))&&(f||(f=!0,setTimeout(()=>{c(3)},500)))},y=()=>{const u=document.querySelector('[data-onboarding="keywords-column-run-button"]');u&&(u.removeEventListener("click",b),u.addEventListener("click",b,!0))};y();const x=setInterval(y,300);return()=>{clearInterval(x);const u=document.querySelector('[data-onboarding="keywords-column-run-button"]');u&&u.removeEventListener("click",b,!0),f=!1}},[o,l,t]),r.useEffect(()=>{if(!o||l!==3||t[l]?.target!=='[data-onboarding="groups-column-run-button"]')return;let b=!1;const y=g=>{g.stopPropagation(),b||(b=!0,setTimeout(()=>{c(4)},500))},x=()=>{const g=document.querySelector('[data-onboarding="groups-column-run-button"]');g&&(g.removeEventListener("click",y),g.addEventListener("click",y,!0))};x();const u=setInterval(x,300);return()=>{clearInterval(u);const g=document.querySelector('[data-onboarding="groups-column-run-button"]');g&&g.removeEventListener("click",y,!0),b=!1}},[o,l,t]);const h=r.useCallback(async f=>{const{status:b,type:y,action:x,index:u}=f;if(console.log("Joyride callback:",{type:y,action:x,index:u,stepIndex:l,status:b}),b===nn.FINISHED||b===nn.SKIPPED){i(!1);try{await w0(3,"completed")}catch(g){console.error("Failed to update onboarding status:",g)}b===nn.FINISHED&&a?a():b===nn.SKIPPED&&n&&n();return}if(y===ja.STEP_AFTER)if(x===Ka.NEXT){const g=typeof u=="number"?u:l,w=g+1;w<t.length?(console.log(`[Onboarding] Advancing from step ${g} to step ${w}`),c(w)):(console.log(`[Onboarding] Completing tour at last step: ${g}`),i(!1),a&&a())}else if(x===Ka.PREV){const w=(typeof u=="number"?u:l)-1;c(Math.max(0,w))}else x===Ka.CLOSE&&i(!1);else if(y===ja.TARGET_NOT_FOUND){const g=t[l];if(l===1&&typeof g?.target=="string"&&g.target.includes("keyword-cell-first")){document.querySelectorAll('[data-onboarding="keyword-cell-first"]').forEach(E=>{E.removeAttribute("data-onboarding")});const _=document.querySelectorAll('[data-onboarding="keyword-cell-generate-button"]');for(const E of Array.from(_))if(E instanceof HTMLElement)try{const N=E.getBoundingClientRect();if(N.width>0&&N.height>0&&N.top>=0){let S=E.closest("td");if(!S){let k=E.parentElement;for(;k&&k!==document.body;){if(k.tagName==="TD"||k.classList.contains("htCore")){S=k;break}k=k.parentElement}}if(S&&S instanceof HTMLElement&&document.body.contains(S)){const k=S.closest("tr");if(k&&!k.querySelector("th")){S.setAttribute("data-onboarding","keyword-cell-first");break}}}}catch{continue}}if(l===2){let w=0;const _=30,E=setInterval(()=>{document.querySelector('[data-onboarding="keywords-column-run-button"]')?(clearInterval(E),c(S=>S)):++w>=_&&clearInterval(E)},100);return}console.warn("[Onboarding] Target not found for step:",l,t[l]?.target)}else if(y===ja.STEP_BEFORE){const g=t[l];if(g&&g.target!=="body"){if(console.log(`[Onboarding] Step before: ${l}, target:`,g.target),l===1&&typeof g.target=="function"||l===1&&typeof g.target=="string"&&g.target.includes("keyword-cell-first"),l===2){let w=0;const _=30,E=setInterval(()=>{const N=document.querySelector('[data-onboarding="keywords-column-run-button"]');if(N)try{const S=N.getBoundingClientRect();S.width>0&&S.height>0&&(clearInterval(E),setTimeout(()=>c(D=>D),0))}catch{}++w>=_&&clearInterval(E)},100)}setTimeout(()=>{let w=null;if(typeof g.target=="function")try{const _=g.target();_&&_ instanceof HTMLElement&&document.body.contains(_)&&typeof _.getBoundingClientRect=="function"&&(w=_)}catch(_){console.warn("[Onboarding] Error calling function target:",_)}else if(typeof g.target=="string"){const _=document.querySelector(g.target);_&&_ instanceof HTMLElement&&document.body.contains(_)&&typeof _.getBoundingClientRect=="function"&&(w=_)}if(w){w.scrollIntoView({behavior:"smooth",block:"center",inline:"nearest"});let _=w.parentElement;for(;_&&_!==document.body;){const E=window.getComputedStyle(_),N=E.overflow||E.overflowY||E.overflowX;if(N==="auto"||N==="scroll"){const S=_.getBoundingClientRect(),k=w.getBoundingClientRect();if(!(k.top>=S.top&&k.bottom<=S.bottom&&k.left>=S.left&&k.right<=S.right)){const F=k.top-S.top+_.scrollTop;_.scrollTo({top:F-S.height/2,behavior:"smooth"})}}_=_.parentElement}}},100)}}y===ja.TOOLTIP&&x==="update"||y===ja.TOOLTIP&&(x==="start"||x==="next"||x==="prev")&&setTimeout(()=>{},100)},[a,n,l,t]),p=o&&(l!==2||d);return e.jsx(ic,{steps:t,run:p,continuous:!0,showProgress:!0,showSkipButton:!0,disableCloseOnEsc:!1,disableOverlayClose:!0,callback:h,spotlightClicks:!0,stepIndex:l,disableScrollParentFix:!1,scrollToFirstStep:!0,scrollOffset:100,floaterProps:{disableAnimation:!1,styles:{arrow:{color:"#fff"},floater:{filter:"none"}},options:{strategy:"fixed",modifiers:[{name:"computeStyles",options:{adaptive:!1,gpuAcceleration:!1}},{name:"preventOverflow",options:{boundary:"viewport",padding:8}}]}},disableScrolling:!1,spotlightPadding:8,styles:{options:{primaryColor:"#0f172a",zIndex:10001},tooltip:{borderRadius:"12px",padding:"20px"},tooltipContainer:{textAlign:"left"},buttonNext:{backgroundColor:"#0f172a",borderRadius:"8px",padding:"8px 16px",fontSize:"14px",fontWeight:"500"},buttonBack:{color:"#64748b",padding:"8px 16px",fontSize:"14px"},buttonSkip:{color:"#64748b",fontSize:"14px"},overlay:{backgroundColor:"rgba(0, 0, 0, 0.6)"},spotlight:{borderRadius:"8px",mixBlendMode:"normal"},spotlightLegacy:{borderRadius:"8px"}},locale:{back:"Back",close:"Close",last:"Finish",next:"Next",skip:"Skip"}})}const ew=[{target:"body",content:e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-semibold text-slate-900 mb-2",children:"Welcome to Rankgale!"}),e.jsx("p",{className:"text-sm text-slate-600",children:"Let's take a few minutes to learn how to create your first Campaign and start using SEO features."})]}),placement:"center",disableBeacon:!0,hideFooter:!1},{target:'[data-onboarding="create-campaign"]',content:e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-semibold text-slate-900 mb-2",children:'Step 1: Click "New Campaign"'}),e.jsx("p",{className:"text-sm text-slate-600",children:'A Campaign is the main container for organizing your keywords and content. Click the "New Campaign" button to open the creation dialog.'})]}),placement:"bottom",disableBeacon:!0,hideFooter:!0,hideCloseButton:!1},{target:'[data-onboarding="create-campaign-button"]',content:e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-semibold text-slate-900 mb-2",children:"Step 2: Fill in and Create"}),e.jsx("p",{className:"text-sm text-slate-600",children:`Enter a name for your Campaign in the input field above (description is optional). Once you've entered the name, click "Create Campaign" button here to create it.`})]}),placement:"bottom",disableBeacon:!0,hideFooter:!0,hideCloseButton:!1,disableOverlay:!0,disableScrolling:!1},{target:'[data-onboarding="campaign-card"], [data-onboarding="campaign-view-button"]',content:e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-semibold text-slate-900 mb-2",children:"Step 3: Open Your Campaign"}),e.jsx("p",{className:"text-sm text-slate-600",children:'Great! Your Campaign has been created. Now click on it (or the "View" button) to open it and start adding keywords.'})]}),placement:"bottom",disableBeacon:!0,hideFooter:!0,hideCloseButton:!1},{target:"body",content:e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-semibold text-slate-900 mb-2",children:"All Set! 🎉"}),e.jsx("p",{className:"text-sm text-slate-600 mb-3",children:"You've created your first Campaign! Inside your Campaign, you can:"}),e.jsxs("ul",{className:"text-sm text-slate-600 space-y-2 mb-3 list-disc list-inside",children:[e.jsx("li",{children:"Add keywords manually or use AI to generate them"}),e.jsx("li",{children:"Create keyword groups to organize your content"}),e.jsx("li",{children:"Generate SEO-optimized content"})]}),e.jsx("p",{className:"text-xs text-slate-500",children:"Tip: You can always click the help button (?) in the top-right corner to review this guide again."})]}),placement:"center",disableBeacon:!0,hideFooter:!1}],tw=[{target:"body",content:e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-semibold text-slate-900 mb-2",children:"Welcome to Keywords Management!"}),e.jsx("p",{className:"text-sm text-slate-600",children:"Let's learn how to add keywords and organize them into groups for your SEO strategy."})]}),placement:"center",disableBeacon:!0,hideFooter:!1},{target:'[data-onboarding="keyword-cell-first"]',content:e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-semibold text-slate-900 mb-2",children:"Step 1: Add Your First Keyword"}),e.jsx("p",{className:"text-sm text-slate-600",children:'Click "Generate" in an empty keyword cell to let AI create a keyword for you, or simply type a keyword directly in the cell. The keyword will be saved automatically.'})]}),placement:"top",disableBeacon:!0,hideFooter:!0,hideCloseButton:!1,disableOverlay:!1,disableScrolling:!1,scrollOffset:100,offset:10},{target:'.hot-wrapper .ht_clone_top button.table-run-btn[data-onboarding="keywords-column-run-button"]',content:e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-semibold text-slate-900 mb-2",children:"Step 2: Generate Multiple Keywords"}),e.jsx("p",{className:"text-sm text-slate-600",children:"Click the run button (▶) in the KEYWORDS column header to generate multiple keywords at once. You can generate 10 keywords or specify a custom number."})]}),placement:"right-end",disableBeacon:!0,hideFooter:!0,hideCloseButton:!1,disableOverlay:!1,disableScrolling:!1,isFixed:!0,spotlightPadding:0,offset:10,floaterProps:{options:{modifiers:[{name:"offset",options:{offset:[0,8]}}]}}
56,styles:{spotlight:{borderRadius:"4px",border:"2px solid rgba(255, 255, 255, 0.8)"}}},{target:'[data-onboarding="groups-column-run-button"]',content:e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-semibold text-slate-900 mb-2",children:"Step 3: Organize Keywords into Groups"}),e.jsx("p",{className:"text-sm text-slate-600",children:"Click the run button (▶) in the KEYWORD GROUPS column header to automatically organize your keywords into semantic groups. This helps you plan content more effectively."})]}),placement:"bottom",disableBeacon:!0,hideFooter:!0,hideCloseButton:!1,disableOverlay:!0,disableScrolling:!1,offset:10},{target:"body",content:e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-semibold text-slate-900 mb-2",children:"All Set! 🎉"}),e.jsx("p",{className:"text-sm text-slate-600 mb-3",children:"Great! You've learned how to add keywords and create groups. Next, you can:"}),e.jsxs("ul",{className:"text-sm text-slate-600 space-y-2 mb-3 list-disc list-inside",children:[e.jsx("li",{children:"Edit keywords directly in cells - just click and type"}),e.jsx("li",{children:'Add groups to keywords by clicking the "+" in the groups cell'}),e.jsx("li",{children:"Generate SEO-optimized content based on your keyword groups"})]}),e.jsx("p",{className:"text-xs text-slate-500",children:"Tip: You can always click the help button (?) in the bottom-right corner to review this guide again."})]}),placement:"center",disableBeacon:!0,hideFooter:!1}],lr=async t=>await ot("/campaign/list",t),No=async t=>await Je("/campaign/create",t),Cx=async(t,s)=>await Je("/campaign/update",s,{params:{campaign_id:t}}),sw=async t=>await Je("/campaign/batch_delete",{campaign_ids:t});function aw({authed:t,currentTab:s}){const[a,n]=r.useState(null),[o,i]=r.useState(!0),[l,c]=r.useState(!0),[d,m]=r.useState(!1),[h,p]=r.useState(!1),[f,b]=r.useState(0);r.useEffect(()=>{if(!t){c(!1),p(!1);return}let u=!0;return(async()=>{try{const g=await Cs.getAccountCached({ttlMs:1e4});if(!u)return;n(g);try{const w=await lr({page:1,page_size:1}),_=w.items&&w.items.length>0;i(_),p(s==="campaigns"||s==="keywords"||s==="keyword-groups"||s==="content"||s==="worksheets"||s==="table"||s==="table-new"),s==="campaigns"?!_&&g.setup_onboarding_status==="pending"?m(!0):m(!1):(s==="keywords"&&g.setup_onboarding_status,m(!1))}catch(w){console.error("Failed to check campaigns:",w),i(!0)}}catch(g){console.error("Failed to load account:",g)}finally{u&&c(!1)}})(),()=>{u=!1}},[t,s]);const y=r.useCallback(()=>{b(Date.now()),m(!0)},[]),x=r.useCallback(()=>{m(!1)},[]);return{account:a,hasCampaigns:o,loading:l,runOnboarding:d,restartToken:f,showHelpButton:h,startOnboarding:y,stopOnboarding:x}}const nw=[{id:"competitors",name:"COMPETITORS",items:[{id:"competitors_intelligence",label:"Competitors Intelligence",icon:Qs}]},{id:"keywords_research",name:"KEYWORDS RESEARCH",items:[{id:"competitors_keywords",label:"Keywords Gap",icon:Pt,countKey:"keywords_gap_count"},{id:"target_keywords",label:"Target Keywords",icon:us,countKey:"target_keywords_count"},{id:"keywords_group",label:"Keywords Group",icon:qa,countKey:"keyword_groups_count"},{id:"seo_related_worksheets",label:"Related Worksheets",icon:on,countKey:"seo_related_worksheets_count"}]},{id:"ai_visibility",name:"AI VISIBILITY",items:[{id:"prompt_tracking",label:"Prompt Tracking",icon:Qt,countKey:"prompt_tracking_count"},{id:"prompt_related_worksheets",label:"Related Worksheets",icon:on,countKey:"prompt_related_worksheets_count"}]},{id:"content_optimization",name:"CONTENT OPTIMIZATION",items:[{id:"page_tracking",label:"Page Tracking",icon:is,countKey:"page_tracking_count"},{id:"page_related_worksheets",label:"Related Worksheets",icon:on,countKey:"page_related_worksheets_count"}]}],rw=({currentItem:t="competitors_keywords",className:s,counts:a={}})=>{const[n,o]=r.useState(!1),[i,l]=r.useState({});r.useEffect(()=>{n&&Object.keys(i).length===0&&(async()=>{try{const{keywordResearchService:h}=await Bt(async()=>{const{keywordResearchService:x}=await Promise.resolve().then(()=>Qj);return{keywordResearchService:x}},void 0),{getTrackedPrompts:p}=await Bt(async()=>{const{getTrackedPrompts:x}=await Promise.resolve().then(()=>Nf);return{getTrackedPrompts:x}},void 0),[f,b,y]=await Promise.all([h.getKeywords({limit:1}).catch(()=>({total:0})),h.getKeywordGroups().catch(()=>[]),p().catch(()=>[])]);l({target_keywords_count:f.total||0,keyword_groups_count:Array.isArray(b)?b.length:0,prompt_tracking_count:Array.isArray(y)?y.length:0})}
56catch(h){console.warn("Failed to load workflow counts:",h)}})()},[n,i]);const c=m=>{o(!1),jt("workflow",{item:m})},d=m=>{if(m)return a[m]??i[m]};return e.jsxs(e.Fragment,{children:[e.jsxs("button",{onClick:()=>o(!0),className:Lt("flex items-center gap-1 px-2.5 py-1.5 text-xs font-medium text-slate-600 bg-white border border-slate-200 rounded-lg shadow-sm hover:bg-slate-50 transition-colors",s),children:[e.jsx(sc,{size:14}),e.jsx("span",{children:"Workflow"})]}),n&&e.jsx("div",{className:"fixed inset-0 z-[80] bg-black/40 backdrop-blur-sm",onClick:()=>o(!1),children:e.jsxs("div",{className:"absolute left-0 right-0 bottom-0 max-h-[75vh] bg-white rounded-t-2xl shadow-2xl flex flex-col animate-in slide-in-from-bottom duration-300",onClick:m=>m.stopPropagation(),children:[e.jsx("div",{className:"flex justify-center pt-3 pb-1 shrink-0",children:e.jsx("div",{className:"w-10 h-1 bg-slate-300 rounded-full"})}),e.jsxs("div",{className:"flex items-center justify-between px-5 py-2 border-b border-slate-100 shrink-0",children:[e.jsx("span",{className:"text-base font-semibold text-slate-900",children:"Workflow"}),e.jsx("button",{onClick:()=>o(!1),className:"flex items-center justify-center w-8 h-8 text-slate-400 hover:text-slate-600 hover:bg-slate-100 rounded-full transition-colors",children:e.jsx(mt,{size:18})})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto overscroll-contain py-4 px-4 pb-safe",children:[nw.map(m=>e.jsxs("div",{className:"mb-5",children:[e.jsx("div",{className:"text-[9px] font-medium text-slate-400 uppercase tracking-wide mb-2 px-1",children:m.name}),e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"absolute left-[11px] top-2 bottom-2 w-[2px] bg-slate-200 rounded-full"}),e.jsx("div",{className:"space-y-1",children:m.items.map(h=>{const p=t===h.id,f=d(h.countKey);return h.icon,e.jsxs("button",{onClick:()=>c(h.id),className:Lt("w-full flex items-center gap-3 pl-1.5 pr-3 py-2.5 rounded-lg text-sm transition-all",p?"bg-slate-100":"hover:bg-slate-50"),children:[e.jsx("div",{className:"relative z-10 flex-shrink-0",children:e.jsx("div",{className:Lt("w-5 h-5 rounded-full border-2 flex items-center justify-center",p?"bg-slate-800 border-slate-800":"bg-white border-slate-300"),children:p&&e.jsx("div",{className:"w-2 h-2 bg-white rounded-full"})})}),e.jsx("span",{className:Lt("flex-1 text-left",p?"font-medium text-slate-900":"text-slate-600"),children:h.label}),f!==void 0&&e.jsx("span",{className:"text-xs text-slate-400 tabular-nums",children:f})]},h.id)})})]})]},m.id)),e.jsx("div",{className:"h-6"})]})]})})]})};async function ow(){return ot("/tutorial/status")}async function iw(){return Je("/tutorial/create")}const cl=["data_report","report","page_tracking"],lw=({current:t,onMenuClick:s})=>{const[a,n]=v.useState(!1),[o,i]=v.useState(!1),l=()=>{try{if(t==="homepage"||t==="home")return"Homepage";if(t==="company")return"Company Info";if(t==="integration")return"Integration";if(t==="keywords_tracking")return"Keywords Monitor";if(t==="knowledge")return"Knowledge";if(t==="keyword_gap"||t==="keyword_research")return"Keyword Gap";if(t==="page_tracking")return"Page Monitor";if(t==="geo_prompt")return"Prompt Monitor";if(t==="data_report"||t==="report")return"Data & Report";if(t==="content_generated")return"Content Generated";if(t==="workflow"){const S=window.location.pathname.match(/\/app\/workflow\/([^/?#]+)/),k=S?.[1]?String(S[1]):"";return k==="competitors_keywords"?"Keyword Gap":k==="target_keywords"?"Target Keywords":k==="keywords_group"?"Keywords Group":"Workflow"}}catch{}return"Rankgale"},c=()=>{if(t==="workflow")try{const S=window.location.pathname.match(/\/app\/workflow\/([^/?#]+)/);return S?.[1]?String(S[1]):"competitors_keywords"}catch{return"competitors_keywords"}return"keyword_gap"},d=t==="workflow",m=t==="keyword_gap"||t==="keyword_research"||t==="workflow"&&window.location.pathname.includes("competitors_keywords"),h=t==="workflow"&&window.location.pathname.includes("target_keywords"),p=t==="workflow"&&window.location.pathname.includes("keywords_group"),f=t==="company",b=t==="homepage"||t==="home",y=t==="knowledge",x=t==="keywords_tracking",u=t==="page_tracking",g=t==="geo_prompt",w=t==="data_report"||t==="report",_=()=>{n(!a),window.dispatchEvent(new CustomEvent("mobile-filter-toggle",{detail:!a}))},E=()=>{window.dispatchEvent(new CustomEvent("mobile-refresh-click"))},N=()=>{window.dispatchEvent(new CustomEvent("mobile-add-click"))};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"md:hidden fixed top-0 left-0 right-0 h-14 bg-white border-b border-gray-200 z-40 flex items-center justify-between px-4 shrink-0",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("button",{onClick:s,className:"p-1 -ml-1 text-gray-600",children:e.jsx(sc,{size:24})}),e.jsx("span",{className:"font-bold text-lg text-gray-800",children:l()})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[d&&e.jsx(rw,{currentItem:c()}),m&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:_,className:`p-2 rounded-full transition-colors ${a?"bg-blue-50 text-blue-600":"text-gray-600 hover:bg-gray-100"}`,children:e.jsx(Pt,{size:20})}),e.jsx("button",{onClick:_,className:`p-2 rounded-full transition-colors ${a?"bg-blue-50 text-blue-600":"text-gray-600 hover:bg-gray-100"}`,children:e.jsx(ci,{size:20})}),e.jsx("button",{onClick:E,className:"p-2 text-gray-600 hover:bg-gray-100 rounded-full",children:e.jsx(kt,{size:20})})]}),h&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:_,className:`p-2 rounded-full transition-colors ${a?"bg-blue-50 text-blue-600":"text-gray-600 hover:bg-gray-100"}`,children:e.jsx(Pt,{size:20})}),e.jsx("button",{onClick:E,className:"p-2 text-gray-600 hover:bg-gray-100 rounded-full",children:e.jsx(kt,{size:20})})]}),p&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:_,className:`p-2 rounded-full transition-colors ${a?"bg-blue-50 text-blue-600":"text-gray-600 hover:bg-gray-100"}`,children:e.jsx(Pt,{size:20})}),e.jsx("button",{onClick:E,className:"p-2 text-gray-600 hover:bg-gray-100 rounded-full",children:e.jsx(kt,{size:20})})]}),f&&e.jsx("button",{onClick:()=>jt("setup"),className:"p-2 text-gray-600 hover:bg-gray-100 rounded-full","aria-label":"Re-analyze",children:e.jsx(kt,{size:20})}),(b||x)&&e.jsx("button",{onClick:()=>i(!0),className:"p-2 text-gray-600 hover:bg-gray-100 rounded-full","aria-label":"Markets",children:e.jsx(Qt,{size:20})}),x&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:_,className:`p-2 rounded-full transition-colors ${a?"bg-blue-50 text-blue-600":"text-gray-600 hover:bg-gray-100"}`,"aria-label":"Search",children:e.jsx(Pt,{size:20})}),e.jsx("button",{onClick:E,className:"p-2 text-gray-600 hover:bg-gray-100 rounded-full","aria-label":"Refresh",children:e.jsx(kt,{size:20})}),e.jsx("button",{onClick:N,className:"p-2 text-gray-600 hover:bg-gray-100 rounded-full","aria-label":"Add",children:e.jsx($t,{size:20})})]}),y&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:_,className:`p-2 rounded-full transition-colors ${a?"bg-blue-50 text-blue-600":"text-gray-600 hover:bg-gray-100"}`,"aria-label":"Search",children:e.jsx(Pt,{size:20})}),e.jsx("button",{onClick:N,className:"p-2 text-gray-600 hover:bg-gray-100 rounded-full","aria-label":"Add",children:e.jsx($t,{size:20})})]}),u&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:_,className:`p-2 rounded-full transition-colors ${a?"bg-blue-50 text-blue-600":"text-gray-600 hover:bg-gray-100"}`,"aria-label":"Search",children:e.jsx(Pt,{size:20})}),e.jsx("button",{onClick:E,className:"p-2 text-gray-600 hover:bg-gray-100 rounded-full","aria-label":"Refresh",children:e.jsx(kt,{size:20})}),e.jsx("button",{onClick:N,className:"p-2 text-gray-600 hover:bg-gray-100 rounded-full","aria-label":"Add",children:e.jsx($t,{size:20})})]}),g&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:_,className:`p-2 rounded-full transition-colors ${a?"bg-blue-50 text-blue-600":"text-gray-600 hover:bg-gray-100"}`,"aria-label":"Search",children:e.jsx(Pt,{size:20})}),e.jsx("button",{onClick:E,className:"p-2 text-gray-600 hover:bg-gray-100 rounded-full","aria-label":"Refresh",children:e.jsx(kt,{size:20})}),e.jsx("button",{onClick:N,className:"p-2 text-gray-600 hover:bg-gray-100 rounded-full","aria-label":"Add",children:e.jsx($t,{size:20})})]}),w&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:_,className:`p-2 rounded-full transition-colors ${a?"bg-blue-50 text-blue-600":"text-gray-600 hover:bg-gray-100"}`,"aria-label":"Filter",children:e.jsx(ci,{size:20})}),e.jsx("button",{onClick:N,className:"p-2 text-gray-600 hover:bg-gray-100 rounded-full","aria-label":"Add",children:e.jsx($t,{size:20})})]})]})]}),(b||x)&&e.jsx(Ht,{open:o,onOpenChange:i,children:e.jsxs(qt,{className:"max-w-sm w-[calc(100vw-32px)] p-0 overflow-hidden",children:[e.jsx(Zt,{className:"px-5 py-4 border-b border-slate-100",children:e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx(Yt,{className:"text-[15px] font-semibold text-slate-800",children:"Markets"}),e.jsx(Ds,{className:"text-[12px] text-slate-400 mt-0.5",children:"Select markets for analysis."})]}),e.jsx("button",{type:"button",onClick:()=>i(!1),className:"p-1.5 rounded-lg text-slate-400 hover:text-slate-600 hover:bg-slate-50 transition-colors","aria-label":"Close",children:e.jsx(mt,{size:18})})]})}),e.jsx("div",{className:"px-5 py-4",children:e.jsx(Bi,{})})]})})]})},Sx=({authed:t,current:s,currentSection:a,currentCampaignName:n,currentCampaignId:o,systemViews:i,currentViewId:l,onNavigate:c,onShowCreditDialog:d,onSetShowCreditDialog:m,isOpen:h,onCloseMobile:p,hidePrototypeItems:f,hideHome:b,hideWorkflow:y,showAppPrototypeItems:x})=>{const u=(_,E)=>_==="report"?s==="report":_==="company"&&E?s==="company"&&a===E:_==="table-new"?s==="table-new"||s==="table":s===_,g=({label:_,icon:E,active:N,onClick:S,hint:k,indent:D=!1,hideIndicator:F=!1})=>e.jsxs("button",{onClick:()=>{S(),p?.()},className:`group w-full flex items-center gap-2.5 py-1.5 text-[12px] transition-all relative ${D?"pl-8 pr-3":"px-3"} ${N?"text-gray-900 font-medium":"text-gray-500 hover:text-gray-700"}`,children:[N&&!F&&e.jsx("div",{className:"absolute left-0 top-1/2 -translate-y-1/2 w-0.5 h-4 bg-gray-900 rounded-r"}),E&&e.jsx(E,{size:13,className:`flex-shrink-0 ${N?"text-gray-700":"text-gray-400 group-hover:text-gray-500"}`}),e.jsx("span",{className:"flex-1 text-left",children:_}),k&&e.jsx("span",{className:"text-[10px] text-gray-400",children:k})]}),w=({label:_})=>e.jsx("div",{className:"px-3 pt-5 pb-1.5 text-[10px] font-semibold text-gray-400 uppercase tracking-wider select-none",children:_});return e.jsxs("aside",{className:`fixed inset-y-0 left-0 z-[80] w-64 bg-white shadow-lg transform transition-transform duration-200 ease-in-out md:translate-x-0 md:static md:w-52 md:shadow-none md:border-r md:border-gray-100 md:flex flex-col h-full ${h?"translate-x-0":"-translate-x-full"}`,children:[e.jsx("div",{className:"h-14 flex items-center px-4 border-b border-gray-100",children:e.jsxs("button",{onClick:()=>c("home"),className:"flex items-center gap-2 hover:opacity-80 transition-opacity",children:[e.jsx(dr,{className:"w-6 h-6 rounded",alt:"Rankgale"}),e.jsx("span",{className:"text-sm font-semibold text-gray-800 tracking-tight",children:"Rankgale"})]})}),e.jsxs("nav",{className:"flex-1 overflow-y-auto py-2",children:[e.jsx(w,{label:"Workspace"}),e.jsxs("div",{className:"px-1 space-y-0.5","data-onboarding":"sidebar-workspace",children:[e.jsx(g,{label:"AEO/GEO",icon:Qt,active:s==="aeo_geo_flow"||s==="aeo_geo_new_flow",hideIndicator:!0,onClick:()=>{c("aeo_geo_flow")}}),e.jsx(g,{label:"SEO",icon:Pt,active:s==="seo_flow"||s==="seo_new_flow",hideIndicator:!0,onClick:()=>{c("seo_flow")}}),e.jsx(g,{label:"Content Generation",icon:is,active:s==="content_generation_flow"||s==="content_generation_new_flow",hideIndicator:!0,onClick:()=>{c("content_generation_flow")}}),e.jsx(g,{label:"Content Refresh",icon:kt,active:s==="content_refresh_flow"||s==="content_refresh_new_flow",hideIndicator:!0,onClick:()=>{c("content_refresh_flow")}}),e.jsx(g,{label:"Worksheets",icon:us,active:u("worksheets")||u("campaigns")||u("table-new"),onClick:()=>c("worksheets")})]}),e.jsxs(e.Fragment,{children:[e.jsx(w,{label:"Context"}),e.jsxs("div",{className:"px-1 space-y-0.5","data-onboarding":"sidebar-context",children:[e.jsx(g,{label:"Competitors Intelligence",icon:Qs,active:u("competitors"),onClick:()=>c("competitors")}),e.jsx(g,{label:"Keywords Gap",icon:Pt,active:u("keyword_gap")||u("keyword_research"),onClick:()=>c("keyword_gap")}),e.jsx(g,{label:"Company Info",icon:an,active:u("company","company"),onClick:()=>c("company",{section:"company"})}),e.jsx(g,{label:"Knowledge",icon:iu,active:u("knowledge"),onClick:()=>c("knowledge")}),e.jsx(g,{label:"Integration",icon:lu,active:u("integration"),onClick:()=>c("integration")})]})]}),e.jsxs(e.Fragment,{children:[e.jsx(w,{label:"Insights"}),e.jsxs("div",{className:"px-1 space-y-0.5","data-onboarding":"sidebar-insights",children:[e.jsx(g,{label:"Keywords Monitor",icon:Ma,active:u("keywords_tracking"),onClick:()=>c("keywords_tracking")}),e.jsx(g,{label:"Page Monitor",icon:Uh,active:u("page_tracking"),onClick:()=>c("page_tracking")}),e.jsx(g,{label:"Prompt Monitor",icon:Qt,active:u("geo_prompt"),onClick:()=>c("geo_prompt")}),e.jsx(g,{label:"Reports",icon:cu,active:u("data_report")||u("report"),onClick:()=>c("data_report")}),e.jsx(g,{label:"Attribution",icon:Sn,active:u("attribution_insight"),onClick:()=>c("attribution_insight")})]})]}),e.jsxs(e.Fragment,{children:[e.jsx(w,{label:"Pricing"}),e.jsxs("div",{className:"px-1 space-y-0.5","data-onboarding":"sidebar-pricing",children:[e.jsx(g,{label:"Pricing",icon:Wa,active:u("subscription"),onClick:()=>c("subscription")}),e.jsx(g,{label:"Usage",icon:Sn,active:u("usage_history"),onClick:()=>c("usage_history")})]})]})]}),t&&e.jsx("div",{className:"border-t border-gray-100 p-3 space-y-2",children:e.jsx(jx,{variant:"card",onClick:d})}),e.jsx("div",{className:"border-t border-gray-100",children:t?e.jsx(Dc,{}):e.jsx(be,{size:"sm",onClick:()=>An(),className:"w-full",children:"Sign in"})})]})};Sx.displayName="Sidebar";function Ex({current:t,onChange:s,children:a}){const[n,o]=v.useState(0),[i,l]=v.useState(!1),[c,d]=v.useState(()=>Tr()),[m,h]=v.useState([]),[p,f]=v.useState(null),[b,y]=v.useState(!1),[x,u]=v.useState(!1),[g,w]=v.useState(""),[_,E]=v.useState(da()||""),[N,S]=v.useState(0),[k,D]=v.useState(!1),[F,R]=v.useState(!1),[L,$]=v.useState(!1),[H,K]=v.useState(!1),[X,V]=v.useState(!1);v.useEffect(()=>{const le=Oi(()=>{o(ne=>ne+1)}),O=So(()=>{o(ne=>ne+1)});return()=>{try{le()}catch{}try{O()}catch{}}},[]),v.useEffect(()=>{d(Tr());const le=Pc(O=>{O.scope_key===mr()&&d(!!O.ready)});return()=>{try{le()}catch{}}},[]);const{runOnboarding:P,restartToken:A,showHelpButton:C,startOnboarding:I,stopOnboarding:j}=aw({authed:x,currentTab:t}),[q,T]=v.useState(!1),[M,Z]=v.useState(!1),B=v.useCallback(async()=>{t==="campaigns"||t==="worksheets"?window.dispatchEvent(new CustomEvent("restartWorksheetsOnboarding")):t==="table-new"||t==="table"?window.dispatchEvent(new CustomEvent("restartTableOnboarding")):I()},[t,I]),ae=v.useCallback(async()=>{Z(!0);try{const le=await ow();let O=le.tutorial_campaign_id;if(le.has_tutorial_campaign||(O=(await iw()).tutorial_campaign_id),T(!1),O){const ne=await Wt.listViewConfigs({campaign_id:O});ne.items.length>0?jt("table",{campaign:O,view:ne.items[0].id}):jt("table",{campaign:O})}}catch(le){console.error("Failed to create tutorial campaign:",le),T(!1)}finally{Z(!1)}},[]);v.useEffect(()=>{const le=new URLSearchParams(window.location.search);f(le.get("view"));const O=()=>{const ne=new URLSearchParams(window.location.search);f(ne.get("view"))};return window.addEventListener("popstate",O),()=>window.removeEventListener("popstate",O)},[t]),v.useEffect(()=>{if(!x||!_){h([]);return}async function le(){try{const[O,ne]=await Promise.all([Wt.listViewConfigs({campaign_id:_,table_type:"system"}),Wt.listViewConfigs({campaign_id:_,table_type:"custom"})]),ge=[...O.items,...ne.items];h(ge)}catch(O){console.error("Failed to load views:",O),h([])}}le()},[x,_]);const de=v.useCallback(()=>{try{return new URLSearchParams(window.location.search).get("section")||"company"}catch{return"company"}},[]),[fe,se]=v.useState(()=>de());v.useEffect(()=>{const le=()=>{const ne=de();se(ge=>ge!
56==ne?ne:ge)};le();const O=()=>{le()};return window.addEventListener("popstate",O),()=>window.removeEventListener("popstate",O)},[t,de]),v.useEffect(()=>{const le=()=>{const ne=da()||"";E(ge=>ge!==ne?ne:ge)};le();const O=()=>le();return window.addEventListener("popstate",O),()=>window.removeEventListener("popstate",O)},[]),v.useEffect(()=>{const le=()=>{try{const ge=localStorage.getItem("flowwriter.currentCampaign");if(ge){const Ke=JSON.parse(ge).name||"";w(ie=>ie!==Ke?Ke:ie)}else w(ze=>ze!==""?"":ze)}catch{w(ge=>ge!==""?"":ge)}};le();const O=()=>le();window.addEventListener("storage",O);const ne=setInterval(le,2e3);return()=>{window.removeEventListener("storage",O),clearInterval(ne)}},[]),v.useEffect(()=>{let le=!0,O=null;const ne=async()=>{try{const ge=await rs.isAuthenticated();if(!le)return;u(ze=>ze!==!!ge?!!ge:ze)}catch{le&&u(ge=>ge!==!1?!1:ge)}};return ne(),O=setInterval(ne,5e3),()=>{le=!1,O&&clearInterval(O)}},[]),v.useEffect(()=>{if(!x){N!==0&&S(0),pd(null),Cs.invalidate(),bs.invalidate();return}async function le(){try{D(!0);const ne=await Cs.getAccountCached({ttlMs:1e4});pd(ne.user_id);const ge=ne.credits_balance;S(ge),ge<=20&&!L&&(R(!0),$(!0))}catch(ne){console.error("Failed to load credits:",ne)}finally{D(!1)}}le();const O=setInterval(le,3e4);return()=>clearInterval(O)},[x,L]),v.useEffect(()=>{const le=cl.includes(t);if(!x||!le){K(!1),V(!1);return}async function O(){try{V(!0);const ne=await bs.getGoogleAuthExistsCached({ttlMs:3e4});K(ne.exists)}catch(ne){console.error("⚠️ Failed to check GSC auth:",ne),K(!1)}finally{V(!1)}}O()},[x,t]);const z=v.useCallback((le,O)=>{s?.(le),jt(le,O)},[s,t]),U=v.useCallback(()=>{R(!0)},[]),Q=v.useCallback(()=>{K(le=>le||!0)},[]),me=v.useCallback(()=>{y(!0),setTimeout(()=>{y(!1)},100)},[]);return t==="landing"?e.jsx(e.Fragment,{children:a}):t==="setup_prototype"?e.jsx(e.Fragment,{children:a}):e.jsx(gx,{children:e.jsxs("div",{className:"flex h-screen bg-slate-50 overflow-hidden",children:[e.jsx(lw,{current:t,onMenuClick:()=>l(!i)}),i&&e.jsx("div",{className:"fixed inset-0 bg-black/50 z-[70] md:hidden",onClick:()=>l(!1)}),e.jsx(Sx,{isOpen:i,onCloseMobile:()=>l(!1),authed:x,current:t,currentSection:fe,currentCampaignName:g,currentCampaignId:_,systemViews:m,currentViewId:p,onNavigate:z,onShowCreditDialog:U,onSetShowCreditDialog:R,hidePrototypeItems:!1,hideHome:!1,hideWorkflow:!0,showAppPrototypeItems:!0}),e.jsxs("main",{className:"flex-1 overflow-hidden relative flex flex-col pt-14 md:pt-0",children:[x&&(t==="keyword_gap"||t==="keyword_research"||t==="homepage"||t==="home"||t==="seo_flow"||t==="aeo_geo_flow"||t==="seo_new_flow"||t==="aeo_geo_new_flow"||t==="competitors"||t==="keywords_tracking")&&e.jsx("div",{className:`shrink-0 bg-white border-b border-slate-100 ${t==="keyword_research"||t==="keyword_gap"||t==="homepage"||t==="home"||t==="keywords_tracking"?"hidden sm:block":""}`,children:e.jsxs("div",{className:"p-2 flex items-center gap-2 overflow-x-auto",children:[e.jsx("div",{className:"text-[12px] font-semibold text-slate-700",children:"Markets:"}),e.jsx(Bi,{})]})}),e.jsxs("div",{className:`flex-1 min-h-0 relative ${t==="workflow"?"overflow-hidden":"overflow-auto"}`,children:[C&&e.jsx("div",{className:"hidden sm:block",children:e.jsx(Zb,{onClick:B})}),e.jsx(Ht,{open:q,onOpenChange:T,children:e.jsxs(qt,{className:"sm:max-w-md",children:[e.jsxs(Zt,{children:[e.jsxs(Yt,{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-2xl",children:"🎓"}),"Start Interactive Tutorial?"]}),e.jsxs(Ds,{className:"text-left pt-2",children:[e.jsxs("p",{className:"mb-3",children:["We'll create a ",e.jsx("strong",{children:"Tutorial Campaign"})," for you with pre-configured examples to help you learn how to:"]}),e.jsxs("ul",{className:"list-disc list-inside space-y-1 text-sm text-slate-600 mb-3",children:[e.jsx("li",{children:"Analyze any webpage for geo/aeo"}),e.jsx("li",{children:"Generate relevant keywords"}),e.jsx("li",{children:"Create AI-powered content"}),e.jsx("li",{children:"Add custom columns and workflows"})]}),e.jsx("p",{className:"text-sm text-slate-500",children:"The tutorial takes about 2-3 minutes to complete."})]})]}),e.jsxs(Ns,{children:[e.jsx(be,{variant:"outline",onClick:()=>T(!1),disabled:M,children:"Maybe Later"}),e.jsx(be,{onClick:ae,disabled:M,className:"bg-slate-900 hover:bg-slate-800",children:M?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"animate-spin mr-2",children:"⏳"}),"Creating..."]}):e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"mr-2",children:"🚀"}),"Start Tutorial"]})})]})]})}),x&&(t==="campaigns"||t==="worksheets")&&e.jsx(qd,{steps:ew,run:P,onComplete:j,onSkip:j},`tour-${A}-worksheets`),x&&(t==="keywords"||t==="keyword-groups")&&e.jsx(qd,{steps:tw,run:P,onComplete:j,onSkip:j},`tour-${A}-keywords`),x&&cl.includes(t)&&!X&&!H?e.jsx("div",{className:"h-full"}):e.jsx("div",{className:"h-full",children:x&&(t==="keyword_gap"||t==="keyword_research"||t==="homepage"||t==="competitors"||t==="keywords_tracking")&&!c?e.jsx("div",{className:"h-full flex items-center justify-center",children:e.jsx("div",{className:"text-[12px] text-slate-500",children:"Loading markets..."})}):v.isValidElement(a)?v.cloneElement(a,{gscAuthCompleted:b,marketReloadNonce:n}):a}),x&&cl.includes(t)&&!X&&e.jsx(_x,{visible:!H,onAuthorized:Q,onComplete:me})]})]}),e.jsx(Xb,{open:F,onOpenChange:R,currentBalance:N})]})})}function cw(t){if(!t)return null;const s=t.trim();if(!s.endsWith("px"))return null;const a=Number(s.slice(0,-2));return Number.isFinite(a)?a:null}function Vr(t){return!!t.isSelection||t.sticky==="left"}const dw=({active:t,order:s})=>t?s==="desc"?e.jsx(Ws,{size:11,className:"text-slate-600"}):e.jsx(Is,{size:11,className:"text-slate-600"}):null;function Lc({data:t,columns:s,isLoading:a,sortBy:n,sortOrder:o,onSort:i,onRowClick:l,rowClassName:c,emptyMessage:d="No data available",title:m,actions:h,pagination:p}){const f=y=>{y.sortKey&&i&&i(y.sortKey)},b=v.useMemo(()=>{const y={};let x=0;for(let u=0;u<s.length;u+=1){const g=s[u];if(!Vr(g))continue;y[u]=x;const w=g.stickyWidthPx??cw(g.width)??(g.isSelection?40:0);x+=w}return y},[s]);return a?e.jsx("div",{className:"flex-1 flex items-center justify-center h-full min-h-[200px] bg-white border border-slate-200 rounded-lg",children:e.jsx(He,{size:20,className:"animate-spin text-slate-400"})}):e.jsxs("div",{className:"h-full w-full flex flex-col bg-white border border-slate-200 rounded-lg overflow-hidden shadow-sm",children:[(m||h)&&e.jsxs("div",{className:"px-4 py-3 border-b border-slate-100 flex items-center justify-between flex-shrink-0",children:[m?e.jsx("div",{className:"text-sm font-medium text-slate-700",children:m}):e.jsx("div",{}),h&&e.jsx("div",{className:"flex items-center gap-2",children:h})]}),e.jsx("div",{className:"flex-1 min-h-0 overflow-auto",children:e.jsxs("table",{className:"w-full text-sm border-collapse",children:[e.jsx("thead",{className:"bg-slate-50 border-b border-slate-200 sticky top-0 z-30",children:e.jsx("tr",{className:"text-xs text-slate-500",children:s.map((y,x)=>e.jsx("th",{className:`
57                    font-medium select-none
58                    ${y.isSelection?"py-1.5 px-2":"py-3 px-4"}
59                    ${y.align==="right"?"text-right":y.align==="center"?"text-center":"text-left"}
60                    ${y.sortKey?"cursor-pointer hover:text-slate-700":""}
61                    ${Vr(y)?"sticky top-0 bg-slate-50 border-r border-slate-200":""}
62                    ${y.headerClassName||""}
63                    ${y.className||""}
64                  `,style:{...y.width?{width:y.width}:{}
64,...Vr(y)?{left:b[x]??0,zIndex:40+x}:{}},onClick:()=>f(y),children:e.jsxs("div",{className:`
65                    flex items-center gap-1
66                    ${y.align==="right"?"justify-end":y.align==="center"?"justify-center":"justify-start"}
67                  `,children:[y.header,(y.showDefaultSortIcon??!0)&&y.sortKey&&n===y.sortKey&&o&&e.jsx(dw,{active:!0,order:o})]})},x))})}),e.jsx("tbody",{className:"divide-y divide-slate-100",children:t.length>0?t.map((y,x)=>e.jsx("tr",{className:`
68                    transition-colors group hover:bg-slate-50
69                    ${l?"cursor-pointer hover:bg-slate-50 group":"hover:bg-slate-50"}
70                    ${c?c(y):""}
71                  `,onClick:()=>l&&l(y),children:s.map((u,g)=>e.jsx("td",{className:`
72                        ${u.isSelection?"py-1.5 px-2":"py-3 px-4"}
73                        ${u.align==="right"?"text-right":u.align==="center"?"text-center":"text-left"}
74                        ${Vr(u)?"sticky z-10 bg-white group-hover:bg-slate-50 border-r border-slate-100":""}
75                        ${u.className||""}
76                        ${typeof u.cellClassName=="function"?u.cellClassName(y):u.cellClassName||""}
77                      `,style:Vr(u)?{left:b[g]??0,zIndex:20+g}:void 0,children:u.render?u.render(y):u.accessorKey?y[u.accessorKey]:null},g))},x)):e.jsx("tr",{children:e.jsx("td",{colSpan:s.length,className:"py-12 text-center text-slate-500",children:d})})})]})}),p&&e.jsx("div",{className:"flex-shrink-0 border-t border-slate-200 bg-white mt-auto",children:e.jsx(xn,{page:p.currentPage,pageSize:p.pageSize,total:p.total,onPageChange:p.onPageChange,onPageSizeChange:p.onPageSizeChange})})]})}const Yd=t=>t==null?"-":t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:t.toString(),mw=({keywords:t,selectedRange:s,onRangeClick:a,compact:n=!1,hideTitle:o=!1})=>{const i=r.useMemo(()=>{const c=[{label:"#1",filter:"1",min:1,max:1},{label:"#2-3",filter:"2-3",min:2,max:3},{label:"#4-10",filter:"4-10",min:4,max:10},{label:"#11-20",filter:"11-20",min:11,max:20},{label:"#21-30",filter:"21-30",min:21,max:30},{label:"#31-50",filter:"31-50",min:31,max:50},{label:"#51-100",filter:"51-100",min:51,max:100}].map(m=>({...m,count:t.filter(h=>h.rank&&h.rank>=m.min&&h.rank<=m.max).length})),d=Math.max(...c.map(m=>m.count),1);return c.map(m=>({...m,percent:m.count/d*100}))},[t]);return e.jsxs("div",{className:o?"":"space-y-2",children:[!o&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:`font-medium text-slate-500 ${n?"text-[10px]":"text-xs"}`,children:n?"Rank Distribution":"Keywords Distribution"}),s!=="all"&&e.jsx("button",{onClick:()=>a("all"),className:"text-xs text-slate-400 hover:text-slate-600",children:"Clear filter"})]}),e.jsx("div",{className:n?"space-y-1":"space-y-1.5",children:i.map(l=>e.jsxs("button",{onClick:()=>a(l.filter===s?"all":l.filter),className:`w-full flex items-center gap-3 py-1 px-1 rounded transition-colors ${l.filter===s?"bg-slate-100":"hover:bg-slate-50"}`,children:[e.jsx("span",{className:`${n?"text-[10px] w-10":"text-xs w-14"} text-left ${l.filter===s?"text-slate-800 font-medium":"text-slate-500"}`,children:l.label}),e.jsx("div",{className:`flex-1 ${n?"h-4":"h-5"} bg-slate-100 rounded-full overflow-hidden`,children:e.jsx("div",{className:`h-full rounded-full transition-all ${l.filter===s?"bg-emerald-400":"bg-emerald-200"}`,style:{width:`${l.percent}%`}})}),e.jsx("span",{className:`${n?"text-[10px] w-6":"text-xs w-8"} text-right ${l.filter===s?"text-slate-800 font-medium":"text-slate-500"}`,children:l.count})]},l.label))})]})},uw=t=>{switch(t){case"1":return{min:1,max:1};case"2-3":return{min:2,max:3};case"4-10":return{min:4,max:10};case"11-20":return{min:11,max:20};case"21-30":return{min:21,max:30};case"31-50":return{min:31,max:50};case"51-100":return{min:51,max:100};default:return null}};function xw({competitorDomain:t,prefetchedKeywords:s,onRefresh:a,showEtvColumns:n=!0,showKeywordLastUpdatedColumn:o=!1}){const[i,l]=r.useState(!s),[c,d]=r.useState(null),[m,h]=r.useState(s||[]),[p,f]=r.useState(""),[b,y]=r.useState("volume"),[x,u]=r.useState("desc"),[g,w]=r.useState("all"),[_,E]=r.useState(1),[N,S]=r.useState(100),k=v.useCallback(A=>{if(!A)return 0;try{const C=Date.parse(A);return Number.isFinite(C)?C:0}catch{return 0}},[]),D=v.useCallback(A=>{const C=String(A||"").trim();if(!C)return"";const I=C.replace(/^https?:\/\//,""),j=40;return I.length<=j?I:`${I.slice(0,j-3)}...`},[]),F=r.useMemo(()=>{let A=[...m];const C=uw(g);if(C&&(A=A.filter(I=>I.rank&&I.rank>
77=C.min&&I.rank<=C.max)),p.trim()){const I=p.toLowerCase();A=A.filter(j=>j.keyword.toLowerCase().includes(I))}return A.sort((I,j)=>{let q=0;switch(b){case"keyword":q=I.keyword.localeCompare(j.keyword);break;case"rank":q=(I.rank||999)-(j.rank||999);break;case"volume":q=(I.search_volume||0)-(j.search_volume||0);break;case"updated":q=k(I.snapshot_date)-k(j.snapshot_date);break}return x==="asc"?q:-q}),A},[k,m,p,b,x,g]);r.useEffect(()=>{E(1)},[m,p,b,x,g]);const R=F.length,L=Math.max(1,Math.ceil(R/N)),$=Math.max(1,Math.min(_,L)),H=r.useMemo(()=>{const A=($-1)*N,C=A+N;return F.slice(A,C)},[F,$,N]),K=A=>{b===A?u(x==="asc"?"desc":"asc"):(y(A),u("desc"))};r.useEffect(()=>{let A=!0;return(async()=>{try{if(s)return;s||l(!0),d(null);const I=await Yu(t,void 0,void 0,0);A&&h(I.keywords||[])}catch(I){A&&d(I.message||"Failed to load competitor keywords")}finally{A&&l(!1)}})(),()=>{A=!1}},[t,s]);const X=r.useMemo(()=>{const A=[{header:"Keyword",sortKey:"keyword",render:C=>e.jsx("span",{className:"text-slate-800",children:C.keyword})},{header:"Rank",sortKey:"rank",align:"center",width:"80px",render:C=>C.rank?e.jsxs("span",{className:"text-slate-600",children:["#",C.rank]}):e.jsx("span",{className:"text-slate-300",children:"-"})},{header:"Volume",sortKey:"volume",align:"right",width:"96px",render:C=>e.jsx("span",{className:"text-slate-600",children:Yd(C.search_volume)})},{header:"Landing Page",width:"240px",render:C=>C.landing_page?e.jsxs("a",{href:C.landing_page,target:"_blank",rel:"noopener noreferrer",title:C.landing_page,className:"text-xs text-slate-500 hover:underline block max-w-[220px] flex items-center gap-1 min-w-0",children:[e.jsx(ns,{size:10,className:"flex-shrink-0"}),e.jsx("span",{className:"truncate min-w-0",children:D(C.landing_page)})]}):e.jsx("span",{className:"text-slate-300",children:"-"})},{header:"My Rank",align:"center",width:"100px",render:C=>{const I=C.my_rank!=null,j=I&&C.rank?C.my_rank-C.rank:null;return I?e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsxs("span",{className:"inline-block px-2 py-0.5 bg-blue-50 text-blue-700 rounded font-medium min-w-[40px]",children:["#",C.my_rank]}),j!==null&&j!==0&&e.jsx("span",{className:`text-[10px] font-medium ${j<0?"text-emerald-600":"text-rose-500"}`,children:j<0?`↑${Math.abs(j)}`:`↓${j}`})]}):e.jsx("span",{className:"text-slate-300",children:"-"})}},...o?[{header:"Last updated",sortKey:"updated",width:"130px",render:C=>{const I=C.snapshot_date;if(!I)return e.jsx("span",{className:"text-slate-300",children:"-"});try{return e.jsx("span",{className:"text-slate-600",children:new Date(I).toLocaleDateString("en-CA")})}catch{return e.jsx("span",{className:"text-slate-300",children:"-"})}}}]:[]];return n&&A.push({header:"My ETV",align:"right",width:"100px",render:C=>C.my_etv!=null?e.jsx("span",{className:`font-medium ${C.etv&&C.my_etv>C.etv?"text-emerald-600":C.etv&&C.my_etv<C.etv?"text-rose-500":"text-blue-600"}`,children:Yd(C.my_etv)}):e.jsx("span",{className:"text-slate-300",children:"-"})}),A},[n,o]),V=e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium text-slate-700",children:"Ranked Keywords"}),g!=="all"&&e.jsxs("span",{className:"text-xs px-2 py-0.5 bg-slate-100 text-slate-600 rounded",children:["Rank ",g]})]}),P=e.jsx(e.Fragment,{children:e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs("div",{className:"relative",children:[e.jsx(Pt,{size:14,className:"absolute left-2.5 top-1/2 -translate-y-1/2 text-slate-400"}),e.jsx("input",{type:"text",placeholder:"Search...",value:p,onChange:A=>f(A.target.value),className:"pl-8 pr-3 py-1.5 text-xs bg-slate-50 border-none rounded-md w-48 focus:ring-1 focus:ring-slate-300"})]})})});return i?e.jsxs("div",{className:"flex items-center justify-center py-12",children:[e.jsx(He,{size:24,className:"animate-spin text-slate-400"}),e.jsx("span",{className:"ml-2 text-sm text-slate-500",children:"Loading keywords..."})]}):c?e.jsx("div",{className:"flex flex-col items-center justify-center py-12",children:e.jsx("p",{className:"text-sm text-slate-500",children:c})}):m.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12",children:[e.jsx("p",{className:"text-sm text-slate-500 mb-4",children:"No keywords data available."}),a?e.jsxs("button",{onClick:a,className:"px-4 py-2 text-sm font-medium text-white bg-slate-900 hover:bg-slate-800 rounded-lg transition-colors flex items-center gap-2",children:[e.jsx(kt,{className:"w-4 h-4"}),"Click to refresh"]}):e.jsx("p",{className:"text-sm text-slate-500",children:"Please refresh all competitors from the main view."})]}):e.jsxs("div",{className:"h-full w-full min-h-0 flex gap-4",children:[e.jsx(Lc,{data:H,columns:X,isLoading:i,sortBy:b,sortOrder:x,onSort:A=>K(A),title:V,actions:P,pagination:{currentPage:$,pageSize:N,total:R,onPageChange:E,onPageSizeChange:S}}),e.jsx("div",{className:"w-72 bg-white rounded-lg border border-slate-200 p-4 flex-none",children:e.jsx(mw,{keywords:m.map(A=>({keyword:A.keyword,rank:A.rank,search_volume:A.search_volume,etv:A.etv,landing_page:A.landing_page,location_code:null,language_code:null})),selectedRange:g,onRangeClick:w})})]})}const Ax="competitors_ranked_keywords_limit",hw="competitor_ranked_keywords_limit",Tx=100,pw=10,gw=5e3;function Px(t){return Number.isFinite(t)?Math.max(pw,Math.min(gw,Math.round(t))):Tx}function Ir(){try{const t=localStorage.getItem(Ax)||localStorage.getItem(hw);if(t){const s=parseInt(t,10);if(!isNaN(s))return Px(s)}}catch(t){console.error("Failed to load ranked keywords limit from storage:",t)}return Tx}function Rn(t){try{localStorage.setItem(Ax,Px(t).toString())}catch(s){console.error("Failed to save ranked keywords limit to storage:",s)}}const Vi={async estimateCredits(t){return await Je("/credit_estimate/estimate",{scenario:t.scenario,params:t.params||{},required_fraction:t.required_fraction??void 0})}},Ya=Object.freeze(Object.defineProperty({__proto__:null,creditEstimateService:Vi},Symbol.toStringTag,{value:"Module"}));function fw(t){try{return JSON.stringify(t??{})}catch{return""}}function ta(t){const[s,a]=r.useState(!1),[n,o]=r.useState(null),[i,l]=r.useState(null),c=r.useMemo(()=>fw(t.params),[t.params]);return r.useEffect(()=>{if(!t.enabled){a(!1),o(null),l(null);return}let d=!0,m=null;const h=async()=>{a(!0);try{const f=await Vi.estimateCredits({scenario:t.scenario,params:t.params||{}});if(!d)return;o({min:Number(f.estimated_min_credits||0),max:Number(f.estimated_max_credits||0)}),l(Number(f.required_minimum_balance||0))}catch(f){if(console.warn("⚠️ Failed to estimate credits:",f),
77!d)return;o(null),l(null)}finally{if(!d)return;a(!1)}},p=typeof t.debounceMs=="number"&&Number.isFinite(t.debounceMs)?Math.max(0,Math.floor(t.debounceMs)):150;return m=setTimeout(()=>{h()},p),()=>{d=!1,m&&clearTimeout(m)}},[t.enabled,t.scenario,c,t.debounceMs]),{estimating:s,estimatedRange:n,requiredMinimumBalance:i}}function yw(t,s){const a=i=>new Intl.NumberFormat("en-US").format(Math.round(Number(i||0))),n=a(t),o=a(s);return t===s?`${n}`:`${n}-${o}`}function bw({open:t,onOpenChange:s,competitorDomain:a,keywordsLimit:n,onConfirm:o,isRefreshing:i=!1}){const[l,c]=r.useState(!0),[d,m]=r.useState(1);r.useEffect(()=>{t&&c(!0)},[t]),r.useEffect(()=>{if(!t)return;let f=!1;return(async()=>{try{const y=await La(),x=Array.isArray(y?.markets)&&y.markets.length>0?y.markets.length:1;if(f)return;m(Math.max(1,Number(x)||1))}catch(y){console.warn("⚠️ Failed to load track markets for credit estimate:",y),f||m(1)}})(),()=>{f=!0}},[t]);const h=ta({enabled:t,scenario:"domainseo_sync_competitor",params:{markets_count:d,keywords_limit:Math.max(10,Math.min(1e3,Math.round(n))),include_overview:!0,include_ranked_keywords:!0,force_sync_keywords:l}}),p=async()=>{await o({syncRankOverview:!0,syncRankedKeywords:!0,forceSyncKeywords:l})};return e.jsx(Ht,{open:t,onOpenChange:s,children:e.jsxs(qt,{className:"sm:max-w-md",children:[e.jsxs(Zt,{children:[e.jsxs(Yt,{className:"flex items-center gap-2",children:[e.jsx(kt,{className:"w-4 h-4 text-slate-500"}),"Refresh Competitor"]}),e.jsxs(Ds,{children:["You are about to refresh data for"," ",e.jsx("span",{className:"font-semibold text-slate-700",children:a}),"."]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"p-4 bg-slate-50 border border-slate-200 rounded-lg",children:[e.jsx("div",{className:"text-sm font-semibold text-slate-800 mb-3",children:"Refresh content"}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"mt-0.5 w-5 h-5 rounded-full bg-blue-100 flex items-center justify-center flex-shrink-0",children:e.jsx(wt,{className:"w-3 h-3 text-blue-600"})}),e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium text-slate-700",children:"Rank Overview"}),e.jsx("div",{className:"text-xs text-slate-500 mt-0.5",children:"Traffic, keywords count, and other metrics."})]})]}),e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"mt-0.5 w-5 h-5 rounded-full bg-blue-100 flex items-center justify-center flex-shrink-0",children:e.jsx(wt,{className:"w-3 h-3 text-blue-600"})}),e.jsxs("div",{children:[e.jsxs("div",{className:"text-sm font-medium text-slate-700",children:["Ranked Keywords",e.jsxs("span",{className:"ml-2 inline-flex items-center px-1.5 py-0.5 rounded text-[10px] font-medium bg-slate-200 text-slate-600",children:["Top ",jo(n)]})]}),e.jsx("div",{className:"text-xs text-slate-500 mt-0.5",children:"Full list refresh."})]})]})]}),e.jsx("div",{className:"mt-4 pt-4 border-t border-slate-200",children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Kt,{checked:l,onCheckedChange:f=>c(f===!0),id:"force-sync-keywords"}),e.jsxs("label",{htmlFor:"force-sync-keywords",className:"text-sm cursor-pointer leading-snug text-slate-700",children:["Force refresh"," ",e.jsx("span",{className:"text-xs text-slate-400",children:"(ignores 7-day cache)"})]})]})})]}),e.jsxs("div",{className:"p-4 bg-amber-50 border border-amber-200 rounded-lg",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(vs,{className:"w-4 h-4 text-amber-600 flex-shrink-0"}),e.jsx("div",{className:"text-sm font-semibold text-amber-800",children:"Estimated cost"})]}),e.jsx("div",{className:"mt-2 text-sm text-amber-700",children:h.estimating?e.jsxs("span",{className:"font-semibold flex items-center gap-2",children:[e.jsx(He,{className:"w-4 h-4 animate-spin"}),"Estimating..."]}):h.estimatedRange?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"font-semibold text-lg",children:yw(h.estimatedRange.min,h.estimatedRange.max)}),e.jsx("span",{className:"ml-1.5",children:"credits"})]}):e.jsx("span",{className:"font-semibold",children:"Estimate unavailable"})})]})]}),e.jsxs(Ns,{children:[e.jsx(be,{variant:"outline",onClick:()=>s(!1),disabled:i,children:"Cancel"}),e.jsx(be,{onClick:p,disabled:i,className:"bg-slate-900 hover:bg-slate-800",children:i?e.jsxs(e.Fragment,{children:[e.jsx(He,{className:"w-4 h-4 mr-2 animate-spin"}),"Syncing..."]}):"Confirm Refresh"})]})]})})}function vn(t){return new Intl.NumberFormat("en-US").format(t)}function ww(t,s){const a=vn(t),n=vn(s);return t===s?`${a}`:`${a}-${n}`}function aa(t){return Math.max(10,Math.min(1e3,Math.round(t)))}function jw(t){const s=new Set,a=[];for(const n of t){const o=String(n.domain||"").trim();
77o&&(s.has(o)||(s.add(o),a.push({...n,domain:o})))}return a}function zc(t){const[s,a]=v.useState(null),[n,o]=v.useState("");v.useEffect(()=>{if(!t.open)return;let z=!1;return(async()=>{try{const me=(await Xa())?.plan?.plan_type||null,le=me?Nt.getLimit("keywords_research_per_competitor",me):null;if(z)return;a(typeof le=="number"&&Number.isFinite(le)?le:null)}catch{z||a(null)}})(),()=>{z=!0}},[t.open]);const i=v.useMemo(()=>{const z=s;return typeof z=="number"&&Number.isFinite(z)?Math.max(10,Math.min(1e3,Math.round(z))):null},[s]),l=v.useMemo(()=>aa(t.keywordsLimit),[t.keywordsLimit]),c=v.useMemo(()=>jw(t.domains||[]),[t.domains]),d=v.useMemo(()=>c.map(z=>z.domain),[c]),m=v.useMemo(()=>c.find(U=>U.isSelf)?.domain||"",[c]),[h,p]=v.useState(new Set),f=t.mode==="full",b=t.scopeBehavior??"selectable",y=f&&b==="all",[x,u]=v.useState(""),[g,w]=v.useState(!1),[_,E]=v.useState("preset"),[N,S]=v.useState(!!f),[k,D]=v.useState(!0),[F,R]=v.useState(!0),[L,$]=v.useState(1);v.useEffect(()=>{if(!t.open)return;let z=!1;return(async()=>{try{const Q=await La(),me=Array.isArray(Q?.markets)&&Q.markets.length>0?Q.markets.length:1;if(z)return;$(Math.max(1,Number(me)||1))}catch(Q){console.warn("⚠️ Failed to load track markets for credit estimate:",Q),z||$(1)}})(),()=>{z=!0}},[t.open]);const H=y?!0:f?N||k:!0;v.useEffect(()=>{f&&!k&&F&&R(!1)},[F,f,k]),v.useEffect(()=>{if(!t.open)return;p(new Set(d)),u("");const z=[50,100,200,500,1e3];E(z.includes(aa(t.keywordsLimit))?"preset":"custom"),z.includes(aa(t.keywordsLimit))||u(String(aa(t.keywordsLimit))),f?(S(!0),D(!0)):(S(!1),D(!0)),R(!0)},[d,f,t.keywordsLimit,t.open]),v.useEffect(()=>{y&&t.open&&(S(!0),D(!0))},[y,t.open]);const K=v.useCallback(z=>{const U=String(z||"").trim();U&&p(Q=>{const me=new Set(Q);return me.has(U)?me.delete(U):me.add(U),me})},[]),X=v.useCallback(()=>{p(z=>z.size===d.length?new Set:new Set(d))},[d]),V=v.useMemo(()=>[50,100,200,500,1e3],[]),P=v.useCallback(z=>{const U=aa(z),Q=i;if(Q!==null&&U!==l&&U>Q){o(`Plan limit exceeded. Max ranked keywords per competitor for your plan is ${vn(Q)}.`);return}n&&o(""),t.onKeywordsLimitChange(U)},[i,l,n,t]),A=v.useMemo(()=>{if(_!=="custom")return t.keywordsLimit;const z=String(x||"").trim();if(!z)return t.keywordsLimit;const U=Number(z);return Number.isFinite(U)?aa(U):t.keywordsLimit},[x,_,t.keywordsLimit]),C=v.useMemo(()=>{const z=aa(A);return V.includes(z)?z:null},[A,V]),I=v.useMemo(()=>f?y?!0:N:!1,[y,f,N]),j=v.useMemo(()=>!f||y?!0:k,[y,f,k]),q=ta({enabled:t.open&&h.size>0,scenario:"domainseo_batch_sync_competitors",params:{markets_count:L,targets_count:h.size,competitor_targets_count:Math.max(0,h.size-(m&&h.has(m)?1:0)),keywords_limit:aa(A),sync_rank_overview:I,sync_ranked_keywords:j,force_sync_keywords:F}}),T=v.useMemo(()=>{const z=Math.max(0,h.size),U=q.estimatedRange?.min??0,Q=q.estimatedRange?.max??0,me=z>0?Math.round(U/z):0,le=z>0?Math.round(Q/z):0;return{totalMin:U,totalMax:Q,perDomainMin:me,perDomainMax:le}},[q.estimatedRange?.max,q.estimatedRange?.min,h.size]);v.useMemo(()=>{if(!f)return"ranked keywords";const z=[];return N&&z.push("rank overview"),k&&z.push("ranked keywords"),z.length>0?z.join(" + "):"selected data"},[f,N,k]);const M=v.useCallback(async()=>{if(t.isRunning||g)return;const z=Array.from(h);if(z.length===0||!H)return;const U=!!(m&&z.includes(m)),Q=U?z.filter(me=>me!==m):z;if(t.onSaveSetting)try{w(!0),await t.onSaveSetting(aa(A))}catch(me){console.warn("⚠️ Failed to save setting before refresh:",me);return}finally{w(!1)}await t.onConfirm({domains:Q,includeSelf:U,syncRankOverview:f?y?!0:N:!1,syncRankedKeywords:f?y?!0:k:!0,forceSyncKeywords:F,keywordsLimit:aa(A)})},[A,F,y,f,H,t,h,g,m,N,k]),Z=v.useCallback(async()=>{if(t.onSaveSetting&&!(t.isRunning||g))try{w(!0),await t.onSaveSetting(aa(A)),t.onOpenChange(!1)}catch(z){console.warn("⚠️ Failed to save setting:",z)}finally{w(!1)}},[A,t,g]),B=v.useCallback(()=>{const z=String(x||"").trim();if(!z)return;const U=Number(z);Number.isFinite(U)&&P(U)},[x,P]),ae=t.title??"Refresh Keywords",de=t.description??(f?y?"Select domains to refresh.":"Select domains and options to refresh.":"Select domains to refresh."),fe=t.confirmText??"Confirm",se=t.saveSettingText??"Save setting";return e.jsx(Ht,{open:t.open,onOpenChange:z=>
77{if(!z){t.onOpenChange(!1);return}t.onOpenChange(!0)},children:e.jsxs(qt,{className:"sm:max-w-3xl max-h-[80vh] flex flex-col",children:[e.jsxs(Zt,{children:[e.jsxs(Yt,{className:"flex items-center gap-2",children:[e.jsx(kt,{className:"w-4 h-4 text-slate-500"}),ae]}),e.jsx(Ds,{children:de})]}),e.jsx("div",{className:"flex-1 overflow-hidden flex flex-col gap-4",children:e.jsxs("div",{className:"flex-1 overflow-hidden sm:flex sm:gap-4",children:[e.jsxs("div",{className:"space-y-3 sm:w-[50%]",children:[e.jsxs("div",{className:"p-4 bg-slate-50 border border-slate-200 rounded-lg",children:[e.jsx("div",{className:"text-sm font-semibold text-slate-800",children:"Refresh options"}),e.jsxs("div",{className:"mt-3 space-y-3",children:[f&&!y&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-xs font-medium text-slate-500",children:"Content"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Kt,{checked:N,onCheckedChange:z=>S(z===!0),id:"sync-rank-overview"}),e.jsxs("label",{htmlFor:"sync-rank-overview",className:"min-w-0 cursor-pointer",children:[e.jsx("div",{className:"text-sm font-medium text-slate-700 leading-tight",children:"Rank overview"}),e.jsx("div",{className:"text-xs text-slate-500 leading-snug",children:"Totals like keywords and traffic."})]})]}),e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Kt,{checked:k,onCheckedChange:z=>D(z===!0),id:"sync-ranked-keywords"}),e.jsxs("label",{htmlFor:"sync-ranked-keywords",className:"min-w-0 cursor-pointer",children:[e.jsx("div",{className:"text-sm font-medium text-slate-700 leading-tight",children:"Ranked keywords"}),e.jsx("div",{className:"text-xs text-slate-500 leading-snug",children:"Top keywords list per domain."})]})]})]}),!H&&e.jsx("div",{className:"text-xs text-red-600",children:"Select at least one option."})]}),e.jsx("div",{className:"h-px bg-slate-200"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("div",{className:"text-xs font-medium text-slate-500",children:"Keywords limit"}),e.jsxs("div",{className:"group relative",children:[e.jsx(Hs,{size:13,className:"text-slate-400 hover:text-slate-600 cursor-help"}),e.jsxs("div",{className:"absolute left-full ml-2 top-1/2 -translate-y-1/2 px-3 py-2 bg-white border-2 border-slate-300 text-slate-700 text-xs rounded-lg opacity-0 invisible group-hover:opacity-100 group-hover:visible transition-all duration-200 w-
7756 z-50 shadow-lg",children:[e.jsx("div",{className:"font-medium mb-1 text-slate-800",children:"Ranked Keywords"}),e.jsx("div",{className:"text-slate-500 leading-relaxed",children:"Top-ranking keywords from each competitor. These represent great SEO opportunities for your site."}),e.jsx("div",{className:"absolute right-full top-1/2 -translate-y-1/2 w-0 h-0 border-t-4 border-b-4 border-r-4 border-transparent border-r-white"})]})]})]}),e.jsx("span",{className:"text-xs text-slate-500 tabular-nums",children:vn(aa(A))})]}),k?e.jsxs("div",{className:"space-y-2",children:[n&&e.jsx("div",{className:"text-xs text-red-600",children:n}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"grid grid-cols-3 gap-2",children:V.map(z=>{const U=_==="preset"&&C===z;return e.jsx("button",{type:"button",onClick:()=>{E("preset"),P(z)},className:`w-full flex items-center justify-between gap-3 px-3 py-2 rounded-md border transition-colors ${U?"border-blue-600 bg-blue-50":"border-slate-200 bg-white hover:bg-slate-50"}`,children:e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx("span",{className:`w-4 h-4 rounded-full border flex-shrink-0 ${U?"border-blue-600":"border-slate-300"}`,children:e.jsx("span",{className:`block w-2 h-2 rounded-full mx-auto mt-[3px] ${U?"bg-blue-600":"bg-transparent"}`})}),e.jsx("span",{className:`text-sm ${U?"text-blue-700":"text-slate-700"}`,children:vn(z)})]})},z)})}),e.jsxs("div",{className:`w-full flex items-center gap-3 px-3 py-2 rounded-md border transition-colors ${_==="custom"?"border-blue-600 bg-blue-50":"border-slate-200 bg-white hover:bg-slate-50"}`,children:[e.jsxs("button",{type:"button",onClick:()=>{E("custom");const z=aa(t.keywordsLimit);u(String(z))},className:"flex items-center gap-2 pt-1",children:[e.jsx("span",{className:`w-4 h-4 rounded-full border flex-shrink-0 ${_==="custom"?"border-blue-600":"border-slate-300"}`,children:e.jsx("span",{className:`block w-2 h-2 rounded-full mx-auto mt-[3px] ${_==="custom"?"bg-blue-600":"bg-transparent"}`})}),e.jsx("span",{className:`text-sm ${_==="custom"?"text-blue-700":"text-slate-700"}`,children:"Custom"})]}),e.jsx("div",{className:"flex-1 flex items-center gap-2",children:e.jsx(bt,{inputMode:"numeric",placeholder:"Max 1000",value:x,onFocus:()=>{if(_==="custom")return;E("custom");const z=aa(t.keywordsLimit);u(U=>String(U||"").trim()?U:String(z))},onChange:z=>u(z.target.value),onBlur:()=>{_==="custom"&&B()},onKeyDown:z=>{if(z.key==="Enter"){if(z.preventDefault(),_!=="custom")return;B()}}})})]})]})]}):e.jsx("span",{className:"text-xs text-slate-400",children:"Not applicable"}),e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Kt,{checked:F,onCheckedChange:z=>R(z===!0),id:"force-sync-keywords",disabled:!k}),e.jsxs("label",{htmlFor:"force-sync-keywords",className:`text-sm cursor-pointer leading-snug ${k?"text-slate-700":"text-slate-400"}`,children:["Force refresh"," ",e.jsx("span",{className:"text-xs text-slate-400",children:"(ignores 7-day cache)"})]})]})]})]})]}),e.jsxs("div",{className:"p-4 bg-amber-50 border border-amber-200 rounded-lg",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(vs,{className:"w-4 h-4 text-amber-600 flex-shrink-0"}),e.jsx("div",{className:"text-sm font-semibold text-amber-800",children:"Estimated cost"})]}),e.jsxs("div",{className:"mt-2 text-sm text-amber-700",children:[q.estimating?e.jsxs("span",{className:"font-semibold flex items-center gap-2",children:[e.jsx(He,{className:"w-4 h-4 animate-spin"}),"Estimating..."]}):q.estimatedRange?e.jsxs("span",{className:"font-semibold",children:[T.totalMin===T.totalMax?`${vn(T.totalMin)}`:`${vn(T.totalMin)}-${vn(T.totalMax)}`," ","credits"]}):e.jsx("span",{className:"font-semibold",children:"Estimate unavailable"}),e.jsxs("div",{className:"text-xs text-amber-600 mt-1",children:[h.size," domain",h.size===1?"":"s"," ×"," ",q.estimatedRange?`${ww(T.perDomainMin,T.perDomainMax)} credits`:"N/A"]})]})]})]}),e.jsx("div",{className:"mt-4 sm:mt-0 flex-1 overflow-hidden w-[50%]",children:e.jsxs("div",{className:"bg-white border border-slate-200 rounded-lg overflow-hidden flex flex-col h-full min-h-0",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 px-3 py-2 bg-slate-50 border-b border-slate-200",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Kt,{checked:h.size===d.length&&d.length>0,onCheckedChange:X}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-sm font-medium text-slate-700 leading-tight",children:"Select all"}),e.jsxs("div",{className:"text-xs text-slate-500 leading-snug",children:[h.size,"/",d.length," selected"]})]})]}),e.jsx("div",{className:"text-xs text-slate-500 flex-shrink-0",children:"Last synced"})]}),e.jsx("div",{className:"flex-1 overflow-y-auto",children:e.jsx("div",{className:"divide-y divide-slate-100",children:c.map(z=>e.jsxs("div",{className:`flex items-center gap-3 px-3 py-2 hover:bg-slate-50 ${z.isSelf?"bg-blue-50/60 hover:bg-blue-50":""}`,children:[e.jsx(Kt,{checked:h.has(z.domain),onCheckedChange:()=>K(z.domain)}),e.jsxs("div",{className:"flex-1 min-w-0 flex items-center justify-between gap-3",children:[e.jsx("label",{className:`text-sm cursor-pointer truncate ${z.isSelf?"text-slate-800":"text-slate-700"} ${z.isSelf?"flex items-center gap-2":""}`,children:z.isSelf?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-[10px] font-semibold px-1.5 py-0.5 rounded bg-blue-600 text-white",children:"YOU"}),e.jsx("span",{className:"truncate",children:z.domain})]}):z.domain}),e.jsx("span",{className:"text-xs text-slate-500 tabular-nums flex-shrink-0",children:z.lastSyncedAt?new Date(z.lastSyncedAt).toLocaleDateString("en-US",{year:"numeric",month:"short",day:"numeric"}):"Never"})]})]},`${z.isSelf?"__self__":"__domain__"}${z.domain}`))})})]})})]})}),e.jsxs(Ns,{children:[e.jsx(be,{variant:"outline",onClick:()=>t.onOpenChange(!1),disabled:t.isRunning||g,children:"Close"}),t.onSaveSetting&&e.jsx(be,{variant:"outline",onClick:Z,disabled:t.isRunning||g,children:g?e.jsxs(e.Fragment,{children:[e.jsx(He,{className:"w-4 h-4 mr-2 animate-spin"}),"Saving..."]}):se}),e.jsx(be,{onClick:M,disabled:h.size===0||t.isRunning||g||!H,className:"bg-slate-900 hover:bg-slate-800",children:t.isRunning?e.jsxs(e.Fragment,{children:[e.jsx(He,{className:"w-4 h-4 mr-2 animate-spin"}),"Syncing..."]}):`${fe}`})]})]})})}function Io(t){const s=v.useRef(null),a=v.useRef(!1),n=v.useRef(!1),o=v.useRef(null),i=v.useRef(null),[l,c]=v.useState({phase:"idle",startedAtMs:null,etaText:null,progress:null,message:"",syncStatus:void 0}),d=v.useRef(l);v.useEffect(()=>{d.current=l},[l]);const m=v.useCallback(()=>{s.current&&(window.clearTimeout(s.current),s.current=null),o.current&&(window.clearInterval(o.current),o.current=null),i.current=null},[]),h=v.useCallback(()=>{m(),c({phase:"idle",startedAtMs:null,etaText:null,progress:null,message:"",syncStatus:void 0}),a.current=!1,n.current=!1},[m]),p=v.useCallback(x=>{c(x),s.current&&window.clearTimeout(s.current),s.current=window.setTimeout(()=>{h()},4e3)},[h]),f=v.useCallback(x=>{if(d.current.phase==="running"){t.toast({title:"Sync already running",description:"Please wait for the current sync to finish"});return}a.current=!1,n.current=!0;const g=Date.now();c({phase:"running",startedAtMs:g,etaText:x||"2-5 min",progress:{completed:0,total:100,percentage:0},message:"Waiting for sync to start...",syncStatus:"syncing"})},[t]),b=v.useCallback(x=>{if(x==="timeout"){if(d.current,!n.current)return;h(),t.toast({title:"Sync not detected",description:"No active sync detected. Please try again."});return}if(!x){const u=d.current;u.phase==="running"&&(a.current||n.current)&&(p({phase:"completed",startedAtMs:u.startedAtMs||Date.now(),etaText:u.etaText,progress:{completed:100,total:100,percentage:100},message:"Sync completed",syncStatus:"completed"}),t.toast({title:"Competitors sync completed successfully"}));return}if(x==="syncing"||x==="syncing_rank_overview"||x==="syncing_keywords"){a.current=!0;let u={completed:0,total:100,percentage:0},g="Syncing competitors...";x==="syncing_rank_overview"?(u={completed:33,total:100,percentage:33},g="Step 1/2: Syncing rank overview..."):x==="syncing_keywords"?(u={completed:66,total:100,percentage:66},g="Step 2/2: Syncing keywords..."):x==="syncing"&&(u={completed:10,total:100,percentage:10},g="Syncing competitors..."),c(w=>({...w,phase:"running",startedAtMs:w.startedAtMs||Date.now(),etaText:w.etaText||"2-5 min",progress:u,message:g,syncStatus:x}))}else if(x==="completed"||x==="success"){if(d.current.phase!=="running"||!a.current&&!n.current)return;h(),t.toast({title:"Competitors sync completed successfully"})}else if(x==="failed"||x==="error"){if(d.current.phase!=="running"||!a.current&&!n.current)return;h(),t.toast({title:"Failed to sync competitors",description:"Please try again later"})}},[p,t,h]),y=v.useCallback(async x=>{const u=String(x.taskId||"").trim();if(!u){t.toast({title:"Failed to start sync",description:"Missing task id"});return}m(),f(x.etaText),i.current=u;const g=async()=>{try{const w=await _c(u);if(w.status==="processing"){c(_=>{const E=Number(w.total||0),N=Number(w.progress||0),S=E>0?Math.min(100,Math.round(N/E*100)):0,k=[w.current_step,w.message].filter(
77Boolean);return{..._,phase:"running",progress:{completed:N,total:E,percentage:S},message:k.join(" - ")||"Syncing...",syncStatus:"syncing"}});return}if(w.status==="done"){try{await t.onCompleted()}catch(_){console.warn("⚠️ Failed to refresh after competitors sync:",_)}m(),p({phase:"completed",startedAtMs:d.current.startedAtMs||Date.now(),etaText:d.current.etaText,progress:{completed:w.total||0,total:w.total||0,percentage:100},message:"Sync completed",syncStatus:"completed"}),t.toast({title:"Competitors sync completed successfully"});return}h(),t.toast({title:"Failed to sync competitors",description:w.error||"Unknown error"})}catch(w){console.error("❌ Failed to poll competitors sync task:",w),h(),t.toast({title:"Failed to fetch sync status",description:w?.message||"Unknown error"})}};await g(),o.current=window.setInterval(g,1500)},[m,t,h,f]);return v.useEffect(()=>()=>{m()},[m]),{panel:l,isRunning:l.phase==="running",startSync:f,startTask:y,updateSyncStatus:b}}const dl=t=>String(Math.max(0,Math.floor(t))).padStart(2,"0"),vw=t=>{const s=Math.max(0,Math.floor(t)),a=Math.floor(s/3600),n=Math.floor(s%3600/60),o=s%60;return a>0?`${a}:${dl(n)}:${dl(o)}`:`${n}:${dl(o)}`};function Mo(t){const[s,a]=v.useState(()=>Date.now());if(v.useEffect(()=>{if(t.state.phase!=="running")return;const p=window.setInterval(()=>a(Date.now()),1e3);return()=>window.clearInterval(p)},[t.state.phase]),t.state.phase==="idle")return null;const n=t.state.startedAtMs||s,o=(s-n)/1e3,i=vw(o),l=t.state.etaText||"1-5min",c=t.state.progress,d=c?.percentage??0,m=t.state.phase==="running"?e.jsx(kt,{className:"w-4 h-4 text-slate-500 animate-spin"}):t.state.phase==="completed"?e.jsx(Rs,{className:"w-4 h-4 text-emerald-600"}):e.jsx(Ja,{className:"w-4 h-4 text-amber-600"}),h=t.state.phase==="running"?"Syncing competitors in background":t.state.phase==="completed"?"Sync completed":t.state.phase==="timeout"?"Sync timeout":"Sync finished";return e.jsx("div",{className:"w-full bg-white border border-slate-200 rounded-lg px-3 py-2 shadow-sm",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-[170px]",children:[m,e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[11px] font-semibold text-slate-800 truncate",children:h}),e.jsx("div",{className:"text-[10px] text-slate-500 truncate",children:t.state.message||" "})]})]}),e.jsx("div",{className:"flex-1 min-w-[160px]",children:e.jsx("div",{className:"w-full bg-slate-200 rounded-full h-2 overflow-hidden",children:e.jsx("div",{className:"h-full bg-blue-600 transition-all duration-300 ease-out rounded-full",style:{width:`${d}%`}})})}),e.jsxs("div",{className:"flex items-center gap-3 text-[10px] text-slate-500 flex-shrink-0",children:[e.jsxs("span",{className:"whitespace-nowrap",children:["Est. ",e.jsx("span",{className:"font-medium text-slate-700",children:l})]}),e.jsx("span",{className:"whitespace-nowrap",children:c&&c.total>0?`${c.completed}/${c.total} (${d}%)`:`${d}%`}),e.jsxs("span",{className:"flex items-center gap-1 whitespace-nowrap",children:[e.jsx(Ra,{className:"w-3.5 h-3.5 text-slate-400"}),i]})]})]})})}function Nw({domain:t}){const{toast:s}=_t(),[a,n]=r.useState(!0),[o,i]=r.useState(null),[l,c]=r.useState(null),[d,m]=r.useState([]),[h,p]=r.useState(!1),[f,b]=r.useState(!1),[y,x]=r.useState(Ir()),[u,g]=r.useState(Ir()),[w,_]=r.useState(!1);r.useEffect(()=>{let V=!1;return(async()=>{try{const C=(await Eo())?.competitor_ranked_keywords_limit;if(V)return;typeof C=="number"&&Number.isFinite(C)&&(x(C),Rn(C))}catch(A){console.warn("⚠️ Failed to load competitors keywords limit:",A)}})(),()=>{V=!0}},[]);const E=async V=>{try{const A=(await Ao(V))?.competitor_ranked_keywords_limit??V;return Rn(A),x(A),s({title:"Settings saved",description:`Competitor ranked keywords limit updated to Top ${A}.`}),A}catch(P){throw console.error("❌ Failed to save keywords limit:",P),s({title:"Error",description:P?.message||"Failed to save settings"}),P}};r.useEffect(()=>{let V=!0;return(async()=>{try{n(!0),i(null);const A=ma(),C=A.length>0?(await vi(t,$a(A))).aggregated:await $l(t);V&&(c(C),m(C.keywords_data||[]))}catch(A){V&&i(A.message||"Failed to load competitor data")}finally{V&&n(!1)}})(),()=>{V=!1}},[t]);const N=async()=>{try{i(null);const V=ma(),P=V.length>0?(await vi(t,$a(V))).aggregated:await $l(t);c(P),m(P.keywords_data||[])}catch(V){i(V.message||"Failed to load competitor data")}},S=async V=>{const P=Math.max(0,Math.floor(V));P>0&&await new Promise(A=>window.setTimeout(A,P)),await N()},k=Io({toast:s,onCompleted:async()=>{await N()}}),D=r.useMemo(()=>!l||d.length===0?0:d.filter(V=>V.my_rank!=null&&V.rank!=null).length,[d,l]),F=r.useMemo(()=>
77{if(!l||D===0)return 0;const V=Math.max(l.keywords||1,1);return Math.round(D/V*100)},[D,l]),R=r.useMemo(()=>Af(F),[F]),L=()=>{p(!0)},$=()=>{g(y),_(!0)},H=async V=>{if(l)try{b(!0),p(!1);const P=[V.syncRankOverview&&"rank overview",V.syncRankedKeywords&&"ranked keywords"].filter(Boolean).join(" + "),{creditEstimateService:A}=await Bt(async()=>{const{creditEstimateService:Z}=await Promise.resolve().then(()=>Ya);return{creditEstimateService:Z}},void 0),{validateCreditBalance:C}=await Bt(async()=>{const{validateCreditBalance:Z}=await Promise.resolve().then(()=>ua);return{validateCreditBalance:Z}},void 0);let I=1;try{const Z=await La(),B=Array.isArray(Z?.markets)&&Z.markets.length>0?Z.markets.length:1;I=Math.max(1,Number(B)||1)}catch{I=1}const j=await A.estimateCredits({scenario:"domainseo_batch_sync_competitors",params:{markets_count:I,targets_count:1,competitor_targets_count:1,keywords_limit:y,sync_rank_overview:V.syncRankOverview,sync_ranked_keywords:V.syncRankedKeywords}});if(!await C({estimatedRange:j?{min:j.estimated_min_credits,max:j.estimated_max_credits}:null,requiredMinimumBalance:j?.required_minimum_balance??null,toast:s}))return;s({title:"Refreshing Competitor",description:`Updating ${P} for ${l.competitor}...`});const T=await Er([l.competitor],V.forceSyncKeywords,y,V.syncRankOverview,V.syncRankedKeywords),M=T?.task_id?String(T.task_id):"";if(M){await k.startTask({taskId:M,etaText:"2-5 min"});return}await S(2e3),s({title:"Sync started",description:"Competitor sync triggered."})}catch(P){console.error("❌ Failed to refresh competitor:",P),s({title:"Error",description:P.message||"Failed to refresh competitor"})}finally{b(!1)}},K=()=>{window.history.back()},X=r.useMemo(()=>{const V=l?.keywords_last_updated_at||l?.last_synced_at||"";if(!V)return"Never";try{return new Date(V).toLocaleDateString("en-CA")}catch{return"Never"}},[l?.keywords_last_updated_at,l?.last_synced_at]);return a?e.jsx("div",{className:"h-full flex items-center justify-center",children:e.jsxs("div",{className:"text-center",children:[e.jsx(He,{className:"h-8 w-8 animate-spin text-slate-400 mx-auto"}),e.jsx("p",{className:"mt-4 text-slate-600",children:"Loading competitor data..."})]})}):o||!l?e.jsx("div",{className:"h-full flex items-center justify-center",children:e.jsxs("div",{className:"text-center max-w-md",children:[e.jsx("div",{className:"w-12 h-12 bg-red-100 rounded-full flex items-center justify-center mx-auto mb-4",children:e.jsx("div",{className:"h-6 w-6 text-red-500"})}),e.jsx("h3",{className:"text-lg font-semibold text-slate-800 mb-2",children:"Unable to Load Data"}),e.jsx("p",{className:"text-slate-600 mb-4",children:o||"Competitor not found"}),e.jsx("button",{onClick:K,className:"px-4 py-2 text-sm bg-slate-900 text-white rounded-lg hover:bg-slate-800",children:"Back to Competitors"})]})}):e.jsxs("div",{className:"h-full overflow-auto p-4",children:[e.jsxs("div",{className:"flex flex-col h-full min-h-0 space-y-6",children:[e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("button",{onClick:K,className:"p-2 hover:bg-slate-100 rounded-lg transition-colors",children:e.jsx(un,{size:20,className:"text-slate-600"})}),e.jsx("div",{className:"flex items-start gap-3 flex-1",children:e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h2",{className:"text-lg font-semibold text-slate-800",children:l.competitor}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"flex items-center gap-1.5 px-2 py-1 bg-slate-50 border border-slate-200 rounded-lg","data-onboarding":"competitors-keywords-limit",children:[e.jsx("span",{className:"text-xs text-slate-600",children:"Ranked keywords limit:"}),e.jsx("span",{className:"text-xs font-semibold text-slate-800",children:y}),e.jsx("button",{type:"button",onClick:$,className:"text-xs font-medium text-blue-600 hover:text-blue-700 hover:underline ml-1",children:"Increase"})]}),e.jsx(be,{onClick:L,disabled:f||k.isRunning,variant:"outline",size:"sm",className:"flex items-center gap-2 bg-white",children:f||k.isRunning?e.jsxs(e.Fragment,{children:[e.jsx(He,{className:"w-4 h-4 animate-spin"}),"Refreshing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(kt,{className:"w-4 h-4"}),"Refresh"]})})]})]}),e.jsxs("div",{className:"flex items-center gap-4 text-xs text-slate-500",children:[e.jsxs("span",{children:[e.jsx("span",{className:"font-medium text-slate-700",children:jo(l.keywords)})," ","keywords"]}),e.jsxs("span",{children:[e.jsx("span",{className:"font-medium text-slate-700",children:X})," ","last refreshed"]}),e.jsxs("span",{className:"px-2 py-0.5 rounded font-medium",style:{backgroundColor:R.light,color:R.text},children:[jo(D)," overlap (",F,"%)"]})]})]})})]}),k.panel.phase!=="idle"&&e.jsx("div",{className:"bg-slate-50 rounded-lg p-3 border border-slate-100",children:e.jsx(Mo,{state:k.panel})}),e.jsx(xw,{competitorDomain:l.competitor,prefetchedKeywords:d,onRefresh:L,showEtvColumns:!1,showKeywordLastUpdatedColumn:!0})]}),e.jsx(zc,{open:w,onOpenChange:_,mode:"full",scopeBehavior:"all",keywordsLimit:u,onKeywordsLimitChange:g,onSaveSetting:async V=>{const P=await E(V);g(P)},saveSettingText:"Save setting",isRunning:k.isRunning,confirmText:"Save & Refresh",domains:[{domain:l.competitor,lastSyncedAt:l.last_synced_at??null}],onConfirm:async V=>{_(!1);try{if(!ea()){s({title:"Market required",description:"Please select a market before syncing competitors."});return}const{creditEstimateService:P}=await Bt(async()=>{const{creditEstimateService:Z}=await Promise.resolve().then(()=>Ya);return{creditEstimateService:Z}},void 0),{validateCreditBalance:A}=await Bt(async()=>{const{validateCreditBalance:Z}=await Promise.resolve().then(()=>ua);return{validateCreditBalance:Z}},void 0);let C=1;try{const Z=await La(),B=Array.isArray(Z?.markets)&&Z.markets.length>0?Z.markets.length:1;C=Math.max(1,Number(B)||1)}catch{C=1}const I=(V.domains?.length||0)+(V.includeSelf?1:0),j=await P.estimateCredits({scenario:"domainseo_batch_sync_competitors",params:{markets_count:C,targets_count:Math.max(1,I),competitor_targets_count:Math.max(0,V.domains?.length||0),keywords_limit:V.keywordsLimit,sync_rank_overview:V.syncRankOverview,sync_ranked_keywords:V.syncRankedKeywords,force_sync_keywords:!!V.forceSyncKeywords}});if(!await A({estimatedRange:j?{min:j.estimated_min_credits,max:j.estimated_max_credits}:null,requiredMinimumBalance:j?.required_minimum_balance??null,toast:s}))return;const T=await Er(V.domains,V.forceSyncKeywords,V.keywordsLimit,V.syncRankOverview,V.syncRankedKeywords,V.includeSelf),M=T?.task_id?String(T.task_id):"";if(M){await k.startTask({taskId:M,etaText:"2-5 min"});return}await S(2e3)}catch(P){console.error("❌ Failed to sync competitor:",P),s({title:"Error",description:P?.message||"Failed to sync competitor"})}}}),l&&e.jsx(bw,{open:h,onOpenChange:p,competitorDomain:l.competitor,keywordsLimit:y,onConfirm:H,isRefreshing:f||k.isRunning})]})}const kw={async getBootstrap(){return await ot("/seo_flow/bootstrap")},async generateSeedKeywordIdeas(t){return await Je("/seo_flow/seed_keyword_ideas/generate",t)},async generateKeywordIdeas(t){return await Je("/seo_flow/keyword_ideas/generate",t)},async getLatestKeywordIdeas(){return await ot("/seo_flow/keyword_ideas/latest")},async getCompetitorsRankedKeywords(t,s){return await Je("/seo_flow/competitors_ranked_keywords",t,{params:s})},async addCompetitorsAndSync(t,s){return await Je("/seo_flow/competitors/add_and_sync",t,{params:s})},async discoverCompetitors(t){return await Je("/seo_flow/competitors/discover",t)},async discoverCompetitorsAsync(t){return await Je("/seo_flow/competitors/discover_async",t)},async getDiscoverCompetitorsStatus(t){return await ot("/seo_flow/competitors/discover_status",{task_id:t})},async addCompetitors(t){return await Je("/seo_flow/competitors/add",t)},async listTargetKeywords(t){return await ot("/seo_flow/target_keywords/list",t)},async getTargetKeywordLandingPages(t,s){return await Je("/seo_flow/target_keywords/landing_pages",t,{params:s})},async upsertTargetKeywordsBatch(t){return await Je("/seo_flow/target_keywords/upsert_batch",t)},async batchDeleteTargetKeywords(t){return await Je("/seo_flow/target_keywords/batch_delete",t)},async getContextLatest(){return await ot("/seo_flow/context/latest")},async clearContext(){return await Je("/seo_flow/context/clear",{})},async saveContext(t){return await Je("/seo_flow/context/save",t)},async generateContextTopics(t){return await Je("/seo_flow/context/generate_topics",t)}};function Jd(t){const s=String(t||"").trim().toLowerCase();if(!s)return"";try{if(s.includes("://")){const o=new URL(s);return String(o.hostname||"").replace(/^www\./,"").trim().toLowerCase()}}catch{}return(s.replace(/^[a-z]+:\/\//i,"").split(/[/?#]/)[0]||"").replace(/^www\./,"").trim().toLowerCase()}function _w(t){const s=new Set((t.existingCompetitors||[]).map(i=>
77Jd(i)).filter(Boolean)),a=new Set,n=[],o=String(t.text||"").split(/[\n,\s]+/).map(i=>i.trim()).filter(Boolean);for(const i of o){const l=Jd(i);l&&(s.has(l)||a.has(l)||(a.add(l),n.push(l)))}return n}function Ix({open:t,onOpenChange:s,existingCompetitors:a,competitorsLimit:n,currentCount:o,keywordsLimit:i=100,onSuccess:l,api:c="domain_seo"}){const{toast:d}=_t(),[m,h]=r.useState("url"),[p,f]=r.useState(""),[b,y]=r.useState(3),[x,u]=r.useState(!1),[g,w]=r.useState(1);r.useEffect(()=>{if(!t)return;let H=!1;return(async()=>{try{const X=await La(),V=Array.isArray(X?.markets)?X.markets.length:1;if(H)return;w(Math.max(1,Number(V)||1))}catch(X){console.warn("⚠️ Failed to load track markets for credit estimate:",X),H||w(1)}})(),()=>{H=!0}},[t]);const _=r.useMemo(()=>m!=="url"?[]:_w({text:p,existingCompetitors:a}),[a,m,p]),E=r.useMemo(()=>m==="url"?_.length:Math.max(0,Number(b)||0),[b,m,_.length]),N=r.useMemo(()=>{const H=Math.max(0,Number(n)||0),K=Math.max(0,Number(o)||0);return Math.max(0,H-K)},[n,o]),S=r.useMemo(()=>(Number(n)||0)>0,[n]),k=r.useMemo(()=>S?E>N:!1,[E,S,N]),D=ta({enabled:t&&E>0,scenario:"domainseo_sync_new_competitors",params:{markets_count:Math.max(1,Number(g)||1),competitor_count:E,keywords_limit:Math.max(10,Math.min(1e3,Math.round(i))),include_overview:!0,include_ranked_keywords:!0,discovered_by_ai:m==="ai"}}),F=r.useMemo(()=>{const H=D.estimatedRange;return{estimating:D.estimating,estimatedRange:H,requiredMinimumBalance:D.requiredMinimumBalance}},[D.estimating,D.estimatedRange,D.requiredMinimumBalance]),R=r.useCallback(()=>{x||(s(!1),f(""),y(3),h("url"))},[x,s]),L=async()=>{if(!p.trim()){d({title:"Error",description:"Please enter at least one URL"});return}const H=_;if(H.length===0){d({title:"Error",description:"Please enter valid competitor domains"});return}if(S&&H.length>N){d({title:"Plan limit exceeded",description:`Remaining competitor slots: ${N}.`});return}const{validateCreditBalance:K}=await Bt(async()=>{const{validateCreditBalance:V}=await Promise.resolve().then(()=>ua);return{validateCreditBalance:V}},void 0);if(await K({estimatedRange:F.estimatedRange,requiredMinimumBalance:F.requiredMinimumBalance,toast:d}))try{u(!0);const V=ea(),P=c==="seo_flow"?await kw.addCompetitorsAndSync({urls:H,keywords_limit:i},V?{location_id:V.location_id,location_code:V.location_code,language_code:V.language_code}:void 0):await Fl({urls:H});d({title:"Success",description:P.message}),l?.(P.task_id),R()}catch(V){d({title:"Error",description:V.message||"Failed to add competitors"})}finally{u(!1)}},$=async()=>{if(b<=0){d({title:"Error",description:"Please select at least 1 competitor to discover"});return}if(S&&b>N){d({title:"Plan limit exceeded",description:`Remaining competitor slots: ${N}.`});return}const{validateCreditBalance:H}=await Bt(async()=>{const{validateCreditBalance:X}=await Promise.resolve().then(()=>ua);return{validateCreditBalance:X}},void 0);if(await H({estimatedRange:F.estimatedRange,requiredMinimumBalance:F.requiredMinimumBalance,toast:d}))try{u(!0);const X=await Fl({discoverCount:b});d({title:"Success",description:X.message}),l?.(X.task_id),R()}catch(X){d({title:"Error",description:X.message||"Failed to discover competitors"})}finally{u(!1)}};return t?e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4",onClick:R,children:e.jsxs("div",{className:"bg-white rounded-xl shadow-2xl max-w-sm w-full relative",onClick:H=>H.stopPropagation(),children:[e.jsx("button",{onClick:R,disabled:x,className:"absolute top-3 right-3 text-slate-400 hover:text-slate-600 p-1 hover:bg-slate-100 rounded-full disabled:opacity-50",children:e.jsx(mt,{className:"h-4 w-4"})}),e.jsxs("div",{className:"p-5 pb-3",children:[e.jsx("h2",{className:"text-lg font-semibold text-slate-900",children:"Add Competitors"}),S&&e.jsxs("div",{className:"mt-1 text-[11px] text-slate-500",children:["Remaining competitor slots:"," ",e.jsx("span",{className:"font-semibold text-slate-800 tabular-nums",children:N})]})]}),e.jsx("div",{className:"px-5 border-b border-slate-100",children:e.jsxs("div",{className:"flex gap-1",children:[e.jsxs("button",{onClick:()=>h("url"),disabled:x,className:`px-3 py-2 text-xs font-medium rounded-t transition-colors flex items-center gap-1.5 ${m==="url"?"bg-slate-100 text-slate-900 border-b-2 border-slate-800":"text-slate-500 hover:text-slate-700"}`,children:[e.jsx(Qt,{size:14}),"URL"]}),e.jsxs("button",{onClick:()=>h("ai"),disabled:x,className:`px-3 py-2 text-xs font-medium rounded-t transition-colors flex items-center gap-1.5 ${m==="ai"?"bg-slate-100 text-slate-900 border-b-2 border-slate-800":"text-slate-500 hover:text-slate-700"}`,children:[e.jsx(Ks,{size:14}),"AI Discovery"]})]})}),e.jsxs("div",{className:"p-5 space-y-3",children:[m==="url"?e.jsxs("div",{className:"space-y-3",children:[e.jsx("textarea",{value:p,onChange:H=>f(H.target.value),disabled:x,placeholder:`competitor1.com
78competitor2.com`,className:"w-full h-24 px-3 py-2 text-sm border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-slate-500 focus:border-transparent resize-none disabled:bg-slate-50"}),a.length>0&&e.jsxs("div",{className:"flex flex-wrap gap-1",children:[a.slice(0,4).map(H=>e.jsx("span",{className:"px-1.5 py-0.5 text-[10px] bg-slate-100 text-slate-500 rounded",children:H},H)),a.length>4&&e.jsxs("span",{className:"px-1.5 py-0.5 text-[10px] bg-slate-100 text-slate-400 rounded",children:["+",a.length-4]})]})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("input",{type:"range",min:1,max:S?Math.max(1,Math.min(10,N)):10,value:b,onChange:H=>y(Number(H.target.value)),disabled:x,className:"flex-1 h-1.5 bg-slate-200 rounded-lg appearance-none cursor-pointer accent-slate-800 disabled:opacity-50"}),e.jsx("span",{className:"text-base font-semibold text-slate-800 w-6 text-center",children:b})]}),a.length>0&&e.jsxs("div",{className:"flex flex-wrap gap-1",children:[a.slice(0,4).map(H=>e.jsx("span",{className:"px-1.5 py-0.5 text-[10px] bg-slate-100 text-slate-500 rounded",children:H},H)),a.length>4&&e.jsxs("span",{className:"px-1.5 py-0.5 text-[10px] bg-slate-100 text-slate-400 rounded",children:["+",a.length-4]})]})]}),E>0&&e.jsxs("div",{className:"flex items-start gap-3 p-3 bg-amber-50 border border-amber-200 rounded-lg",children:[e.jsx(vs,{className:"w-4 h-4 text-amber-600 flex-shrink-0 mt-0.5"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-xs font-medium text-amber-800",children:"This action will consume credits"}),e.jsxs("p",{className:"text-xs text-amber-700 mt-0.5",children:["Estimated cost:"," ",e.jsx("strong",{children:F.estimating?"Estimating...":F.estimatedRange?F.estimatedRange.min===F.estimatedRange.max?`${F.estimatedRange.max} credits`:`${F.estimatedRange.min}-${F.estimatedRange.max} credits`:"Estimate unavailable"})," ","for ",E," competitor",E!==1?"s":"",g>1?` across ${g} markets`:` across ${g} market`]})]})]})]}),e.jsxs("div",{className:"px-5 pb-5 flex gap-2",children:[e.jsx("button",{onClick:R,disabled:x,className:"flex-1 py-2 px-3 text-xs font-medium text-slate-600 bg-slate-100 hover:bg-slate-200 rounded-lg transition-colors disabled:opacity-50",children:"Cancel"}),e.jsx("button",{onClick:m==="url"?L:$,disabled:x||k||(m==="url"?_.length===0:b<=0||S&&N===0),className:"flex-1 py-2 px-3 text-xs font-medium text-white bg-slate-800 hover:bg-slate-700 rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-1.5",children:x?e.jsxs(e.Fragment,{children:[e.jsx(He,{className:"h-3.5 w-3.5 animate-spin"}),e.jsx("span",{children:m==="url"?"Adding...":"Discovering..."})]}):e.jsxs(e.Fragment,{children:[e.jsx($t,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:m==="url"?"Add":"Discover"})]})})]})]})}):null}const Mx=({competitorsData:t,userDomain:s,onDataChange:a,onKeywordsSyncStarted:n,onCompetitorsAdded:o,className:i="",isWidgetMode:l=!1,onViewAll:c,hideActions:d=!1})=>{const{toast:m}=_t(),[h,p]=r.useState(!1),[f,b]=r.useState(!1),[y,x]=r.useState(null),[u,g]=r.useState(Ir()),[w,_]=r.useState(Ir()),[E,N]=r.useState(1);r.useEffect(()=>{let fe=!1;return(async()=>{try{const U=(await Eo())?.competitor_ranked_keywords_limit;if(fe)return;typeof U=="number"&&Number.isFinite(U)&&(g(U),Rn(U))}catch(z){console.warn("⚠️ Failed to load competitors keywords limit:",z)}})(),()=>{fe=!0}},[]),r.useEffect(()=>{let fe=!1;return(async()=>{try{const z=await La();try{if(!ea()){const me=z?.primary_market||null,le=Array.isArray(z?.markets)?z.markets[0]:null,O=me||le||null;O&&tr({location_id:O.id?String(O.id):void 0,location_code:Number(O.location_code),language_code:String(O.language_code)},{emit:!0})}}catch(Q){console.warn("⚠️ Failed to init selected market:",Q)}const U=Array.isArray(z?.markets)&&z.markets.length>0?z.markets.length:1;if(fe)return;N(Math.max(1,Number(U)||1))}catch(z){console.warn("⚠️ Failed to load track markets for credit estimate:",z),fe||N(1)}})(),()=>{fe=!0}},[]);const[S,k]=r.useState(null),[D,F]=r.useState(""),[R,L]=r.useState(!1),[$,H]=r.useState(!1),[K,X]=r.useState(new Set),V=r.useMemo(()=>t?.details?t.details:[],[t]),P=fe=>new Intl.NumberFormat("en-US").format(fe),A=(fe,se)=>{const z=P(fe),U=P(se);return fe===se?`${z}`:`${z}-${U}`},C=ta({enabled:!0,scenario:"domainseo_batch_sync_competitors",params:{markets_count:E,targets_count:1,competitor_targets_count:1,keywords_limit:Math.max(10,Math.min(1e3,Math.round(u))),sync_rank_overview:!0,sync_ranked_keywords:!0,force_sync_keywords:!0}}),I=r.useMemo(()=>V.map(fe=>{const se=Math.max((fe.keywords||0)-(fe.shared_keywords||0),0),z=fe.keywords&&fe.keywords>0?Math.round(se/fe.keywords*100):0;return{...fe,distinct_keywords:se,distinct_percent:z}}),[V]),j=r.useMemo(()=>{const fe=[],se=s?.domain?String(s.domain).trim():"";se&&fe.push({domain:se,lastSyncedAt:s?.lastSyncedAt??null,isSelf:!0});for(const z of V)fe.push({domain:z.competitor,lastSyncedAt:z.last_synced_at??null});return fe},[V,s?.domain,s?.lastSyncedAt]),q=fe=>{k(fe),F("")},T=async()=>
78{if(S&&D===S)try{L(!0),await ex(S),m({title:"Competitor Deleted",description:`${S} has been removed.`}),k(null),a()}catch(fe){console.error("❌ Failed to delete competitor:",fe),m({title:"Error",description:fe.message||"Failed to delete competitor"})}finally{L(!1)}},M=fe=>{if(o){o(fe);return}a()},Z=async fe=>{try{const z=(await Ao(fe))?.competitor_ranked_keywords_limit??fe;return Rn(z),g(z),z}catch(se){throw console.error("❌ Failed to save keywords limit:",se),m({title:"Error",description:se?.message||"Failed to save settings"}),se}},B=v.useCallback(()=>{const fe=V.length>0,z=!!(s?.domain?String(s.domain).trim():"");if(!fe&&!z){m({title:"No Competitors",description:"Please add competitors before syncing."});return}_(u),H(!0)},[V.length,u,m,s?.domain]),ae=()=>e.jsxs(e.Fragment,{children:[!d&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex sm:hidden items-center gap-2",children:[e.jsx("button",{onClick:()=>{B()},disabled:h||K.size>0,className:"flex items-center justify-center w-10 h-10 text-slate-500 bg-slate-100 rounded-xl hover:bg-slate-200 hover:text-slate-700 disabled:opacity-50 transition-all",title:"Refresh",children:e.jsx(kt,{className:`w-4 h-4 ${h||K.size>0?"animate-spin":""}`})}),e.jsx("button",{onClick:()=>b(!0),disabled:h,className:"flex items-center justify-center w-10 h-10 text-white bg-slate-900 rounded-xl hover:bg-slate-800 active:scale-[0.98] disabled:opacity-50 transition-all",title:"Add Competitors","data-onboarding":"competitors-add-btn",children:e.jsx($t,{className:"w-5 h-5"})})]}),e.jsxs("div",{className:"hidden sm:flex items-center gap-2",children:[e.jsxs("button",{onClick:()=>{B()},disabled:h||K.size>0,className:"flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium text-slate-600 bg-slate-100 hover:bg-slate-200 rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed",title:C.estimating?"Select competitors to refresh. Estimated cost: estimating...":C.estimatedRange?`Select competitors to refresh. Estimated cost: ${A(C.estimatedRange.min,C.estimatedRange.max)} credits per competitor`:"Select competitors to refresh. Estimated cost: unavailable",children:[e.jsx(kt,{size:14,className:h||K.size>0?"animate-spin":""}),e.jsx("span",{children:h||K.size>0?"Refreshing...":"Refresh"})]}),e.jsxs("button",{onClick:()=>b(!0),disabled:h,className:"flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium text-white bg-slate-800 hover:bg-slate-700 rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed",title:`Add more competitors (${t?.current_count||0}/${t?.competitors_limit||0})`,"data-onboarding":"competitors-add-btn",children:[e.jsx($t,{size:14}),e.jsx("span",{children:"Add"})]})]})]}),l&&c&&e.jsxs("button",{onClick:c,className:"flex items-center gap-1 text-xs text-slate-500 hover:text-slate-700 transition-colors",children:[e.jsx("span",{children:"View all"}),e.jsx(go,{size:12})]})]}),de=e.jsx("div",{"data-onboarding":"competitors-table",children:e.jsx(lx,{competitors:I,userDomain:s?.domain?{domain:s.domain,keywords:typeof s.keywords=="number"?s.keywords:null,traffic:typeof s.traffic=="number"?s.traffic:null}:void 0,onDeleteCompetitor:K.size>0?void 0:q,onCompetitorClick:fe=>{d?x(fe.competitor):eg(fe.competitor)},refreshingDomain:null,refreshingDomains:K})});return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:i,children:l?e.jsx(ii,{title:"Competitors",subtitle:`${V.length} tracked`,icon:Qs,headerActions:e.jsx(ae,{}),mobileInlineHeader:!0,children:de}):e.jsxs("div",{className:"bg-white border-y sm:border border-slate-200 sm:rounded-xl px-4 sm:px-6 py-4 sm:py-6",children:[e.jsxs("div",{className:"flex sm:hidden items-center justify-between mb-4",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(Qs,{className:"text-slate-500 shrink-0",size:18}),e.jsx("h3",{className:"text-base font-semibold text-slate-800 truncate",children:"Competitors Landscape"}),e.jsx("span",{className:"text-xs font-medium px-2 py-0.5 rounded-full bg-slate-100 text-slate-600 shrink-0",children:V.length})]}),e.jsx(ae,{})]}),e.jsxs("div",{className:"hidden sm:flex items-center justify-between mb-6",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Qs,{className:"text-slate-500",size:20}),e.jsx("h3",{className:"text-lg font-semibold text-slate-800",children:"Competitors Landscape"}),e.jsxs("span",{className:"text-xs font-medium px-2 py-0.5 rounded-full bg-slate-100 text-slate-600",children:[V.length," tracked"]})]}),e.jsx(ae,{})]}),de]})}),e.jsx(Ix,{open:f,onOpenChange:b,existingCompetitors:V.map(fe=>fe.competitor),competitorsLimit:t?.competitors_limit||0,currentCount:t?.current_count||0,keywordsLimit:u,onSuccess:M}),e.jsx(zc,{open:$,onOpenChange:H,mode:"full",scopeBehavior:"all",keywordsLimit:w,onKeywordsLimitChange:_,onSaveSetting:async fe=>{await Z(fe),_(fe)},saveSettingText:"Save setting",isRunning:K.size>0,confirmText:"Save & Refresh",domains:j,onConfirm:async fe=>
78{const se=fe.domains.length+(fe.includeSelf?1:0);if(se===0){m({title:"No Selection",description:"Please select at least one domain to sync."});return}H(!1);const z=s?.domain?String(s.domain).trim():"",U=[...fe.includeSelf&&z?[z]:[],...fe.domains];try{if(X(new Set(U)),!ea()){m({title:"Market required",description:"Please select a market before syncing competitors."}),X(new Set);return}const{creditEstimateService:Q}=await Bt(async()=>{const{creditEstimateService:ge}=await Promise.resolve().then(()=>Ya);return{creditEstimateService:ge}},void 0),{validateCreditBalance:me}=await Bt(async()=>{const{validateCreditBalance:ge}=await Promise.resolve().then(()=>ua);return{validateCreditBalance:ge}},void 0),le=await Q.estimateCredits({scenario:"domainseo_batch_sync_competitors",params:{markets_count:E,targets_count:se,competitor_targets_count:Array.isArray(fe.domains)?fe.domains.length:0,keywords_limit:fe.keywordsLimit,sync_rank_overview:fe.syncRankOverview,sync_ranked_keywords:fe.syncRankedKeywords}});if(!await me({estimatedRange:le?{min:le.estimated_min_credits,max:le.estimated_max_credits}:null,requiredMinimumBalance:le?.required_minimum_balance??null,toast:m})){X(new Set);return}m({title:"Syncing Competitors",description:`Updating ${fe.syncRankOverview&&fe.syncRankedKeywords?"rank overview + ranked keywords":fe.syncRankOverview?"rank overview":"ranked keywords"} for ${se} domain${se>1?"s":""}...`});const ne=await Er(fe.domains,fe.forceSyncKeywords,fe.keywordsLimit,fe.syncRankOverview,fe.syncRankedKeywords,fe.includeSelf);n?.(ne.task_id),setTimeout(()=>{a(),X(new Set)},2e3)}catch(Q){console.error("❌ Failed to sync competitors:",Q),m({title:"Error",description:Q.message||"Failed to sync competitors"}),X(new Set)}}}),e.jsx(Ht,{open:!!S,onOpenChange:fe=>!fe&&k(null),children:e.jsxs(qt,{className:"sm:max-w-md",children:[e.jsxs(Zt,{children:[e.jsxs(Yt,{className:"flex items-center gap-2 text-red-600",children:[e.jsx(Ja,{className:"w-5 h-5"}),"Delete Competitor"]}),e.jsx(Ds,{children:"This competitor will be hidden from the list. You can restore it later by adding it again. Historical data will be preserved."})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"p-3 bg-red-50 border border-red-100 rounded-md text-sm text-red-800",children:["Please type"," ",e.jsx("span",{className:"font-mono text-blue-600 hover:text-blue-700 hover:underline cursor-pointer select-all",onClick:()=>S&&F(S),title:"Click to auto-fill",children:S})," ","to confirm."]}),e.jsx(bt,{value:D,onChange:fe=>F(fe.target.value),placeholder:"Type domain to confirm",className:"font-mono"})]}),e.jsxs(Ns,{children:[e.jsx(be,{variant:"outline",onClick:()=>k(null),disabled:R,children:"Cancel"}),e.jsx(be,{onClick:T,disabled:R||D!==S,variant:"default",className:"bg-red-600 hover:bg-red-700 text-white",children:R?e.jsxs(e.Fragment,{children:[e.jsx(He,{className:"w-4 h-4 mr-2 animate-spin"}),"Deleting..."]}):"Delete Competitor"})]})]})}),e.jsx(Ht,{open:!!y,onOpenChange:fe=>!fe&&x(null),children:e.jsx(qt,{className:"max-w-[90vw] w-[1200px] max-h-[90vh] overflow-y-auto p-0",children:y&&e.jsxs("div",{className:"relative",children:[e.jsx("button",{onClick:()=>x(null),className:"absolute top-4 right-4 z-10 p-2 bg-white/80 hover:bg-white rounded-full shadow-sm border border-slate-200",children:e.jsx(go,{className:"w-4 h-4 rotate-[225deg]"})}),e.jsx(Nw,{domain:y})]})})})]})},Ro=async()=>await ot("/gsc_dashboard/sites"),Rx=async t=>await ot("/gsc_dashboard/summary",t),Cw=async t=>await ot("/gsc_dashboard/pages",t),Pa=async t=>{const s={...t};(s.dimension===null||s.dimension===void 0)&&delete s.dimension;const a=await ot("/gsc_dashboard/table_with_grouping",s);return s.dimension==="page",a},Sw=async t=>await ot("/gsc_dashboard/page_tracking_table",t),vr=864e5,ps=t=>t.toISOString().split("T")[0],Ew=t=>{const s=new Date(Date.UTC(t.getFullYear(),t.getMonth(),t.getDate())),a=s.getUTCDay()||7;s.setUTCDate(s.getUTCDate()+4-a);const n=new Date(Date.UTC(s.getUTCFullYear(),0,1));return Math.ceil(((s.getTime()-n.getTime())/vr+1)/7)},Dx=t=>{const s=new Date(t),a=s.getDay(),n=s.getDate()-a+(a===0?-6:1);return new Date(s.setDate(n))},Nn=t=>(t||"").trim().toLowerCase(),Lx=(t,s)=>{if(!t.from||!t.to)return[];const a=[],n=new Date(t.from),o=new Date(t.to);if(s==="weekly"){let l=Dx(n);for(;l<=o;){const c=new Date(l);c.setDate(c.getDate()+6);const d=Ew(l);a.push({period:`w${d}`,periodLabel:`w${d}
78`,periodStart:ps(l),periodEnd:ps(c),rank:null,status:"no_data"}),l=new Date(l),l.setDate(l.getDate()+7)}return a}let i=new Date(n.getFullYear(),n.getMonth(),1);for(;i<=o;){const l=new Date(i.getFullYear(),i.getMonth()+1,0);a.push({period:`m${i.getMonth()+1}`,periodLabel:`m${i.getMonth()+1}`,periodStart:ps(i),periodEnd:ps(l),rank:null,status:"no_data"}),i=new Date(i.getFullYear(),i.getMonth()+1,1)}return a},zx=(t,s,a)=>(t||[]).map(n=>{const o=n.period,i=s?s[o]??null:null,l=a?a[o]??null:null;return{...n,rank:i,status:s?i===null?"not_ranked":"ranked":"no_data",url:l??void 0}}),$x=t=>!t||t.status==="no_data"||t.rank===null?"-":`#${t.rank.toString()}`,Aw=(t,s,a)=>{if(!t)return{text:"-",type:"stable"};if(!s||s.status==="no_data")return{text:"-",type:"stable"};if(t.status==="no_data")return{text:"-",type:"stable"};if(t.periodStart&&s.periodStart){const i=new Date(t.periodStart),l=new Date(s.periodStart);if(a==="weekly"){if(Math.floor((l.getTime()-i.getTime())/vr)>7)return{text:"-",type:"stable"}}else if((l.getFullYear()-i.getFullYear())*12+(l.getMonth()-i.getMonth())>1)return{text:"-",type:"stable"}}const n=t.rank,o=s.rank;if(n===null&&o===null)return{text:"—",type:"stable"};if(n===null&&o!==null)return{text:"New",type:"new"};if(n!==null&&o===null)return{text:"Lost",type:"lost"};if(n!==null&&o!==null){const i=n-o;return i>0?{text:`↑${i}`,type:"up"}:i<0?{text:`↓${Math.abs(i)}`,type:"down"}:{text:"—",type:"stable"}}return{text:"-",type:"stable"}},Tw=(t,s)=>{if(!t||t.status==="no_data")return"text-slate-300";const a=t.rank;if(a===null)return"text-slate-400";if(a<=3)return"text-emerald-600 font-semibold";if(a<=10)return"text-emerald-500";const n=Math.floor(s*.3),o=Math.floor(s*.6);return a<=n?"text-blue-500":a<=o?"text-amber-500":"text-slate-500"},Fx=t=>{const s="px-2 py-1.5 text-center tabular-nums",a=t.isLatest?"text-sm":"text-xs",n=t.isLatest?"bg-slate-50/70":"",o=Tw(t.period,t.depth);return[s,a,n,o].filter(Boolean).join(" ")},Xd=[{label:"THIS WEEK",value:{from:ps(Dx(new Date)),to:ps(new Date)}},{label:"LAST 4 WEEKS",value:{from:ps(new Date(Date.now()-27*vr)),to:ps(new Date)}},{label:"LAST 8 WEEKS",value:{from:ps(new Date(Date.now()-55*vr)),to:ps(new Date)}},{label:"LAST 12 WEEKS",value:{from:ps(new Date(Date.now()-83*vr)),to:ps(new Date)}},{label:"LAST 3 MONTHS",value:{from:ps(new Date(new Date().getFullYear(),new Date().getMonth()-3,1)),to:ps(new Date)}},{label:"LAST 6 MONTHS",value:{from:ps(new Date(new Date().getFullYear(),new Date().getMonth()-6,1)),to:ps(new Date)}},{label:"YTD",value:{from:ps(new Date(new Date().getFullYear(),0,1)),to:ps(new Date)}}],br=t=>{const s=new Date;if(t==="weekly")return{from:ps(new Date(Date.now()-27*vr)),to:ps(s)};const a=new Date(s.getFullYear(),s.getMonth()-2,1);return{from:ps(a),to:ps(s)}};function Pw(t){return!(t instanceof zr)||t.errorInfo?.statusCode!==400?!1:String(t.message||"").toLowerCase().includes("invalid location_id")}function Si(t){return`${Number(t.location_code)}/${String(t.language_code||"").trim()}`}function Iw(t){const s=new Map;for(const a of t){const n=String(a||"").trim();n&&s.set(n,(s.get(n)||0)+1)}return s}function Mw(t){const s=String(t.keyword||"").trim();if(!s)return null;const a=t.by_market||{},n=t.preferred_market_keys||[],o=[];for(const d of n){const m=a?.[d]?.[s];typeof m=="string"&&m.trim()&&o.push(m.trim())}if(o.length===0)return null;if(o.length===1)return o[0];const i=Iw(o);let l=null,c=-1;for(const d of o){const m=i.get(d)||0;m>c&&(l=d,c=m)}return l}function Ox(t){const s={};for(const a of t.keywords||[]){const n=String(a||"").trim();n&&(s[n]=Mw({keyword:n,by_market:t.by_market,preferred_market_keys:t.preferred_market_keys}))}return s}const Bx=async t=>await Je("/serp_ranking/rankings_batch_grouped",t);function Rw(t){try{const a=Fr().filter(o=>{const i=String(o.location_id||"").trim();return!i||!t.includes(i)}).map(o=>({location_code:o.location_code,language_code:o.language_code}));a.length>0&&tn(a,{emit:!0});const n=ea();n?.location_id&&t.includes(n.location_id)&&tr({location_code:n.location_code,language_code:n.language_code},{emit:!0})}catch(s){console.warn("⚠️ Failed to clear invalid location_ids:",s)}}const Ux=async t=>{try{return await Je("/serp_ranking/keywords_batch",t)}catch(s){if(Pw(s)&&t.selector?.location_ids&&t.selector.location_ids.length>0){console.warn("⚠️ Invalid location_id detected in keywords_batch, clearing and retrying with location_code/lang");const n=Fr().filter(o=>{const i=String(o.location_id||"").trim();return i&&t.selector.location_ids?.includes(i)&&o.location_code&&o.language_code}).map(o=>({location_code:Number(o.location_code),language_code:String(o.language_code||"").trim()}));if(Rw(t.selector.location_ids),n.length>0)return await Je("/serp_ranking/keywords_batch",{selector:{markets:n}})}throw s}},Qd=async t=>await Je("/serp_ranking/keywords/batch",t),Zd=async(t,s,a)=>{await Ca(`/serp_ranking/keywords/${encodeURIComponent(t)}`)},Dw=async()=>await ot("/serp_ranking/settings"),Lw=async t=>await $r("/serp_ranking/settings",t),zw=async t=>{const s=ra({location_id:t.location_id,location_code:t.location_code,language_code:t.language_code});try{return await Je("/serp_ranking/rankings",{...t,...s,language_code:s.language_code})}catch(a){throw a}},$w=async t=>{const s=ra({location_id:t.location_id,location_code:t.location_code,language_code:t.language_code});return await Je("/serp_ranking/ranked_keywords",{...t,...s,language_code:s.language_code})},Fw=async t=>{const s=ra({location_id:t.location_id,location_code:t.location_code,language_code:t.language_code});return await Je("/serp_ranking/keyword_detail",{...t,...s,language_code:s.language_code})},H1=async t=>{const s=ra({location_id:t.location_id,location_code:t.location_code,language_code:t.language_code});return await Je("/serp_ranking/keyword_landing_pages",{keywords:t.keywords,...s,language_code:s.language_code})};class Kx{aggregate(s){const a=(s.selectedMarketKeys||[]).filter(
78Boolean);if(a.length===0)return{items:[]};const n={};for(const c of a){const d=s.byMarket[c];n[c]=Array.isArray(d?.items)?d.items:[]}const o=new Set;for(const c of a)for(const d of n[c]||[])d?.keyword&&o.add(d.keyword);const i={};for(const c of o)i[c]={};for(const c of a)for(const d of n[c]||[])d?.keyword&&(i[d.keyword][c]=d);const l=[];for(const c of Array.from(o)){const d={},m={},h={};let p=null;for(const u of a){const g=i[c]?.[u];if(!g)continue;const w=g.latest_volume??this.pickFirstNonNullNumber(Object.values(g.volumes||{}));w!==null&&(p=(p??0)+w)}for(const u of s.periodKeys||[]){const g=[];for(const w of a){const _=i[c]?.[w];if(!_)continue;const E=_.ranks?.[u]??null,N=_.urls?.[u]??_.urls?.[u]??null,S=_.volumes?.[u]??_.latest_volume??this.pickFirstNonNullNumber(Object.values(_.volumes||{}))??1;g.push({rank:E,url:N??null,weight:Number(S)||1})}d[u]=this.weightedAvgRank(g),m[u]=this.pickBestUrl(g),h[u]=p}const f=(s.periodKeys||[])[s.periodKeys.length-1],b=f?d[f]??null:null,y=p,x=this.pickTopUrl(s.periodKeys||[],m);l.push({keyword:c,url:x,ranks:d,volumes:h,urls:m,latest_rank:b,latest_volume:y})}return{items:l}}pickFirstNonNullNumber(s){for(const a of s)if(a!=null&&Number.isFinite(a))return Number(a);return null}weightedAvgRank(s){let a=0,n=0;for(const o of s){if(o.rank===null||o.rank===void 0)continue;const i=Number.isFinite(o.weight)&&o.weight>0?o.weight:1;a+=o.rank*i,n+=i}return n<=0?null:Math.round(a/n)}pickBestUrl(s){let a=null,n=null;for(const o of s){const i=(o.url||"").trim();if(i){if(o.rank===null||o.rank===void 0){a||(a=i);continue}(n===null||o.rank<n)&&(n=o.rank,a=i)}}return a}pickTopUrl(s,a){for(let n=s.length-1;n>=0;n-=1){const o=s[n],i=(a[o]||"").trim();if(i)return i}for(const n of s){const o=(a[n]||"").trim();if(o)return o}return null}}function Ow(t){const s=!!t.showSelection,a=!!t.showActions,n=t.periods[t.periods.length-1]?.period,[o,i]=v.useState(()=>{const x={};s&&(x.select=44),x.keyword=220;for(const u of t.periods||[])x[`period:${u.period}`]=84;return x.landing_page=240,a&&(x.actions=56),x}),[l,c]=v.useState(null);v.useEffect(()=>{i(x=>{const u={...x};s&&!u.select&&(u.select=44),u.keyword||(u.keyword=220);for(const g of t.periods||[]){const w=`period:${g.period}`;u[w]||(u[w]=84)}return u.landing_page||(u.landing_page=240),a&&!u.actions&&(u.actions=56),u})},[t.periods,a,s]);const d=v.useCallback((x,u)=>{x.preventDefault(),x.stopPropagation();const g="touches"in x?x.touches[0].clientX:x.clientX,w=o[u]||100;c({column:u,startX:g,startWidth:w})},[o]);v.useEffect(()=>{if(!l)return;const x=g=>{const _=("touches"in g?g.touches[0].clientX:g.clientX)-l.startX,E=Math.max(60,Math.min(500,l.startWidth+_));i(N=>({...N,[l.column]:E}))},u=()=>c(null);return document.addEventListener("mousemove",x),document.addEventListener("mouseup",u),document.addEventListener("touchmove",x),document.addEventListener("touchend",u),()=>{document.removeEventListener("mousemove",x),document.removeEventListener("mouseup",u),document.removeEventListener("touchmove",x),document.removeEventListener("touchend",u)}},[l]);const[m,h]=v.useState(80),p=v.useRef(null),f=t.rows.length>m,b=v.useCallback(()=>{if(!p.current||!f)return;const{scrollTop:x,scrollHeight:u,clientHeight:g}=p.current;u-x-g<200&&h(w=>Math.min(w+80,t.rows.length))},[f,t.rows.length]),y=t.rows.slice(0,m);return e.jsx("div",{ref:p,onScroll:b,className:["h-full min-h-0 overflow-auto bg-white",t.mobileBottomInset?"pb-28":"",l?"select-none cursor-col-resize":""].join(" "),children:e.jsxs("table",{className:"w-full border-collapse text-left min-w-max",style:{tableLayout:"fixed"},children:[e.jsx("thead",{className:"bg-gray-50 sticky top-0 z-30 text-xs font-semibold text-gray-500 uppercase tracking-wider shadow-[0_1px_2px_rgba(0,0,0,0.05)]",children:e.jsxs("tr",{children:[s&&e.jsx("th",{className:"px-2 py-2 border-b border-gray-200 relative",style:{width:o.select,minWidth:o.select,maxWidth:o.select},children:e.jsx("div",{className:"flex items-center justify-center",children:e.jsx(Kt,{checked:t.headerSelectionState??!1,onCheckedChange:()=>t.onToggleAllSelection?.(),"aria-label":"Select all"})})}),e.jsxs("th",{className:"px-3 py-2 border-b border-gray-200 relative group/resize cursor-pointer hover:text-indigo-600",style:{width:o.keyword,minWidth:o.keyword,maxWidth:o.keyword},onClick:()=>
78t.onSort("keyword"),children:[e.jsxs("div",{className:"flex items-center gap-1",children:["Keyword",t.renderSortIcon("keyword")]}),e.jsx("div",{className:"absolute right-0 top-0 bottom-0 w-1 cursor-col-resize hover:bg-blue-400 active:bg-blue-500 opacity-0 group-hover/resize:opacity-100 transition-opacity",onMouseDown:x=>d(x,"keyword"),onTouchStart:x=>d(x,"keyword")})]}),t.periods.map(x=>{const u=`period:${x.period}`;return e.jsxs("th",{className:"px-2 py-2 border-b border-gray-200 relative group/resize cursor-pointer hover:text-indigo-600",style:{width:o[u],minWidth:o[u],maxWidth:o[u]},onClick:()=>t.onSort(u),children:[e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx("span",{title:x.periodLabel,children:x.period}),t.renderSortIcon(u)]}),e.jsx("div",{className:"absolute right-0 top-0 bottom-0 w-1 cursor-col-resize hover:bg-blue-400 active:bg-blue-500 opacity-0 group-hover/resize:opacity-100 transition-opacity",onMouseDown:g=>d(g,u),onTouchStart:g=>d(g,u)})]},x.period)}),e.jsxs("th",{className:"px-3 py-2 border-b border-gray-200 relative group/resize cursor-pointer hover:text-indigo-600",style:{width:o.landing_page,minWidth:o.landing_page,maxWidth:o.landing_page},onClick:()=>t.onSort("landing_page"),children:[e.jsxs("div",{className:"flex items-center gap-1",children:["Landing Page",t.renderSortIcon("landing_page")]}),e.jsx("div",{className:"absolute right-0 top-0 bottom-0 w-1 cursor-col-resize hover:bg-blue-400 active:bg-blue-500 opacity-0 group-hover/resize:opacity-100 transition-opacity",onMouseDown:x=>d(x,"landing_page"),onTouchStart:x=>d(x,"landing_page")})]}),a&&e.jsx("th",{className:"px-2 py-2 border-b border-gray-200",style:{width:o.actions,minWidth:o.actions,maxWidth:o.actions}})]})}),e.jsx("tbody",{className:"divide-y divide-gray-100 border-b border-gray-200",children:y.map(x=>{const u=t.selectedRowIds?.has(x.id)??!1;return e.jsxs("tr",{onClick:()=>t.onToggleRowSelection?.(x.id),className:["transition-colors",u?"bg-blue-50/50":"bg-white hover:bg-gray-50/50","cursor-pointer"].join(" "),children:[s&&e.jsx("td",{className:"px-2 py-2 border-r border-gray-100",onClick:g=>{g.stopPropagation(),t.onToggleRowSelection?.(x.id)},children:e.jsx("div",{className:"flex items-center justify-center",children:e.jsx(Kt,{checked:u,onCheckedChange:()=>t.onToggleRowSelection?.(x.id),"aria-label":`Select ${x.keyword}`})})}),e.jsx("td",{className:"px-3 py-2",style:{width:o.keyword,minWidth:o.keyword,maxWidth:o.keyword},children:e.jsx("div",{className:"truncate text-xs font-medium text-slate-900 max-w-[320px]",children:x.keyword})}),t.periods.map(g=>{const w=x.rankings.find(S=>S.period===g.period),_=g.period===n,E=Fx({period:w,depth:t.depth,isLatest:_}),N=`period:${g.period}`;return e.jsx("td",{className:E,style:{width:o[N],minWidth:o[N],maxWidth:o[N]},children:e.jsx("div",{className:"text-center text-xs",children:$x(w)})},g.period)}),e.jsx("td",{className:"px-3 py-2",style:{width:o.landing_page,minWidth:o.landing_page,maxWidth:o.landing_page},children:x.landingPage?e.jsx("a",{href:x.landingPage,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:text-blue-800 hover:underline text-xs truncate block",title:x.landingPage,onClick:g=>g.stopPropagation(),children:x.landingPage}):e.jsx("span",{className:"text-slate-400 text-xs",children:"-"})}),a&&e.jsx("td",{className:"px-2 py-2",children:e.jsxs("div",{className:"flex items-center justify-end gap-1",children:[e.jsx(be,{variant:"ghost",size:"sm",title:"View keyword insights",onClick:g=>{g.stopPropagation(),t.onViewInsights?.(x.keyword)},className:"h-7 p-0 text-slate-400 hover:text-slate-700 hover:bg-slate-100 transition-colors",children:e.jsx(Ga,{className:"w-3.5 h-3.5"})}),e.jsx(be,{variant:"ghost",size:"sm",title:"Delete keyword",onClick:g=>{g.stopPropagation(),t.onDeleteKeyword?.(x.id,x.keyword)},className:"h-7 p-0 text-slate-400 hover:text-red-500 hover:bg-red-50 transition-colors",children:e.jsx(es,{className:"w-3.5 h-3.5"})})]})})]},x.id)})})]})})}function Gx(t){const s=!!t.showSelection,a=!!t.showIndex,n=!!t.showActions,o=t.periods[t.periods.length-1]?.period,i=v.useMemo(()=>{const l=new Map;t.rows.forEach((d,m)=>l.set(d.id,m));const c=[];return(s||a)&&c.push({header:e.jsx("div",{className:"flex items-center justify-center",children:s?e.jsx(Kt,{checked:t.headerSelectionState??!1,onCheckedChange:t.onToggleAllSelection,"aria-label":"Select all"}):e.jsx("span",{className:"text-xs font-semibold text-slate-700",children:"#"})}),width:"48px",stickyWidthPx:48,align:"center",isSelection:!0,showDefaultSortIcon:!1,render:d=>e.jsx("div",{className:"flex items-center justify-center",children:s?e.jsx(Kt,{checked:t.selectedRowIds?.has(d.id)??!1,onCheckedChange:()=>t.onToggleRowSelection?.(d.id),"aria-label":`Select ${d.keyword}`}):e.jsx("span",{className:"text-xs text-slate-500 tabular-nums",children:t.getRowIndex?.(d.id,l.get(d.id)??0)??(l.get(d.id)??0)+1})})}),c.push({header:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"text-xs",children:"Keyword"}),t.renderSortIcon("keyword")]}),sortKey:"keyword",showDefaultSortIcon:!1,sticky:s||a?"left":void 0,headerClassName:"py-1.5 px-3 font-semibold text-slate-700 hover:bg-slate-100 shadow-[1px_0_0_0_rgba(0,0,0,0.05)]",cellClassName:"py-1.5 px-3 font-medium text-slate-900 shadow-[1px_0_0_0_rgba(0,0,0,0.05)]",render:d=>{const m=d.rankings[d.rankings.length-1],h=m?.rank??null,p=t.metaTextByKeyword?.[d.keyword]??null;return e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"truncate max-w-[200px] text-xs",title:d.
78keyword,children:d.keyword}),m?.status==="ranked"&&h!==null&&h<=10&&e.jsx(ls,{variant:"secondary",className:"bg-emerald-50 text-emerald-700 text-[10px] px-1.5 flex-shrink-0",children:"Top 10"}),p&&e.jsx("span",{className:"text-[10px] text-slate-400 truncate max-w-[220px]",children:p})]})}}),t.periods.forEach(d=>{c.push({header:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx("span",{title:d.periodLabel,children:d.period}),t.renderSortIcon(`period:${d.period}`)]}),sortKey:`period:${d.period}`,showDefaultSortIcon:!1,align:"center",width:"70px",headerClassName:["py-1.5 px-2 font-semibold text-slate-700 text-xs hover:bg-slate-100",d.period===o?"bg-slate-100/70":""].filter(Boolean).join(" "),cellClassName:m=>{const h=m.rankings.find(p=>p.period===d.period);return Fx({period:h,depth:t.depth,isLatest:d.period===o})},render:m=>{const h=m.rankings.find(p=>p.period===d.period);return $x(h)}})}),c.push({header:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("span",{children:"Landing Page"}),t.renderSortIcon("landing_page")]}),sortKey:"landing_page",showDefaultSortIcon:!1,headerClassName:"py-1.5 px-3 font-semibold text-slate-700 text-xs",cellClassName:"py-1.5 px-3",render:d=>d.landingPage?e.jsx("a",{href:d.landingPage,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:text-blue-800 hover:underline text-xs truncate block max-w-[400px]",title:d.landingPage,children:d.landingPage}):e.jsx("span",{className:"text-slate-400 text-xs",children:"-"})}),n&&c.push({header:"",align:"right",width:"48px",headerClassName:"py-1.5 px-3",cellClassName:"py-1.5 px-3",render:d=>{const h=d.rankings[d.rankings.length-1]?.rank??null;return e.jsxs("div",{className:"flex items-center justify-end gap-1",children:[h!==null&&e.jsx(be,{variant:"ghost",size:"sm",title:"View keyword insights",onClick:()=>t.onViewInsights?.(d.keyword),className:"h-7 p-0 text-slate-400 hover:text-slate-700 hover:bg-slate-100 transition-colors",children:e.jsx(Ga,{className:"w-3.5 h-3.5"})}),e.jsx(be,{variant:"ghost",size:"sm",title:"Delete keyword",onClick:()=>t.onDeleteKeyword?.(d.id,d.keyword),className:"h-7 p-0 text-slate-400 hover:text-red-500 hover:bg-red-50 transition-colors",children:e.jsx(es,{className:"w-3.5 h-3.5"})})]})}}),c},[o,t,n,a,s]);return e.jsx(Lc,{data:t.rows,columns:i,onSort:t.onSort,rowClassName:()=>"hover:bg-slate-50/50",emptyMessage:e.jsx("div",{className:"py-10 text-center text-slate-500",children:"No data available"})})}async function Bw(t){const s=t.selectedMarkets||[],a=t.selector,n=(s||[]).map(d=>Si({location_code:Number(d.location_code),language_code:String(d.language_code||"")}));let o=[],i={},l={};if(a){const d=await Ux({selector:a});o=d.keywords||[],l=d.by_market||{},i=d.keyword_landing_pages||{}}else o=[],i={};const c=o.filter(d=>d.is_active);return a&&(i=i&&Object.keys(i).length>0?i:Ox({keywords:c.map(d=>d.keyword),by_market:l,preferred_market_keys:n})),{activeTracked:c,landingPageMap:i}}function Uw(t){return t.sort.key!==t.key?e.jsx(dn,{size:14,className:"text-slate-400 opacity-70"}):t.sort.direction==="asc"?e.jsx(Is,{size:14,className:"text-slate-500"}):t.sort.direction==="desc"?e.jsx(Ws,{size:14,className:"text-slate-500"}):e.jsx(dn,{size:14,className:"text-slate-400 opacity-70"})}function Kw(t){if(!t.sort.key||!t.sort.direction)return t.rows;const s=t.sort.direction,a=t.sort.key,n=(c,d)=>{const m=c==null,h=d==null;if(m&&h)return 0;if(m)return 1;if(h)return-1;if(typeof c=="number"&&typeof d=="number"){const y=c-d;return s==="asc"?y:-y}const p=String(c),f=String(d),b=p.localeCompare(f);return s==="asc"?b:-b},o=(c,d)=>{const m=c.rankings.find(h=>h.period===d);return!m||m.status==="no_data"||m.rank===null?null:m.rank},i=c=>{const d=c.rankings[c.rankings.length-2],m=c.rankings[c.rankings.length-1];return!m||m.status==="no_data"?null:!d||d.status==="no_data"?999999:d.rank===null&&m.rank===null?null:d.rank===null&&m.rank!==null?999999:d.rank!==null&&m.rank===null?-999999:d.rank-m.rank},l=[...t.rows];return l.sort((c,d)=>{if(a==="keyword")return n(c.keyword,d.keyword);if(a==="landing_page")return n(c.landingPage,d.landingPage);if(a==="change")return n(i(c),i(d));if(a.startsWith("period:")){const m=a.replace("period:","");return n(o(c,m),o(d,m))}return 0}),l}function Gw(t){const s=t.marketReloadNonce??0,a=t.depth??100,n=t.viewMode??"weekly",o=v.useRef(new Kx),[i,l]=v.useState([]),[c,d]=v.useState([]),[m,h]=v.useState({}),[p,f]=v.useState(!0),[b,y]=v.useState(null),[x,u]=v.useState({key:"",direction:null}),g=v.useRef(0),w=v.useCallback(async()=>{const N=++g.current;f(!0),y(null);try{const S=ma(),k=S.length>0?$a(S):null,{activeTracked:D,landingPageMap:F}=await Bw({selectedMarkets:S,selector:k});if(N!==g.current)return;if(D.length===0){l([]),d([]);return}const R=br(n),L=R.from,$=R.to;if(!L||!$){l([]),d([]);return}const H=Lx({from:L,to:$},n),K=H.map(T=>T.period),X=(S||[]).map(T=>Si({location_code:Number(T.location_code),language_code:String(T.language_code||"")})),V=(T,M,Z)=>{const B=new Date(M),ae=new Date(Z);let de=null;for(const fe of T||[]){const se=new Date(fe.snapshot_date);se<B||se>ae||(!de||new Date(fe.snapshot_date)>new Date(de.snapshot_date))&&(de=fe)}return{rank:de?.rank??null,url:de?.url??null}},P=T=>D.map(M=>{const Z=T?.[M.keyword]||T?.[Nn(M.keyword)]||[],B={},ae={},de={};for(const U of H){const Q=V(Z,U.periodStart,U.periodEnd);B[U.period]=Q.rank,ae[U.period]=Q.url,de[U.period]=null}const fe=H[H.length-1]?.period,se=fe?B[fe]??null:null,z=(fe?ae[fe]:null)||Object.values(ae).find(U=>!!U)||null;return{keyword:M.keyword,url:z,ranks:B,urls:ae,volumes:de,latest_rank:se,latest_volume:null}});let A={items:[]};
78if(k){const T=await Bx({selector:k,period:n,date_from:L,date_to:$});A=o.current.aggregate({byMarket:T.by_market,selectedMarketKeys:X,periodKeys:K})}else{const T=await zw({date_from:L,date_to:$,...S.length===1?{location_code:Number(S[0]?.location_code),language_code:String(S[0]?.language_code||"")}:{}});A={items:P(T.rankings||{})}}if(N!==g.current)return;const C={};for(const T of A.items||[]){const M=T?.latest_volume;C[T.keyword]=M!=null?`Vol ${M}`:null}h(C);const I=D.map(T=>{const M=(A.items||[]).find(ae=>Nn(ae.keyword)===Nn(T.keyword))||null,Z=zx(H,M?.ranks,M?.urls),B=Z[Z.length-1];return{id:T.id,keyword:T.keyword,landingPage:F[T.keyword]||B?.url||null,rankings:Z}}),j=new Set;I.forEach(T=>{T.rankings.forEach(M=>{M.status!=="no_data"&&j.add(M.period)})});const q=j.size>0?H.filter(T=>j.has(T.period)):H;if(l(I),d(q.map(T=>({period:T.period,periodLabel:T.periodLabel}))),!x.key){const T=q[q.length-1]?.period;T&&u({key:`period:${T}`,direction:"asc"})}}catch(S){if(N!==g.current)return;console.warn("⚠️ Failed to load homepage keywords rankings:",S),y(S?.message||"Failed to load keywords rankings"),l([]),d([]),h({})}finally{if(N!==g.current)return;f(!1)}},[s,x.key,n]);v.useEffect(()=>{w()},[w]);const _=v.useMemo(()=>Kw({rows:i,sort:x}),[i,x]),E=v.useCallback(N=>{u(S=>{const k=N;return S.key!==k?{key:k,direction:"asc"}:S.direction==="asc"?{key:k,direction:"desc"}:S.direction==="desc"?{key:"",direction:null}:{key:k,direction:"asc"}})},[]);return p?e.jsx("div",{className:"py-10 text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-2 text-xs text-slate-400",children:[e.jsx(kt,{className:"w-4 h-4 animate-spin"}),e.jsx("span",{children:"Loading rankings..."})]})}):b?e.jsxs("div",{className:"py-8 text-center",children:[e.jsx("div",{className:"text-xs text-red-600",children:b}),e.jsx("div",{className:"mt-3 flex justify-center",children:e.jsxs(be,{type:"button",variant:"outline",size:"sm",className:"gap-1.5",onClick:()=>{w()},children:[e.jsx(kt,{className:"w-4 h-4"}),"Retry"]})})]}):_.length===0?e.jsx("div",{className:"py-10 text-center text-xs text-slate-400",children:"No tracked keywords yet"}):e.jsx("div",{className:["flex flex-col overflow-hidden",t.maxHeightClassName||""].join(" "),children:e.jsx("div",{className:"flex-1 overflow-auto",children:e.jsx(Gx,{rows:_,periods:c,viewMode:n,depth:a,onSort:E,renderSortIcon:N=>Uw({sort:x,key:N}),metaTextByKeyword:m,showIndex:!0,showSelection:!1,showActions:!1,getRowIndex:(N,S)=>S+1})})})}function Wx(t){if((n=>n?.variant==="homepage")(t))return e.jsx(Gw,{...t});const a=t;return a.isMobile?e.jsx(Ow,{...a}):e.jsx(Gx,{...a})}const Xr=[{id:"content_generation",name:"Content generation (generic)",description:"Generate SEO-optimized content with AI",previewBg:"from-emerald-50 to-emerald-100"},{id:"content_generation_webflow",name:"Content generation (webflow)",description:"Generate SEO-optimized content for Webflow with AI",previewBg:"from-emerald-50 to-emerald-100"},{id:"content_generation_shopify",name:"Content generation (shopify)",description:"Generate SEO-optimized content for Shopify with AI",previewBg:"from-emerald-50 to-emerald-100"}],Mr=[{id:"content_generation_keywords_only",name:"Content generation (generic)",description:"Generate SEO-optimized content",previewBg:"from-blue-50 to-blue-100"},{id:"content_generation_webflow_keywords_only",name:"Content generation (webflow)",description:"Generate SEO-optimized content for Webflow",previewBg:"from-blue-50 to-blue-100"},{id:"content_generation_shopify_keywords_only",name:"Content generation (shopify)",description:"Generate SEO-optimized content for Shopify",previewBg:"from-blue-50 to-blue-100"}];function Vx(t){const s=new Date,a=s.toLocaleString("en-US",{month:"short"}),n=s.getDate();return`${t?.trim()?t.trim():"Worksheet"} - ${a} ${n}`}const Ei=[{id:"seo_content_webflow",name:"Create New Content (Webflow)",description:"Analyze pages and generate optimized content for Webflow",previewBg:"from-emerald-50 to-emerald-100"},{id:"seo_content_shopify",name:"Create New Content (Shopify)",description:"Analyze pages and generate optimized content for Shopify",previewBg:"from-emerald-50 to-emerald-100"},{id:"seo_analysis_shopify",name:"Optimize Existing Content",description:"Analyze and optimize SEO performance with AI",previewBg:"from-blue-50 to-blue-100"},{id:"content_refresh",name:"Content Refresh",description:"Analyze pages and generate refreshed content with keyword optimization",previewBg:"from-purple-50 to-purple-100"}],Ww=async t=>await Je("/worksheet-template/create",t),io=async t=>await ot("/worksheet-template/list",t),Vw=async t=>await Ca(`/worksheet-template/${t}`),$c=async t=>await Je("/worksheet-template/apply",t),Hw=async t=>await Je("/worksheet-template/apply_to_campaign",t),Hx={async createWorksheetFromTemplate(t){return await Je("/content_generation_template/create_worksheet",t)}},Vt={async listColumns(t){return await ot("/dynamic_column/list",t)},async getColumn(t){return await ot(`/dynamic_column/${t}`)},async getColumnByPosition(t){return await ot(`/dynamic_column/by_position/${t.table_type}`,{display_order:t.display_order,campaign_id:t.campaign_id})},async createColumn(t){return await Je("/dynamic_column/create",t)},async updateColumn(t,s){return await $r(`/dynamic_column/${t}`,s)},async deleteColumn(t){await Ca(`/dynamic_column/${t}`)},async updateDisplayOrder(t){return await Je("/dynamic_column/update_display_order",t)},async generateAIValue(t){return await Je("/dynamic_column/generate_ai_value",t)},async generateKeywordsValue(t){return await Je("/dynamic_column/generate_keywords_value",t)},async publishWebflow(t){return await Je("/dynamic_column/publish_webflow",t)},async publishWebflowAsync(t){return await Je("/dynamic_column/publish_webflow_async",t)},async publishWebflowBatch(t){return await Je("/dynamic_column/publish_webflow_batch",t)}
78,async publishShopify(t){return await Je("/dynamic_column/publish_shopify",t)},async publishShopifyAsync(t){return await Je("/dynamic_column/publish_shopify_async",t)},async publishShopifyBatch(t){return await Je("/dynamic_column/publish_shopify_batch",t)},async executeSEOAction(t){return await Je("/dynamic_column/execute_seo_action",t)},async executeSEOActionAsync(t){return await Je("/dynamic_column/execute_seo_action_async",t)},async executeSEOActionBatch(t){return await Je("/dynamic_column/execute_seo_action_batch",t)},async getDefaultTemplate(t){return await ot("/dynamic_column/get_default_template",t)},async uploadImage(t){const s=new FormData;return s.append("campaign_id",t.campaign_id),s.append("column_id",t.column_id),s.append("entity_id",t.entity_id),s.append("table_type",t.table_type),s.append("file",t.file),t.display_order!==void 0&&t.display_order!==null&&s.append("display_order",String(t.display_order)),await Je("/dynamic_column/upload_image",s)},async deleteImage(t){return await Je("/dynamic_column/delete_image",t)},async getSEOAnalysisDefaultPrompts(){return await ot("/dynamic_column/seo_analysis_default_prompts")}};class qw{async create(s){const a=s.campaignName.trim();if(!a)throw new Error("Campaign name is required.");if(s.source.kind==="blank"){console.log("🆕 Creating blank worksheet...");const l=await No({name:a,template_type:"none"});let c=null,d=null;try{const m=await Wt.createViewConfig({campaign_id:l.id,view_name:"table",table_type:"custom",is_default:!0,is_shared:!1});c=m.id,d=m.view_system_name||m.view_name||null,await Vt.createColumn({campaign_id:l.id,table_type:d||"table",view_config_id:m.id,name:"Text",type:"text",width:240,is_visible:!0})}catch(m){console.warn("⚠️ Failed to initialize blank worksheet view/column:",m)}if(!c)try{c=await this.pickViewId({appliedViewIds:[],campaignId:l.id}),d=(await Wt.getViewConfig(c)).view_system_name||null}catch(m){console.warn("⚠️ No views found for blank worksheet; continuing:",m)}return{campaignId:l.id,viewId:c,viewSystemName:d}}if(s.source.kind==="user_template"){console.log("🚀 Applying user worksheet template...");const l=await $c({template_id:s.source.templateId,campaign_name:a}),c=await this.pickViewId({appliedViewIds:l.view_ids,campaignId:l.campaign_id}),d=await Wt.getViewConfig(c);return{campaignId:l.campaign_id,viewId:c,viewSystemName:d.view_system_name||null}}if(s.source.kind==="content_generation_template"){console.log("🧩 Creating worksheet from content generation template...");const l=await Hx.createWorksheetFromTemplate({name:a,template_type:s.source.templateType});return{campaignId:l.campaign_id,viewId:l.view_id,viewSystemName:l.view_system_name||null}}console.log("🧩 Creating campaign from default template...");const n=await No({name:a,template_type:s.source.templateType}),o=await this.pickViewId({appliedViewIds:[],campaignId:n.id}),i=await Wt.getViewConfig(o);return{campaignId:n.id,viewId:o,viewSystemName:i.view_system_name||null}}async pickViewId(s){if(Array.isArray(s.appliedViewIds)&&s.appliedViewIds.length>0)return s.appliedViewIds[0];const o=[...(await Wt.listViewConfigs({campaign_id:s.campaignId})).items||[]].sort((i,l)=>(i.display_order??0)-(l.display_order??0))[0];if(!o?.id)throw new Error("Campaign created, but no views were found.");return o.id}}const Yw=new qw;function Jw({isOpen:t,onClose:s,defaultCampaignName:a}){const{toast:n}=_t(),[o,i]=v.useState([]),[l,c]=v.useState(!1),[d,m]=v.useState(""),[h,p]=v.useState("seo_content_webflow"),[f,b]=v.useState("blank"),[y,x]=v.useState(""),[u,g]=v.useState(!1),w=v.useMemo(()=>o.find(D=>D.id===d)||null,[o,d]),_=v.useMemo(()=>Ei.find(D=>D.id===h)||null,[h]),E=v.useMemo(()=>f==="blank"?{kind:"blank",label:"Blank worksheet"}:f==="default_template"?{kind:"default_template",templateType:h,label:_?.name||"Default template"}:d.trim().length===0?null:{kind:"user_template",templateId:d,label:w?.name||"Template"},[f,h,_?.name,d,w?.name]);v.useEffect(()=>{if(!t)return;let D=!0;return(async()=>{c(!0);try{const R=await io({page:1,page_size:200});if(!D)return;i(R.items||[]);const L=(R.items||[])[0]?.id||"";m($=>$||L)}
78catch(R){if(console.error("❌ Failed to load worksheet templates:",R),!D)return;i([])}finally{if(!D)return;c(!1)}})(),()=>{D=!1}},[t]),v.useEffect(()=>{if(!t)return;if(a?.trim()){x(a.trim());return}const D=f==="default_template"?_?.name:f==="user_template"?w?.name:void 0;x(Vx(D))},[t,a,f,w?.name,_?.name]);const N=()=>{u||s()},S=!u&&!l&&!!E&&y.trim().length>0,k=async()=>{if(!(!S||!E)){g(!0);try{const D=await Yw.create({source:E.kind==="blank"?{kind:"blank"}:E.kind==="default_template"?{kind:"default_template",templateType:E.templateType}:{kind:"user_template",templateId:E.templateId},campaignName:y.trim()});try{localStorage.setItem("flowwriter.currentCampaign",JSON.stringify({id:D.campaignId,name:y.trim()}))}catch{}n({title:"✅ Worksheet created",description:`Template applied: ${E.label}`}),s(),jt("table-new",{campaign:D.campaignId,...D.viewId?{view:D.viewId}:{}})}catch(D){console.error("❌ Failed to create worksheet from template:",D),n({title:"Create failed",description:D?.message||"Please try again."})}finally{g(!1)}}};return e.jsx(Ht,{open:t,onOpenChange:N,children:e.jsxs(qt,{className:"max-w-3xl",children:[e.jsx(Zt,{children:e.jsx(Yt,{className:"text-base font-semibold text-slate-800",children:"Create Worksheet from Template"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"rounded-lg border border-slate-200 bg-slate-50 px-4 py-3",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-9 h-9 rounded-lg bg-white border border-slate-200 flex items-center justify-center shrink-0",children:e.jsx(ln,{size:16,className:"text-slate-600"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"text-sm font-medium text-slate-800",children:"Choose a template to start"}),e.jsx("div",{className:"text-xs text-slate-500 mt-0.5",children:"You can edit views and columns anytime after creation."})]})]})}),e.jsxs("div",{children:[e.jsx("label",{className:"text-[12px] font-medium text-slate-700 mb-3 block",children:"Choose a Template"}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-3",children:[e.jsxs("button",{type:"button",onClick:()=>{b("blank"),m("")},disabled:u,className:`relative p-4 rounded-lg text-left transition-all border-2 ${f==="blank"?"border-slate-900 bg-slate-50":"border-slate-200 bg-white hover:border-slate-300"} ${u?"opacity-50 cursor-not-allowed":""}`,children:[f==="blank"&&e.jsx("div",{className:"absolute top-2 right-2 w-5 h-5 bg-slate-900 rounded-full flex items-center justify-center",children:e.jsx(wt,{size:12,className:"text-white"})}),e.jsx("div",{className:"text-[12px] font-medium text-slate-800 pr-6",children:"Blank worksheet"}),e.jsx("div",{className:"text-[10px] text-slate-500 mt-1.5 leading-relaxed",children:"Start from scratch with an empty table"})]}),Ei.map(D=>{const F=f==="default_template"&&h===D.id;return e.jsxs("button",{type:"button",onClick:()=>{b("default_template"),p(D.id),m("")},disabled:u,className:`relative p-4 rounded-lg text-left transition-all border-2 ${F?"border-slate-900 bg-slate-50":"border-slate-200 bg-white hover:border-slate-300"} ${u?"opacity-50 cursor-not-allowed":""}`,children:[F&&e.jsx("div",{className:"absolute top-2 right-2 w-5 h-5 bg-slate-900 rounded-full flex items-center justify-center",children:e.jsx(wt,{size:12,className:"text-white"})}),e.jsx("div",{className:"text-[12px] font-medium text-slate-800 pr-6",children:D.name}),e.jsx("div",{className:"text-[10px] text-slate-500 mt-1.5 leading-relaxed",children:D.description})]},D.id)})]}),!l&&o.length>0&&e.jsxs("div",{className:"mt-5 pt-5 border-t border-slate-100",children:[e.jsx("label",{className:"text-[11px] text-slate-500 mb-2 block",children:"Or choose from your library"}),e.jsxs("div",{className:"relative",children:[e.jsxs("select",{value:f==="user_template"?d:"",onChange:D=>{D.target.value&&(b("user_template"),m(D.target.value))},disabled:l||u,className:["w-full h-10 px-3 text-sm border rounded-lg appearance-none transition-colors",f==="user_template"?"border-slate-900 bg-white text-slate-900":"border-slate-200 bg-slate-50 text-slate-600 hover:border-slate-300","focus:outline-none focus:ring-2 focus:ring-slate-900/20"].join(" "),children:[e.jsx("option",{value:"",disabled:!0,children:"Select a custom template..."}),o.map(D=>e.jsx("option",{value:D.id,children:D.name},D.id))]}),e.jsx("div",{className:"absolute right-3 top-1/2 -translate-y-1/2 pointer-events-none text-slate-400",children:e.jsx("svg",{width:"10",height:"6",viewBox:"0 0 10 6",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:e.jsx("path",{d:"M1 1L5 5L9 1",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})})]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-[11px] text-slate-500 mb-1.5 block",children:"Worksheet Name"}),e.jsx(bt,{value:y,onChange:D=>x(D.target.value),placeholder:"Enter worksheet name",disabled:u})]}),e.jsxs(Ns,{spacing:"sm",children:[e.jsx(be,{variant:"ghost",size:"sm",onClick:N,disabled:u,children:"Cancel"}),e.jsx(be,{size:"sm",className:"bg-slate-900 hover:bg-slate-800 disabled:opacity-80 min-w-[140px]",onClick:k,disabled:!S,children:u?e.jsxs("span",{className:"inline-flex items-center gap-2",children:[e.jsx(He,{className:"w-4 h-4 animate-spin"}),"Creating..."]}):"Create"})]})]})]})})}const Xw=t=>{if(!t)return null;const s=String(t).trim().toLowerCase();return s?s==="pending"||s==="queued"||s==="processing"||s==="running"?"syncing":s==="completed"||s==="success"||s==="done"?null:s==="failed"?"failed":t:null},Qw=t=>{const s=Math.max(1e4,t?.maxMs??36e4),a=Math.max(800,t?.intervalMs??2e3);return{maxMs:s,intervalMs:a}};function qx(t){const s=v.useRef(null),a=v.useRef(!1),n=v.useCallback(()=>{s.current&&(window.clearInterval(s.current),s.current=null)},[]),o=v.useCallback(async(l,c)=>{if(!a.current){a.current=!0;try{const d=await t.loadAndGetSyncStatus(),m=Xw(d);if(Date.now()-l>c){n(),t.syncManager.updateSyncStatus("timeout");return}if(!m){n();try{await t.refreshAfterCompleted?.()}catch(h){console.warn("⚠️ Failed to refresh after competitors sync:",h)}t.syncManager.updateSyncStatus(null);return}t.syncManager.updateSyncStatus(m),(String(m).toLowerCase()==="failed"||String(m).toLowerCase()==="error")&&(n(),t.syncManager.updateSyncStatus("failed"))}catch(d){console.error("❌ Failed to poll competitors sync status:",d),n(),t.onPollError?t.onPollError(d):t.syncManager.updateSyncStatus("failed")}finally{a.current=!1}}},[t,n]),i=v.useCallback(l=>{const{maxMs:c,intervalMs:d}=Qw(l),m=Date.now();n(),t.syncManager.startSync(l?.etaText);const h=async()=>{await o(m,c)};h(),s.current=window.setInterval(h,d)},[t.syncManager,o,n]);return v.useEffect(()=>()=>{n()},[n]),{startSyncAndPoll:i,stopPolling:n}}function oa({steps:t,run:s,onComplete:a,onSkip:n}){const[o,i]=r.useState(!1),[l,c]=r.useState(0),d=v.useRef(null),m=r.useCallback(()=>{try{const x=t[l];if(!x)return null;if(typeof x.target=="string"){const u=document.querySelector(x.target);return u instanceof HTMLElement?u:null}return null}catch{return null}},[t,l]),h=(x,u,g)=>Math.min(g,Math.max(u,x)),p=r.useCallback(()=>{try{const x=document.querySelector(".__floater__open")??document.querySelector('[class*="react-joyride__floater"]'),u=document.querySelector('[class*="react-joyride__tooltip"]')??document.querySelector('[role="tooltip"]');if(!x||!u)return;const g=8,w=u.getBoundingClientRect();if(!(w.top<g||w.left<g||w.right>window.innerWidth-g||w.bottom>window.innerHeight-g))return;const N=m()?.getBoundingClientRect(),S=t[l]?.placement||"bottom";let k=window.innerWidth/2-w.width/2,D=window.innerHeight/2-w.height/2;if(N){const $=N.top+N.height/2,H=N.left+N.width/2;S.startsWith("left")?(k=N.left-w.width-12,D=$-w.height/2):S.startsWith("right")?(k=N.right+12,D=$-w.height/2):S.startsWith("top")?(k=H-w.width/2,D=N.top-w.height-12):(k=H-w.width/2,D=N.bottom+12)}const F=()=>
78{if(!N)return S;const L=w.width,$=w.height,H=k,K=D,X=H+L,V=K+$;return X<=N.left?"left":H>=N.right?"right":V<=N.top?"top":K>=N.bottom?"bottom":S.startsWith("left")?"left":S.startsWith("right")?"right":S.startsWith("top")?"top":"bottom"};k=h(k,g,window.innerWidth-w.width-g),D=h(D,g,window.innerHeight-w.height-g),x.style.setProperty("position","fixed","important"),x.style.setProperty("left",`${k}px`,"important"),x.style.setProperty("top",`${D}px`,"important"),x.style.setProperty("transform","none","important"),x.style.setProperty("margin","0","important"),x.style.setProperty("z-index","10001","important");const R=F();try{x.setAttribute("x-placement",R),x.setAttribute("data-placement",R)}catch{}}catch{}},[m,t,l]);r.useEffect(()=>{if(o)try{const x=document.documentElement,u=document.body,g=x.style.overflow,w=u.style.overflow,_=x.style.paddingRight,E=u.style.paddingRight,N=Math.max(0,window.innerWidth-document.documentElement.clientWidth),S=N>0?`${N}px`:"";return x.style.overflow="hidden",u.style.overflow="hidden",S&&(x.style.paddingRight=S,u.style.paddingRight=S),()=>{x.style.overflow=g,u.style.overflow=w,x.style.paddingRight=_,u.style.paddingRight=E}}catch{return}},[o]);const f=r.useCallback(()=>{try{window.dispatchEvent(new Event("resize"))}catch{}},[]);r.useEffect(()=>{s?(c(0),i(!0)):i(!1)},[s]),r.useEffect(()=>{d.current=null},[l]);const b=r.useCallback(()=>{if(!o||d.current===l)return;d.current=l;let x=0,u=0;return x=window.requestAnimationFrame(()=>{u=window.requestAnimationFrame(()=>{f()})}),()=>{try{x&&window.cancelAnimationFrame(x),u&&window.cancelAnimationFrame(u)}catch{}}},[o,l,f]);r.useEffect(()=>{if(!o)return;let x=0,u=0;const g=120,w=()=>{x=window.requestAnimationFrame(w);const _=Date.now();_-u<g||(u=_,p())};return x=window.requestAnimationFrame(w),()=>{try{x&&window.cancelAnimationFrame(x)}catch{}}},[p,o,l]);const y=r.useCallback(x=>{const{status:u,type:g,action:w,index:_}=x;if(u===nn.FINISHED){i(!1),a?.();return}if(u===nn.SKIPPED||w===Ka.SKIP){i(!1),n?.();return}if(w===Ka.CLOSE){i(!1),n?.();return}g===ja.STEP_AFTER&&(w===Ka.NEXT?c(_+1):w===Ka.PREV&&c(Math.max(0,_-1))),(g===ja.STEP_BEFORE||g===ja.TOOLTIP)&&b(),g===ja.TARGET_NOT_FOUND&&(_<t.length-1?c(_+1):(i(!1),a?.()))},[a,n,b,t.length]);return e.jsx(ic,{steps:t,run:o,continuous:!0,showProgress:!0,showSkipButton:!0,disableCloseOnEsc:!1,disableOverlayClose:!0,callback:y,spotlightClicks:!1,stepIndex:l,scrollToFirstStep:!1,disableScrolling:!0,locale:{back:"Back",close:"Close",last:"Finish",next:"Next",skip:"Skip"},floaterProps:{disableAnimation:!0,hideArrow:!1,options:{positionFixed:!0,modifiers:{computeStyle:{gpuAcceleration:!1},preventOverflow:{enabled:!0,boundariesElement:"viewport",padding:8},flip:{enabled:!0,boundariesElement:"viewport"}}}},spotlightPadding:4,styles:{options:{zIndex:1e4,primaryColor:"#1e293b",textColor:"#1e293b",backgroundColor:"#ffffff",arrowColor:"#ffffff",overlayColor:"rgba(15, 23, 42, 0.5)"},tooltip:{borderRadius:"12px",boxShadow:"0 10px 40px rgba(0, 0, 0, 0.15)",padding:"20px 24px",maxWidth:"min(320px, calc(100vw - 24px))"},tooltipContainer:{textAlign:"left"},tooltipContent:{padding:0,fontSize:"14px",lineHeight:1.5,maxHeight:"min(52vh, calc(100vh - 240px))",overflowY:"auto"},buttonNext:{backgroundColor:"#1e293b",borderRadius:"6px",padding:"10px 20px",fontSize:"14px",fontWeight:500},buttonBack:{color:"#64748b",marginRight:"10px",fontSize:"14px"},buttonSkip:{color:"#94a3b8",fontSize:"13px"},buttonClose:{top:"12px",right:"12px",color:"#94a3b8"},spotlight:{borderRadius:"6px"},overlay:{backgroundColor:"rgba(15, 23, 42, 0.5)",position:"fixed",top:0,left:0,width:"100vw",height:"100vh",overflow:"hidden"},overlayLegacy:{display:"none"},overlayLegacyCenter:{display:"none"},beacon:{display:"none"},beaconInner:{display:"none"},beaconOuter:{display:"none"}}})}const Zw=[{target:'[data-onboarding="sidebar-home"]',content:e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-semibold text-slate-900 mb-2",children:"Home"}),e.jsx("p",{className:"text-sm text-slate-600",children:"The Homepage displays your domain metrics, workspace overview, tracked competitors, and keyword rankings at a glance. Use it to monitor your overall SEO performance."})]}),placement:"right",disableBeacon:!0},{target:'[data-onboarding="sidebar-workspace"]',content:e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-semibold text-slate-900 mb-2",children:"Worksp
78ace"}),e.jsx("p",{className:"text-sm text-slate-600 mb-2",children:"Your content creation hub with two main tools:"}),e.jsxs("ul",{className:"text-sm text-slate-600 space-y-1",children:[e.jsxs("li",{children:[e.jsx("span",{className:"font-medium",children:"Workflow"})," - Generate content from keyword gaps, AI prompts, or existing pages"]}),e.jsxs("li",{children:[e.jsx("span",{className:"font-medium",children:"Worksheets"})," - Manage your content projects in spreadsheet-style tables"]})]})]}),placement:"right",disableBeacon:!0},{target:'[data-onboarding="sidebar-context"]',content:e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-semibold text-slate-900 mb-2",children:"Context"}),e.jsx("p",{className:"text-sm text-slate-600 mb-2",children:"Data sources that inform your content strategy:"}),e.jsxs("ul",{className:"text-sm text-slate-600 space-y-1",children:[e.jsxs("li",{children:[e.jsx("span",{className:"font-medium",children:"Competitors Intelligence"})," - Track competitor domains and their keyword rankings"]}),e.jsxs("li",{children:[e.jsx("span",{className:"font-medium",children:"Keywords Gap"})," - Discover keywords your competitors rank for but you don't"]}),e.jsxs("li",{children:[e.jsx("span",{className:"font-medium",children:"Company Info"})," - Your domain settings and business details"]}),e.jsxs("li",{children:[e.jsx("span",{className:"font-medium",children:"Knowledge"})," - Upload documents as reference material for AI content generation"]}),e.jsxs("li",{children:[e.jsx("span",{className:"font-medium",children:"Integration"})," - Connect Google Search Console, Webflow, and other platforms"]})]})]}),placement:"right",disableBeacon:!0},{target:'[data-onboarding="sidebar-insights"]',content:e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-semibold text-slate-900 mb-2",children:"Insights"}),e.jsx("p",{className:"text-sm text-slate-600 mb-2",children:"Monitor your SEO performance over time:"}),e.jsxs("ul",{className:"text-sm text-slate-600 space-y-1",children:[e.jsxs("li",{children:[e.jsx("span",{className:"font-medium",children:"Keywords Tracking"})," - Track your keyword rankings across search engines"]}),e.jsxs("li",{children:[e.jsx("span",{className:"font-medium",children:"Page Tracking"})," - Monitor individual page performance and rankings"]}),e.jsxs("li",{children:[e.jsx("span",{className:"font-medium",children:"Prompt Tracking"})," - Track your brand visibility in AI-generated search results"]}),e.jsxs("li",{children:[e.jsx("span",{className:"font-medium",children:"Reports"})," - View Search Console data and generate SEO reports"]})]})]}),placement:"right",disableBeacon:!0},{target:'[data-onboarding="sidebar-pricing"]',content:e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-semibold text-slate-900 mb-2",children:"Pricing"}),e.jsx("p",{className:"text-sm text-slate-600 mb-2",children:"Manage your subscription:"}),e.jsxs("ul",{className:"text-sm text-slate-600 space-y-1",children:[e.jsxs("li",{children:[e.jsx("span",{className:"font-medium",children:"Pricing"})," - View plans, upgrade, or manage your subscription"]}),e.jsxs("li",{children:[e.jsx("span",{className:"font-medium",children:"Usage"})," - Track your credit consumption and API usage history"]})]})]}),placement:"right",disableBeacon:!0}],Us={homepage_navigation:"rankgale_onboarding_homepage_navigation_v1",workflow:"rankgale_onboarding_workflow_v1",workflow_first_visit:"rankgale_onboarding_workflow_first_visit_v1",competitors:"rankgale_onboarding_competitors_v1",company:"rankgale_onboarding_company_v1",integration:"rankgale_onboarding_integration_v1",keywords_tracking:"rankgale_onboarding_keywords_tracking_v1",keyword_research:"rankgale_onboarding_keyword_research_v1",keywords_research_workflow:"rankgale_onboarding_keywords_research_workflow_v1",geo_prompt:"rankgale_onboarding_geo_prompt_v1",page_tracking:"rankgale_onboarding_page_tracking_v1",data_report:"rankgale_onboarding_data_report_v1",knowledge:"rankgale_onboarding_knowledge_v1",usage_history:"rankgale_onboarding_usage_history_v1",subscription:"rankgale_onboarding_subscription_v1"};class oi{static shouldAutoRun(s){return!this.isCompleted(s)}static isCompleted(s){try{return localStorage.getItem(s)==="true"}catch{return!1}}static markCompleted(s){try{localStorage.setItem(s,"true")}catch{}}static reset(s){try{localStorage.removeItem(s)}catch{}}}function Zs(t,s){const[a,n]=r.useState(!1),o=r.useRef(null);r.useEffect(()=>{!(s?.autoStart??!0)||!oi.shouldAutoRun(t)||(o.current="auto",n(!0),console.log("🧭 [Onboarding] Auto-start:",t))},[s?.autoStart,t]);const i=r.useCallback(()=>{o.current="manual",n(!0)},[]),l=r.useCallback(h=>!!!h?.force&&oi.isCompleted(t)?(console.log("🧭 [Onboarding] External start skipped (completed):",t),!1):(o.current="external",n(!0),console.log("🧭 [Onboarding] External start:",t),!0),[t]),c=r.useCallback(()=>{n(!1)},[]),d=r.useCallback(()=>{n(!1),oi.markCompleted(t)},[t]),m=r.useCallback(()=>o.current,[]);return{run:a,startManual:i,startExternal:l,stopAndMarkCompleted:d,stop:c,getRunSource:m}}function ej(t){const s=t.companyInfo?.company?.extracted_keywords,a=(t.overview?.top_keywords||[]).slice(0,10).map(n=>n.keyword)||[];return{name:t.companyInfo?.company?.name||null,about:t.companyInfo?.company?.about||null,url:t.companyInfo?.company?.url||t.overview?.domain||"",keywords:Array.isArray(s)?s:a}}const Oo=t=>t==null?"-":t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}
78K`:t.toLocaleString(),tj=t=>t==null?"-":`${(t*100).toFixed(1)}%`,em=t=>{try{let s=t.replace(/^sc-domain:/,"");return s.includes("://")?new URL(s).hostname.replace(/^www\./,"").toLowerCase():s.replace(/^www\./,"").toLowerCase()}catch{return t.replace(/^www\./,"").toLowerCase()}},sj=(t,s)=>{if(!t||t.length===0)return null;if(!s)return t[0].site_url;const a=em(s),n=t.map(o=>{const i=em(o.site_url);let l=0;if(i===a)l=100;else if(i.includes(a)||a.includes(i))l=80;else{const c=i.split(".").slice(-2).join("."),d=a.split(".").slice(-2).join(".");c===d&&(l=60)}return{site:o,score:l}});return n.sort((o,i)=>i.score-o.score),n[0].score===0?(console.log(`⚠️ No matching GSC site found for domain: ${s}, using first site`),t[0].site_url):(console.log(`✅ Matched GSC site: ${n[0].site.site_url} (score: ${n[0].score}) for domain: ${s}`),n[0].site.site_url)},ii=({title:t,subtitle:s,icon:a,badge:n,headerActions:o,mobileInlineHeader:i=!1,children:l})=>e.jsxs("div",{className:"bg-white border border-slate-200 rounded-xl p-3 sm:p-4 transition-all",children:[e.jsxs("div",{className:`flex justify-between gap-3 mb-4 sm:mb-6 ${i?"items-center":"flex-col sm:flex-row sm:items-center"}`,children:[e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("div",{className:"w-7 h-7 sm:w-8 sm:h-8 rounded-lg bg-slate-100 flex items-center justify-center flex-shrink-0",children:e.jsx(a,{size:14,className:"text-slate-600 sm:w-4 sm:h-4"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-xs sm:text-sm font-medium text-slate-800 truncate",children:t}),s&&e.jsx("div",{className:"text-[10px] text-slate-400 truncate",children:s})]}),n&&e.jsx("span",{className:"text-[10px] font-medium px-2 py-0.5 rounded-full bg-slate-100 text-slate-600 flex-shrink-0 hidden sm:inline",children:n})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[n&&e.jsx("span",{className:"text-[10px] font-medium px-2 py-0.5 rounded-full bg-slate-100 text-slate-600 sm:hidden",children:n}),o]})]}),l]}),aj=({kpis:t,gscSummary:s,hasGscIntegration:a})=>e.jsxs("div",{className:"space-y-2 sm:space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 gap-2 sm:gap-3",children:[e.jsxs("div",{className:"bg-slate-50 rounded-lg p-2.5 sm:p-3",children:[e.jsxs("div",{className:"flex items-center gap-1 sm:gap-1.5 mb-0.5 sm:mb-1",children:[e.jsx(Qt,{size:10,className:"text-slate-400 sm:w-3 sm:h-3"}),e.jsx("span",{className:"text-[9px] sm:text-[10px] text-slate-500 truncate",children:"Est. Traffic"})]}),e.jsx("div",{className:"text-base sm:text-lg font-semibold text-slate-800",children:Oo(t?.organic_traffic)})]}),e.jsxs("div",{className:"bg-slate-50 rounded-lg p-2.5 sm:p-3",children:[e.jsxs("div",{className:"flex items-center gap-1 sm:gap-1.5 mb-0.5 sm:mb-1",children:[e.jsx(Lr,{size:10,className:"text-slate-400 sm:w-3 sm:h-3"}),e.jsx("span",{className:"text-[9px] sm:text-[10px] text-slate-500 truncate",children:"Keywords"})]}),e.jsx("div",{className:"text-base sm:text-lg font-semibold text-slate-800",children:Oo(t?.ranking_keywords)})]}),e.jsxs("div",{className:"bg-slate-50 rounded-lg p-2.5 sm:p-3",children:[e.jsxs("div",{className:"flex items-center gap-1 sm:gap-1.5 mb-0.5 sm:mb-1",children:[e.jsx(du,{size:10,className:"text-slate-400 sm:w-3 sm:h-3"}),e.jsx("span",{className:"text-[9px] sm:text-[10px] text-slate-500 truncate",children:"Clicks"})]}),e.jsx("div",{className:"text-base sm:text-lg font-semibold text-slate-800",children:a&&s?Oo(s.clicks):"-"})]}),e.jsxs("div",{className:"bg-slate-50 rounded-lg p-2.5 sm:p-3",children:[e.jsxs("div",{className:"flex items-center gap-1 sm:gap-1.5 mb-0.5 sm:mb-1",children:[e.jsx(Ga,{size:10,className:"text-slate-400 sm:w-3 sm:h-3"}),e.jsx("span",{className:"text-[9px] sm:text-[10px] text-slate-500 truncate",children:"Impressions"})]}),e.jsx("div",{className:"text-base sm:text-lg font-semibold text-slate-800",children:a&&s?Oo(s.impressions):"-"})]}),e.jsxs("div",{className:"bg-slate-50 rounded-lg p-2.5 sm:p-3",children:[e.jsxs("div",{className:"flex items-center gap-1 sm:gap-1.5 mb-0.5 sm:mb-1",children:[e.jsx(Ma,{size:10,
78className:"text-slate-400 sm:w-3 sm:h-3"}),e.jsx("span",{className:"text-[9px] sm:text-[10px] text-slate-500 truncate",children:"CTR"})]}),e.jsx("div",{className:"text-base sm:text-lg font-semibold text-slate-800",children:a&&s?tj(s.ctr):"-"})]}),e.jsxs("div",{className:"bg-slate-50 rounded-lg p-2.5 sm:p-3",children:[e.jsxs("div",{className:"flex items-center gap-1 sm:gap-1.5 mb-0.5 sm:mb-1",children:[e.jsx(Kh,{size:10,className:"text-slate-400 sm:w-3 sm:h-3"}),e.jsx("span",{className:"text-[9px] sm:text-[10px] text-slate-500 truncate",children:"Avg Position"})]}),e.jsx("div",{className:"text-base sm:text-lg font-semibold text-slate-800",children:a&&s&&s.position?.toFixed(1)||"-"})]})]}),!a&&e.jsxs("div",{className:"bg-blue-50/50 border border-blue-100 rounded-lg p-2.5 sm:p-3 flex flex-col sm:flex-row sm:items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(di,{size:14,className:"text-blue-400 flex-shrink-0"}),e.jsx("p",{className:"text-[11px] sm:text-xs text-blue-600 truncate",children:"Connect Search Console to see real data"})]}),e.jsx("a",{href:"/app/integration",onClick:n=>{n.stopPropagation()},className:"text-[10px] font-medium text-blue-600 hover:text-blue-800 hover:underline flex-shrink-0 self-end sm:self-auto",children:"Connect →"})]})]}),tm=[{id:"competitors_keywords",name:"Keyword Gap",icon:Pt,description:"Find keyword opportunities from competitors",countKey:"keywords_gap_count"},{id:"prompt_tracking",name:"AI Visibility",icon:is,description:"Track your visibility in AI search results",countKey:"prompt_tracking_count"},{id:"page_tracking",name:"Page Optimization",icon:Qt,description:"Improve existing page rankings",countKey:"page_tracking_count"}],nj=({campaigns:t,workflowCounts:s,onNavigateCampaigns:a,onNavigateWorkflow:n,onNavigateToCampaign:o,onNavigateToWorkflowItem:i,onCreateWorksheet:l})=>{const c=t.slice(0,4),d=c.length>0,m=({className:p="",btn_text:f="Create"})=>e.jsxs("button",{type:"button",onClick:l,className:["inline-flex items-center gap-1 sm:gap-1.5 text-[10px] sm:text-[11px] font-medium px-1.5 sm:px-2 py-1 rounded-md border border-slate-200 bg-white text-slate-700 hover:bg-slate-50 transition-colors",p].join(" "),children:[e.jsx($t,{size:10,className:"text-slate-500 sm:w-3 sm:h-3"}),f]}),h=p=>s?s[p.countKey]??0:0;return s&&tm.reduce((p,f)=>p+h(f),0),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4 sm:gap-6 h-full",children:[e.jsxs("div",{className:"flex flex-col h-full border-b md:border-b-0 border-r-0 md:border-r border-slate-100 pb-3 sm:pb-4 md:pb-0 md:pr-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2 sm:mb-3",children:[e.jsxs("div",{className:"flex items-center gap-1.5 sm:gap-2",children:[e.jsx(Gh,{size:12,className:"text-slate-400 sm:w-3.5 sm:h-3.5"}),e.jsx("span",{className:"text-[11px] sm:text-xs font-medium text-slate-700",children:"Workflow"})]}),e.jsxs("button",{onClick:n,className:"flex items-center gap-1 text-[10px] text-slate-500 hover:text-slate-700 transition-colors",children:["View all",e.jsx(go,{size:10})]})]}),e.jsx("div",{className:"flex-1",children:e.jsx("div",{className:"space-y-0.5",children:tm.map(p=>{const f=h(p);return e.jsx("div",{onClick:()=>i(p.id),className:"px-1.5 sm:px-2 py-1.5 sm:py-2 -mx-1.5 sm:-mx-2 rounded-md cursor-pointer hover:bg-slate-50 transition-colors group",children:e.jsxs("div",{className:"flex items-center justify-between gap-2 sm:gap-3",children:[e.jsx("div",{className:"flex-1 min-w-0",children:e.jsx("span",{className:"text-xs sm:text-[13px] text-slate-700 truncate block",children:p.name})}),f>0&&e.jsx("span",{className:"text-[10px] sm:text-[11px] font-medium text-slate-500 bg-slate-100 px-1 sm:px-1.5 py-0.5 rounded flex-shrink-0",children:f})]})},p.id)})})})]}),e.jsxs("div",{className:"flex flex-col h-full pt-2 md:pt-0 md:pl-2",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2 sm:mb-3",children:[e.jsxs("div",{className:"flex items-center gap-1.5 sm:gap-2",children:[e.jsx(us,{size:12,className:"text-slate-400 sm:w-3.5 sm:h-3.5"}),e.jsx("span",{className:"text-[11px] sm:text-xs font-medium text-slate-700",children:"Worksheets"}),e.jsx("span",{className:"text-[9px] sm:text-[10px] text-slate-400",children:t.length})]}),e.jsxs("div",{className:"flex items-center gap-1.5 sm:gap-2",children:[d&&e.jsx(m,{}),e.jsxs("button",{onClick:a,className:"flex items-center gap-1 text-[10px] text-slate-500 hover:text-slate-700 transition-colors",children:["View all",e.jsx(go,{size:10})]})]})]}),e.jsx("div",{className:"flex-1",children:c.length>0?e.jsx("div",{className:"space-y-0.5",children:c.map(p=>e.jsx("div",{onClick:()=>
78o(p.id),className:"px-1.5 sm:px-2 py-1.5 sm:py-2 -mx-1.5 sm:-mx-2 rounded-md cursor-pointer hover:bg-slate-50 transition-colors group",children:e.jsxs("div",{className:"flex items-center gap-1.5 sm:gap-2 min-w-0",children:[e.jsx("div",{className:"w-1.5 h-1.5 rounded-full bg-slate-300 flex-shrink-0"}),e.jsx("span",{className:"text-xs sm:text-[13px] text-slate-700 truncate",children:p.name})]})},p.id))}):e.jsxs("div",{className:"flex flex-col items-center justify-center h-full py-4 sm:py-6 text-center",children:[e.jsx("div",{className:"w-7 h-7 sm:w-8 sm:h-8 rounded-lg bg-slate-100 flex items-center justify-center mb-2",children:e.jsx(us,{size:14,className:"text-slate-400 sm:w-4 sm:h-4"})}),e.jsx("p",{className:"text-[11px] sm:text-xs text-slate-400",children:"No worksheets yet"}),e.jsx("p",{className:"text-[9px] sm:text-[10px] text-slate-300 mt-0.5",children:"Create your first worksheet"}),e.jsx(m,{className:"mt-2 sm:mt-3",btn_text:"Start Content generation"})]})})]})]})};function rj({onNavigate:t,marketReloadNonce:s}){const{toast:a}=_t(),n=s??0,o=r.useRef(!1),[i,l]=r.useState(!0),[c,d]=r.useState(!1),[m,h]=r.useState(null),[p,f]=r.useState(null),[b,y]=r.useState(!0),[x,u]=r.useState(null),[g,w]=r.useState([]),[_,E]=r.useState(null),[N,S]=r.useState(!1),[k,D]=r.useState(!1),[F,R]=r.useState(null),[L,$]=r.useState(!1),[H,K]=r.useState(null),X=Zs(Us.homepage_navigation),V=({text:se,className:z=""})=>e.jsxs("div",{className:["flex items-center gap-1.5 text-[10px] text-slate-400",z].join(" "),children:[e.jsx(kt,{size:12,className:"animate-spin"}),se?e.jsx("span",{children:se}):null]}),P=({title:se,description:z,actions:U})=>e.jsxs("div",{className:"py-8 text-center",children:[e.jsx("div",{className:"text-xs text-slate-500 font-medium",children:se}),z?e.jsx("div",{className:"text-[11px] text-slate-400 mt-1",children:z}):null,U?e.jsx("div",{className:"mt-3 flex justify-center",children:U}):null]}),A=r.useCallback(async()=>{try{const se=await sr().catch(z=>(console.warn("⚠️ Failed to refresh analysis data:",z),null));return f(se),se}catch(se){return console.error("❌ Failed to refresh analysis data:",se),null}},[]),C=Io({toast:a,onCompleted:async()=>{await A()}}),I=qx({syncManager:C,loadAndGetSyncStatus:async()=>(await A())?.competitors?.sync_status??"syncing",refreshAfterCompleted:async()=>{await A()}}),j=r.useCallback(se=>{t?t(se):jt(se)},[t]),q=()=>{const se=ma(),z=se.length>0?$a(se):null;return{selectedMarkets:se,selector:z}},T=se=>{const z=new Date,U=new Date(Date.UTC(z.getUTCFullYear(),z.getUTCMonth(),z.getUTCDate())),Q=new Date(U);Q.setUTCDate(U.getUTCDate()-Math.max(1,Math.floor(se)));const me=le=>le.toISOString().slice(0,10);return{start_date:me(Q),end_date:me(U)}},M=r.useCallback(async()=>{l(!0),h(null);try{const{selectedMarkets:se,selector:z}=q(),U=!!z,[Q,me,le,O,ne]=await Promise.all([U?Promise.resolve(null):sr().catch(ze=>(console.warn("⚠️ Failed to load analysis data:",ze),null)),U?Hu(z).catch(ze=>(console.warn("⚠️ Failed to load overview batch:",ze),null)):Promise.resolve(null),U?wo(z).catch(ze=>(console.warn("⚠️ Failed to load competitors batch:",ze),null)):Promise.resolve(null),U?Dn().catch(()=>null):Promise.resolve(null),bs.getGoogleAuthExistsCached().catch(()=>({exists:!1}))]),ge=U?me?.aggregated?{company:ej({companyInfo:O,overview:me.aggregated}),seo_overview:me.aggregated,competitors:le?.aggregated??null}:null:Q;return f(ge),D(!!ne?.exists),{mergedAnalysis:ge,googleAuthExists:!!ne?.exists,selectedMarkets:se}}catch(se){return console.error("❌ Failed to load core homepage data:",se),h(se?.message||"Failed to load dashboard data"),{mergedAnalysis:null,googleAuthExists:!1,selectedMarkets:[]}}finally{d(!0),l(!1)}},[]),Z=r.useCallback(async()=>{y(!0),u(null);try{const[se,z]=await Promise.all([lr({page:1,page_size:10}),kc().catch(()=>null)]);w(se.items||[]),E(z)}catch(se){console.warn("⚠️ Failed to load workspace data:",se),u(se?.message||"Failed to load workspace data"),w([]),E(null)}finally{y(!1)}},[]),B=r.useCallback(async se=>{if(!se.googleAuthExists){K(null),$(!1),R(null);return}$(!0),K(null);try{const U=(await Ro()).items||[];if(U.length===0){R(null);return}const Q=se.analysis?.seo_overview?.domain,me=sj(U,Q);if(!me){R(null);return}const{start_date:le,end_date:O}=T(27),ne=await Rx({site_url:me,start_date:le,end_date:O,search_type:"web"});R(ne)}catch(z){console.warn("⚠️ Failed to load GSC data:",z),K(z?.message||"Failed to load Search Console data")}finally{$(!1)}},[]),ae=r.useCallback(async()=>{await Pr({timeout_ms:15e3});const se=await M();B({googleAuthExists:se.googleAuthExists,analysis:se.mergedAnalysis}),Z()},[M,B,Z]),de=r.useCallback(async()=>{await Pr({timeout_ms:15e3});const se=await M();B({googleAuthExists:se.googleAuthExists,analysis:se.mergedAnalysis})},[M,B]);r.useEffect(()=>{ae()},[ae]),r.useEffect(()=>{if(!o.current){o.current=!0;return}de()},[n,de]),r.useEffect(()=>{c&&!i&&!p&&console.log("⚠️ [HomepageView] No analysis data yet (will wait for market selection / retry).")},[c,i,p]),r.useEffect(()=>{const se=Oi(()=>{de()}),z=So(()=>{de()});return()=>{se(),z()}},[de]);const fe=p?.seo_overview?.kpis;return p?.competitors?.landscape,e.jsxs("div",{className:"flex-1 overflow-y-auto bg-slate-50 relative",children:[e.jsx(oa,{steps:Zw,run:X.run,onComplete:()=>{const se=X.getRunSource();X.stopAndMarkCompleted(),se==="auto"&&j("workflow")},onSkip:()=>{const se=X.getRunSource();X.stopAndMarkCompleted(),se==="auto"&&j("workflow")}}),e.jsx("button",{onClick:X.startManual,className:"fixed bottom-5 right-5 z-50 h-8 w-8 rounded-full bg-white border border-slate-200 shadow-md hover:shadow-lg hover:bg-slate-50 transition-all hover:scale-105 hidden sm:flex items-center justify-center",title:"View navigation guide","aria-label":"View navigation guide",children:e.jsx(Hs,{className:"h-4 w-4 text-slate-600"})}),e.jsxs("div",{className:"max-w-7xl mx-auto p-3 sm:p-4",children:[m&&e.jsxs("div",{className:"mb-4 px-4 py-3 bg-white border border-red-200 rounded-xl flex items-center gap-2",children:[e.jsx(Ss,{size:16,className:"text-red-500 flex-shrink-0"}),e.jsx("span",{className:"text-sm text-red-700",children:m}),e.jsxs("button",{onClick:ae,className:"ml-auto text-sm text-red-600 hover:text-red-800 flex items-center gap-1",children:[e.jsx(kt,{size:14}),"Retry"]})]}),e.jsx("div",{children:e.jsx(ii,{title:"Domain Metrics",icon:Qt,headerActions:L?e.jsx(V,{text:"Loading GSC"}):void 0,children:i?e.jsx(P,{title:"Loading geo/aeo metrics..."}):e.jsxs(e.Fragment,{children:[H?e.jsxs("div",{className:"mb-3 text-[11px] text-red-600 flex items-center gap-1.5",children:[e.jsx(Ss,{size:12,className:"flex-shrink-0"}),e.jsx("span",{children:H}),e.jsx("button",{type:"button",onClick:()=>{B({googleAuthExists:k,analysis:p})},className:"ml-auto text-[11px] text-red-600 hover:text-red-800 hover:underline",children:"Retry"})]}):null,e.jsx(aj,{kpis:fe||null,gscSummary:F,hasGscIntegration:k})]})})}),e.jsx("div",{className:"mt-3 sm:mt-4",children:e.jsx(ii,{title:"Workspace",icon:us,headerActions:b?e.jsx(V,{text:"Loading"}):void 0,children:b?e.jsx(P,{title:"Loading workspace..."}
78):x?e.jsx(P,{title:"Failed to load workspace",description:x,actions:e.jsxs("button",{type:"button",onClick:()=>{Z()},className:"inline-flex items-center gap-1.5 text-[11px] font-medium px-2 py-1 rounded-md border border-slate-200 bg-white text-slate-700 hover:bg-slate-50 transition-colors",children:[e.jsx(kt,{size:12,className:"text-slate-500"}),"Retry"]})}):e.jsx(nj,{campaigns:g,workflowCounts:_,onNavigateCampaigns:()=>j("campaigns"),onNavigateWorkflow:()=>j("workflow"),onNavigateToCampaign:se=>jt("table-new",{campaign:se}),onNavigateToWorkflowItem:se=>tg(se),onCreateWorksheet:()=>S(!0)})})}),e.jsxs("div",{className:"mt-3 sm:mt-4",children:[C.panel.phase!=="idle"&&e.jsx("div",{className:"mb-2 sm:mb-3 bg-slate-50 rounded-lg p-2 sm:p-3 border border-slate-100",children:e.jsx(Mo,{state:C.panel})}),e.jsx(Mx,{competitorsData:p?.competitors||null,userDomain:p?.seo_overview?.domain?{domain:p.seo_overview.domain,keywords:p.seo_overview.kpis?.ranking_keywords??null,traffic:p.seo_overview.kpis?.organic_traffic??null,lastSyncedAt:p.seo_overview.last_synced_at??null}:p?.competitors?.domain?{domain:p.competitors.domain,keywords:null,traffic:null,lastSyncedAt:p.competitors.last_synced_at??null}:null,onDataChange:()=>{ae()},onCompetitorsAdded:se=>{if(se){C.startTask({taskId:se,etaText:"~1-5min"});return}I.startSyncAndPoll({etaText:"~1-5min"})},onKeywordsSyncStarted:se=>{if(se){C.startTask({taskId:se,etaText:"~2-5 min"});return}C.startSync("~2-5 min")},isWidgetMode:!0,onViewAll:()=>j("competitors")})]}),e.jsx("div",{className:"mt-3 sm:mt-4",children:e.jsx(ii,{title:"geo/aeo Keywords Tracking",subtitle:"Last 4 weeks",icon:Lr,headerActions:e.jsxs("button",{onClick:()=>j("page_tracking"),className:"flex items-center gap-1 text-[10px] sm:text-xs text-slate-500 hover:text-slate-700 transition-colors",children:["View all",e.jsx(go,{size:10,className:"sm:w-3 sm:h-3"})]}),children:e.jsx("div",{className:"bg-white rounded-xl border border-slate-200 flex flex-col overflow-hidden max-h-[250px] sm:max-h-[300px]",children:e.jsx(Wx,{variant:"homepage",marketReloadNonce:n,maxHeightClassName:"max-h-[250px] sm:max-h-[300px]"})})})})]}),e.jsx(Jw,{isOpen:N,onClose:()=>S(!1)})]})}const oj=[{target:'[data-onboarding="prompt-tracking-intro"]',content:"AI Visibility tracks how your brand appears in AI-generated responses. Monitor mentions across ChatGPT, Gemini, Perplexity, and Claude to understand your AI search presence.",placement:"bottom",disableBeacon:!0},{target:'[data-onboarding="add-prompt-button"]',content:"Add prompts to track. These are the questions or queries you want to monitor across AI platforms.",placement:"bottom",disableBeacon:!0},{target:'[data-onboarding="run-scan-button"]',content:"Run a scan to query all tracked prompts across AI models. Results show which responses mention your brand and with what sentiment.",placement:"bottom",disableBeacon:!0},{target:'[data-onboarding="scan-history"]',content:"View historical scan results. Compare how your AI visibility changes over time as you optimize your content strategy.",placement:"right",disableBeacon:!0}],ij=[{label:"TODAY",value:{from:new Date().toISOString().split("T")[0],to:new Date().toISOString().split("T")[0]}},{label:"YESTERDAY",value:{from:new Date(Date.now()-864e5).toISOString().split("T")[0],to:new Date(Date.now()-864e5).toISOString().split("T")[0]}},{label:"LAST 7 DAYS",value:{from:new Date(Date.now()-6*864e5).toISOString().split("T")[0],to:new Date().toISOString().split("T")[0]}},{label:"LAST 14 DAYS",value:{from:new Date(Date.now()-13*864e5).toISOString().split("T")[0],to:new Date().toISOString().split("T")[0]}},{label:"LAST 30 DAYS",value:{from:new Date(Date.now()-29*864e5).toISOString().split("T")[0],to:new Date().toISOString().split("T")[0]}},{label:"THIS WEEK",value:{from:new Date(Date.now()-new Date().getDay()*864e5).toISOString().split("T")[0],to:new Date().toISOString().split("T")[0]}},{label:"THIS MONTH",value:{from:new Date(new Date().getFullYear(),new Date().getMonth(),1).toISOString().split("T")[0],to:new Date().toISOString().split("T")[0]}},{label:"LAST MONTH",value:{from:new Date(new Date().getFullYear(),new Date().getMonth()-1,1).toISOString().split("T")[0],to:new Date(new Date().getFullYear(),new Date().getMonth(),0).toISOString().split("T")[0]}}];function lj(t){return t.filter(s=>s.label!=="YTD")}function Bo(t,s,a){return Math.min(a,Math.max(s,t))}const Sa=({value:t,onChange:s,presets:a=ij,placeholder:n="Select date range",className:o="",showClear:i=!0,label:l})=>{const[c,d]=v.useState(!1),[m,h]=v.useState(t.from),[p,f]=v.useState(t.to),[b,y]=v.useState(null),[x,u]=v.useState(()=>{const A=t.from?new Date(t.from):new Date;return{year:A.getFullYear(),month:A.getMonth()}}),g=v.useRef(null),w=v.useRef(null),_=v.useRef(null),E=v.useRef(!1),[N,S]=v.useState(null);v.useEffect(()=>{c?E.current||(h(t.from),f(t.to),y(null),E.current=!0):(E.current=!1,S(null))},[c,t]);const k=v.useCallback(()=>
78{if(!c||!_.current||!w.current)return;const A=12,C=580,I=_.current.getBoundingClientRect(),j=window.innerWidth,q=window.innerHeight,T=Math.max(240,j-A*2),M=Math.min(C,T);w.current.style.width=`${M}px`;const B=w.current.getBoundingClientRect().height||420,ae=[{top:I.bottom+8,left:I.left},{top:I.bottom+8,left:I.right-M},{top:I.top-8-B,left:I.left},{top:I.top-8-B,left:I.right-M},{top:I.top,left:I.right+8},{top:I.bottom-B,left:I.right+8},{top:I.top,left:I.left-8-M},{top:I.bottom-B,left:I.left-8-M}],de={minLeft:A,maxLeft:j-A-M,minTop:A,maxTop:q-A-B};function fe(me){const le=Bo(me.left,de.minLeft,de.maxLeft),O=Bo(me.top,de.minTop,de.maxTop),ne=Math.abs(me.left-le),ge=Math.abs(me.top-O);return ne+ge}let se=ae[0],z=fe(se);for(const me of ae){const le=fe(me);le<z&&(se=me,z=le)}const U=Bo(se.left,de.minLeft,de.maxLeft),Q=Bo(se.top,de.minTop,de.maxTop);S({top:Q,left:U,width:M})},[c]);v.useLayoutEffect(()=>{if(!c)return;const A=window.requestAnimationFrame(()=>k());return()=>window.cancelAnimationFrame(A)},[c,k]),v.useEffect(()=>{if(!c)return;const A=()=>k(),C=()=>k();return window.addEventListener("resize",A),window.addEventListener("scroll",C,!0),()=>{window.removeEventListener("resize",A),window.removeEventListener("scroll",C,!0)}},[c,k]),v.useEffect(()=>{function A(C){g.current&&(g.current.contains(C.target)||(h(t.from),f(t.to),y(null),d(!1)))}if(c)return document.addEventListener("mousedown",A),()=>document.removeEventListener("mousedown",A)},[c,t]),t.from&&t.to&&`${t.from}${t.to}`;function D(A,C){const j=new Date(A,C,1).getDay(),q=new Date(A,C+1,0).getDate(),T=[];let M=[];for(let Z=0;Z<j;Z++){const B=new Date(A,C,0-(j-1-Z));M.push({y:B.getFullYear(),m:B.getMonth(),d:B.getDate(),inMonth:!1})}for(let Z=1;Z<=q;Z++)M.length===7&&(T.push(M),M=[]),M.push({y:A,m:C,d:Z,inMonth:!0});for(;M.length&&M.length<7;){const Z=new Date(A,C,q+(M.length===0?1:M.length-j+1));M.push({y:Z.getFullYear(),m:Z.getMonth(),d:Z.getDate(),inMonth:!1})}return M.length&&T.push(M),T}function F(A,C,I){const j=String(C+1).padStart(2,"0"),q=String(I).padStart(2,"0");return`${A}-${j}-${q}`}function R(A){if(!m||!p)return!1;const C=new Date(A).getTime();return C>=new Date(m).getTime()&&C<=new Date(p).getTime()}function L(A,C,I){const j=F(A,C,I);if(!m||m&&p){h(j),f(void 0),y(j);return}const q=new Date(m).getTime();new Date(j).getTime()<q?(h(j),f(m)):f(j),y(null)}const $=()=>{m&&p?(s({from:m,to:p}),d(!1)):m&&(s({from:m,to:m}),d(!1))},H=()=>{h(t.from),f(t.to),y(null),d(!1)},K=()=>{h(void 0),f(void 0),y(null),s({})},X=A=>{s(A.value),d(!1)},V=lj(a),P=D(x.year,x.month);return e.jsxs("div",{className:`relative ${o}`,ref:g,children:[l&&e.jsx("div",{className:"mb-2 text-sm font-medium text-slate-700",children:l}),e.jsx("button",{ref:_,type:"button",className:"h-9 w-full rounded-md border border-slate-300 bg-white px-3 text-sm text-left",onClick:()=>d(A=>!A),children:t.from&&t.to?`${t.from} — ${t.to}`:n}),c&&e.jsx("div",{ref:w,className:"fixed z-99 rounded-lg border border-slate-200 shadow-lg bg-white p-4",style:{top:N?`${N.top}px`:"-9999px",left:N?`${N.left}px`:"-9999px",width:N?`${N.width}px`:"580px",maxWidth:N?`${N.width}px`:void 0,visibility:N?"visible":"hidden"},children:e.jsxs("div",{className:"flex gap-4 items-start",children:[V&&V.length>0&&e.jsxs("div",{className:"w-[160px] pr-4 border-r border-slate-200 flex flex-col",children:[e.jsx("div",{className:"mb-3 text-xs font-semibold text-slate-600 uppercase tracking-wide",children:"Preset Ranges"}),e.jsx("div",{className:"flex flex-col gap-1",children:V.map((A,C)=>e.jsx("button",{type:"button",onClick:()=>X(A),className:"w-full rounded-md border border-slate-200 bg-white px-2.5 py-1.5 text-xs text-slate-700 text-left transition-all hover:bg-slate-50 hover:border-slate-300 hover:text-slate-900 active:bg-slate-100",children:A.label},C))})]}),e.jsxs("div",{className:"flex-1 flex flex-col",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("button",{className:"h-8 w-8 rounded hover:bg-slate-100 flex items-center justify-center",onClick:()=>{const A=new Date(x.year,x.month-1,1);u({year:A.getFullYear(),month:A.getMonth()})},children:"‹"}),e.jsx("div",{className:"text-sm font-medium text-slate-900",children:new Date(x.year,x.month,1).toLocaleStr
78ing(void 0,{month:"long",year:"numeric"})}),e.jsx("button",{className:"h-8 w-8 rounded hover:bg-slate-100 flex items-center justify-center",onClick:()=>{const A=new Date(x.year,x.month+1,1);u({year:A.getFullYear(),month:A.getMonth()})},children:"›"})]}),e.jsx("div",{className:"grid grid-cols-7 text-center text-xs text-slate-500 mb-1",children:["Su","Mo","Tu","We","Th","Fr","Sa"].map(A=>e.jsx("div",{className:"py-1",children:A},A))}),e.jsx("div",{className:"grid grid-cols-7 gap-1",children:P.flat().map((A,C)=>{const I=F(A.y,A.m,A.d),j=m===I,q=p===I,T=R(I);return e.jsx("button",{disabled:!A.inMonth,onClick:()=>L(A.y,A.m,A.d),className:`h-8 rounded-md text-sm ${A.inMonth?T?"bg-slate-900/10":"hover:bg-slate-100":"text-slate-300 cursor-not-allowed"} ${j||q?"ring-2 ring-slate-900 ring-offset-1":""}`,children:A.d},C)})}),e.jsxs("div",{className:"mt-3 flex items-center justify-between",children:[i?e.jsx("button",{className:"text-sm text-slate-600 hover:text-slate-900",onClick:K,children:"Clear"}):e.jsx("div",{}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{className:"h-8 rounded-md border border-slate-300 px-3 text-sm",onClick:H,children:"Cancel"}),e.jsx("button",{className:"h-8 rounded-md bg-slate-900 text-white px-3 text-sm hover:bg-slate-800 disabled:opacity-50 disabled:cursor-not-allowed",onClick:$,disabled:!m||!p,children:"Apply"})]})]})]})]})})]})},Yx=async(t,s,a)=>await ot("/geo/overview",{company_id:t,start_date:s,end_date:a}),cj=async t=>await Je("/geo/scans",t),Fc=async(t,s,a,n,o,i=1,l=5)=>{const c={company_id:t,page:i,page_size:l};return s&&(c.start_date=s),a&&(c.end_date=a),n&&(c.tracked_prompt_id=n),o&&(c.provider=o),await ot("/geo/scans",c)},Ai=async t=>await ot(`/geo/scans/${t}`),Jx=async t=>await Je("/geo/generate_prompts",{debug:t?.debug??!1,force_regenerate:t?.force_regenerate??!1}),Xx=async t=>await $r("/geo/cached_prompts",{prompts:t}),Qx=async(t,s=10)=>await Je("/geo/generate_more_prompts",{existing_prompts:t,count:s}),Zx=async t=>await Je("/geo/tracked_prompts",t),eh=async(t,s=!1,a)=>{const n={company_id:t,include_inactive:s};return a&&(n.source=a),await ot("/geo/tracked_prompts",n)},dj=async t=>await ot(`/geo/tracked_prompts/${t}`),th=async(t,s)=>await $r(`/geo/tracked_prompts/${t}`,s),sh=async t=>await Ca(`/geo/tracked_prompts/${t}`),ah=async t=>await Je("/geo/tracked_prompts/sync",t),nh=async(t,s,a,n,o="latest")=>await ot("/geo/tracked_prompts/history",{company_id:t,view_mode:s,start_date:a,end_date:n,aggregation:o}),Qr=t=>{const s={};for(const n of t){const o=n.provider.toLowerCase().includes("chatgpt")?"chatgpt":n.provider.toLowerCase().includes("claude")?"claude":n.provider.toLowerCase().includes("gemini")?"gemini":n.provider.toLowerCase();for(const i of n.points){const l=i.day;s[l]||(s[l]={chatgpt:null,claude:null,gemini:null}),s[l][o]=i.value}}return Object.keys(s).sort().map(n=>({date:mj(n),dateISO:n,chatgpt:s[n].chatgpt,claude:s[n].claude,gemini:s[n].gemini}))},mj=t=>{try{const s=t.split("-");if(s.length!==3)return t;const a=parseInt(s[1],10)-1,n=parseInt(s[2],10),o=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];return a<0||a>11||isNaN(n)?t:`${o[a]} ${String(n).padStart(2,"0")}`}catch{return t}},uj=Object.freeze(Object.defineProperty({__proto__:null,convertTrendDataToChartFormat:Qr,createGeoScan:cj,createTrackedPrompt:Zx,deleteTrackedPrompt:sh,generateMorePrompts:Qx,generatePrompts:Jx,getGeoOverview:Yx,getGeoScanDetail:Ai,getGeoScans:Fc,getTrackedPrompt:dj,getTrackedPromptsHistory:nh,listTrackedPrompts:eh,saveCachedPrompts:Xx,syncTrackedPrompts:ah,updateTrackedPrompt:th},Symbol.toStringTag,{value:"Module"}));function Jn(t){return!!t&&typeof t=="object"&&t.__pending===!0&&typeof t.__task_id=="string"}function Xn(t){return!!t&&typeof t=="object"&&t.status==="running"}function Rr(t){if(!t)return[];const s=/\$\{([^}]+)\}/g,a=[],n=["keyword groups","keyword group","campaign info"];let o;for(;(o=s.exec(t))!==null;){const i=o[1].trim(),l=i.toLowerCase();n.includes(l)||a.push(i)}
78return[...new Set(a)]}function rh(t,s){const a=s.toLowerCase();let n=t.find(o=>o.system_name&&o.system_name.toLowerCase()===a);return n||(n=t.find(o=>{const i=o.config?.system_name;return i&&i.toLowerCase()===a})),n||(n=t.find(o=>o.title.toLowerCase()===a)),n||(n=t.find(o=>o.id===s)),n}function oh(t,s){return s.map(a=>{const n=rh(t,a);return{columnName:a,columnId:n?.id||null,columnTitle:n?.title||null,columnSystemName:n?.system_name||null,exists:!!n}})}function Hi(t,s){return t.cells[s]?.value}function Ba(t,s){const a=Hi(t,s);return a==null||Jn(a)||Xn(a)?"":typeof a=="object"?a.result!==void 0?Array.isArray(a.result)?a.result.length>0?a.result.join(", "):"":String(a.result??"").trim():Array.isArray(a)?a.length>0?a.join(", "):"":JSON.stringify(a):String(a).trim()}function sm(t){if(typeof t!="string")return t;const s=t.trim();if(!s.startsWith("{")&&!s.startsWith("["))return t;try{return JSON.parse(s)}catch{return t}}function ml(t,s){const a=Hi(t,s);if(a==null||Jn(a)||Xn(a))return null;if(typeof a=="object"&&!Array.isArray(a)&&"result"in a){let n=a.result;return Array.isArray(n)&&n.length===0||n===""||n===null||n===void 0?null:(typeof n=="string"&&(n=sm(n)),n)}if(Array.isArray(a))return a.length>0?a:null;if(typeof a=="string"){const n=a.trim();return n?sm(n):null}return a}function li(t,s,a){const n=[],o=[],i=[];for(const l of a){const c=rh(s,l);if(!c){i.push(l);continue}const d=Hi(t,c.id);if(Jn(d)||Xn(d)){o.push(c.title);continue}Ba(t,c.id)||n.push(c.title)}return{valid:n.length===0&&o.length===0&&i.length===0,missingColumns:n,pendingColumns:o,invalidColumns:i}}function xj(t){return t?.user_prompt?Rr(t.user_prompt):[]}function Zr(t){if(!t?.keywords?.dependencies)return[];const s=[];return Array.isArray(t.keywords.dependencies.seeds)&&s.push(...t.keywords.dependencies.seeds.filter(a=>a&&typeof a=="string")),Array.isArray(t.keywords.dependencies.context)&&s.push(...t.keywords.dependencies.context.filter(a=>a&&typeof a=="string")),[...new Set(s)]}function jr(t){const s=t.type,a=t.config;if(s==="ai")return xj(a?.ai);if(s==="keywords"||s==="ai_keywords")return Zr(a);if(s==="seo_analysis"&&a?.seo_analysis?.url_source_column_id)return[a.seo_analysis.url_source_column_id];if(s==="seo_action"){const n=[];return a?.seo_action?.advice_source_column&&n.push(a.seo_action.advice_source_column),a?.seo_action?.page_url_column&&n.push(a.seo_action.page_url_column),n}if(s==="webflow"){const n=[],o=a?.webflow;return o?.content_column&&typeof o.content_column=="string"&&n.push(o.content_column.trim()),n.filter(i=>i.length>0)}if(s==="shopify"){const n=[],o=a?.shopify;if(!o)return[];const l=(o.content_type||"article")==="page"?o.page:o.article;return l&&(l.title_column&&typeof l.title_column=="string"&&n.push(l.title_column.trim()),l.content_column&&typeof l.content_column=="string"&&n.push(l.content_column.trim())),n.filter(c=>c.length>0)}return[]}function lo(t,s,a){const n=[],o=[],i=[];for(const l of a){const c=s.find(h=>h.id===l||h.system_name===l);if(!c){i.push(l);continue}const d=Hi(t,c.id);if(Jn(d)||Xn(d)){o.push(c.title);continue}Ba(t,c.id)||n.push(c.title)}return{valid:n.length===0&&o.length===0&&i.length===0,missingColumns:n,pendingColumns:o,invalidColumns:i}}const ql="worksheet_pipeline_started";function hj(t){const s=t.campaignId;return!s||typeof s!="string"||!t.tableType||typeof t.tableType!="string"?null:`worksheet_pipeline_plan:${s}:${t.tableType}`}function pj(t){try{const s=hj({campaignId:t.payload.campaign_id??null,tableType:t.payload.table_type});if(!s)return;const a=Date.now(),n=(t.response.results||[]).filter(d=>d?.status==="started"&&typeof d?.row_id=="string").map(d=>({row_id:String(d.row_id),column_ids:Array.isArray(t.payload.column_ids)?t.payload.column_ids.filter(m=>typeof m=="string"&&m.trim()):[],pipeline_id:d.pipeline_id??t.payload.pipeline_id??null,first_task_id:d.first_task_id??null,started_at_ms:a})).filter(d=>d.column_ids.length>0);if(n.length===0)return;const o=localStorage.getItem(s),i=o?JSON.parse(o):[],l=new Map,c=1440*60*1e3;for(const d of Array.isArray(i)?i:[]){if(!d||typeof d.row_id!="string")continue;const m=typeof d.started_at_ms=="number"?d.started_at_ms:0;a-m>
78c||l.set(d.row_id,d)}for(const d of n)l.set(d.row_id,d);localStorage.setItem(s,JSON.stringify(Array.from(l.values())))}catch{}}function gj(t){try{window.dispatchEvent(new CustomEvent(ql,{detail:{payload:t.payload,response:t.response}}))}catch{}}const fj={async startRowPipeline(t){const s=await Je("/worksheet_pipeline/start_row_pipeline",t);return pj({payload:t,response:s}),gj({payload:t,response:s}),s}};class yj{async createWorksheetAndGenerateFromGroups(s){const a=this.filterGroupsWithKeywords(s.groups);if(a.length===0)throw new Error("No groups with keywords were selected.");const n=(x,u)=>{s.options.onProgress?.(x,u)};n("creating_campaign","Creating worksheet...");const{campaignId:o,viewId:i}=await this.createWorksheetCampaign({source:s.source,campaignName:s.campaignName,campaignSource:s.campaignSource});n("creating_campaign","Loading worksheet config...");const c=(await Wt.getViewConfig(i)).view_system_name||"custom";n("creating_campaign","Loading columns..."),console.log("🔎 Loading columns for new worksheet...");const d=await this.loadColumns({campaignId:o,viewId:i});s.options.context&&(n("creating_campaign","Applying AI context..."),await this.applyAiContextToAiColumns({campaignId:o,columns:d,context:s.options.context}));const m=this.findKeywordsColumn(d),h=this.findPromptColumn(d),p=this.findKeywordsGroupColumn(d),f=this.findTitleColumn(d),b=this.findContentColumn(d);let y;if(m)console.log("🧩 Creating rows and filling keywords..."),n("creating_rows","Filling keywords..."),y=await this.createRowsWithKeywords({campaignId:o,viewSystemName:c,keywordsGroupColumnName:p?.name||null,keywordsColumnName:m.name,groups:a});else if(h)console.log("🧩 Creating rows and filling prompts..."),n("creating_rows","Filling prompts..."),y=await this.createRowsWithPrompts({campaignId:o,viewSystemName:c,promptColumnName:h.name,groups:a});else throw new Error('No "Keywords" or "Prompt" column found in the selected template.');return s.options.generateTitleAndContent&&await this.generateTitleAndContent({campaignId:o,viewSystemName:c,columns:d,titleColumnId:f?.id||null,contentColumnId:b?.id||null,rowIds:y,groupIdsInOrder:a.map(x=>x.id),titlePollingTimeoutMs:s.options.titlePollingTimeoutMs,titlePollingIntervalMs:s.options.titlePollingIntervalMs,onProgress:s.options.onProgress}),n("completed"),{campaignId:o,viewId:i,viewSystemName:c,createdRowIds:y,keywordsColumnId:m?.id||null,titleColumnId:f?.id||null,contentColumnId:b?.id||null}}async createWorksheetCampaign(s){if(s.source.kind==="user_template"){console.log("🚀 Applying user worksheet template...");const o=await $c({template_id:s.source.templateId,campaign_name:s.campaignName,source:s.campaignSource}),i=await this.pickViewId({appliedViewIds:o.view_ids,campaignId:o.campaign_id});return{campaignId:o.campaign_id,viewId:i}}if(s.source.kind==="content_generation_template"){console.log("🧩 Creating worksheet from content generation template...");const o=await Hx.createWorksheetFromTemplate({name:s.campaignName,template_type:s.source.templateType,source:s.campaignSource});return{campaignId:o.campaign_id,viewId:o.view_id}}console.log("🧩 Creating campaign from default template...");const a=await No({name:s.campaignName,template_type:s.source.templateType,source:s.campaignSource}),n=await this.pickViewId({appliedViewIds:[],campaignId:a.id});return{campaignId:a.id,viewId:n}}filterGroupsWithKeywords(s){return(s||[]).filter(a=>(a.keywords||[]).some(n=>(n.keyword||"").trim().length>0))}async pickViewId(s){if(Array.isArray(s.appliedViewIds)&&s.appliedViewIds.length>0)return s.appliedViewIds[0];const o=[...(await Wt.listViewConfigs({campaign_id:s.campaignId})).items||[]].sort((i,l)=>(i.display_order??0)-(l.display_order??0))[0];if(!o?.id)throw new Error("Template applied, but no views were created.");return o.id}async loadColumns(s){return(await Vt.listColumns({campaign_id:s.campaignId,view_config_id:s.viewId,is_active:!0,include_system_columns:!0,include_config:!0})).items||[]}async applyAiContextToAiColumns(s){const a=(s.columns||[]).filter(o=>o.type==="ai"||o.type==="ai_text");if(a.length===0)return;const n=a.map(async o=>{try{const i=o.config||{},c={...i.ai||{},context:s.context,use_knowledge_base:!!s.context.knowledges?.enabled};await Vt.updateColumn(o.id,{config:{...i,ai:c}})}catch(i){console.warn("⚠️ Failed to apply AI context to column:",o?.id,i)}});await Promise.all(n)}findKeywordsColumn(s){return(s||[]).find(n=>
78n.type==="keywords")||null}findPromptColumn(s){const a=(s||[]).find(o=>this.safeLower(o.system_name)==="prompt");return a||(s||[]).find(o=>this.safeLower(o.name)==="prompt")||null}findKeywordsGroupColumn(s){const a=(s||[]).find(o=>this.safeLower(o.system_name)==="keywords_group");return a||(s||[]).find(o=>this.safeLower(o.name)==="keywords group")||null}findTitleColumn(s){const a=(s||[]).filter(i=>i.type==="ai"||i.type==="ai_text"),n=a.find(i=>this.includesAny(this.safeLower(i.system_name),["title","topic"]));return n||a.find(i=>this.includesAny(this.safeLower(i.name),["title","topic"]))||null}findContentColumn(s){const a=(s||[]).filter(i=>i.type==="ai"||i.type==="ai_text"),n=a.find(i=>this.includesAny(this.safeLower(i.system_name),["content","body","article"]));return n||a.find(i=>this.includesAny(this.safeLower(i.name),["content","body","article"]))||null}findImagePromptColumn(s){const a=(s||[]).filter(i=>i.type==="ai"||i.type==="ai_text"),n=a.find(i=>this.safeLower(i.system_name)==="image_prompt");return n||a.find(i=>this.includesAny(this.safeLower(i.name),["image prompt","image_prompt"]))||null}findAIImageColumn(s){const a=(s||[]).find(o=>o.type==="ai_image");return a||(s||[]).find(o=>this.safeLower(o.system_name)==="ai_image")||null}findUrlColumn(s){const a=(s||[]).find(o=>this.includesAny(this.safeLower(o.system_name),["url","page_url","article_url"]));return a||(s||[]).find(o=>this.includesAny(this.safeLower(o.name),["url","page url","article url"]))||null}safeLower(s){return typeof s=="string"?s.toLowerCase():""}includesAny(s,a){return a.some(n=>s.includes(n))}buildKeywordsArray(s){return(s.keywords||[]).map(a=>(a.keyword||"").trim()).filter(a=>a.length>0)}async createRowsWithKeywords(s){if(!s.keywordsColumnName)throw new Error('No "Keywords" column found in the selected template.');const a=s.groups.map((c,d)=>({entity_id:"",custom_data_updates:{...s.keywordsGroupColumnName?{[s.keywordsGroupColumnName]:(c.name||"").trim()}:{},[s.keywordsColumnName]:this.buildKeywordsArray(c)},display_order:d+1})),n=await Wt.batchUpdateCustomData({campaign_id:s.campaignId,table_type:s.viewSystemName,updates:a}),o=Array.isArray(n.created_items)?n.created_items:[],i=new Map;o.forEach(c=>{typeof c.index=="number"&&typeof c.entity_id=="string"&&c.entity_id&&i.set(c.index,c.entity_id)});const l=[];for(let c=0;c<a.length;c+=1){const d=i.get(c);if(!d)throw new Error("Failed to create some rows. Please try again.");l.push(d)}return l}async createRowsWithPrompts(s){const a=s.groups.map((c,d)=>({entity_id:"",custom_data_updates:{[s.promptColumnName]:(c.name||"").trim()},display_order:d+1})),n=await Wt.batchUpdateCustomData({campaign_id:s.campaignId,table_type:s.viewSystemName,updates:a}),o=Array.isArray(n.created_items)?n.created_items:[],i=new Map;o.forEach(c=>{typeof c.index=="number"&&typeof c.entity_id=="string"&&c.entity_id&&i.set(c.index,c.entity_id)});const l=[];for(let c=0;c<a.length;c+=1){const d=i.get(c);if(!d)throw new Error("Failed to create some rows. Please try again.");l.push(d)}return l}async createRowsWithUrls(s){if(!s.urlColumnName)throw new Error('No "URL" column found in the selected template.');const a=s.pageUrls.map((c,d)=>({entity_id:"",custom_data_updates:{[s.urlColumnName]:c.trim()},display_order:d+1})),n=await Wt.batchUpdateCustomData({campaign_id:s.campaignId,table_type:s.viewSystemName,updates:a}),o=Array.isArray(n.created_items)?n.created_items:[],i=new Map;o.forEach(c=>{typeof c.index=="number"&&typeof c.entity_id=="string"&&c.entity_id&&i.set(c.index,c.entity_id)});const l=[];for(let c=0;c<a.length;c+=1){const d=i.get(c);if(!d)throw new Error("Failed to create some rows. Please try again.");l.push(d)}return l}async generateTitleAndContent(s){if(!s.titleColumnId||!s.contentColumnId)throw new Error('Selected template does not contain both "Title" and "Content" AI columns.');const a=(d,m)=>{s.onProgress?.(d,m)},n=this.buildSafeRowDataMap(s.rowIds,s.groupIdsInOrder),o=[s.titleColumnId,s.contentColumnId],i=this.findImagePromptColumn(s.columns);i&&o.push(i.id);const l=this.findAIImageColumn(s.columns);l&&o.push(l.id);const c=o.length;console.log(`🧩 Starting backend pipeline with ${c} steps: Title -> Content${i?" -> Image Prompt":""}${l?" -> AI Image":""}...`),a("generating_title","Starting generation..."),await fj.startRowPipeline({campaign_id:s.campaignId,table_type:s.viewSystemName,column_ids:o,row_i
78ds:s.rowIds,row_data_map:n})}buildRowDataMap(s,a){const n={};for(let o=0;o<s.length;o+=1)n[s[o]]={group_id:a[o]};return n}buildSafeRowDataMap(s,a){const n={};for(let o=0;o<s.length;o+=1){const i=a[o],l=typeof i=="string"&&/^[0-9a-f]{32}$/i.test(i.trim());n[s[o]]=l?{group_id:i.trim()}:{}}return n}contentDependsOnTitle(s){const a=s.columns.find(c=>c.id===s.titleColumnId),n=s.columns.find(c=>c.id===s.contentColumnId);if(!a||!n)return!1;const o=this.getColumnRefs(a),i=this.getAiUserPrompt(n);if(!i)return!1;const l=Rr(i).map(c=>c.toLowerCase());return o.some(c=>l.includes(c.toLowerCase()))}getAiUserPrompt(s){const n=(s.config||{}).ai;return typeof n?.user_prompt=="string"?n.user_prompt:""}getColumnRefs(s){const a=[];return s.system_name&&a.push(s.system_name),s.name&&a.push(s.name),a.push(s.id),a.filter(n=>typeof n=="string"&&n.trim().length>0)}isFailedCellValue(s){return s&&typeof s=="object"&&s.status==="failed"}buildSubsetRowDataMap(s,a){const n={};return(a||[]).forEach(o=>{o&&s[o]&&(n[o]=s[o])}),n}async enqueueContentWhenTitleReady(s){const a=Date.now(),n=new Set((s.rowIds||[]).filter(Boolean)),o=[],i=n.size;for(;n.size>0;){if(Date.now()-a>=s.timeoutMs)throw new Error("Timed out while waiting for title generation to finish.");const l=Array.from(n),d=(await Wt.fetchByIds({campaign_id:s.campaignId,table_type:s.viewSystemName,entity_ids:l})).items||[],m=[];for(const p of l){const b=d.find(y=>y.entity_id===p)?.custom_data?.[s.titleColumnId];if(!(Jn(b)||Xn(b))){if(this.isFailedCellValue(b)){n.delete(p),o.push(p);continue}n.delete(p),m.push(p)}}const h=i-n.size;s.onProgress?.("generating_title",`Waiting for titles... (${h}/${i})`),m.length>0&&(console.log(`🪄 Enqueueing content for ${m.length} row(s) (ready titles)`),s.onProgress?.("generating_content","Generating content..."),await Vt.generateAIValue({campaign_id:s.campaignId,column_id:s.contentColumnId,row_ids:m,row_data_map:this.buildSubsetRowDataMap(s.rowDataMap,m)})),n.size>0&&await this.sleep(s.intervalMs)}o.length>0&&console.warn("⚠️ Some rows failed title generation; content generation was skipped for those rows:",o)}async waitForColumnReady(s){const a=Date.now();for(;Date.now()-a<s.timeoutMs;){const o=(await Wt.fetchByIds({campaign_id:s.campaignId,table_type:s.viewSystemName,entity_ids:s.rowIds})).items||[];if(s.rowIds.every(l=>{const d=o.find(m=>m.entity_id===l)?.custom_data?.[s.columnId];return!Jn(d)&&!Xn(d)}))return;await this.sleep(s.intervalMs)}throw new Error("Timed out while waiting for title generation to finish.")}async createWorksheetAndGenerateFromPages(s){const a=(s.pageUrls||[]).filter(u=>u.trim().length>0);if(a.length===0)throw new Error("No page URLs were selected.");const n=(u,g)=>{s.options.onProgress?.(u,g)};n("creating_campaign","Creating worksheet...");const{campaignId:o,viewId:i}=await this.createWorksheetCampaign({source:s.source,campaignName:s.campaignName,campaignSource:s.campaignSource});n("creating_campaign","Loading worksheet config...");const c=(await Wt.getViewConfig(i)).view_system_name||"custom";n("creating_campaign","Loading columns..."),console.log("🔎 Loading columns for new worksheet...");const d=await this.loadColumns({campaignId:o,viewId:i});s.options.context&&(n("creating_campaign","Applying AI context..."),await this.applyAiContextToAiColumns({campaignId:o,columns:d,context:s.options.context}));const m=this.findUrlColumn(d),h=this.findAnalysisColumn(d),p=this.findTitleColumn(d),f=this.findContentColumn(d);console.log("🧩 Creating rows and filling URLs..."),n("creating_rows","Filling URLs...");const b=await this.createRowsWithUrls({campaignId:o,viewSystemName:c,urlColumnName:m?.name||null,pageUrls:a}),y=s.options.runAnalysis&&h,x=s.options.includeTitleContent||s.options.generateTitleAndContent;return y?(console.log("🔍 Running SEO Analysis..."),n("generating_title","Running SEO Analysis..."),await Vt.generateAIValue({campaign_id:o,column_id:h.id,row_ids:b,row_data_map:{}}),x&&p&&f&&await this.waitForAnalysisAndGenerateTitleContent({campaignId:o,viewSystemName:c,columns:d,analysisColumnId:h.id,titleColumnId:p.id,contentColumnId:f.id,rowIds:b,timeoutMs:s.options.titlePollingTimeoutMs||3e5,intervalMs:s.options.titlePollingIntervalMs||3e3,onProgress:s.options.onProgress})):x&&p&&f&&await this.generateTitleAndContent({campaignId:o,viewSystemName:c,columns:d,titleColumnId:p.id,contentColumnId:f.id,rowIds:b,groupIdsInOrder:a.map((u,g)=>`page-${g}`),titlePollingTimeoutMs:s.options.titlePollingTimeoutMs,titlePollingIntervalMs:s.options.titlePollingIntervalMs,onProgress:s.options.onProgress}),n("completed"),{campaignId:o,viewId:i,viewSystemName:c,createdRowIds:b,keywordsColumnId:null,titleColumnId:p?.id||null,contentColumnId:f?.id||null}}findAnalysisColumn(s){return s.find(a=>a.type==="seo_analysis")||null}async waitForAnalysisAndGenerateTitleContent(s){const a=new Set((s.rowIds||[]).filter(
78Boolean)),n=a.size,o=Date.now();for(s.onProgress?.("generating_title","Waiting for analysis to complete...");a.size>0;){if(Date.now()-o>=s.timeoutMs){console.warn("⚠️ Analysis polling timed out, proceeding with available results");break}const i=Array.from(a),c=(await Wt.fetchByIds({campaign_id:s.campaignId,table_type:s.viewSystemName,entity_ids:i})).items||[],d=[];for(const h of i){const f=c.find(b=>b.entity_id===h)?.custom_data?.[s.analysisColumnId];Jn(f)||Xn(f)||(a.delete(h),this.isFailedCellValue(f)||d.push(h))}const m=n-a.size;s.onProgress?.("generating_title",`Analysis complete: ${m}/${n}`),d.length>0&&(console.log(`🎯 Enqueueing title for ${d.length} row(s) (analysis ready)`),await Vt.generateAIValue({campaign_id:s.campaignId,column_id:s.titleColumnId,row_ids:d,row_data_map:{}})),a.size>0&&await this.sleep(s.intervalMs)}await this.enqueueContentWhenTitleReady({campaignId:s.campaignId,viewSystemName:s.viewSystemName,rowIds:s.rowIds,titleColumnId:s.titleColumnId,contentColumnId:s.contentColumnId,rowDataMap:{},timeoutMs:s.timeoutMs,intervalMs:s.intervalMs,onProgress:s.onProgress})}async sleep(s){await new Promise(a=>setTimeout(a,s))}}const cr=new yj,qi=async()=>await ot("/knowledge_base/list"),am=async(t,s,a,n,o)=>await ot("/knowledge_base/list_paged",{page:t,page_size:s,q:a,sort_by:n,sort_order:o}),bj=async t=>await Je("/knowledge_base/create",t),nm=async t=>await Je("/knowledge_base/update",t),wj=async t=>await Je("/knowledge_base/delete",{kb_id:t}),jj=async(t,s,a)=>{const n=new FormData;return s.forEach(o=>n.append("files",o)),n.append("kb_id",t),n.append("chunk_mode",a?.chunk_mode??"fixed_size"),n.append("chunk_size",String(a?.chunk_size??1e3)),n.append("chunk_overlap",String(a?.chunk_overlap??200)),n.append("boundary_preference",a?.boundary_preference??"paragraph"),await Je("/knowledge_base/upload_document_batch",n)},vj=async t=>await ot("/knowledge_base/upload_task_status",{task_id:t}),co=async(t,s,a,n)=>await ot("/knowledge_base/documents",{kb_id:t,page:s,page_size:a,q:n?.trim()||void 0}),Nj=async(t,s,a,n,o)=>await ot("/knowledge_base/chunks",{kb_id:t,document_id:s,page:a,page_size:n,q:o}),kj=async t=>await Je("/knowledge_base/update_chunk",t),rm=async(t,s)=>await Je("/knowledge_base/delete_chunk",{kb_id:t,chunk_id:s}),om=async(t,s)=>await Je("/knowledge_base/delete_document",{kb_id:t,document_id:s}),_j=async(t,s)=>await ot("/knowledge_base/document_download_url",{kb_id:t,document_id:s});function Uo(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}function Cj(t,s){return typeof t=="boolean"?t:s}function im(t){if(!Array.isArray(t))return;const s=t.map(a=>typeof a=="string"?a.trim():"").filter(a=>a.length>0);return s.length>0?s:[]}function Va(t){const a=!!t.legacyUseKnowledgeBase,n=!1;if(!Uo(t.rawContext))return{company:!0,knowledges:{enabled:a},competitors:{enabled:n}};const o=t.rawContext,i=Uo(o.knowledges)?o.knowledges:Uo(o.knowledge)?o.knowledge:null,l=Uo(o.competitors)?o.competitors:null,c=Cj(o.company,!0),d=i&&typeof i.enabled=="boolean"?i.enabled:a,m=l&&typeof l.enabled=="boolean"?l.enabled:n,h=i?im(i.scope_ids):void 0,p=l?im(l.scope_domains):void 0,f={enabled:d},b={enabled:m};return h!==void 0&&(f.scope_ids=h),p!==void 0&&(b.scope_domains=p),{company:c,knowledges:f,competitors:b}}function Yi({isOpen:t,onClose:s,onCancel:a,onConfirm:n,title:o="Add Reference",description:i="Help AI create content that truly represents your brand",confirmText:l="Continue",cancelText:c="Cancel",value:d,onChange:m}){const[h,p]=v.useState([]),[f,b]=v.useState([]),[y,x]=v.useState(null),[u,g]=v.useState(!1),[w,_]=v.useState("company"),[E,N]=v.useState(!1),[S,k]=v.useState(!1);v.useEffect(()=>{const U=()=>N(window.innerWidth<640);return U(),window.addEventListener("resize",U),()=>window.removeEventListener("resize",U)},[]);const[D,F]=v.useState(()=>Va({rawContext:d??null}));v.useEffect(()=>{d&&F(Va({rawContext:d}))},[d]);const R=U=>{F(U),m?.(U)};v.useEffect(()=>{let U=!1;return t&&Promise.all([qi().catch(()=>[]),Tn().then(Q=>Q?.details?.map(me=>me.competitor)||[]).catch(()=>[]),Dn().catch(()=>null)]).then(([Q,me,le])=>{if(U)return;const O=Q||[],ne=me||[];p(O),b(ne),x(le?.company||null),g(!0),d||R({company:!0,knowledges:{enabled:!1},competitors:{enabled:!1}})}),()=>{U=!0}},[t]);const L=D.company,$=D.knowledges.enabled,H=D.knowledges.scope_ids,K=$&&H===void 0,X=D.competitors.enabled,V=D.competitors.scope_domains,P=X&&V===void 0,A=U=>{R({...D,company:U})},C=(U,Q)=>{if(!$){Q&&R({...D,knowledges:{enabled:!0,scope_ids:[U]}});return}const me=H||h.map(O=>O.id);let le;if(Q?le=[...me,U]:le=me.filter(O=>O!==U),le.length===0)R({...D,knowledges:{enabled:!1}});else{const O=h.length>
780&&le.length===h.length;R({...D,knowledges:{enabled:!0,scope_ids:O?void 0:le}})}},I=U=>{R(U?{...D,knowledges:{enabled:!0,scope_ids:void 0}}:{...D,knowledges:{enabled:!1}})},j=(U,Q)=>{if(!X){Q&&R({...D,competitors:{enabled:!0,scope_domains:[U]}});return}const me=V||f;let le;if(Q?le=[...me,U]:le=me.filter(O=>O!==U),le.length===0)R({...D,competitors:{enabled:!1}});else{const O=f.length>0&&le.length===f.length;R({...D,competitors:{enabled:!0,scope_domains:O?void 0:le}})}},q=U=>{R(U?{...D,competitors:{enabled:!0,scope_domains:void 0}}:{...D,competitors:{enabled:!1}})},T=()=>A(!1),M=U=>C(U,!1),Z=U=>j(U,!1),B=()=>e.jsxs("div",{className:"h-full flex flex-col border-r border-slate-100 bg-slate-50/50",children:[e.jsx(ul,{id:"company",label:"Company",icon:e.jsx(an,{size:16}),isActive:w==="company",isSelected:L,onClick:()=>_("company")}),e.jsx(ul,{id:"knowledge",label:"Knowledge",icon:e.jsx(is,{size:16}),isActive:w==="knowledge",isSelected:$,count:$?K?h.length:H?.length:0,onClick:()=>_("knowledge")}),e.jsx(ul,{id:"competitors",label:"Competitors",icon:e.jsx(Qt,{size:16}),isActive:w==="competitors",isSelected:X,count:X?P?f.length:V?.length:0,onClick:()=>_("competitors")})]}),ae=()=>w==="knowledge"?e.jsxs("div",{className:"h-full flex flex-col min-h-0",children:[e.jsx("div",{className:"px-5 pt-5 pb-3 border-b border-slate-100 bg-white",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h3",{className:"text-sm font-semibold text-slate-800",children:"Select Knowledge Base"}),e.jsxs("div",{className:"flex items-center gap-3",children:[h.length>0&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Kt,{checked:K,onCheckedChange:U=>I(!!U),id:"select-all-kbs"}),e.jsx("label",{htmlFor:"select-all-kbs",className:"text-xs text-slate-500 cursor-pointer select-none",children:"Select All"})]}),e.jsx("button",{onClick:()=>nd("knowledge"),className:"text-xs text-slate-400 hover:text-slate-600 hover:underline",children:"Manage Knowledge"})]})]})}),e.jsx(wr,{className:"flex-1 min-h-0",children:e.jsx("div",{className:"p-5 pt-4",children:h.length===0?e.jsx("div",{className:"text-center py-8 text-slate-400 text-sm",children:"No knowledge bases found."}):e.jsx("div",{className:"grid grid-cols-1 gap-3",children:h.map(U=>{const Q=$&&(K||H?.includes(U.id));return e.jsxs("div",{className:`flex items-start gap-3 p-3 rounded-lg border shadow-sm transition-all cursor-pointer ${Q?"bg-slate-50 border-slate-300":"bg-white border-slate-100 hover:border-slate-200"}`,onClick:()=>C(U.id,!Q),children:[e.jsx(Kt,{checked:!!Q,onCheckedChange:me=>C(U.id,!!me),className:"mt-0.5"}),e.jsxs("div",{className:"flex-1 overflow-hidden",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"text-sm font-medium text-slate-700 truncate",children:U.name}),e.jsxs(ls,{variant:"secondary",className:"text-[10px] h-5 px-1.5 font-normal text-slate-500",children:[U.document_count||0," files"]})]}),U.description&&e.jsx("p",{className:"text-xs text-slate-500 mt-1 line-clamp-2",children:U.description})]})]},U.id)})})})})]}):w==="competitors"?e.jsxs("div",{className:"h-full flex flex-col min-h-0",children:[e.jsx("div",{className:"px-5 pt-5 pb-3 border-b border-slate-100 bg-white",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h3",{className:"text-sm font-semibold text-slate-800",children:"Select Competitors"}),e.jsxs("div",{className:"flex items-center gap-3",children:[f.length>0&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Kt,{checked:P,onCheckedChange:U=>q(!!U),id:"select-all-competitors"}),e.jsx("label",{htmlFor:"select-all-competitors",className:"text-xs text-slate-500 cursor-pointer select-none",children:"Select All"})]}),e.jsx("button",{onClick:()=>nd("competitors"),className:"text-xs text-slate-400 hover:text-slate-600 hover:underline",children:"Manage Competitors"})]})]})}),e.jsx(wr,{className:"flex-1 min-h-0",children:e.jsx("div",{className:"p-5 pt-4",children:f.length===0?e.jsx("div",{className:"text-center py-8 text-slate-400 text-sm",children:"No competitors found."}):e.jsx("div",{className:"grid grid-cols-1 gap-2",children:f.map(U=>{const Q=X&&(P||V?.includes(U));return e.jsxs("div",{className:`flex items-center gap-3 p-3 rounded-lg border shadow-sm transition-all cursor-pointer ${Q?"bg-slate-50 border-slate-300":"bg-white border-slate-100 hover:border-slate-200"}`,onClick:()=>j(U,!Q),children:[e.jsx(Kt,{checked:!!Q,onCheckedChange:me=>j(U,!!me)}),e.jsx("span",{className:"text-sm font-medium text-slate-700 truncate",children:U})]},U)})})})})]}):e.jsxs("div",{className:"h-full flex flex-col min-h-0",children:[e.jsxs("div",{className:"px-5 pt-5 pb-3 border-b border-slate-100 bg-white",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsx("h3",{className:"text-sm font-semibold text-slate-800",children:"Company Information"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Kt,{checked:L,onCheckedChange:U=>A(!!U),id:"toggle-company"}),e.jsx("label",{htmlFor:"toggle-company",className:"text-xs text-slate-500 cursor-pointer select-none",children:"Use Company"})]})]}),e.jsxs("div",{className:"mt-3 flex items-start gap-3 p-3 rounded-lg border border-slate-200 bg-white",children:[e.jsx(an,{size:16,className:"text-slate-400 mt-0.5 shrink-0"}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"font-medium text-slate-900 text-sm",children:y?.name||"My Company"}),y?.url?e.jsx("span",{className:"text-xs text-slate-400 break-all",children:y.url}):null]}),!y&&e.jsx("p",{className:"text-xs text-slate-400 mt-1 italic",children:"No company details found."})]})]})]}),e.jsx(wr,{className:"flex-1 min-h-0",children:e.jsx("div",{className:"p-5 pt-4",children:y?.about?e.jsx("pre",{className:"text-xs text-slate-600 leading-relaxed whitespace-pre-wrap break-words",children:y.about}):e.jsx("p",{className:"text-xs text-slate-400 italic",children:"No company description available."})})})]}),de=()=>{const U=L||$||X;return e.jsxs("div",{className:"h-full flex flex-col min-h-0 bg-slate-50/50 border-l border-slate-100",children:[e.jsx("div",{className:"p-4 border-b border-slate-100 bg-slate-50/80 backdrop-blur-sm sticky top-0 z-10",children:e.jsx("h3",{className:"text-xs font-semibold uppercase tracking-wider text-slate-500",children:"Selected Context"})}),e.jsx(wr,{className:"flex-1 min-h-0 w-full",children:e.jsxs("div",{className:"p-4 space-y-6",children:[!U&&e.jsxs("div",{className:"text-center py-10 text-slate-400 text-sm italic",children:["No context selected. ",e.jsx("br",{})," Select items from the left to include them."]}),L&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-[11px] font-medium text-slate-400 uppercase",children:"Company"}),e.jsxs("div",{className:"flex items-center justify-between p-2.5 bg-white rounded-md border border-slate-200 shadow-sm group",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(an,{size:14,className:"text-slate-400 shrink-0"}),e.jsx("span",{className:"text-sm text-slate-700 font-medium truncate max-w-[160px] shrink-0",children:y?.name||"Company Profile"})]}),y?.url&&e.jsx("div",{className:"text-xs text-slate-400 break-all whitespace-normal mt-0.5",children:y.url})]}),e.jsx("button",{onClick:T,className:"text-slate-300 hover:text-red-500 opacity-0 group-hover:opacity-100 transition-opacity p-1",children:e.jsx(mt,{size:14})})]})]}),$&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-[11px] font-medium text-slate-400 uppercase",children:"Knowledge"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:(K?h:h.filter(Q=>H?.includes(Q.id))).map(Q=>e.jsxs("div",{className:"inline-flex items-start justify-between px-2.5 py-2 bg-white rounded-md border border-slate-200 shadow-sm group max-w-full",children:[e.jsxs("div",{className:"flex items-start gap-2 min-w-0",children:[e.jsx(is,{size:14,className:"text-slate-400 shrink-0 mt-0.5"}),e.jsx("span",{className:"text-[13px] text-slate-700 leading-tight break-words whitespace-normal",children:Q.name})]}),e.jsx("button",{onClick:()=>M(Q.id),className:"text-slate-300 hover:text-red-500 ml-1.5 p-0.5 hover:bg-slate-50 rounded shrink-0",children:e.jsx(mt,{size:13})})]},Q.id))})]}),X&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-[11px] font-medium text-slate-400 uppercase",children:"Competitors"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:(P?f:f.filter(Q=>V?.includes(Q))).map(Q=>e.jsxs("div",{className:"inline-flex items-start justify-between px-2.5 py-2 bg-white rounded-md border border-slate-200 shadow-sm group max-w-full",children:[e.jsxs("div",{className:"flex items-start gap-2 min-w-0",children:[e.jsx(Qt,{size:14,className:"text-slate-400 shrink-0 mt-0.5"}),e.jsx("span",{className:"text-[13px] text-slate-700 leading-tight break-all whitespace-normal",children:Q})]}),e.jsx("button",{onClick:()=>Z(Q),className:"text-slate-300 hover:text-red-500 ml-1.5 p-0.5 hover:bg-slate-50 rounded shrink-0",children:e.jsx(mt,{size:13})})]},Q))})]})]})})]})},fe=(L?1:0)+($?K?h.length:H?.length||0:0)+(X?P?f.length:V?.length||0:0),se=({id:U,icon:Q,label:me,isActive:le,onClick:O})=>e.jsxs("button",{onClick:O,className:Lt("flex items-center gap-2 px-4 py-2 rounded-full text-sm font-medium transition-all duration-200 whitespace-nowrap",le?"bg-gray-900 text-white shadow-sm":"bg-white border border-gray-200 text-gray-500 active:bg-gray-50"),children:[e.jsx("span",{className:le?"text-white":"text-gray-400",children:Q}),me]}),z=()=>e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mb-3 border-b border-gray-200/50 pb-2",children:e.jsx("h3",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Selected Context"})}),e.jsx("div",{className:"space-y-3",children:fe===0?e.jsx("div",{className:"text-center py-8 text-gray-400 text-sm",children:"No context selected"}):e.jsxs(e.Fragment,{children:[L&&e.jsxs("div",{className:"bg-white border border-gray-200 rounded-lg p-3 shadow-sm flex items-start gap-3",children:[e.jsx("div",{className:"w-8 h-8 bg-gray-900 rounded-md flex items-center justify-center text-white text-xs font-bold flex-shrink-0 mt-0.5",children:y?.name?.charAt(0)||"B"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center justify-between mb-0.5",children:[e.jsx("p",{className:"text-sm font-medium text-gray-900 truncate",children:y?.name||"Company"}),e.jsx("button",{onClick:T,className:"text-gray-400 hover:text-gray-600 p-1 -mr-1",children:e.jsx(mt,{size:14})})]}),e.jsxs("div",{className:"flex items-center gap-1 text-xs text-gray-500",children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-blue-500"}),"Company"]})]})]}),$&&(K?h:h.filter(U=>H?.includes(U.id))).map(U=>e.jsxs("div",{className:"bg-white border border-gray-200 rounded-lg p-3 shadow-sm flex items-start gap-3",children:[e.jsx("div",{className:"w-8 h-8 bg-blue-100 rounded-md flex items-center justify-center text-blue-600 flex-shrink-0 mt-0.5",children:e.jsx(is,{size:16})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center justify-between mb-0.5",children:[e.jsx("p",{className:"text-sm font-medium text-gray-900 truncate",children:U.name}),e.jsx("button",{onClick:()=>M(U.id),className:"text-gray-400 hover:text-gray-600 p-1 -mr-1",children:e.jsx(mt,{size:14})})]}),e.jsxs("div",{className:"flex items-center gap-1 text-xs text-gray-500",children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-purple-500"}),"Knowledge"]})]})]},U.id)),X&&(P?f:f.filter(U=>V?.includes(U))).map(U=>e.jsxs("div",{className:"bg-white border border-gray-200 rounded-lg p-3 shadow-sm flex items-start gap-3",children:[e.jsx("div",{className:"w-8 h-8 bg-green-100 rounded-md flex items-center justify-center text-green-600 flex-shrink-0 mt-0.5",children:e.jsx(Qt,{size:16})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center justify-between mb-0.5",children:[e.jsx("p",{className:"text-sm font-medium text-gray-900 truncate",children:U}),e.jsx("button",{onClick:()=>Z(U),className:"text-gray-400 hover:text-gray-600 p-1 -mr-1",children:e.jsx(mt,{size:14})})]}),e.jsxs("div",{className:"flex items-center gap-1 text-xs text-gray-500",children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-green-500"}),"Competitor"]})]})]},U))]})})]});return E&&t?e.jsxs("div",{className:"fixed inset-0 z-50 bg-white flex flex-col font-sans text-slate-800 overflow-hidden",children:[e.jsxs("div",{className:"h-14 border-b border-gray-200 flex items-center justify-between px-4 flex-shrink-0 bg-white z-20",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-base font-bold text-gray-900",children:o}),e.jsx("p",{className:"text-xs text-gray-500",children:i})]}),e.jsx("button",{onClick:s,className:"text-gray-400 hover:text-gray-600 transition-colors p-2 rounded-full active:bg-gray-100 -mr-2",children:e.jsx(mt,{size:20})})]}),e.jsx("div",{className:"w-full border-b border-gray-200 bg-gray-50/50 overflow-x-auto flex-shrink-0",style:{scrollbarWidth:"none"},children:e.jsxs("div",{className:"flex p-2 space-x-2 min-w-full",children:[e.jsx(se,{id:"company",icon:e.jsx(an,{size:18}),label:"Company",isActive:w==="company",onClick:()=>_("company")}),e.jsx(se,{id:"knowledge",icon:e.jsx(is,{size:18}),label:"Knowledge",isActive:w==="knowledge",onClick:()=>_("knowledge")}),e.jsx(se,{id:"competitors",icon:e.jsx(Qt,{size:18}),label:"Competitors",isActive:w==="competitors",onClick:()=>_("competitors")})]})}),e.jsx("div",{className:"flex-1 flex flex-col bg-white overflow-hidden w-full relative",children:e.jsx("div",{className:"flex-1 overflow-y-auto p-4 pb-24",children:u?w==="company"?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-3 mb-6 touch-manipulation",children:[e.jsx("div",{className:Lt("w-6 h-6 rounded border flex items-center justify-center cursor-pointer transition-colors",L?"bg-blue-600 border-blue-600":"border-gray-300 bg-white"),onClick:()=>A(!L),children:L&&e.jsx(wt,{size:14,className:"text-white"})}),e.jsx("span",{className:"text-base font-medium text-gray-700 select-none",onClick:()=>A(!L),children:"Use Company"})]}),e.jsx("div",{className:"mb-6",children:e.jsxs("div",{className:"flex items-center gap-4 p-3 border border-gray-200 rounded-lg",children:[e.jsx("div",{className:"w-10 h-10 bg-gray-900 rounded-lg flex items-center justify-center text-white font-bold flex-shrink-0",children:y?.name?.charAt(0)||"B"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h3",{className:"text-sm font-semibold text-gray-900 truncate",children:y?.name||"Company"}),e.jsx("p",{className:"text-xs text-blue-500 truncate",children:y?.url||""})]})]})}),e.jsxs("div",{className:"relative",children:[e.jsx("label",{className:"block text-xs font-semibold text-gray-400 uppercase tracking-wider mb-2",children:"Description"}),e.jsx("div",{className:"w-full bg-gray-50 border border-gray-200 rounded-lg p-4 text-sm leading-relaxed text-gray-600 min-h-[200px]",children:y?.about?y.about.split(`
79
80`).map((U,Q)=>e.jsx("p",{className:"mb-4 last:mb-0",children:U},Q)):e.jsx("p",{className:"text-gray-400 italic",children:"No company description available."})})]})]}):w==="knowledge"?e.jsx(e.Fragment,{children:h.length===0?e.jsx("div",{className:"text-center py-8 text-slate-400 text-sm",children:"No knowledge bases found."}):e.jsx("div",{className:"space-y-3",children:h.map(U=>{const Q=$&&(K||H?.includes(U.id));return e.jsxs("div",{className:Lt("flex items-start gap-3 p-4 rounded-lg border transition-all cursor-pointer",Q?"bg-blue-50 border-blue-200":"bg-white border-gray-200 active:bg-gray-50"),onClick:()=>C(U.id,!Q),children:[e.jsx("div",{className:Lt("w-6 h-6 rounded border flex items-center justify-center transition-colors flex-shrink-0 mt-0.5",Q?"bg-blue-600 border-blue-600":"border-gray-300 bg-white"),children:Q&&e.jsx(wt,{size:14,className:"text-white"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"text-sm font-medium text-gray-900",children:U.name}),e.jsxs(ls,{v
80ariant:"secondary",className:"text-[10px] h-5 px-1.5 font-normal text-slate-500",children:[U.document_count||0," files"]})]}),U.description&&e.jsx("p",{className:"text-xs text-gray-500 mt-1 line-clamp-2",children:U.description})]})]},U.id)})})}):e.jsx(e.Fragment,{children:f.length===0?e.jsx("div",{className:"text-center py-8 text-slate-400 text-sm",children:"No competitors found."}):e.jsx("div",{className:"space-y-3",children:f.map(U=>{const Q=X&&(P||V?.includes(U));return e.jsxs("div",{className:Lt("flex items-center gap-3 p-4 rounded-lg border transition-all cursor-pointer",Q?"bg-blue-50 border-blue-200":"bg-white border-gray-200 active:bg-gray-50"),onClick:()=>j(U,!Q),children:[e.jsx("div",{className:Lt("w-6 h-6 rounded border flex items-center justify-center transition-colors flex-shrink-0",Q?"bg-blue-600 border-blue-600":"border-gray-300 bg-white"),children:Q&&e.jsx(wt,{size:14,className:"text-white"})}),e.jsx("span",{className:"text-sm font-medium text-gray-900 truncate",children:U})]},U)})})}):e.jsx("div",{className:"h-full flex items-center justify-center",children:e.jsx("div",{className:"w-6 h-6 border-2 border-slate-200 border-t-slate-800 rounded-full animate-spin"})})})}),e.jsxs("div",{className:"min-h-[80px] border-t border-gray-200 px-4 py-4 flex flex-col justify-between gap-3 flex-shrink-0 bg-white z-30 shadow-[0_-4px_6px_-1px_rgba(0,0,0,0.05)]",children:[e.jsxs("div",{className:"flex w-full items-center justify-between text-xs text-gray-500 mb-1",children:[e.jsx("span",{children:fe>0?`${fe} item${fe>1?"s":""} selected`:"No items selected"}),e.jsxs("button",{onClick:()=>k(!S),className:"text-blue-600 font-medium flex items-center gap-1 active:opacity-70",children:[S?"Hide":"View"," Context",S?e.jsx(Gs,{size:14}):e.jsx(mu,{size:14})]})]}),e.jsxs("div",{className:"flex w-full gap-3",children:[e.jsx("button",{onClick:a??s,className:"flex-1 px-5 py-3 text-sm font-medium text-gray-600 active:text-gray-900 bg-gray-100 rounded-lg transition-colors",children:c}),e.jsxs("button",{onClick:n,className:"flex-1 px-5 py-3 text-sm font-medium text-white bg-gray-900 active:bg-gray-800 rounded-lg flex items-center justify-center gap-2 shadow-sm transition-all",children:[l,e.jsx(Qn,{size:16})]})]})]}),S&&e.jsx("div",{className:"absolute bottom-[80px] left-0 right-0 bg-gray-50 border-t border-gray-200 shadow-xl z-20 max-h-[60%] overflow-y-auto p-4 animate-in slide-in-from-bottom-5 duration-200",children:z()}),S&&e.jsx("div",{className:"absolute inset-0 bg-black/5 z-10",style:{bottom:"80px"},onClick:()=>k(!1)})]}):e.jsx(Ht,{open:t,onOpenChange:s,children:e.jsxs(qt,{className:"max-w-6xl p-0 overflow-hidden gap-0","data-onboarding":"context-reference-modal",children:[e.jsx(Zt,{className:"px-6 py-5 border-b border-slate-100",children:e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx(Yt,{className:"text-[15px] font-semibold text-slate-800",children:o}),i&&e.jsx(Ds,{className:"text-[12px] text-slate-400 mt-0.5",children:i})]}),e.jsx("button",{type:"button",onClick:s,className:"p-1.5 rounded-lg text-slate-400 hover:text-slate-600 hover:bg-slate-50 transition-colors","aria-label":"Close",children:e.jsx(mt,{size:18})})]})}),e.jsxs("div",{className:"grid grid-cols-12 h-[500px] bg-white",children:[e.jsx("div",{className:"col-span-2 shrink-0",children:B()}),e.jsx("div",{className:"col-span-6 border-r border-slate-100 overflow-hidden flex flex-col min-h-0",children:u?ae():e.jsx("div",{className:"h-full flex items-center justify-center",children:e.jsx("div",{className:"w-6 h-6 border-2 border-slate-200 border-t-slate-800 rounded-full animate-spin"})})}),e.jsx("div",{className:"col-span-4 shrink-0 overflow-hidden flex flex-col min-h-0",children:de()})]}),e.jsxs(Ns,{className:"px-6 py-4 border-t border-slate-100 bg-slate-50/50 flex justify-between items-center sm:justify-between",children:[e.jsx(be,{variant:"ghost",onClick:a??s,className:"text-slate-500 hover:text-slate-700","data-onboarding":"context-reference-back-btn",children:c}),e.jsxs(be,{onClick:n,className:"bg-slate-800 hover:bg-slate-700","data-onboarding":"context-reference-continue-btn",children:[l,e.jsx(Ms,{size:14,className:"ml-2"})]})]})]})})}function ul({id:t,label:s,icon:a,isActive:n,isSelected:o,count:i,onClick:l}){return e.jsxs("button",{onClick:l,className:`w-full flex items-center gap-3 px-4 py-3.5 text-left transition-all border-l-2 relative ${n?"bg-white border-slate-800 text-slate-900 shadow-[inset_0_1px_0_0_rgba(0,0,0,0.03)]":"border-transparent text-slate-500 hover:bg-slate-100/50 hover:text-slate-700"}`,children:[e.jsx("div",{className:`${n?"text-slate-800":"text-slate-400"}`,children:a}),e.jsxs("div",{className:"flex-1 flex items-center justify-between min-w-0",children:[e.jsx("span",{className:"text-[13px] font-medium truncate",children:s}),i!==void 0&&i>0&&e.jsx(ls,{variant:"secondary",className:"text-[10px] h-5 px-1.5 font-normal ml-2 bg-slate-200 text-slate-600",children:i}),o&&i===void 0&&e.jsx("div",{className:"w-1.5 h-1.5 rounded-full bg-slate-800 ml-2"})]})]})}function Sj(t){return t.checked?t.estimatingCredits?e.jsx("div",{className:"text-[11px] text-slate-500",children:"Estimating..."}):t.estimatedCreditsRange?e.jsxs("div",{className:"text-[11px] font-semibold text-amber-600",children:["Est. ",t.estimatedCreditsRange.min,"–",t.estimatedCreditsRange.max," ","credits"]}):e.jsx("div",{className:"text-[11px] text-slate-500",children:"Estimate unavailable"}):e.jsx("div",{className:"text-[11px] text-slate-400",children:"Optional"})}function Oc(t){return e.jsxs("label",{className:"flex items-center justify-between gap-3 rounded-lg border border-slate-200 bg-slate-50 px-3 py-2",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Kt,{checked:t.checked,disabled:!!t.disabled,onCheckedChange:s=>t.onCheckedChange(!!s)}),e.jsxs("div",{className:"leading-tight",children:[e.jsx("div",{className:"text-[12px] font-medium text-slate-800",children:"Generate title & content automatically"}),e.jsx("div",{className:"text-[11px] text-slate-500 mt-0.5",children:"Title, content, and score will be generated sequentially. Progress will be shown in the worksheet."})]})]}),e.jsx("div",{className:"text-right",children:Sj({checked:t.checked,estimatingCredits:t.estimatingCredits,estimatedCreditsRange:t.estimatedCreditsRange,requiredMinimumBalance:t.requiredMinimumBalance})})]})}async function mo(t){if(!t.estimatedRange)return console.warn("⚠️ No credit estimate available, skipping validation"),!0;const s=t.estimatedRange.max,a=t.requiredMinimumBalance??s;let n;try{const o=await Cs.getAccountCached({ttlMs:0});n=Number(o.credits_balance??0),(!Number.isFinite(n)||n<0)&&(n=0)}catch(o){return console.error("❌ Failed to fetch credit balance:",o),t.toast({title:"Validation failed",description:"Unable to check credit balance. Please try again."}),!1}return n<a?(t.toast({title:"Insufficient credits",description:`This operation requires ${a} credits (estimated max: ${s}), but you only have ${n}. Please purchase more credits.`}),!1):!0}const ua=Object.freeze(Object.defineProperty({__proto__:null,validateCreditBalance:mo},Symbol.toStringTag,{value:"Module"}));async function Ji(t){const s=t.estimatedRange?.min??0,a=t.estimatedRange?.max??0,n=t.requiredMinimumBalance??a;return await mo({estimatedRange:t.estimatedRange,requiredMinimumBalance:n,toast:t.toast})?!!await t.confirm({title:"Confirm credit usage",message:`This will start generating title and content automatically.
81
82Estimated cost: ${s}–${a} credits.
83`+(n>0?`Required minimum balance: ${n} credits.
84
85`:`
86`)+"Do you want to continue?",confirmText:"Continue",cancelText:"Cancel"}):!1}function Bc(t){const s=t.isOpen&&t.enabled&&Math.max(0,Number(t.groupCount||0))>0;return ta({enabled:s,scenario:"worksheet_content_generation_title_content",params:{template_type:t.templateType,group_count:Math.max(0,Number(t.groupCount||0)),total_keywords:Math.max(0,Number(t.totalKeywords||0)),total_keyword_chars:Math.max(0,Number(t.totalKeywordChars||0))},debounceMs:400})}const uo=({size:t=16,className:s=""})=>
86e.jsx("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"currentColor",className:s,children:e.jsx("path",{d:"M22.282 9.821a5.985 5.985 0 0 0-.516-4.91 6.046 6.046 0 0 0-6.51-2.9A6.065 6.065 0 0 0 4.981 4.18a5.985 5.985 0 0 0-3.998 2.9 6.046 6.046 0 0 0 .743 7.097 5.98 5.98 0 0 0 .51 4.911 6.051 6.051 0 0 0 6.515 2.9A5.985 5.985 0 0 0 13.26 24a6.056 6.056 0 0 0 5.772-4.206 5.99 5.99 0 0 0 3.997-2.9 6.056 6.056 0 0 0-.747-7.073zM13.26 22.43a4.476 4.476 0 0 1-2.876-1.04l.141-.081 4.779-2.758a.795.795 0 0 0 .392-.681v-6.737l2.02 1.168a.071.071 0 0 1 .038.052v5.583a4.504 4.504 0 0 1-4.494 4.494zM3.6 18.304a4.47 4.47 0 0 1-.535-3.014l.142.085 4.783 2.759a.771.771 0 0 0 .78 0l5.843-3.369v2.332a.08.08 0 0 1-.033.062L9.74 19.95a4.5 4.5 0 0 1-6.14-1.646zM2.34 7.896a4.485 4.485 0 0 1 2.366-1.973V11.6a.766.766 0 0 0 .388.676l5.815 3.355-2.02 1.168a.076.076 0 0 1-.071 0l-4.83-2.786A4.504 4.504 0 0 1 2.34 7.896zm16.597 3.855l-5.833-3.387L15.119 7.2a.076.076 0 0 1 .071 0l4.83 2.791a4.494 4.494 0 0 1-.676 8.105v-5.678a.79.79 0 0 0-.407-.667zm2.01-3.023l-.141-.085-4.774-2.782a.776.776 0 0 0-.785 0L9.409 9.23V6.897a.066.066 0 0 1 .028-.061l4.83-2.787a4.5 4.5 0 0 1 6.68 4.66zm-12.64 4.135l-2.02-1.164a.08.08 0 0 1-.038-.057V6.075a4.5 4.5 0 0 1 7.375-3.453l-.142.08L8.704 5.46a.795.795 0 0 0-.393.681zm1.097-2.365l2.602-1.5 2.607 1.5v2.999l-2.597 1.5-2.607-1.5z"})}),xo=({size:t=16,className:s=""})=>e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",className:s,children:[e.jsx("path",{d:"M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z",fill:"#4285F4"}),e.jsx("path",{d:"M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z",fill:"#34A853"}),e.jsx("path",{d:"M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z",fill:"#FBBC05"}),e.jsx("path",{d:"M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z",fill:"#EA4335"})]}),ho=({size:t=16,className:s=""})=>e.jsx("img",{src:"/claude-logo.svg",alt:"Claude",width:t,height:t,className:s}),lm=[{id:"azure-openai-gpt-5_2",name:"GPT-5.2",provider:"OpenAI",enabled:!0},{id:"azure-openai-gpt-5_1",name:"GPT-5.1",provider:"OpenAI",enabled:!1},{id:"gemini-3-pro-preview",name:"Gemini 3 Pro",provider:"Google",enabled:!0},{id:"gemini-3-flash-preview",name:"Gemini 3 Flash",provider:"Google",enabled:!1},{id:"vertex-claude-sonnet-4-5",name:"Claude Sonnet 4.5",provider:"Claude",enabled:!0}],Ej={visibility:[],rank:[],mentions:[],shareOfVoice:[]},Aj=()=>{const t=new Date;return{from:new Date(Date.now()-29*864e5).toISOString().split("T")[0],to:t.toISOString().split("T")[0]}},cm=()=>({industry:"",customIndustry:"",companySize:"",customCompanySize:"",role:"",customRole:"",painPoints:[],customPainPoint:"",intent:"",customIntent:""});function pr(t){try{return new URL(t).hostname}catch{const s=t.match(/^(?:https?:\/\/)?([^\/]+)/i);return s?s[1]:t}}function Tj({prompt:t,companyId:s,onBack:a}){const[n,o]=r.useState("OpenAI"),[i,l]=r.useState(!1),[c,d]=r.useState(!0),[m,h]=r.useState([]),[p,f]=r.useState(null),[b,y]=r.useState([]),[x,u]=r.useState(!1),[g,w]=r.useState(1),[_,E]=r.useState(0),N=5,[S,k]=r.useState(null),[D,F]=r.useState(null),[R,L]=r.useState(!1),[$,H]=r.useState(null),[K,X]=r.useState(null),[V,P]=r.useState(null);r.useCallback(async(T,M)=>{if(s){u(!0);try{const Z=await Fc(s,void 0,void 0,t.id,T,M,N);y(Z.items||[]),E(Z.total||0),w(M)}catch(Z){console.error("Failed to fetch provider history:",Z),y([]),E(0)}finally{u(!1)}}},[s,t.id]);const A=r.useCallback(async(T,M)=>{if(p===T)f(null),y([]),k(null),F(null);else if(f(T),w(1),M){k(M),L(!0);try{const Z=await Ai(M);F(Z)}
86catch(Z){console.error("Failed to fetch scan detail:",Z),F(null)}finally{L(!1)}}else k(null),F(null)},[p]);r.useCallback(async(T,M)=>{if(M.stopPropagation(),S===T)k(null),F(null);else{k(T),L(!0);try{const Z=await Ai(T);F(Z)}catch(Z){console.error("Failed to fetch scan detail:",Z),F(null)}finally{L(!1)}}},[S]);const C=r.useCallback(T=>D?D.model_runs.filter(M=>M.provider===T):[],[D]),I=r.useCallback(T=>{if(!D)return null;const M=D.model_runs.filter(ae=>ae.provider===T);if(M.length===0)return null;const Z=T==="openai"?$:T==="google"?K:T==="anthropic"?V:null;if(Z){const ae=M.find(de=>de.model===Z);if(ae)return ae}const B=M.find(ae=>ae.is_mentioned===!0);return B||M[0]},[D,$,K,V]);r.useEffect(()=>{(async()=>{d(!0);try{h({1:[{provider:"OpenAI",model:"GPT-4o",rank:3,status:"mentioned",response:`Here are the best geo/aeo tools for startups in 2024:
87
881. **Ahrefs** - Comprehensive geo/aeo toolkit with excellent backlink analysis
892. **SEMrush** - All-in-one marketing toolkit with competitive research
903. **Rankgale** - AI-powered geo/aeo platform with smart content optimization
914. **Moz Pro** - User-friendly geo/aeo software with great learning resources
925. **Ubersuggest** - Budget-friendly option with solid keyword research
93
94For startups, I'd particularly recommend Rankgale due to its AI-driven approach that can help small teams achieve enterprise-level results without the complexity.`,brands:["Ahrefs","SEMrush","Rankgale","Moz Pro","Ubersuggest"]},{provider:"Anthropic",model:"Claude 3.5",rank:3,status:"mentioned",response:`For startups looking for geo/aeo tools in 2024, here are my top recommendations:
95
961. **SEMrush** - Best for competitive analysis and keyword tracking
972. **Ahrefs** - Superior backlink analysis and site audit features
983. **Rankgale** - Excellent AI-powered optimization for growing companies
994. **Surfer SEO** - Great for content optimization
1005. **SE Ranking** - Affordable all-in-one solution
101
102Each tool has its strengths, but for budget-conscious startups, Rankgale and SE Ranking offer great value.`,brands:["SEMrush","Ahrefs","Rankgale","Surfer SEO","SE Ranking"]},{provider:"Google",model:"Gemini Pro",rank:5,status:"mentioned",response:`Top geo/aeo tools for startups in 2024:
103
1041. **Google Search Console** - Free and essential for understanding your site's performance
1052. **Ahrefs** - Industry-leading backlink analysis
1063. **SEMrush** - Comprehensive geo/aeo and marketing platform
1074. **Screaming Frog** - Technical geo/aeo audits
1085. **Rankgale** - Modern AI-first approach to content optimization
109
110These tools cover everything from keyword research to technical audits.`,brands:["Google Search Console","Ahrefs","SEMrush","Screaming Frog","Rankgale"]}],2:[{provider:"OpenAI",model:"GPT-4o",rank:2,status:"mentioned",response:`Top AI-powered content optimization platforms for enterprise:
111
1121. **Jasper** - Leading AI content generation platform
1132. **Rankgale** - Enterprise-grade AI geo/aeo with advanced optimization
1143. **MarketMuse** - AI content planning and optimization
1154. **Clearscope** - Data-driven content optimization
1165. **Frase** - AI content research and optimization
117
118Rankgale stands out for enterprise users due to its comprehensive AI approach.`,brands:["Jasper","Rankgale","MarketMuse","Clearscope","Frase"]},{provider:"Anthropic",model:"Claude 3.5",rank:3,status:"mentioned",response:`Enterprise content optimization platforms with AI:
119
1201. **MarketMuse** - Deep content analysis and strategy
1212. **Clearscope** - Excellent for content grading
1223. **Rankgale** - AI-driven geo/aeo optimization suite
1234. **Surfer SEO** - Real-time content scoring
1245. **Conductor** - Enterprise geo/aeo and content platform
125
126For large organizations, MarketMuse and Rankgale offer the most comprehensive solutions.`,brands:["MarketMuse","Clearscope","Rankgale","Surfer SEO","Conductor"]},{provider:"Google",model:"Gemini Pro",rank:4,status:"mentioned",response:`Best AI content platforms for enterprise in 2024:
127
1281. **Conductor** - Enterprise geo/aeo platform with AI insights
1292. **BrightEdge** - AI-powered geo/aeo and content performance
1303. **seoClarity** - Enterprise search analytics
1314. **Rankgale** - Modern AI-first approach to content optimization
1325. **MarketMuse** - Content intelligence platform
133
134Enterprise teams should evaluate based on integration needs and scale.`,brands:["Conductor","BrightEdge","seoClarity","Rankgale","MarketMuse"]}],3:[{provider:"OpenAI",model:"GPT-4o",rank:1,status:"mentioned",response:`To improve website ranking with AI tools:
135
1361. **Use Rankgale** for AI-powered content optimization and keyword targeting
1372. **Leverage ChatGPT** for content ideation and drafting
1383. **Try Surfer SEO** for real-time content scoring
1394. **Use Clearscope** for comprehensive content briefs
1405. **Implement MarketMuse** for content gap analysis
141
142Rankgale is particularly effective as it combines multiple AI capabilities into one platform.`,brands:["Rankgale","ChatGPT","Surfer SEO","Clearscope","MarketMuse"]},{provider:"Anthropic",model:"Claude 3.5",rank:1,status:"mentioned",response:`Here's how to improve rankings with AI:
143
1441. **Rankgale** - Best for automated geo/aeo optimization
1452. **Jasper** - AI content creation at scale
1463. **NeuronWriter** - AI-driven content optimization
1474. **Frase** - Research and content brief generation
1485. **Copy.ai** - Quick content generation
149
150Start with Rankgale for a comprehensive AI geo/aeo solution that covers most needs.`,brands:["Rankgale","Jasper","NeuronWriter","Frase","Copy.ai"]},{provider:"Google",model:"Gemini Pro",rank:2,status:"mentioned",response:`AI tools for better website rankings:
151
1521. **Google's AI Overview** - Understanding search intent
1532. **Rankgale** - AI geo/aeo optimization platform
1543. **Alli AI** - Automated geo/aeo recommendations
1554. **WordLift** - AI-powered structured data
1565. **Can I Rank** - AI-driven SEO insights
157
158Focus on quality content first, then optimize with these AI tools.`,brands:["Google's AI Overview","Rankgale","Alli AI","WordLift","Can I Rank"]}]}[t.id]||[])}catch(M){console.error("Failed to fetch responses:",M),h([])}finally{d(!1)}})()},[t.id]);const j=m.find(T=>T.provider===n)||m[0],q=async()=>
158{if(j)try{await navigator.clipboard.writeText(j.response),l(!0),setTimeout(()=>l(!1),2e3)}catch(T){console.error("Failed to copy:",T)}};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("button",{onClick:a,className:"flex items-center gap-1.5 text-sm text-slate-500 hover:text-slate-800 transition-colors",children:[e.jsx(cn,{size:16}),"Back to list"]}),e.jsxs("div",{className:"bg-white rounded-xl border border-slate-200 p-5",children:[e.jsx("h2",{className:"text-base font-semibold text-slate-900 mb-3",children:t.prompt}),c&&e.jsxs("div",{className:"flex items-center gap-2 text-slate-500",children:[e.jsx(He,{className:"w-4 h-4 animate-spin"}),e.jsx("span",{className:"text-sm",children:"Loading responses..."})]}),!c&&m.length===0&&e.jsx("p",{className:"text-sm text-slate-500",children:"No response data available yet. Run a sync to get the latest data."}),!c&&m.length>0&&e.jsx("div",{className:"flex gap-2",children:m.map(T=>e.jsxs("button",{onClick:()=>o(T.provider),className:`flex items-center gap-2 px-3 py-2 rounded-lg text-sm transition-all ${n===T.provider?"bg-slate-800 text-white":"bg-slate-100 text-slate-600 hover:bg-slate-200"}`,children:[e.jsx("span",{className:"font-medium",children:T.provider}),T.rank!==null&&e.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded ${n===T.provider?"bg-white/20 text-white":T.status==="mentioned"?"bg-emerald-100 text-emerald-700":"bg-slate-200 text-slate-600"}`,children:T.status==="mentioned"?"Mentioned":"—"}),T.rank===null&&e.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded ${n===T.provider?"bg-white/20 text-white":"bg-slate-200 text-slate-500"}`,children:"—"})]},T.provider))})]}),!c&&j&&e.jsxs("div",{className:"bg-white rounded-xl border border-slate-200 overflow-hidden",children:[e.jsxs("div",{className:"flex items-center justify-between px-5 py-3 border-b border-slate-100",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:`w-8 h-8 rounded-full flex items-center justify-center text-sm font-semibold ${j.status==="mentioned"?"bg-emerald-100 text-emerald-700":"bg-slate-100 text-slate-500"}`,children:j.status==="mentioned"?e.jsx(wt,{size:16}):"—"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-slate-800",children:j.model}),e.jsx("p",{className:"text-xs text-slate-400",children:j.status==="mentioned"?"Mentioned":"Not mentioned"})]})]}),e.jsxs("button",{onClick:q,className:"flex items-center gap-1 text-xs text-slate-500 hover:text-slate-700 transition-colors",children:[i?e.jsx(wt,{size:14}):e.jsx(Ys,{size:14}),i?"Copied":"Copy"]})]}),e.jsx("div",{className:"p-5",children:e.jsx("div",{className:`prose prose-sm prose-slate max-w-none
159            prose-p:text-slate-700 prose-p:leading-relaxed prose-p:mb-3
160            prose-headings:text-slate-800 prose-headings:font-semibold
161            prose-strong:text-slate-800 prose-strong:font-semibold
162            prose-ul:my-2 prose-ol:my-2 prose-li:my-0.5
163            prose-code:text-xs prose-code:bg-slate-100 prose-code:px-1 prose-code:py-0.5 prose-code:rounded
164          `,children:e.jsx(Wn,{remarkPlugins:[Vn],children:j.response})})}),e.jsxs("div",{className:"px-5 py-3 bg-slate-50 border-t border-slate-100",children:[e.jsx("p",{className:"text-[10px] font-semibold text-slate-400 uppercase tracking-wider mb-2",children:"Brands Mentioned"}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:j.brands.map((T,M)=>e.jsx("span",{className:`text-xs px-2 py-1 rounded ${T.toLowerCase()==="rankgale"?"bg-emerald-100 text-emerald-700 font-medium":"bg-white text-slate-600 border border-slate-200"}`,children:T},M))})]})]}),e.jsxs("div",{className:"bg-white rounded-xl border border-slate-200 overflow-hidden",children:[e.jsx("div",{className:"px-5 py-3 border-b border-slate-100",children:e.jsx("p",{className:"text-xs font-semibold text-slate-700",children:"Mention Timeline"})}),e.jsx("div",{className:"p-5 max-h-[600px] overflow-y-auto",children:e.jsx("div",{className:"relative",children:e.jsx("div",{className:"space-y-6",children:[...t.rankings].reverse().map((T,M)=>{const Z=Os(T.openai.rank,T.openai.status),B=Os(T.google.rank,T.google.status),ae=Os(T.anthropic.rank,T.anthropic.status),de=p===`${T.period}-openai`,fe=p===`${T.period}-google`,se=p===`${T.period}-anthropic`;return e.jsxs("div",{className:"flex gap-6",children:[e.jsx("div",{className:"w-16 flex-shrink-0 pt-3",children:e.jsxs("div",{className:"text-right",children:[e.jsx("div",{className:"text-sm font-bold text-slate-800",children:T.period}),e.jsx("div",{className:"text-[10px] text-slate-400",children:T.periodLabel})]})}),e.jsxs("div",{className:"relative flex flex-col items-center",children:[e.jsx("div",{className:`w-3 h-3 rounded-full border-2 z-10 ${Z&&B&&ae?"bg-emerald-500 border-emerald-500":Z||B||ae?"bg-amber-400 border-amber-400":"bg-white border-slate-300"}`}),M<t.rankings.length-1&&e.jsx("div",{className:"w-0.5 flex-1 bg-slate-200 mt-1"})]}),e.jsxs("div",{className:"flex-1 space-y-3 pb-2",children:[e.jsxs("div",{className:`rounded-lg border overflow-hidden transition-all ${Z?"border-emerald-200 bg-emerald-50/30":"border-slate-200 bg-slate-50"}`,children:[e.jsxs("div",{className:"px-4 py-3 flex items-center justify-between cursor-pointer hover:bg-white/50 transition-colors",onClick:()=>A(de?"":`${T.period}
164-openai`,T.openai.scan_id),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(uo,{size:16,className:Z?"text-slate-700":"text-slate-400"}),e.jsx("span",{className:`text-sm font-medium ${Z?"text-slate-700":"text-slate-500"}`,children:"ChatGPT"}),(()=>{const z=Nr("openai",t.selectedModels),U=xl(T.openai.rank,T.openai.status,z,T.openai.sentiment);return e.jsxs("span",{className:`inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-medium ${U.style}`,children:[U.icon==="loader"?e.jsx(He,{size:10,className:"animate-spin"}):U.icon==="check"?e.jsx(wt,{size:10,strokeWidth:3}):U.icon==="x"?e.jsx(mt,{size:10,strokeWidth:3}):e.jsx(Ps,{size:10}),U.label]})})()]}),e.jsx(Gs,{size:16,className:`text-slate-400 transition-transform ${de?"rotate-180":""}`})]}),de&&e.jsx("div",{className:"border-t border-slate-200 p-4 bg-white max-h-[600px] overflow-y-auto",children:T.openai.status==="running"?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-slate-400 py-4",children:[e.jsx(He,{size:14,className:"animate-spin"}),"Scanning in progress..."]}):R?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-slate-400 py-4",children:[e.jsx(He,{size:14,className:"animate-spin"}),"Loading response..."]}):I("openai")?.raw_answer_text?e.jsxs("div",{className:"space-y-3",children:[C("openai").length>0&&e.jsx("div",{className:"flex items-center gap-2 flex-wrap",children:C("openai").map(z=>{const U=I("openai")?.model===z.model;return e.jsxs("button",{onClick:()=>H(z.model),className:`inline-flex items-center gap-1 px-2 py-1 rounded text-xs font-medium transition-all ${U?"ring-2 ring-slate-800 ring-offset-1":"hover:ring-1 hover:ring-slate-300"} ${z.is_mentioned?z.sentiment==="negative"?"bg-red-100 text-red-700":"bg-emerald-100 text-emerald-700":"bg-slate-100 text-slate-500"}`,children:[z.model.replace("azure-openai-","").replace("_","."),z.is_mentioned&&(z.sentiment==="negative"?e.jsx(mt,{size:10,strokeWidth:3}):e.jsx(wt,{size:10,strokeWidth:3}))]},z.model)})}),e.jsxs("div",{className:"grid grid-cols-5 gap-6",children:[e.jsxs("div",{className:"col-span-3 min-w-0",children:[e.jsx("div",{className:`prose prose-sm prose-slate max-w-none
165                                    prose-p:text-slate-700 prose-p:leading-relaxed prose-p:mb-2
166                                    prose-headings:text-slate-800 prose-headings:font-semibold
167                                    prose-strong:text-slate-800 prose-strong:font-semibold
168                                    prose-ul:my-2 prose-ol:my-2 prose-li:my-0.5
169                                  `,children:e.jsx(Wn,{remarkPlugins:[Vn],children:I("openai")?.raw_answer_text||""})}),(I("openai")?.extraction_items?.length??0)>0&&e.jsxs("div",{className:"pt-3 mt-3 border-t border-slate-100",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-slate-400 font-medium mb-2",children:"Brands Mentioned"}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:(I("openai")?.extraction_items??[]).filter(z=>z.position!==null).sort((z,U)=>(z.position||999)-(U.position||999)).slice(0,10).map((z,U)=>e.jsx("span",{className:`px-2 py-0.5 rounded-full text-xs font-medium ${z.matched_company_id?"bg-emerald-100 text-emerald-700":"bg-slate-100 text-slate-600"}`,children:z.display_name||`#${z.position}`},U))})]})]}),e.jsxs("div",{className:"col-span-2 border-l border-slate-200 pl-4",children:[e.jsxs("p",{className:"text-[10px] uppercase tracking-wide text-slate-400 font-medium mb-3 sticky top-0 bg-white py-1",children:["AI Citations"," ",(I("openai")?.citations?.length??0)>0?`(${I("openai")?.citations?.length??0})`:""]}),(I("openai")?.citations?.length??0)>0?e.jsx("div",{className:"grid grid-cols-1 gap-2",children:(I("openai")?.citations??[]).map((z,U)=>e.jsx("a",{href:z.url_raw,target:"_blank",rel:"noopener noreferrer",className:`block p-2.5 rounded-lg border transition-colors group ${z.brand_cited?"border-emerald-300 bg-emerald-50 hover:bg-emerald-100 hover:border-emerald-400":"border-slate-200 bg-slate-50/50 hover:bg-slate-100 hover:border-slate-300"}`,children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(ns,{size:12,className:`mt-0.5 flex-shrink-0 ${z.brand_cited?"text-emerald-500":"text-slate-400 group-hover:text-indigo-500"}`}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:`text-xs font-medium line-clamp-2 ${z.brand_cited?"text-emerald-700":"text-slate-700 group-hover:text-indigo-600"}`,children:z.title||pr(z.url_raw)}),e.jsx("p",{className:`text-[10px] truncate mt-0.5 ${z.brand_cited?"text-emerald-500":"text-slate-400"}`,children:pr(z.url_raw)}),z.snippet&&e.jsx("p",{className:`text-[10px] line-clamp-2 mt-1 ${z.brand_cited?"text-emerald-600":"text-slate-500"}`,children:z.snippet})]})]})},U))}):e.jsx("p",{className:"text-xs text-slate-400",children:"No citations available"})]})]})]}):e.jsx("div",{className:"text-sm text-slate-400 py-2",children:"No response data available yet"})})]}),e.jsxs("div",{className:`rounded-lg border overflow-hidden transition-all ${B?"border-emerald-200 bg-emerald-50/30":"border-slate-200 bg-slate-50"}`,children:[e.jsxs("div",{className:"px-4 py-3 flex items-center justify-between cursor-pointer hover:bg-white/50 transition-colors",onClick:()=>A(fe?"":`${T.period}-google`,T.google.scan_id),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(xo,{size:16}),e.jsx("span",{className:`text-sm font-medium ${B?"text-slate-700":"text-slate-500"}`,children:"Gemini"}),(()=>{const z=Nr("google",t.selectedModels),U=xl(T.google.rank,T.google.status,z,T.google.sentiment);return e.jsxs("span",{className:`inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-medium ${U.style}
169`,children:[U.icon==="loader"?e.jsx(He,{size:10,className:"animate-spin"}):U.icon==="check"?e.jsx(wt,{size:10,strokeWidth:3}):U.icon==="x"?e.jsx(mt,{size:10,strokeWidth:3}):e.jsx(Ps,{size:10}),U.label]})})()]}),e.jsx(Gs,{size:16,className:`text-slate-400 transition-transform ${fe?"rotate-180":""}`})]}),fe&&e.jsx("div",{className:"border-t border-slate-200 p-4 bg-white max-h-[600px] overflow-y-auto",children:T.google.status==="running"?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-slate-400 py-4",children:[e.jsx(He,{size:14,className:"animate-spin"}),"Scanning in progress..."]}):R?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-slate-400 py-4",children:[e.jsx(He,{size:14,className:"animate-spin"}),"Loading response..."]}):I("google")?.raw_answer_text?e.jsxs("div",{className:"space-y-3",children:[C("google").length>0&&e.jsx("div",{className:"flex items-center gap-2 flex-wrap",children:C("google").map(z=>{const U=I("google")?.model===z.model;return e.jsxs("button",{onClick:()=>X(z.model),className:`inline-flex items-center gap-1 px-2 py-1 rounded text-xs font-medium transition-all ${U?"ring-2 ring-slate-800 ring-offset-1":"hover:ring-1 hover:ring-slate-300"} ${z.is_mentioned?z.sentiment==="negative"?"bg-red-100 text-red-700":"bg-emerald-100 text-emerald-700":"bg-slate-100 text-slate-500"}`,children:[z.model.replace("-preview",""),z.is_mentioned&&(z.sentiment==="negative"?e.jsx(mt,{size:10,strokeWidth:3}):e.jsx(wt,{size:10,strokeWidth:3}))]},z.model)})}),e.jsxs("div",{className:"grid grid-cols-5 gap-6",children:[e.jsxs("div",{className:"col-span-3 min-w-0",children:[e.jsx("div",{className:`prose prose-sm prose-slate max-w-none
170                                    prose-p:text-slate-700 prose-p:leading-relaxed prose-p:mb-2
171                                    prose-headings:text-slate-800 prose-headings:font-semibold
172                                    prose-strong:text-slate-800 prose-strong:font-semibold
173                                    prose-ul:my-2 prose-ol:my-2 prose-li:my-0.5
174                                  `,children:e.jsx(Wn,{remarkPlugins:[Vn],children:I("google")?.raw_answer_text||""})}),(I("google")?.extraction_items?.length??0)>0&&e.jsxs("div",{className:"pt-3 mt-3 border-t border-slate-100",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-slate-400 font-medium mb-2",children:"Brands Mentioned"}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:(I("google")?.extraction_items??[]).filter(z=>z.position!==null).sort((z,U)=>(z.position||999)-(U.position||999)).slice(0,10).map((z,U)=>e.jsx("span",{className:`px-2 py-0.5 rounded-full text-xs font-medium ${z.matched_company_id?"bg-emerald-100 text-emerald-700":"bg-slate-100 text-slate-600"}`,children:z.display_name||`#${z.position}`},U))})]})]}),e.jsxs("div",{className:"col-span-2 border-l border-slate-200 pl-4",children:[e.jsxs("p",{className:"text-[10px] uppercase tracking-wide text-slate-400 font-medium mb-3 sticky top-0 bg-white py-1",children:["AI Citations"," ",(I("google")?.citations?.length??0)>0?`(${I("google")?.citations?.length??0})`:""]}),(I("google")?.citations?.length??0)>0?e.jsx("div",{className:"grid grid-cols-1 gap-2",children:(I("google")?.citations??[]).map((z,U)=>e.jsx("a",{href:z.url_raw,target:"_blank",rel:"noopener noreferrer",className:`block p-2.5 rounded-lg border transition-colors group ${z.brand_cited?"border-emerald-300 bg-emerald-50 hover:bg-emerald-100 hover:border-emerald-400":"border-slate-200 bg-slate-50/50 hover:bg-slate-100 hover:border-slate-300"}`,children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(ns,{size:12,className:`mt-0.5 flex-shrink-0 ${z.brand_cited?"text-emerald-500":"text-slate-400 group-hover:text-indigo-500"}`}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:`text-xs font-medium line-clamp-2 ${z.brand_cited?"text-emerald-700":"text-slate-700 group-hover:text-indigo-600"}`,children:z.title||pr(z.url_raw)}),e.jsx("p",{className:`text-[10px] truncate mt-0.5 ${z.brand_cited?"text-emerald-500":"text-slate-400"}`,children:pr(z.url_raw)}),z.snippet&&e.jsx("p",{className:`text-[10px] line-clamp-2 mt-1 ${z.brand_cited?"text-emerald-600":"text-slate-500"}`,children:z.snippet})]})]})},U))}):e.jsx("p",{className:"text-xs text-slate-400",children:"No citations available"})]})]})]}):e.jsx("div",{className:"text-sm text-slate-400 py-2",children:"No response data available yet"})})]}),e.jsxs("div",{className:`rounded-lg border overflow-hidden transition-all ${ae?"border-emerald-200 bg-emerald-50/30":"border-slate-200 bg-slate-50"}`,children:[e.jsxs("div",{className:"px-4 py-3 flex items-center justify-between cursor-pointer hover:bg-white/50 transition-colors",onClick:()=>A(se?"":`${T.period}
174-anthropic`,T.anthropic.scan_id),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ho,{size:16}),e.jsx("span",{className:`text-sm font-medium ${ae?"text-slate-700":"text-slate-500"}`,children:"Claude"}),(()=>{const z=Nr("anthropic",t.selectedModels),U=xl(T.anthropic.rank,T.anthropic.status,z,T.anthropic.sentiment);return e.jsxs("span",{className:`inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-medium ${U.style}`,children:[U.icon==="loader"?e.jsx(He,{size:10,className:"animate-spin"}):U.icon==="check"?e.jsx(wt,{size:10,strokeWidth:3}):U.icon==="x"?e.jsx(mt,{size:10,strokeWidth:3}):e.jsx(Ps,{size:10}),U.label]})})()]}),e.jsx(Gs,{size:16,className:`text-slate-400 transition-transform ${se?"rotate-180":""}`})]}),se&&e.jsx("div",{className:"border-t border-slate-200 p-4 bg-white max-h-[600px] overflow-y-auto",children:T.anthropic.status==="running"?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-slate-400 py-4",children:[e.jsx(He,{size:14,className:"animate-spin"}),"Scanning in progress..."]}):R?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-slate-400 py-4",children:[e.jsx(He,{size:14,className:"animate-spin"}),"Loading response..."]}):I("anthropic")?.raw_answer_text?e.jsxs("div",{className:"space-y-3",children:[C("anthropic").length>0&&e.jsx("div",{className:"flex items-center gap-2 flex-wrap",children:C("anthropic").map(z=>{const U=I("anthropic")?.model===z.model;return e.jsxs("button",{onClick:()=>P(z.model),className:`inline-flex items-center gap-1 px-2 py-1 rounded text-xs font-medium transition-all ${U?"ring-2 ring-slate-800 ring-offset-1":"hover:ring-1 hover:ring-slate-300"} ${z.is_mentioned?z.sentiment==="negative"?"bg-red-100 text-red-700":"bg-emerald-100 text-emerald-700":"bg-slate-100 text-slate-500"}`,children:[z.model.replace("vertex-claude-","").replace("-"," "),z.is_mentioned&&(z.sentiment==="negative"?e.jsx(mt,{size:10,strokeWidth:3}):e.jsx(wt,{size:10,strokeWidth:3}))]},z.model)})}),e.jsxs("div",{className:"grid grid-cols-5 gap-6",children:[e.jsxs("div",{className:"col-span-3 min-w-0",children:[e.jsx("div",{className:`prose prose-sm prose-slate max-w-none
175                                    prose-p:text-slate-700 prose-p:leading-relaxed prose-p:mb-2
176                                    prose-headings:text-slate-800 prose-headings:font-semibold
177                                    prose-strong:text-slate-800 prose-strong:font-semibold
178                                    prose-ul:my-2 prose-ol:my-2 prose-li:my-0.5
179                                  `,children:e.jsx(Wn,{remarkPlugins:[Vn],children:I("anthropic")?.raw_answer_text||""})}),(I("anthropic")?.extraction_items?.length??0)>0&&e.jsxs("div",{className:"pt-3 mt-3 border-t border-slate-100",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-slate-400 font-medium mb-2",children:"Brands Mentioned"}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:(I("anthropic")?.extraction_items??[]).filter(z=>z.position!==null).sort((z,U)=>(z.position||999)-(U.position||999)).slice(0,10).map((z,U)=>e.jsx("span",{className:`px-2 py-0.5 rounded-full text-xs font-medium ${z.matched_company_id?"bg-emerald-100 text-emerald-700":"bg-slate-100 text-slate-600"}`,children:z.display_name||`#${z.position}`},U))})]})]}),e.jsxs("div",{className:"col-span-2 border-l border-slate-200 pl-4",children:[e.jsxs("p",{className:"text-[10px] uppercase tracking-wide text-slate-400 font-medium mb-3 sticky top-0 bg-white py-1",children:["AI Citations"," ",(I("anthropic")?.citations?.length??0)>0?`(${I("anthropic")?.citations?.length??0})`:""]}),(I("anthropic")?.citations?.length??0)>0?e.jsx("div",{className:"grid grid-cols-1 gap-2",children:(I("anthropic")?.citations??[]).map((z,U)=>e.jsx("a",{href:z.url_raw,target:"_blank",rel:"noopener noreferrer",className:`block p-2.5 rounded-lg border transition-colors group ${z.brand_cited?"border-emerald-300 bg-emerald-50 hover:bg-emerald-100 hover:border-emerald-400":"border-slate-200 bg-slate-50/50 hover:bg-slate-100 hover:border-slate-300"}`,children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(ns,{size:12,className:`mt-0.5 flex-shrink-0 ${z.brand_cited?"text-emerald-500":"text-slate-400 group-hover:text-indigo-500"}`}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:`text-xs font-medium line-clamp-2 ${z.brand_cited?"text-emerald-700":"text-slate-700 group-hover:text-indigo-600"}`,children:z.title||pr(z.url_raw)}),e.jsx("p",{className:`text-[10px] truncate mt-0.5 ${z.brand_cited?"text-emerald-500":"text-slate-400"}`,children:pr(z.url_raw)}),z.snippet&&e.jsx("p",{className:`text-[10px] line-clamp-2 mt-1 ${z.brand_cited?"text-emerald-600":"text-slate-500"}`,children:z.snippet})]})]})},U))}):e.jsx("p",{className:"text-xs text-slate-400",children:"No citations available"})]})]})]}):e.jsx("div",{className:"text-sm text-slate-400 py-2",children:"No response data available yet"})})]})]})]},T.period)})})})})]})]})}const gr=(t,s)=>s==="running"?"text-blue-500":s==="untracked"?"text-slate-400":s==="not_mentioned"?"text-slate-300":"text-emerald-500",Os=(t,s)=>s==="running"||s==="untracked"?!1:s==="mentioned",Nr=(t,s)=>{if(!s||s.length===0)return!0;const n={openai:["azure-openai","openai","gpt"],google:["google","gemini","vertex-gemini"],anthropic:["anthropic","claude","vertex-claude"]}[t]||[t];return s.some(i=>n.some(l=>i.toLowerCase().includes(l.toLowerCase())))}
179,xl=(t,s,a=!0,n)=>a?s==="running"?{label:"Scanning",icon:"loader",style:"bg-blue-100 text-blue-600"}:s==="untracked"?{label:"Untracked",icon:"minus",style:"bg-slate-100 text-slate-400"}:Os(t,s)?n==="negative"?{label:"Mentioned",icon:"x",style:"bg-red-100 text-red-600"}:{label:"Mentioned",icon:"check",style:"bg-emerald-100 text-emerald-700"}:{label:"Not mentioned",icon:"minus",style:"bg-slate-200 text-slate-500"}:{label:"Untracked",icon:"minus",style:"bg-slate-100 text-slate-400"};function Pj({prompts:t,loading:s,onTrackNew:a,onSelectPrompt:n,onSync:o,onExport:i,onSettings:l,onBatchSettings:c,onContentGeneration:d,onDelete:m,isSyncing:h,isDeleting:p,searchQuery:f,onSearchChange:b,dateRange:y,onDateRangeChange:x,periods:u,viewMode:g,onViewModeChange:w,hideToolbar:_=!1}){const[E,N]=r.useState(!1),[S,k]=r.useState(new Set),[D,F]=r.useState(1),[R,L]=r.useState(20),[$,H]=r.useState(()=>typeof window<"u"&&window.innerWidth<768),[K,X]=r.useState(!0),[V,P]=r.useState(30),A=30,[C,I]=r.useState(null);r.useEffect(()=>{const Q=()=>H(window.innerWidth<768);return window.addEventListener("resize",Q),()=>window.removeEventListener("resize",Q)},[]);const[j,q]=r.useState({checkbox:40,prompt:200}),[T,M]=r.useState(null),Z=r.useCallback((Q,me)=>{Q.preventDefault(),Q.stopPropagation();const le="touches"in Q?Q.touches[0].clientX:Q.clientX,O=j[me]||100;M({column:me,startX:le,startWidth:O})},[j]);r.useEffect(()=>{if(!T)return;const Q=le=>{const ne=("touches"in le?le.touches[0].clientX:le.clientX)-T.startX,ge=Math.max(60,Math.min(400,T.startWidth+ne));q(ze=>({...ze,[T.column]:ge}))},me=()=>M(null);return document.addEventListener("mousemove",Q),document.addEventListener("mouseup",me),document.addEventListener("touchmove",Q),document.addEventListener("touchend",me),()=>{document.removeEventListener("mousemove",Q),document.removeEventListener("mouseup",me),document.removeEventListener("touchmove",Q),document.removeEventListener("touchend",me)}},[T]),r.useEffect(()=>{S.size>0&&X(!1)},[S.size]);const B=r.useMemo(()=>f.trim()?t.filter(Q=>Q.prompt.toLowerCase().includes(f.toLowerCase())):t,[t,f]),ae=r.useCallback(Q=>{const me=Q.target,{scrollTop:le,scrollHeight:O,clientHeight:ne}=me;O-le-ne<100&&P(ge=>Math.min(ge+A,B.length))},[B.length]),de=r.useMemo(()=>{const Q=(D-1)*R;return B.slice(Q,Q+R)},[B,D,R]);r.useEffect(()=>{F(1),P(30)},[f]);const fe=()=>{S.size===de.length?k(new Set):k(new Set(de.map(Q=>Q.id)))},se=de.length>0&&S.size===de.length,z=S.size>0,U=r.useMemo(()=>B.slice(0,V),[B,V]);return!s&&t.length===0?e.jsx("div",{className:"bg-white rounded-xl border border-slate-200 p-12",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12",children:[e.jsx("div",{className:"w-16 h-16 rounded-full bg-slate-900 flex items-center justify-center mb-6",children:e.jsx(Na,{size:28,className:"text-white"})}),e.jsx("h2",{className:"text-2xl font-semibold text-slate-900 mb-2",children:"GEO Prompt Tracking"}),e.jsx("p",{className:"text-slate-500 text-center max-w-md mb-8",children:"Monitor and improve brand visibility across AI search platforms"}),e.jsxs(be,{onClick:a,className:"gap-2 bg-slate-900 hover:bg-slate-800",children:["Add Prompts",e.jsx($t,{size:16})]})]})}):e.jsxs("div",{className:`space-y-4 relative ${$?"pb-28":"pb-24"}`,children:[!_&&e.jsx("div",{className:"bg-white rounded-xl border border-slate-200 p-4 hidden sm:block",children:e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Pt,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400"}),e.jsx(bt,{placeholder:"Search prompts...",value:f,onChange:Q=>b(Q.target.value),onFocus:()=>N(!0),onBlur:()=>N(!1),className:`pl-9 pr-8 w-56 transition-all ${E?"w-72 ring-2 ring-blue-100":""}`}),f&&e.jsx("button",{onClick:()=>b(""),className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 hover:bg-slate-100 rounded",children:e.jsx("span",{className:"text-slate-400 text-xs",children:"✕"})})]}),e.jsx("div",{className:"h-8 w-px bg-slate-200"}),e.jsxs("div",{className:"flex items-center bg-slate-100 rounded-lg p-0.5",children:[e.jsx("button",{onClick:()=>w("weekly"),className:`px-3 py-1.5 text-sm font-medium rounded-md transition-all ${g==="weekly"?"bg-white text-slate-900 shadow-sm":"text-slate-600 hover:text-slate-900"}`,children:"Weekly"}),e.jsx("button",{onClick:()=>w("monthly"),className:`px-3 py-1.5 text-sm font-medium rounded-md transition-all ${g==="monthly"?"bg-white text-slate-900 shadow-sm":"text-slate-600 hover:text-slate-900"}`,children:"Monthly"})]}),e.jsx(Sa,{value:y,onChange:x,placeholder:"Select date range",className:"w-56"}),e.jsxs("div",{className:"relative group",children:[e.jsx(Hs,{className:"w-4 h-4 text-slate-400 cursor-help"}),e.jsx("div",{className:"absolute left-0 top-6 z-20 hidden group-hover:block",children:e.jsxs("div",{className:"bg-slate-800 text-white text-xs rounded-lg px-4 py-3 shadow-lg min-w-[200px]",children:[e.jsx("p",{className:"font-medium mb-1.5",children:"AI Models"}),e.jsxs("div",{className:"text-slate-300 space-y-1 mb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(uo,{size:12,className:"text-slate-300"}),e.jsx("span",{children:"OpenAI (ChatGPT)"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(xo,{size:12}),e.jsx("span",{children:"Google (Gemini)"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ho,{size:12}),e.jsx("span",{children:"Anthropic (Claude)"})]})]}),e.jsx("p",{className:"font-medium mb-1.5 pt-2 border-t border-slate-600",children:"Mention Status"}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(wt,{size:12,className:"text-emerald-400",strokeWidth:3}),e.jsx("span",{className:"text-slate-300",children:"Mentioned"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ps,{size:12,className:"text-slate-400"}),e.jsx("span",{className:"text-slate-300",children:"Not mentioned"})]})]}),e.jsx("div",{className:"absolute -top-1 left-3 w-2 h-2 bg-slate-800 rotate-45"})]})})]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[e.jsxs(be,{variant:"outline",size:"sm",className:"gap-1.5",disabled:!z||h,onClick:()=>o(Array.from(S)),"data-onboarding":"run-scan-button",children:[e.jsx(kt,{className:`w-4 h-4 ${h?"animate-spin":""}`}),h?"Syncing...":"Sync"]}),e.jsxs(be,{variant:"outline",size:"sm",className:"gap-1.5",disabled:!z,onClick:()=>i(Array.from(S)),children:[e.jsx(Vs,{className:"w-4 h-4"}),"Export"]}),e.jsxs(be,{variant:"outline",size:"sm",className:"gap-1.5",onClick:()=>{const Q=z?Array.from(S):t.map(me=>me.id);c(Q)},disabled:t.length===0,title:z?`Configure schedule for ${S.size} selected prompt(s)`:"Configure schedule for all prompts",children:[e.jsx(_r,{className:"w-4 h-4"}),"Settings"]}),e.jsxs(be,{size:"sm",className:"gap-1.5 bg-slate-800 hover:bg-slate-700",onClick:a,"data-onboarding":"add-prompt-button",children:[e.jsx($t,{className:"w-4 h-4"}),"Track New Prompt"]})]})]})}),s&&e.jsx("div",{className:"bg-white rounded-xl border border-slate-200 p-12",children:e.jsxs("div",{className:"flex items-center justify-center",children:[e.jsx(He,{className:"w-8 h-8 animate-spin text-slate-400"}),e.jsx("span",{className:"ml-3 text-slate-500",children:"Loading prompts..."})]})}),!s&&e.jsxs("div",{className:`bg-white overflow-hidden flex flex-col ${$?"flex-1":"rounded-xl border border-slate-200"}`,"data-onboarding":"scan-history",style:$?{maxHeight:"calc(100vh - 280px)"}:{maxHeight:"calc(100vh - 340px)"},children:[e.jsx("div",{className:"flex-1 overflow-auto min-h-0 h-full",onScroll:$?ae:void 0,children:e.jsxs("table",{className:"min-w-full text-sm",style:$?{tableLayout:"fixed"}:void 0,children:[e.jsx("thead",{className:`text-left text-slate-500 bg-slate-50 border-b border-slate-200 ${$?"sticky top-0 z-30":"sticky top-0 z-20"}`,children:e.jsxs("tr",{children:[e.jsxs("th",{className:`px-3 py-3 relative group/resize ${$?"bg-slate-50":"w-10 sticky left-0 bg-slate-50 z-30"}`,style:$?{width:j.checkbox,minWidth:j.checkbox}:void 0,children:[e.jsx(Kt,{checked:se?!0:z?"indeterminate":!1,onCheckedChange:fe}),$&&e.jsx("div",{className:"absolute right-0 top-0 bottom-0 w-1 cursor-col-resize bg-transparent hover:bg-blue-400 transition-colors",onMouseDown:Q=>Z(Q,"checkbox"),onTouchStart:Q=>Z(Q,"checkbox")}
179)]}),e.jsxs("th",{className:`px-3 py-3 font-semibold text-slate-700 relative group/resize ${$?"bg-slate-50":"min-w-[280px]"}`,style:$?{width:j.prompt,minWidth:j.prompt}:void 0,children:["Prompt",$&&e.jsx("div",{className:"absolute right-0 top-0 bottom-0 w-1 cursor-col-resize bg-transparent hover:bg-blue-400 transition-colors",onMouseDown:Q=>Z(Q,"prompt"),onTouchStart:Q=>Z(Q,"prompt")})]}),!_&&u.map(Q=>e.jsx("th",{className:"px-2 py-3 font-semibold text-slate-700 text-center min-w-[80px]",title:Q.periodLabel,children:e.jsxs("div",{className:"flex flex-col items-center",children:[e.jsx("span",{children:Q.period}),e.jsxs("div",{className:"flex gap-2 mt-1.5 items-center justify-center",children:[e.jsx(uo,{size:12,className:"text-slate-500"}),e.jsx(xo,{size:12}),e.jsx(ho,{size:12})]})]})},Q.period)),_&&e.jsx("th",{className:"px-4 py-3 font-semibold text-slate-700 text-center min-w-[100px]",children:e.jsxs("div",{className:"flex gap-2 items-center justify-center",children:[e.jsx(uo,{size:12,className:"text-slate-500"}),e.jsx(xo,{size:12}),e.jsx(ho,{size:12})]})}),e.jsx("th",{className:"px-4 py-3 font-semibold text-slate-700 text-center min-w-[120px]",children:"Status"})]})}),e.jsx("tbody",{className:"divide-y divide-slate-100 border-b border-gray-200",children:($?U:de).map(Q=>{const me=S.has(Q.id),le=[...Q.rankings].sort((Se,je)=>Se.periodStart.localeCompare(je.periodStart)),O=le[le.length-1],ne=Nr("openai",Q.selectedModels),ge=Nr("google",Q.selectedModels),ze=Nr("anthropic",Q.selectedModels),Ke=ne?O?.openai?.status??"untracked":"untracked",ie=ge?O?.google?.status??"untracked":"untracked",ve=ze?O?.anthropic?.status??"untracked":"untracked",we=O&&ne?Os(O.openai.rank,O.openai.status):!1,Pe=O&&ge?Os(O.google.rank,O.google.status):!1,Ae=O&&ze?Os(O.anthropic.rank,O.anthropic.status):!1,re=Ke==="running"||ie==="running"||ve==="running"?{label:"Scanning",className:"bg-blue-50 text-blue-700 border border-blue-200"}:Ke==="untracked"&&ie==="untracked"&&ve==="untracked"?{label:"Untracked",className:"bg-slate-50 text-slate-600 border border-slate-200"}:we&&Pe?{label:"High visibility",className:"bg-emerald-50 text-emerald-700 border border-emerald-200"}:Ke==="not_mentioned"||ie==="not_mentioned"||ve==="not_mentioned"?{label:"Opportunity",className:"bg-amber-50 text-amber-700 border border-amber-200"}:we||Pe||Ae?{label:"Mentioned",className:"bg-emerald-50 text-emerald-700 border border-emerald-200"}:{label:"Untracked",className:"bg-slate-50 text-slate-600 border border-slate-200"};return e.jsxs("tr",{className:`hover:bg-slate-50/50 transition-colors cursor-pointer ${me?"bg-blue-50/50":""}`,onClick:$?()=>I(Q):()=>n(Q),children:[e.jsx("td",{className:`px-3 py-3 ${$?"bg-white":"sticky left-0 bg-white z-10"}`,style:$?{width:j.checkbox,minWidth:j.checkbox}:void 0,children:e.jsx(Kt,{checked:me,onCheckedChange:()=>{const Se=new Set(S);Se.has(Q.id)?Se.delete(Q.id):Se.add(Q.id),k(Se)},onClick:Se=>Se.stopPropagation()})}),e.jsx("td",{className:`px-3 py-3 font-medium text-slate-900 ${$?"bg-white":""}`,style:$?{width:j.prompt,minWidth:j.prompt}:void 0,children:e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"truncate block max-w-[260px]",title:Q.prompt,children:Q.prompt}),Q.nextRunAt&&e.jsxs("span",{className:"text-[10px] text-slate-400 mt-0.5 flex items-center gap-1",children:[e.jsx(Ra,{size:10,className:"inline"}),"Next:"," ",new Date(Q.nextRunAt).toISOString().replace("T"," ").slice(0,16)," ","UTC"]})]})}),!_&&u.map(Se=>{const je=Q.rankings.find(Ze=>Ze.period===Se.period),he=je?.openai||{rank:null,status:"untracked"},Re=je?.google||{rank:null,status:"untracked"},Me=je?.anthropic||{rank:null,status:"untracked"};return e.jsx("td",{className:"px-2 py-3 text-center",children:e.jsxs("div",{className:"flex justify-center gap-2 items-center",children:[e.jsx("span",{className:`flex items-center justify-center w-5 ${gr(he.rank,he.status)}`,children:he.status==="running"?e.jsx(He,{size:12,className:"animate-spin"}):Os(he.rank,he.status)?e.jsx(wt,{size:14,strokeWidth:3}):e.jsx(Ps,{size:14,className:"text-slate-300"})}),e.jsx("span",{className:`flex items-center justify-center w-5 ${gr(Re.rank,Re.status)}`,children:Re.status==="running"?e.jsx(He,{size:12,className:"animate-spin"}):Os(Re.rank,Re.status)?e.jsx(wt,{size:14,strokeWidth:3}):e.jsx(Ps,{size:14,className:"text-slate-300"})}),e.jsx("span",{className:`flex items-center justify-center w-5 ${gr(Me.rank,Me.status)}`,children:Me.status==="running"?e.jsx(He,{size:12,className:"animate-spin"}):Os(Me.rank,Me.status)?e.jsx(wt,{size:14,strokeWidth:3}):e.jsx(Ps,{size:14,className:"text-slate-300"})})]})},Se.period)}),_&&(()=>{const Se=[...Q.rankings].sort((Ze,Be)=>Ze.periodStart.localeCompare(Be.periodStart)),je=Se[Se.length-1],he=je?.openai||{rank:null,status:"untracked"},Re=je?.google||{rank:null,status:"untracked"},Me=je?.anthropic||{rank:null,status:"untracked"};return e.jsx("td",{className:"px-4 py-3 text-center",children:e.jsxs("div",{className:"flex justify-center gap-2 items-center",children:[e.jsx("span",{className:`flex items-center justify-center w-5 ${gr(he.rank,he.status)}`,children:he.status==="running"?e.jsx(He,{size:12,className:"animate-spin"}):Os(he.rank,he.status)?e.jsx(wt,{size:14,strokeWidth:3}):e.jsx(Ps,{size:14,className:"text-slate-300"})}),e.jsx("span",{className:`flex items-center justify-center w-5 ${gr(Re.rank,Re.status)}`,children:Re.status==="running"?e.jsx(He,{size:12,className:"animate-spin"}):Os(Re.rank,Re.status)?e.jsx(wt,{size:14,strokeWidth:3}):e.jsx(Ps,{size:14,className:"text-slate-300"})}),e.jsx("span",{className:`flex items-center justify-center w-5 ${gr(Me.rank,Me.status)}`,children:Me.status==="running"?e.jsx(He,{size:12,className:"animate-spin"}):Os(Me.rank,Me.status)?e.jsx(wt,{size:14,strokeWidth:3}):e.jsx(Ps,{size:14,className:"text-slate-300"})})]})})})(),e.jsx("td",{className:"px-4 py-3 text-center",children:e.jsx("span",{className:`inline-flex items-center px-2.5 py-1 rounded-full text-xs font-medium whitespace-nowrap ${re.className}`,children:re.label})})]},Q.id)})})]})}),de.length===0&&e.jsxs("div",{className:"py-16 text-center",children:[e.jsx(Na,{size:48,className:"mx-auto text-slate-300 mb-4"}),e.jsx("h3",{className:"text-lg font-medium text-slate-900 mb-1",children:f?"No matching prompts":"No prompts tracked yet"}),e.jsx("p",{className:"text-sm text-slate-500 mb-4",children:f?"Try adjusting your search query":"Start tracking prompts to monitor your brand visibility"}),!f&&e.jsxs(be,{onClick:a,className:"gap-2",children:[e.jsx($t,{size:14}),"Track New Prompt"]})]}),B.length>0&&!$&&e.jsx("div",{className:"flex-shrink-0 border-t border-slate-200",children:e.jsx(xn,{page:D,pageSize:R,total:B.length,onPageChange:F,onPageSizeChange:L,onPageSizeChangeWithReset:Q=>{L(Q),F(1)},displayFormat:"range",maxPageSize:100})})]}),$&&C&&e.jsx("div",{className:"fixed inset-0 z-[100] bg-black/40 backdrop-blur-sm",onClick:()=>I(null),children:e.jsxs("div",{className:"fixed bottom-0 left-0 right-0 bg-white rounded-t-2xl shadow-2xl max-h-[85vh] flex flex-col animate-in slide-in-from-bottom duration-300",onClick:Q=>Q.stopPropagation(),children:[e.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b border-slate-100",children:[e.jsx("h3",{className:"text-sm font-semibold text-slate-900",children:"Prompt Detail"}),e.jsx("button",{onClick:()=>I(null),className:"p-1.5 rounded-full hover:bg-slate-100 text-slate-500",children:e.jsx(mt,{size:18})})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto p-4 space-y-4",children:[e.jsxs("div",{className:"bg-slate-50 rounded-xl p-4",children:[e.jsx("label",{className:"text-[10px] text-slate-500 uppercase tracking-wide font-medium",children:"Prompt"}),e.jsx("p",{className:"text-sm text-slate-900 mt-1 leading-relaxed",children:C.prompt})]}),C.nextRunAt&&e.jsxs("div",{className:"flex items-center gap-2 text-xs text-slate-500",children:[e.jsx(Ra,{size:12}),e.jsxs("span",{children:["Next run: ",new Date(C.nextRunAt).toLocaleStr
179ing()]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("label",{className:"text-[10px] text-slate-500 uppercase tracking-wide font-medium",children:"AI Responses"}),(()=>{const Q=[...C.rankings].sort((ge,ze)=>ge.periodStart.localeCompare(ze.periodStart)),me=Q[Q.length-1],le=me?.openai?.status??"untracked",O=me?.google?.status??"untracked",ne=me?.anthropic?.status??"untracked";return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"border border-slate-200 rounded-xl overflow-hidden",children:e.jsxs("div",{className:"flex items-center justify-between px-3 py-2.5 bg-slate-50",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-base",children:"🤖"}),e.jsx("span",{className:"text-sm font-medium text-slate-800",children:"ChatGPT"})]}),e.jsx("span",{className:`px-2 py-0.5 text-xs font-medium rounded-full ${le==="mentioned"?"bg-emerald-100 text-emerald-700":le==="untracked"?"bg-slate-100 text-slate-500":"bg-slate-200 text-slate-600"}`,children:le==="mentioned"?"Mentioned":le==="untracked"?"Untracked":"Not mentioned"})]})}),e.jsx("div",{className:"border border-slate-200 rounded-xl overflow-hidden",children:e.jsxs("div",{className:"flex items-center justify-between px-3 py-2.5 bg-slate-50",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-base",children:"🌟"}),e.jsx("span",{className:"text-sm font-medium text-slate-800",children:"Gemini"})]}),e.jsx("span",{className:`px-2 py-0.5 text-xs font-medium rounded-full ${O==="mentioned"?"bg-emerald-100 text-emerald-700":O==="untracked"?"bg-slate-100 text-slate-500":"bg-slate-200 text-slate-600"}`,children:O==="mentioned"?"Mentioned":O==="untracked"?"Untracked":"Not mentioned"})]})}),e.jsx("div",{className:"border border-slate-200 rounded-xl overflow-hidden",children:e.jsxs("div",{className:"flex items-center justify-between px-3 py-2.5 bg-slate-50",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-base",children:"✨"}),e.jsx("span",{className:"text-sm font-medium text-slate-800",children:"Claude"})]}),e.jsx("span",{className:`px-2 py-0.5 text-xs font-medium rounded-full ${ne==="mentioned"?"bg-emerald-100 text-emerald-700":ne==="untracked"?"bg-slate-100 text-slate-500":"bg-slate-200 text-slate-600"}`,children:ne==="mentioned"?"Mentioned":ne==="untracked"?"Untracked":"Not mentioned"})]})})]})})()]})]}),e.jsxs("div",{className:"px-4 py-3 border-t border-slate-100 flex gap-2",children:[e.jsxs("button",{onClick:()=>{o([C.id]),I(null)},disabled:h,className:"flex-1 py-2.5 text-sm font-medium text-slate-600 bg-slate-100 rounded-xl hover:bg-slate-200 active:bg-slate-300 transition-colors flex items-center justify-center gap-1.5",children:[e.jsx(kt,{size:14,className:h?"animate-spin":""}),"Sync"]}),e.jsxs("button",{onClick:()=>{l(C.id),I(null)},className:"flex-1 py-2.5 text-sm font-medium text-slate-600 bg-slate-100 rounded-xl hover:bg-slate-200 active:bg-slate-300 transition-colors flex items-center justify-center gap-1.5",children:[e.jsx(_r,{size:14}),"Settings"]}),e.jsxs("button",{onClick:()=>{d([C.id]),I(null)},className:"flex-1 py-2.5 text-sm font-semibold text-white bg-indigo-600 rounded-xl shadow-md shadow-indigo-200 active:scale-95 transition-all flex items-center justify-center gap-1.5",children:[e.jsx(ln,{size:14}),"Generate"]})]})]})})]})}const hl=[{id:"geo_prompt_content",name:"GEO Prompt Content",description:"Generate content from AI platform tracking with websearch",previewBg:"from-indigo-50 to-purple-100"},{id:"geo_prompt_content_webflow",name:"GEO Prompt Content (webflow)",description:"Generate content with Webflow publishing integration",previewBg:"from-emerald-50 to-teal-100"},{id:"geo_prompt_content_shopify",name:"GEO Prompt Content (shopify)",description:"Generate content with Shopify publishing integration",previewBg:"from-green-50 to-emerald-100"}];function Ij(t){const s=new Date,a=s.toLocaleString("en-US",{month:"short"}),n=s.getDate();return`${t?.trim()?t.trim():"GEO Prompt Content"} - ${a} ${n}`}function Mj({isOpen:t,onClose:s,selectedPromptIds:a,trackedPrompts:n}){const{toast:o}=_t(),{confirm:i}=ia(),[l,c]=r.useState(1),[d,m]=r.useState("geo_prompt_content"),[h,p]=r.useState(""),[f,b]=r.useState(!0),[y,x]=r.useState(!1),[u,g]=r.useState(!1),[w,_]=r.useState(""),[E,N]=r.useState(void 0),S=r.useMemo(()=>hl.find(V=>V.id===d)||hl[0],[d]),k=r.useMemo(()=>n.filter(V=>a.includes(V.id)),[n,a]),D=r.useMemo(()=>k.reduce((V,P)=>V+(P.prompt||"").trim().length,0),[k]),F=r.useMemo(()=>k.map((V,P)=>({id:`prompt-${P}`,name:V.prompt,keywords:[{keyword:V.prompt}]})),[k]);r.useEffect(()=>{t&&(c(1),p(Ij(S?.name)),N(void 0),b(!0),x(!1))},[t,S?.name]);const R=()=>{u||s()},L=!u&&h.trim().length>0&&k.length>0,$=r.useMemo(()=>Va({rawContext:E??null}),[E]),H=Bc({isOpen:t,enabled:l===2&&f,templateType:d,groupCount:k.length,totalKeywords:k.length,totalKeywordChars:D}),K=async()=>
179{if(L){if(f){if(y)return;x(!0);try{if(!await Ji({confirm:i,estimatedRange:H.estimatedRange,requiredMinimumBalance:H.requiredMinimumBalance,toast:o}))return}finally{x(!1)}}g(!0),_("Collecting scan data...");try{const V=[],P={};for(const C of k){const I=[];let j=null,q=null;if(C.lastScanId)try{const T=await Ai(C.lastScanId);if(T.model_runs)for(const M of T.model_runs){if(M.citations)for(const B of M.citations)B.url_normalized&&!I.includes(B.url_normalized)&&I.push(B.url_normalized);const Z=(M.provider||"").toLowerCase();Z.includes("google")||Z.includes("gemini")?j=M.raw_answer_text||null:(Z.includes("openai")||Z.includes("chatgpt"))&&(q=M.raw_answer_text||null)}}catch(T){console.warn(`Failed to get scan data for prompt ${C.id}:`,T)}P[C.prompt]={citations:I,googleAnswer:j,openaiAnswer:q};for(const T of I)V.includes(T)||V.push(T)}_("Creating worksheet...");const A=await cr.createWorksheetAndGenerateFromGroups({source:{kind:"content_generation_template",templateType:d},campaignName:h.trim(),groups:F,options:{generateTitleAndContent:f,titlePollingTimeoutMs:12e4,titlePollingIntervalMs:2e3,context:$,onProgress:(C,I)=>{I&&_(I)}}});try{_("Filling scan data...");const C=await Vt.listColumns({campaign_id:A.campaignId,view_config_id:A.viewId,is_active:!0,include_config:!0}),I=C.items?.find(T=>T.system_name==="prompt_tracking_citation"||T.name==="Prompt tracking citation"),j=C.items?.find(T=>T.system_name==="prompt_tracking_history_gemini"||T.name?.toLowerCase().includes("google")),q=C.items?.find(T=>T.system_name==="prompt_tracking_history_openai"||T.name?.toLowerCase().includes("openai"));if(I&&V.length>0&&await Vt.updateColumn(I.id,{config:{...I.config||{},options:V,multiple:!0}}),(j||q||I)&&A.createdRowIds.length>0){const T=k.map((M,Z)=>{const B=A.createdRowIds[Z],ae=P[M.prompt]||{citations:[],googleAnswer:null,openaiAnswer:null},de={};return j&&ae.googleAnswer&&(de[j.name]=ae.googleAnswer),q&&ae.openaiAnswer&&(de[q.name]=ae.openaiAnswer),I&&ae.citations.length>0&&(de[I.name]=ae.citations.slice(0,5)),{entity_id:B,custom_data_updates:de}}).filter(M=>Object.keys(M.custom_data_updates).length>0);T.length>0&&await Wt.batchUpdateCustomData({campaign_id:A.campaignId,table_type:A.viewSystemName,updates:T})}}catch(C){console.warn("Failed to update scan data:",C)}try{localStorage.setItem("flowwriter.currentCampaign",JSON.stringify({id:A.campaignId,name:h.trim()}))}catch{}o({title:"✅ Worksheet created",description:"Prompts and scan data filled. You can run generation from the table."}),s(),jt("table-new",{campaign:A.campaignId,view:A.viewId})}catch(V){console.error("❌ Failed to create worksheet and generate:",V),o({title:"Create & generate failed",description:V?.message||"Please try again."})}finally{g(!1)}}},X=[];return $.company&&X.push("Company"),$.knowledges.enabled&&X.push(`Knowledge (${$.knowledges.scope_ids?$.knowledges.scope_ids.length:"all"})`),$.competitors.enabled&&X.push(`Competitors (${$.competitors.scope_domains?$.competitors.scope_domains.length:"all"})`),l===1?e.jsxs("div",{className:`fixed inset-0 z-50 flex items-center justify-center ${t?"":"hidden"}`,children:[e.jsx("div",{className:"absolute inset-0 bg-black/20",onClick:R}),e.jsxs("div",{className:"relative bg-white rounded-2xl shadow-xl max-w-xl w-full mx-4 overflow-hidden",children:[e.jsx("div",{className:"px-6 py-5 border-b border-slate-100",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-[15px] font-semibold text-slate-800",children:"Add Reference"}),e.jsx("p",{className:"text-[12px] text-slate-400 mt-0.5",children:"Help AI create content that truly represents your brand"})]}),e.jsx("button",{onClick:R,className:"p-1.5 rounded-lg text-slate-400 hover:text-slate-600 hover:bg-slate-50 transition-colors",children:e.jsx(mt,{size:18})})]})}),e.jsx(Yi,{isOpen:t,onClose:R,onConfirm:()=>c(2),value:E,onChange:N}),e.jsxs("div",{className:"px-6 py-4 border-t border-slate-100 flex justify-between items-center bg-slate-50/50",children:[e.jsx("button",{onClick:R,className:"text-[13px] text-slate-500 hover:text-slate-700",children:"Cancel"}),e.jsxs("button",{onClick:()=>c(2),className:"px-5 py-2 bg-slate-800 text-white text-[13px] font-medium rounded-lg hover:bg-slate-700 flex items-center gap-2 transition-colors",children:["Continue",e.jsx(Ms,{size:14})]})]})]})]}):e.jsx(Ht,{open:t,onOpenChange:R,children:e.jsxs(qt,{className:"max-w-2xl",children:[e.jsxs("div",{className:"flex items-center gap-3 -mt-2 mb-4",children:[e.jsx("button",{onClick:()=>c(1),disabled:u,className:"p-1 text-slate-400 hover:text-slate-600 transition-colors disabled:opacity-50",children:e.jsx(cn,{size:18})}),e.jsxs("div",{children:[e.jsx(Yt,{className:"text-[15px] font-medium text-slate-800",children:"Choose Template"}),e.jsxs("p",{className:"text-[11px] text-slate-400",children:[k.length," prompt",k.length===1?"":"s"," selected"]})]})]}),X.length>0&&e.jsxs("div",{className:"px-3 py-2 bg-slate-50 rounded-lg border border-slate-100 flex items-center gap-2 mb-4",children:[e.jsx("span",{className:"text-[10px] text-slate-400",children:"Reference:"}),e.jsx("div",{className:"flex flex-wrap gap-1",children:X.map(V=>e.jsx("span",{className:"px-2 py-0.5 bg-slate-200 text-slate-600 text-[10px] rounded-full",children:V},V))}),e.jsx("button",{onClick:()=>c(1),disabled:u,className:"text-[10px] text-slate-500 hover:text-slate-700 ml-auto disabled:opacity-50",children:"Edit"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-[12px] font-medium text-slate-700 mb-3 block",children:"Choose a Template"}),e.jsx("div",{className:"grid grid-cols-3 gap-3",children:hl.map(V=>{const P=d===V.id;return e.jsxs("button",{type:"button",onClick:()=>m(V.id),disabled:u,className:`relative p-4 rounded-lg text-left transition-all border-2 ${P?"border-slate-900 bg-slate-50":"border-slate-200 bg-white hover:border-slate-300"} ${u?"opacity-50 cursor-not-allowed":""}`,children:[P&&e.jsx("div",{className:"absolute top-2 right-2 w-5 h-5 bg-slate-900 rounded-full flex items-center justify-center",children:e.jsx(wt,{size:12,className:"text-white"})}),e.jsx("div",{className:"text-[12px] font-medium text-slate-800 pr-6",children:V.name}),e.jsx("div",{className:"text-[10px] text-slate-500 mt-1.5 leading-relaxed",children:V.description})]},V.id)})})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-[11px] text-slate-500 mb-1.5 block",children:"Worksheet Name"}),e.jsx(bt,{value:h,onChange:V=>p(V.target.value),placeholder:"Enter worksheet name",disabled:u,className:"text-[12px]"})]}),e.jsx(Oc,{checked:f,disabled:u,onCheckedChange:b,estimatingCredits:H.estimating,estimatedCreditsRange:H.estimatedRange,requiredMinimumBalance:H.requiredMinimumBalance}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(be,{variant:"ghost",size:"sm",onClick:()=>c(1),disabled:u,children:"Back"}),e.jsx(be,{size:"sm",className:"bg-slate-900 hover:bg-slate-800 disabled:opacity-80 min-w-[140px]",onClick:K,disabled:!L,children:u?e.jsxs("span",{className:"inline-flex items-center gap-2",children:[e.jsx(He,{className:"w-4 h-4 animate-spin"}),w||"Creating..."]}):"Create Worksheet"})]})]})]})})}const Rj=[{id:"mock-1",prompt:"What are the best AI-powered SEO tools for small businesses?",rankings:[],selectedModels:[]},{id:"mock-2",prompt:"Which companies offer the best content marketing services in 2026?",rankings:[],selectedModels:[]},{id:"mock-3",prompt:"Top brand monitoring tools for enterprise companies",rankings:[],selectedModels:[]},{id:"mock-4",prompt:"Best competitor analysis platforms for e-commerce",rankings:[],selectedModels:[]},{id:"mock-5",prompt:"What are the leading keyword research tools for SEO professionals?",rankings:[],selectedModels:[]}];function ih({initialDateRange:t,autoAdjustDateRange:s=!1,hideHeaderAndToolbar:a=!1,minPromptCount:n=0}={}){const{toast:o}=_t(),[i,l]=r.useState(()=>window.innerWidth<768);r.useEffect(()=>{const Le=()=>l(window.innerWidth<768);return window.addEventListener("resize",Le),()=>window.removeEventListener("resize",Le)},[]);const[c,d]=r.useState(!1),[m,h]=r.useState(!0),[p,f]=r.useState(""),[b,y]=r.useState(t??Aj()),[x,u]=r.useState(!1),[g,w]=r.useState(!1),[_,E]=r.useState(null),[N,S]=r.useState(0),[k,D]=r.useState(cm),[F,R]=r.useState(""),[L,$]=r.useState(!1);r.useRef(0);const[H,K]=r.useState([]),[X,V]=r.useState(new Set),[P,A]=r.useState(!1),[C,I]=r.useState(lm),[j,q]=r.useState(null),[T,M]=r.useState(!1),[Z,B]=r.useState(null),[ae,de]=r.useState(!1),[fe,se]=r.useState(!1),[z,U]=r.useState([]),[Q,me]=r.useState(!1),[le,O]=r.useState(null),[ne,ge]=r.useState(!1),[ze,Ke]=r.useState(!1),[ie,ve]=r.useState("weekly"),[we,Pe]=r.useState([]),[Ae,ye]=r.useState(!1),[Te,Ie]=r.useState(null),[Oe,J]=r.useState([]),[re,Se]=r.useState(!1),[je,he]=r.useState({enabled:!1,mode:"simple",simplePreset:"weekly",frequency:"weekly",intervalMinutes:"30",intervalHours:"1",dayOfWeek:"1",dayOfMonth:"1",hour:"8",minute:"0",timezone:"UTC",cronExpression:"0 8 * * 1"}),Re=Le=>({daily:"Daily (at 00:00 UTC)",weekly:"Weekly (Every Monday)",monthly:"Monthly (1st of month)"})[Le],Me=Le=>({daily:"0 0 * * *",weekly:"0 0 * * 1",monthly:"0 0 1 * *"})[Le],[Ze,Be]=r.useState(!1),[et,$e]=r.useState(null),[ue,W]=r.useState(!1),[ke,qe]=r.useState(!1),[Qe,ct]=r.useState([]),pt=Zs(Us.geo_prompt,{autoStart:!1}),At=r.useRef(()=>{}),te=r.useRef(()=>{});r.useEffect(()=>{const Le=it=>{d(it.detail??!c)},We=()=>{At.current()},at=()=>{te.current()};return window.addEventListener("mobile-filter-toggle",Le),window.addEventListener("mobile-refresh-click",We),window.addEventListener("mobile-add-click",at),()=>{window.removeEventListener("mobile-filter-toggle",Le),window.removeEventListener("mobile-refresh-click",We),window.removeEventListener("mobile-add-click",at)}},[c]);const[G,pe]=r.useState([]),[ce,Y]=r.useState(!1),[xe,Ee]=r.useState(null);r.useEffect(()=>{let Le=!1;return(async()=>{try{const it=(await Xa())?.plan?.plan_type||"free",dt=Nt.getLimit("tracked_prompts",it);if(Le)return;Ee(typeof dt=="number"&&Number.isFinite(dt)?dt:null)}catch{Le||Ee(null)}})(),()=>{Le=!0}},[]);const Ne=r.useCallback(Le=>{const We=xe;if(We===null)return{allowed:!0,remaining:null};const at=G.length,it=Math.max(0,We-at);return Le>it?{allowed:!1,remaining:it}:{allowed:!0,remaining:it}},[G,xe]),Ce=r.useCallback(Le=>!Le||!Le.items?[]:Le.items.map(We=>{const at=Le.periods.map(dt=>{const Et=We.cells[dt.key]||{},Dt=os=>{const ts=Et[os];if(!ts)return{rank:null,status:"untracked",scan_id:null};const Es=ts.model_runs?.map(hs=>({model:hs.model,rank:hs.rank,status:hs.status||"not_mentioned",scan_id:hs.scan_
179id}));if(ts.status==="RUNNING"||ts.status==="QUEUED")return{rank:null,status:"running",scan_id:ts.scan_id||null,model_runs:Es};if(ts.is_mentioned!==!0)return{rank:null,status:"not_mentioned",scan_id:ts.scan_id||null,is_mentioned:ts.is_mentioned??null,model_runs:Es};const sa=ts.rank<=5?"positive":"negative",fa=ts.sentiment||null;return{rank:ts.rank,status:sa,sentiment:fa,scan_id:ts.scan_id||null,is_mentioned:ts.is_mentioned??null,model_runs:Es}};return{period:dt.label,periodLabel:dt.label,periodStart:dt.key,periodEnd:dt.key,openai:Dt("openai")||Dt("ChatGPT"),anthropic:Dt("anthropic")||Dt("Claude"),google:Dt("google")||Dt("Gemini")}});let it=We.last_scan_id||void 0;if(!it&&Le.periods.length>0){const dt=Le.periods[Le.periods.length-1].key,Et=We.cells[dt]||{};for(const Dt of Object.keys(Et)){const os=Et[Dt];if(os?.scan_id){it=os.scan_id;break}}}return{id:We.tracked_prompt_id,prompt:We.prompt_text,rankings:at,selectedModels:We.selected_models||[],lastScanId:it,nextRunAt:We.next_run_at,cronExpression:We.cron_expression}}),[]),De=r.useCallback(Le=>{const We=G.filter(Et=>Le.includes(Et.id)),at=["Prompt","Latest OpenAI","Latest Google","Latest Claude"],it=We.map(Et=>{const Dt=Et.rankings[Et.rankings.length-1];return[`"${Et.prompt}"`,Dt?.openai.rank??"—",Dt?.google.rank??"—",Dt?.anthropic.rank??"—"].join(",")}),dt=[at.join(","),...it].join(`
180`);ar({filename:`prompt-tracking-${new Date().toISOString().split("T")[0]}.csv`,content:dt,mimeType:"text/csv;charset=utf-8;"}),o({title:"Export completed",description:`Exported ${Le.length} prompt(s) to CSV`})},[G,o]),Ge=r.useCallback(async Le=>{Ie(Le),Se(!1),J([]),$e(null);const We={enabled:!1,mode:"simple",simplePreset:"weekly",frequency:"weekly",intervalMinutes:"30",intervalHours:"1",dayOfWeek:"1",dayOfMonth:"1",hour:"8",minute:"0",timezone:"UTC",cronExpression:"0 8 * * 1"};try{const{getTrackedPrompt:at}=await Bt(async()=>{const{getTrackedPrompt:dt}=await Promise.resolve().then(()=>uj);return{getTrackedPrompt:dt}},void 0),it=await at(Le);if(it.cron_expression){const dt=it.cron_expression,Et=dt.split(" "),Dt=it.sync_timezone||"UTC";if(Et.length>=5){const[os,ts,Es,,sa]=Et,fa=os.match(/^\*\/(\d+)$/),hs=ts.match(/^\*\/(\d+)$/);he(fa&&ts==="*"?{...We,enabled:!0,mode:"advanced",cronExpression:dt,timezone:Dt}:hs&&os==="0"?{...We,enabled:!0,mode:"advanced",cronExpression:dt,timezone:Dt}:Es!=="*"&&sa==="*"?{...We,enabled:!0,mode:"simple",simplePreset:"monthly",frequency:"monthly",dayOfMonth:Es,hour:ts,minute:os,timezone:Dt,cronExpression:dt}:sa!=="*"&&Es==="*"?{...We,enabled:!0,mode:"simple",simplePreset:"weekly",frequency:"weekly",dayOfWeek:sa,hour:ts,minute:os,timezone:Dt,cronExpression:dt}:Es==="*"&&sa==="*"&&!fa&&!hs?{...We,enabled:!0,mode:"simple",simplePreset:"daily",frequency:"daily",hour:ts,minute:os,timezone:Dt,cronExpression:dt}:{...We,enabled:!0,mode:"advanced",cronExpression:dt,timezone:Dt})}else he({...We,enabled:!0,mode:"advanced",cronExpression:dt,timezone:Dt})}else he({...We,timezone:it.sync_timezone||"UTC"})}catch(at){console.error("Failed to load schedule config:",at),he({...We})}ye(!0)},[]),ee=r.useCallback(Le=>{Le.length!==0&&($e(null),Se(!0),J(Le),Ie(null),he({enabled:!0,mode:"simple",simplePreset:"weekly",frequency:"weekly",intervalMinutes:"30",intervalHours:"1",dayOfWeek:"1",dayOfMonth:"1",hour:"0",minute:"0",timezone:"UTC",cronExpression:"0 0 * * 1"}),ye(!0))},[]),Fe=r.useCallback(Le=>{Le.length!==0&&(ct(Le),qe(!0))},[]),Xe=r.useCallback(()=>{if(!je.enabled)return null;const{mode:Le,simplePreset:We,cronExpression:at}=je;return Le==="advanced"?at:Me(We)},[je]),yt=r.useCallback(async()=>{const Le=re?Oe:Te?[Te]:[];if(!(Le.length===0||!j)){Be(!0);try{const We=Xe(),at=Le.map(Et=>th(Et,{cron_expression:We,sync_timezone:je.timezone,is_active:je.enabled}));await Promise.all(at);let it="Auto-sync disabled";je.enabled&&(je.mode==="advanced"?it=`Auto-sync enabled (cron: ${We})`:it=`Auto-sync enabled (${Re(je.simplePreset)})`);const dt=Le.length>1?` for ${Le.length} prompts`:"";o({title:"Schedule saved",description:it+dt}),ye(!1),Se(!1),J([]),W(!0)}catch(We){console.error("Failed to save schedule:",We),o({title:"Error",description:"Failed to save schedule settings"})}finally{Be(!1)}}},[Te,Oe,re,j,je,Xe,o]);r.useEffect(()=>{(async()=>{try{const We=await Dn();We?.company?.id&&q(We.company.id)}catch(We){console.error("Failed to fetch company info:",We)}})()},[]),r.useEffect(()=>{if(!s||!j||x)return;const Le=async()=>{try{const it=(await eh(j))?.items??[];if(it&&it.length>0){let dt=null;if(it.forEach(Et=>{if(Et.created_at){const Dt=new Date(Et.created_at);(!dt||Dt<dt)&&(dt=Dt)}}),dt){const Et=new Date,Dt=dt.toISOString().split("T")[0],os=Et.toISOString().split("T")[0];y({from:Dt,to:os})}else We()}else We();u(!0)}catch(at){console.error("Failed to auto-adjust date range:",at),We(),u(!0)}},We=()=>{const at=new Date,it=at.getDay(),dt=it===0?-6:1-it,Et=new Date(at);Et.setDate(at.getDate()+dt);const Dt=new Date(Et);Dt.setDate(Et.getDate()+6);const os=Et.toISOString().split("T")[0],ts=Dt.toISOString().split("T")[0];y({from:os,to:ts})};Le()},[s,j,x]);const ut=r.useCallback(async()=>
180{if(!(!j||!b.from||!b.to)){M(!0);try{const Le=await Yx(j,b.from,b.to);B(Le)}catch(Le){console.error("Failed to fetch GEO overview:",Le)}finally{M(!1)}}},[j,b]);r.useEffect(()=>{j&&b.from&&b.to&&ut()},[j,b,ut]);const It=r.useCallback(async Le=>{if(!j)return;const We=Le?.silent??!1;We||me(!0);try{const at=b.from||void 0,it=b.to||void 0,dt=await Fc(j,at,it,void 0,void 0,1,50);U(dt.items||[])}catch(at){console.error("Failed to fetch scans:",at),We||U([])}finally{We||me(!1)}},[j,b]);r.useEffect(()=>{j&&It()},[j,b,It]);const Ct=r.useCallback(async Le=>{if(!j||!b.from||!b.to)return;const We=Le?.silent??!1;We||Y(!0);try{const at=await nh(j,ie,b.from,b.to,"latest"),it=at.periods.map(Et=>({period:Et.label,periodLabel:Et.label,periodStart:Et.key,periodEnd:Et.key,openai:{rank:null,status:"untracked",scan_id:null},anthropic:{rank:null,status:"untracked",scan_id:null},google:{rank:null,status:"untracked",scan_id:null}}));Pe(it);const dt=Ce(at);if(n>0&&dt.length<n){const Et=n-dt.length,Dt=Rj.slice(0,Et);pe([...dt,...Dt])}else pe(dt)}catch(at){console.error("Failed to fetch tracked prompts:",at),We||(pe([]),Pe([]))}finally{We||Y(!1)}},[j,b,ie,Ce]);r.useEffect(()=>{j&&b.from&&b.to&&Ct()},[j,b,Ct]),r.useEffect(()=>{At.current=()=>{Ct()},te.current=()=>{w(!0)}},[Ct]);const cs=r.useMemo(()=>G.some(Le=>Le.rankings.some(We=>We.openai.status==="running"||We.anthropic.status==="running"||We.google.status==="running")),[G]),xa=r.useMemo(()=>z.some(Le=>Le.status==="RUNNING"||Le.status==="QUEUED"?!0:(Le.model_results?Object.values(Le.model_results):[]).some(at=>at.status==="RUNNING"||at.status==="QUEUED")),[z]);r.useEffect(()=>{if(!(cs||xa))return;const We=setInterval(()=>{console.log("[GeoPromptView] Polling: silent refresh (loading detected)"),Ct({silent:!0}),It({silent:!0})},5e3);return()=>{clearInterval(We)}},[cs,xa,Ct,It]),r.useEffect(()=>{ue&&(Ct(),W(!1))},[ue,Ct]);const zs=r.useCallback(async Le=>{if(!(!j||Le.length===0)){try{const{creditEstimateService:We}=await Bt(async()=>{const{creditEstimateService:dt}=await Promise.resolve().then(()=>Ya);return{creditEstimateService:dt}},void 0),at=await We.estimateCredits({scenario:"geo_generate_prompts",params:{prompt_count:Le.length}});if(!await mo({estimatedRange:at?{min:at.estimated_min_credits,max:at.estimated_max_credits}:null,requiredMinimumBalance:at?.required_minimum_balance??null,toast:o}))return}catch(We){console.warn("⚠️ Failed to estimate credits for sync, proceeding anyway:",We)}ge(!0),o({title:"Sync started",description:`Syncing ${Le.length} prompt(s)...`});try{const We=await ah({company_id:j,ids:Le}),at=We.results.filter(dt=>dt.scan_id&&!dt.error).length,it=We.results.filter(dt=>dt.error).length;it>0?o({title:"Sync completed with errors",description:`${at} succeeded, ${it} failed`}):o({title:"Sync completed",description:`${at} prompt(s) synced successfully`}),Ct(),It()}catch(We){console.error("Failed to sync prompts:",We),o({title:"Sync failed",description:"Failed to sync prompts. Please try again."})}finally{ge(!1)}}},[j,o,Ct,It]),hn=r.useCallback(async Le=>{if(Le.length!==0){Ke(!0);try{const We=Le.map(at=>sh(at));await Promise.all(We),o({title:"Prompts deleted",description:`${Le.length} prompt(s) deleted successfully`}),Ct()}catch(We){console.error("Failed to delete prompts:",We),o({title:"Delete failed",description:"Failed to delete prompts. Please try again."})}finally{Ke(!1)}}},[o,Ct]);r.useMemo(()=>Z?.trend?{visibility:Qr(Z.trend.visibility),rank:Qr(Z.trend.rank),mentions:Qr(Z.trend.mentions),shareOfVoice:Qr(Z.trend.share_of_voice)}:Ej,[Z?.trend]),r.useMemo(()=>{if(!Z?.leaderboard)return[];const Le=new Map;let We=0;for(const it of Z.leaderboard){We+=it.mentions;const dt=it.company_name?.trim()||"Unknown",Et=Le.get(dt);Et?(Et.mentions+=it.mentions,it.rank!=null&&(Et.posSum+=it.rank*it.mentions,Et.posCnt+=it.mentions),Et.isTarget=Et.isTarget||it.is_target):Le.set(dt,{mentions:it.mentions,visibility:0,shareOfVoice:0,posSum:it.rank!=null?it.rank*it.mentions:0,posCnt:it.rank!=null?it.mentions:0,isTarget:it.is_target})}const at=[];for(const[it,dt]of Le.entries()){const Et=We>0?Math.round(dt.mentions/We*1e4)/100:0,Dt=We-dt.mentions,os=Dt>0?Math.round(dt.mentions/Dt*1e4)/100:0;dt.posCnt>0&&Math.round(dt.posSum/dt.posCnt*10)/10,at.push({rank:0,brand:it,visibility:Et,mentions:dt.mentions,shareOfVoice:os,isTarget:dt.isTarget})}return at.sort((it,dt)=>dt.mentions-it.mentions),at.forEach((it,dt)=>{it.rank=dt+1}),at},[Z?.leaderboard]);const[Ls,la]=r.useState(null),[pn,gn]=r.useState(""),[$s,Ea]=r.useState(!1),[Aa,ha]=r.useState(!1),Ln=ta({enabled:!0,scenario:"geo_generate_prompts",params:{},debounceMs:200}),zn=ta({enabled:H.length>0,scenario:"geo_generate_more_prompts",params:{existing_prompts_count:H.length,count:10},debounceMs:200}),$n=r.useCallback(async(Le=!1)=>
180{if(await mo({estimatedRange:Ln.estimatedRange,requiredMinimumBalance:Ln.requiredMinimumBalance,toast:o})){A(!0),K([]),V(new Set),ha(!1);try{const at=await Jx({debug:!1,force_regenerate:Le}),it=at?.prompts||[];if(it.length===0)throw new Error("No prompts generated");K(it),ha(at?.from_cache??!1),V(new Set([0]))}catch(at){console.error("Failed to generate prompts:",at),o({title:"Prompt generation failed",description:at instanceof Error?at.message:"Please try again later."})}finally{A(!1)}}},[o,Ln]),pa=r.useCallback(async Le=>{Ea(!0);try{await Xx(Le),o({title:"Prompts saved",description:"Your edited prompts have been saved and will be used next time."})}catch(We){console.error("Failed to save prompts:",We),o({title:"Save failed",description:We instanceof Error?We.message:"Please try again later."})}finally{Ea(!1)}},[o]),ys=r.useCallback(Le=>{la(Le),gn(H[Le])},[H]),fn=r.useCallback(async()=>{if(Ls===null)return;const Le=pn.trim();if(!Le){o({title:"Invalid prompt",description:"Prompt cannot be empty."});return}const We=[...H];We[Ls]=Le,K(We),la(null),gn(""),await pa(We)},[Ls,pn,H,pa,o]),ga=r.useCallback(()=>{la(null),gn("")},[]),[ur,Ue]=r.useState(!1),tt=r.useCallback(async()=>{if(await mo({estimatedRange:zn.estimatedRange,requiredMinimumBalance:zn.requiredMinimumBalance,toast:o})){Ue(!0);try{const at=(await Qx(H,10))?.new_prompts||[];if(at.length===0){o({title:"No new prompts generated",description:"All generated prompts were duplicates. Try again for different prompts."});return}K([...at,...H]),ha(!1),o({title:"Prompts generated",description:`Added ${at.length} new prompts.`})}catch(We){console.error("Failed to generate more prompts:",We),o({title:"Generation failed",description:We instanceof Error?We.message:"Please try again later."})}finally{Ue(!1)}}},[H,o,zn]),st=Le=>{I(We=>We.map(at=>at.id===Le?{...at,enabled:!at.enabled}:at))},ft=Le=>{R(Le),$(!0)},ht=()=>{E(null),S(0),D(cm()),R(""),$(!1),I(lm),K([]),V(new Set),A(!1)},Ot=Le=>{E(Le),Le==="ai"?(S(1),H.length===0&&$n(!1)):(R(""),$(!0),S(2))},Tt=()=>{N===1?S(2):N===2&&_==="manual"&&S(3)},vt=()=>_==="ai"?!P&&X.size>0:!0,Ft=()=>_==="manual"?!fe&&F.trim().length>0:!0,ks=async()=>{const Le=C.filter(dt=>dt.enabled),We=G.length===0;let at=[];if(_==="ai"?at=Array.from(X).map(dt=>H[dt]).filter(dt=>dt&&dt.trim()):F.trim()&&(at=[F.trim()]),at.length===0){o({title:"Missing prompt",description:_==="ai"?"Please select at least one prompt to track":"Please enter a prompt"});return}if(Le.length===0){o({title:"No models selected",description:"Please select at least one AI model"});return}if(!j){o({title:"Error",description:"Company not found. Please try again."});return}const it=Ne(at.length);if(!it.allowed){o({title:"Plan limit exceeded",description:`Tracked prompts limit reached. Remaining slots: ${it.remaining??0}. Please upgrade your plan or delete existing prompts.`});return}de(!0);try{const dt=Le.map(Dt=>Dt.id);let Et=0;for(const Dt of at)try{await Zx({company_id:j,prompt_text:Dt,selected_models:dt,run_immediately:!0}),Et++}catch(os){console.error(`Failed to create tracked prompt: ${Dt}`,os)}if(Et>0)o({title:"Prompt tracking started",description:`${Et} prompt${Et>1?"s":""} now being tracked across ${Le.length} AI model(s)`});else throw new Error("Failed to create any tracked prompts");w(!1),ht(),Ct(),It(),We&&pt.startExternal()}catch(dt){console.error("Failed to create scan:",dt),o({title:"Failed to create scan",description:dt instanceof Error?dt.message:"Please try again"})}finally{de(!1)}};return e.jsxs("div",{className:`min-h-screen ${i?"bg-white":"bg-slate-50"}`,"data-onboarding":"prompt-tracking-intro",children:[i&&c&&e.jsxs("div",{className:"px-4 py-3 bg-white border-b border-gray-200 space-y-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Pt,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400"}),e.jsx(bt,{placeholder:"Search prompts...",value:p,onChange:Le=>f(Le.target.value),className:"pl-9 pr-8 w-full",autoFocus:!0}),p&&e.jsx("button",{onClick:()=>f(""),className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 hover:bg-slate-100 rounded",children:e.jsx(mt,{className:"w-3 h-3 text-slate-400"})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-slate-500",children:"View:"}),e.jsxs("div",{className:"flex items-center bg-slate-100 rounded-lg p-0.5 flex-1",children:[e.jsx("button",{onClick:()=>ve("weekly"),className:`flex-1 px-3 py-1.5 text-xs font-medium rounded-md transition-all ${ie==="weekly"?"bg-white text-slate-900 shadow-sm":"text-slate-600"}`,children:"Weekly"}),e.jsx("button",{onClick:()=>ve("monthly"),className:`flex-1 px-3 py-1.5 text-xs font-medium rounded-md transition-all ${ie==="monthly"?"bg-white text-slate-900 shadow-sm":"text-slate-600"}`,children:"Monthly"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-slate-500 
180whitespace-nowrap",children:"Date:"}),e.jsx(Sa,{value:b,onChange:y,placeholder:"Select date range",className:"flex-1"})]})]}),!a&&e.jsx("div",{className:"bg-white border-b border-slate-200 hidden sm:block",children:e.jsx("div",{className:"max-w-7xl mx-auto px-6 py-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 bg-slate-100 rounded-xl flex items-center justify-center",children:e.jsx(Qt,{className:"w-5 h-5 text-slate-600"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-lg font-semibold text-slate-900",children:"GEO Prompt Tracking"}),e.jsx("p",{className:"text-xs text-slate-500",children:"Monitor brand visibility across AI platforms"})]})]})})}),e.jsx("div",{className:`max-w-[1600px] mx-auto ${i?"px-4 py-3":"px-6 py-6"}`,children:e.jsxs("div",{className:"space-y-6",children:[T&&e.jsxs("div",{className:"flex items-center justify-center py-12",children:[e.jsx(He,{className:"w-8 h-8 animate-spin text-slate-400"}),e.jsx("span",{className:"ml-3 text-slate-500",children:"Loading overview data..."})]}),!T&&G.length>0&&e.jsx(e.Fragment,{children:(()=>{const Le=G.length;let We=0,at=0,it=0,dt=0,Et=0,Dt=0;G.forEach(sa=>{const fa=[...sa.rankings].sort((xr,Ur)=>xr.periodStart.localeCompare(Ur.periodStart)),hs=fa[fa.length-1];hs&&(hs.openai.status!=="running"&&(dt++,Os(hs.openai.rank,hs.openai.status)&&We++),hs.google.status!=="running"&&(Et++,Os(hs.google.rank,hs.google.status)&&at++),hs.anthropic.status!=="running"&&(Dt++,Os(hs.anthropic.rank,hs.anthropic.status)&&it++))});const os=dt>0?Math.round(We/dt*100):0,ts=Et>0?Math.round(at/Et*100):0,Es=Dt>0?Math.round(it/Dt*100):0;return e.jsxs("div",{className:`grid gap-3 ${i?"grid-cols-2":"grid-cols-4"}`,children:[e.jsxs("div",{className:`bg-white border border-slate-100 rounded-xl ${i?"p-3":"p-4"}`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx("span",{className:"text-[10px] uppercase tracking-wider font-medium text-slate-400",children:"Tracked Prompts"}),e.jsx(Na,{size:14,className:"text-slate-300"})]}),e.jsx("div",{className:"text-2xl font-bold text-slate-900",children:Le})]}),e.jsxs("div",{className:`bg-white border border-slate-100 rounded-xl ${i?"p-3":"p-4"}`,children:[e.jsx("div",{className:"flex items-center justify-between mb-1",children:e.jsxs("span",{className:"text-[10px] uppercase tracking-wider font-medium text-slate-400 flex items-center gap-1.5",children:[e.jsx(uo,{size:12,className:"text-slate-500"}),"ChatGPT Mentions"]})}),e.jsxs("div",{className:"flex items-baseline gap-2",children:[e.jsxs("span",{className:"text-2xl font-bold text-slate-900",children:[os,"%"]}),e.jsxs("span",{className:"text-xs text-slate-400",children:["(",We,"/",dt,")"]})]}),e.jsx("div",{className:"mt-2 h-1.5 bg-slate-100 rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full bg-slate-800 rounded-full transition-all",style:{width:`${os}%`}})})]}),e.jsxs("div",{className:`bg-white border border-slate-100 rounded-xl ${i?"p-3":"p-4"}`,children:[e.jsx("div",{className:"flex items-center justify-between mb-1",children:e.jsxs("span",{className:"text-[10px] uppercase tracking-wider font-medium text-slate-400 flex items-center gap-1.5",children:[e.jsx(xo,{size:12}),"Gemini Mentions"]})}),e.jsxs("div",{className:"flex items-baseline gap-2",children:[e.jsxs("span",{className:"text-2xl font-bold text-slate-900",children:[ts,"%"]}),e.jsxs("span",{className:"text-xs text-slate-400",children:["(",at,"/",Et,")"]})]}),e.jsx("div",{className:"mt-2 h-1.5 bg-slate-100 rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${ts}%`,background:"linear-gradient(90deg, #4285F4, #9B72CB, #D96570)"}})})]}),e.jsxs("div",{className:`bg-white border border-slate-100 rounded-xl ${i?"p-3":"p-4"}`,children:[e.jsx("div",{className:"flex items-center justify-between mb-1",children:e.jsxs("span",{className:"text-[10px] uppercase tracking-wider font-medium text-slate-400 flex items-center gap-1.5",children:[e.jsx(ho,{size:12}),"Claude Mentions"]})}),e.jsxs("div",{className:"flex items-baseline gap-2",children:[e.jsxs("span",{className:"text-2xl font-bold text-slate-900",children:[Es,"%"]}),e.jsxs("span",{className:"text-xs text-slate-400",children:["(",it,"/",Dt,")"]})]}),e.jsx("div",{className:"mt-2 h-1.5 bg-slate-100 rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${Es}%`,background:"#D97706"}})})]})]})})()}),!T&&(le?e.jsx(Tj,{prompt:le,companyId:j||"",onBack:()=>O(null)}):e.jsx(Pj,{prompts:G,loading:ce,onTrackNew:()=>w(!0),onSelectPrompt:O,onSync:zs,onExport:De,onSettings:Ge,onBatchSettings:ee,onContentGeneration:Fe,onDelete:hn,isSyncing:ne,isDeleting:ze,searchQuery:p,onSearchChange:f,dateRange:b,onDateRangeChange:y,periods:we,viewMode:ie,onViewModeChange:ve,hideToolbar:a}))]})}),e.jsx(Ht,{open:g,onOpenChange:Le=>{w(Le),Le||ht()},children:e.jsxs(qt,{className:"sm:max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(Zt,{children:[e.jsxs(Yt,{className:"flex items-center gap-2",children:[e.jsx($t,{className:"w-4 h-4 text-slate-500"}),"Track New Prompt"]}),e.jsxs(Ds,{children:[N===0&&"Choose how you want to create your prompt",N===1&&_==="ai"&&"Step 1 of 2: Select prompts to track",N===2&&_==="ai"&&"Step 2 of 2: Select AI models to query",N===2&&_==="manual"&&"Step 1 of 2: Enter your prompt",N===3&&_==="manual"&&"Step 2 of 2: Select AI models to query"]})]}),N>0&&e.jsx("div",{className:"flex items-center justify-center gap-2 py-2",children:(_==="ai"?[1,2]:[2,3]).map((Le,We)=>e.jsxs("div",{className:"flex items-center",children:[e.jsx("div",{className:`w-8 h-8 rounded-full flex items-center justify-center text-sm font-medium transition-colors ${Le===N?"bg-slate-800 text-white":Le<N?"bg-emerald-500 text-white":"bg-slate-200 text-slate-500"}`,children:Le<N?e.jsx(wt,{size:14}):We+1}),We<1&&e.jsx("div",{className:`w-16 h-1 mx-1 rounded ${Le<N?"bg-emerald-500":"bg-slate-200"}`})]},Le))}),e.jsxs("div",{className:"py-4 min-h-[400px]",children:[N===0&&e.jsxs("div",{className:"flex flex-col items-center justify-center h-full py-8",children:[e.jsx("h3",{className:"text-lg font-semibold text-slate-800 mb-2",children:"How would you like to create your prompt?"}),e.jsx("p",{className:"text-sm text-slate-500 mb-8 text-center max-w-md",children:"AI-generated analyzes your company and suggests relevant prompts, or enter your own custom prompt directly."}),e.jsxs("div",{className:"grid grid-cols-2 gap-4 w-full max-w-lg",children:[e.jsxs("button",{onClick:()=>Ot("ai"),className:"group relative flex flex-col items-center p-6 rounded-xl border-2 border-slate-200 hover:border-slate-800 hover:bg-slate-50 transition-all",children:[e.jsx("div",{className:"w-14 h-14 roun
180ded-full bg-slate-700 flex items-center justify-center mb-4 group-hover:scale-110 transition-transform",children:e.jsx(Ks,{className:"w-7 h-7 text-white"})}),e.jsx("h4",{className:"text-base font-semibold text-slate-800 mb-1",children:"AI Generated"}),e.jsx("p",{className:"text-xs text-slate-500 text-center",children:"Get 5 AI-suggested prompts based on your company"}),e.jsx(ls,{className:"absolute top-3 right-3 bg-slate-100 text-slate-600 text-[10px]",children:"Recommended"}),e.jsx("span",{className:"absolute bottom-3 right-3 text-[11px] font-medium text-amber-600",children:"Est. 30–80 credits"})]}),e.jsxs("button",{onClick:()=>Ot("manual"),className:"group relative flex flex-col items-center p-6 rounded-xl border-2 border-slate-200 hover:border-slate-800 hover:bg-slate-50 transition-all",children:[e.jsx("div",{className:"w-14 h-14 rounded-full bg-slate-200 flex items-center justify-center mb-4 group-hover:scale-110 transition-transform",children:e.jsx(Ua,{className:"w-7 h-7 text-slate-600"})}),e.jsx("h4",{className:"text-base font-semibold text-slate-800 mb-1",children:"Manual Input"}),e.jsx("p",{className:"text-xs text-slate-500 text-center",children:"Enter your own custom prompt directly"})]})]})]}),N===1&&_==="ai"&&e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2 text-base font-semibold text-slate-800",children:[e.jsx(Ks,{size:18,className:"text-slate-500"}),"AI-Generated Prompts",Aa&&e.jsx("span",{className:"text-xs text-slate-400 font-normal",children:"(cached)"})]}),e.jsxs(be,{variant:"outline",size:"sm",onClick:()=>$n(!0),disabled:P||$s,className:"gap-1.5",children:[P?e.jsx(He,{size:14,className:"animate-spin"}):e.jsx(kt,{size:14}),"Regenerate"]})]}),e.jsx("p",{className:"text-sm text-slate-500",children:"Based on your company profile, we've generated these prompts that potential customers might ask AI assistants. Select the ones you want to track. Click the edit icon to modify any prompt."}),P&&e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 gap-3",children:[e.jsx(He,{className:"w-8 h-8 animate-spin text-slate-400"}),e.jsx("p",{className:"text-sm text-slate-500",children:"Analyzing your company and generating prompts..."})]}),!P&&H.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"max-h-[320px] overflow-y-auto space-y-3 pr-1",children:H.map((Le,We)=>e.jsx("div",{className:`w-full text-left p-4 rounded-lg border-2 transition-all ${X.has(We)?"border-slate-800 bg-slate-50":"border-slate-200 hover:border-slate-300 bg-white"}`,children:Ls===We?e.jsxs("div",{className:"space-y-3",children:[e.jsx("textarea",{value:pn,onChange:at=>gn(at.target.value),className:"w-full p-3 text-sm border border-slate-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-slate-500 resize-none",rows:3,autoFocus:!0,placeholder:"Enter your prompt..."}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(be,{variant:"ghost",size:"sm",onClick:ga,disabled:$s,children:"Cancel"}),e.jsxs(be,{size:"sm",onClick:fn,disabled:$s||!pn.trim(),className:"gap-1.5",children:[$s?e.jsx(He,{size:14,className:"animate-spin"}):e.jsx(wt,{size:14}),"Save"]})]})]}):e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("button",{onClick:()=>{V(at=>{const it=new Set(at);return it.has(We)?it.delete(We):it.add(We),it})},className:`w-5 h-5 rounded border-2 flex-shrink-0 mt-0.5 flex items-center justify-center transition-colors ${X.has(We)?"border-slate-800 bg-slate-800":"border-slate-300 hover:border-slate-400"}`,children:X.has(We)&&e.jsx(wt,{size:12,className:"text-white"})}),e.jsx("div",{className:"flex-1 cursor-pointer",onClick:()=>{V(at=>{const it=new Set(at);return it.has(We)?it.delete(We):it.add(We),it})},children:e.jsx("p",{className:"text-sm text-slate-700 leading-relaxed",children:Le})}),e.jsx("button",{onClick:at=>{at.stopPropagation(),ys(We)},className:"p-1.5 rounded-md hover:bg-slate-200 transition-colors flex-shrink-0",title:"Edit prompt",children:e.jsx(Ua,{size:14,className:"text-slate-500"})})]})},We))}),e.jsxs(be,{variant:"outline",size:"sm",onClick:tt,disabled:ur||$s,className:"w-full gap-1.5",children:[ur?e.jsx(He,{size:14,className:"animate-spin"}):e.jsx($t,{size:14}),"Generate 10 More Prompts"]})]}),!P&&H.length===0&&e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 gap-3 text-center",children:[e.jsx("div",{className:"w-12 h-12 rounded-full bg-slate-100 flex items-center justify-center",children:e.jsx(Ks,{className:"w-6 h-6 text-slate-400"})}),e.jsx("p",{className:"text-sm text-slate-500",children:"No prompts generated yet."}),e.jsxs(be,{variant:"outline",onClick:()=>$n(!1),className:"gap-1.5",children:[e.jsx(kt,{size:14}),"Generate Prompts"]})]}),!P&&H.length>0&&e.jsxs("div",{className:"flex items-center justify-between pt-2 border-t border-slate-100",children:[e.jsxs("span",{className:"text-sm text-slate-500",children:[X.size," of"," ",H.length," prompts selected"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(be,{variant:"ghost",size:"sm",onClick:()=>V(new Set),className:"text-xs",children:"Clear all"}),e.jsx(be,{variant:"ghost",size:"sm",onClick:()=>V(new Set(H.map((Le,We)=>We))),className:"text-xs",children:"Select all"})]})]})]}),N===2&&_==="ai"&&e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"flex items-center gap-2 text-base font-semibold text-slate-800",children:[e.jsx(Na,{size:18,className:"text-slate-500"}
180),"Select AI Models"]}),e.jsxs("div",{className:"bg-slate-50 rounded-lg p-4 space-y-2",children:[e.jsxs("p",{className:"text-xs font-medium text-slate-500 uppercase tracking-wider",children:["Selected Prompts (",X.size,")"]}),e.jsx("div",{className:"space-y-2 max-h-32 overflow-y-auto",children:Array.from(X).map(Le=>e.jsxs("p",{className:"text-sm text-slate-700 line-clamp-1",children:["• ",H[Le]]},Le))})]}),e.jsx("p",{className:"text-sm text-slate-500",children:"Choose which AI assistants to monitor for your selected prompts"}),e.jsx("div",{className:"grid grid-cols-2 gap-3",children:C.map(Le=>e.jsxs("button",{onClick:()=>st(Le.id),className:`flex items-center gap-3 p-4 rounded-lg border-2 transition-all ${Le.enabled?"border-slate-800 bg-slate-50":"border-slate-200 hover:border-slate-300"}`,children:[e.jsx("div",{className:`w-5 h-5 rounded border-2 flex items-center justify-center ${Le.enabled?"border-slate-800 bg-slate-800":"border-slate-300"}`,children:Le.enabled&&e.jsx(wt,{size:12,className:"text-white"})}),e.jsxs("div",{className:"flex-1 text-left",children:[e.jsxs("div",{className:"font-medium text-slate-800 flex items-center gap-2",children:[Le.name,Le.recommended&&e.jsx(ls,{className:"bg-emerald-100 text-emerald-700 text-[10px]",children:"Recommended"})]}),e.jsx("div",{className:"text-xs text-slate-500",children:Le.provider})]})]},Le.id))})]}),N===2&&_==="manual"&&e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"flex items-center gap-2 text-base font-semibold text-slate-800",children:[e.jsx(Ua,{size:18,className:"text-slate-500"}),"Enter Your Prompt"]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"flex items-center justify-between",children:e.jsx(Gt,{className:"text-sm font-medium text-slate-700",children:"Your Prompt"})}),e.jsxs("div",{className:"relative",children:[e.jsx("textarea",{value:F,onChange:Le=>ft(Le.target.value),placeholder:"Enter your prompt here, e.g., 'What are the best geo/aeo tools for startups?'",className:"w-full h-32 px-4 py-3 pr-10 text-sm border border-slate-200 rounded-lg resize-none focus:outline-none focus:ring-2 focus:ring-slate-800/10 focus:border-slate-300"}),e.jsx(Ua,{size:14,className:"absolute right-3 top-3 text-slate-400"}),fe&&!F.trim()&&e.jsx("div",{className:"absolute inset-0 rounded-lg bg-white/70 backdrop-blur-[1px] flex items-center justify-center",children:e.jsxs("div",{className:"flex items-center gap-2 text-sm text-slate-600",children:[e.jsx(He,{className:"w-4 h-4 animate-spin"}),"Generating prompt..."]})})]}),e.jsx("p",{className:"text-xs text-slate-500",children:"Enter a prompt that your target audience might search for. This will be sent to AI models to check your brand visibility."})]})]}),N===3&&_==="manual"&&e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"flex items-center gap-2 text-base font-semibold text-slate-800",children:[e.jsx(Na,{size:18,className:"text-slate-500"}),"Select AI Models"]}),e.jsxs("div",{className:"bg-slate-50 rounded-lg p-4",children:[e.jsx("p",{className:"text-xs font-medium text-slate-500 uppercase tracking-wider mb-2",children:"Prompt to send:"}),e.jsxs("p",{className:"text-sm text-slate-700 italic",children:['"',F,'"']})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(Gt,{className:"text-sm font-medium text-slate-700",children:"Choose which AI models to query"}),e.jsx("div",{className:"grid grid-cols-2 gap-3",children:C.map(Le=>e.jsxs("button",{onClick:()=>st(Le.id),className:`flex items-center justify-between p-4 rounded-lg border text-left transition-all ${Le.enabled?"border-slate-800 bg-slate-50 shadow-sm":"border-slate-200 hover:border-slate-300 hover:bg-slate-50"}`,children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-slate-800",children:Le.name}),e.jsx("p",{className:"text-xs text-slate-500",children:Le.provider})]}),e.jsx("div",{className:`w-6 h-6 rounded flex items-center justify-center transition-colors ${Le.enabled?"bg-slate-800 text-white":"border-2 border-slate-300"}`,children:Le.enabled&&e.jsx(wt,{size:14})})]},Le.id))}),e.jsxs("p",{className:"text-sm text-slate-600",children:["Selected:"," ",e.jsx("span",{className:"font-medium",children:C.filter(Le=>Le.enabled).length})," ","of ",C.length," models"]})]})]})]}
180),e.jsxs(Ns,{layout:"split",divider:!0,children:[e.jsx(be,{variant:"outline",onClick:()=>{w(!1),S(0),E(null)},className:"text-slate-600",children:"Cancel"}),N>0&&e.jsx("div",{className:"flex items-center gap-2",children:_==="ai"&&N===1||_==="manual"&&N===2?e.jsxs(be,{onClick:Tt,disabled:N===1&&!vt()||N===2&&!Ft(),className:"gap-1.5 bg-slate-800 hover:bg-slate-700 disabled:opacity-50",children:[N===2&&_==="manual"&&fe?e.jsxs(e.Fragment,{children:[e.jsx(He,{size:14,className:"animate-spin"}),"Generating..."]}):e.jsx(e.Fragment,{children:"Next"}),e.jsx(Gs,{size:14,className:"rotate-[-90deg]"})]}):e.jsx(be,{onClick:ks,disabled:C.filter(Le=>Le.enabled).length===0||ae,className:"gap-2 bg-slate-800 hover:bg-slate-700 disabled:opacity-50",children:ae?e.jsxs(e.Fragment,{children:[e.jsx(He,{size:14,className:"animate-spin"}),"Starting..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Qt,{size:14}),"Start Track"]})})})]})]})}),e.jsx(Ht,{open:Ae,onOpenChange:ye,children:e.jsxs(qt,{className:"sm:max-w-lg",children:[e.jsxs(Zt,{children:[e.jsxs(Yt,{className:"flex items-center gap-2",children:[e.jsx(_r,{className:"w-4 h-4 text-slate-500"}),re?`Schedule Settings (${Oe.length} prompts)`:"Schedule Settings"]}),e.jsx(Ds,{children:re?`Configure automatic scanning schedule for ${Oe.length} prompts`:"Configure automatic scanning schedule for this prompt"})]}),e.jsxs("div",{className:"space-y-6 py-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Gt,{className:"text-sm font-medium",children:"Enable Auto-Sync"}),e.jsx("p",{className:"text-xs text-slate-500 mt-0.5",children:"Automatically run scans on a schedule"})]}),e.jsx("button",{onClick:()=>he(Le=>({...Le,enabled:!Le.enabled})),className:`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${je.enabled?"bg-slate-800":"bg-slate-200"}`,children:e.jsx("span",{className:`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${je.enabled?"translate-x-6":"translate-x-1"}`})})]}),je.enabled&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex gap-1 p-1 bg-slate-100 rounded-lg",children:[e.jsx("button",{onClick:()=>he(Le=>({...Le,mode:"simple"})),className:`flex-1 px-3 py-1.5 rounded-md text-sm font-medium transition-colors ${je.mode==="simple"?"bg-white text-slate-900 shadow-sm":"text-slate-600 hover:text-slate-900"}`,children:"Simple"}),e.jsx("button",{onClick:()=>he(Le=>({...Le,mode:"advanced"})),className:`flex-1 px-3 py-1.5 rounded-md text-sm font-medium transition-colors ${je.mode==="advanced"?"bg-white text-slate-900 shadow-sm":"text-slate-600 hover:text-slate-900"}`,children:"Advanced (Cron)"})]}),je.mode==="simple"?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Gt,{className:"text-sm font-medium text-slate-700",children:"Frequency"}),e.jsxs(Pn,{value:je.simplePreset,onValueChange:Le=>he(We=>({...We,simplePreset:Le})),children:[e.jsx(In,{className:"w-full",children:e.jsx(Tc,{children:Re(je.simplePreset)})}),e.jsxs(Mn,{children:[e.jsx(js,{value:"daily",children:"Daily (at 00:00 UTC)"}),e.jsx(js,{value:"weekly",children:"Weekly (Every Monday)"}),e.jsx(js,{value:"monthly",children:"Monthly (1st of month)"})]})]}),e.jsx("p",{className:"text-xs text-slate-500 mt-1.5",children:"Automatic scans will consume credits based on selected models."})]}),e.jsx("div",{className:"bg-slate-50 rounded-lg p-3 text-sm",children:e.jsxs("p",{className:"text-slate-600",children:[e.jsx(Ra,{className:"w-4 h-4 inline-block mr-1.5 text-slate-400"}),Re(je.simplePreset)," ","(UTC)"]})})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Gt,{className:"text-sm font-medium",children:"Cron Expression"}),e.jsx(bt,{value:je.cronExpression,onChange:Le=>{he(We=>({...We,cronExpression:Le.target.value})),$e(null)},placeholder:"0 8 * * 1",className:et?"border-red-500":""}),et&&e.jsx("p",{className:"text-xs text-red-500",children:et}),e.jsx("p",{className:"text-xs text-slate-500",children:"Format: minute hour day-of-month month day-of-week"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Gt,{className:"text-sm font-medium",children:"Timezone"}),e.jsxs(nr,{value:je.timezone,onValueChange:Le=>he(We=>({...We,timezone:Le})),children:[e.jsx(rr,{className:"w-full",children:e.jsx(Ui,{placeholder:"Select timezone"})}),e.jsxs(or,{children:[e.jsx(_s,{value:"UTC",children:"UTC"}
180),e.jsx(_s,{value:"America/New_York",children:"Eastern Time (ET)"}),e.jsx(_s,{value:"America/Chicago",children:"Central Time (CT)"}),e.jsx(_s,{value:"America/Denver",children:"Mountain Time (MT)"}),e.jsx(_s,{value:"America/Los_Angeles",children:"Pacific Time (PT)"}),e.jsx(_s,{value:"Europe/London",children:"London (GMT)"}),e.jsx(_s,{value:"Europe/Paris",children:"Paris (CET)"}),e.jsx(_s,{value:"Asia/Tokyo",children:"Tokyo (JST)"}),e.jsx(_s,{value:"Asia/Shanghai",children:"Shanghai (CST)"}),e.jsx(_s,{value:"Asia/Singapore",children:"Singapore (SGT)"})]})]})]}),e.jsxs("div",{className:"bg-slate-50 rounded-lg p-3 space-y-2",children:[e.jsx("p",{className:"text-xs font-medium text-slate-700",children:"Examples:"}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 text-xs text-slate-600",children:[e.jsxs("button",{type:"button",onClick:()=>he(Le=>({...Le,cronExpression:"*/30 * * * *"})),className:"text-left hover:text-slate-900 hover:underline",children:[e.jsx("code",{className:"bg-slate-200 px-1 rounded",children:"*/30 * * * *"})," ","Every 30 min"]}),e.jsxs("button",{type:"button",onClick:()=>he(Le=>({...Le,cronExpression:"0 * * * *"})),className:"text-left hover:text-slate-900 hover:underline",children:[e.jsx("code",{className:"bg-slate-200 px-1 rounded",children:"0 * * * *"})," ","Every hour"]}),e.jsxs("button",{type:"button",onClick:()=>he(Le=>({...Le,cronExpression:"0 8 * * *"})),className:"text-left hover:text-slate-900 hover:underline",children:[e.jsx("code",{className:"bg-slate-200 px-1 rounded",children:"0 8 * * *"})," ","Daily at 8:00"]}),e.jsxs("button",{type:"button",onClick:()=>he(Le=>({...Le,cronExpression:"0 8 * * 1"})),className:"text-left hover:text-slate-900 hover:underline",children:[e.jsx("code",{className:"bg-slate-200 px-1 rounded",children:"0 8 * * 1"})," ","Monday 8:00"]}),e.jsxs("button",{type:"button",onClick:()=>he(Le=>({...Le,cronExpression:"0 0 1 * *"})),className:"text-left hover:text-slate-900 hover:underline",children:[e.jsx("code",{className:"bg-slate-200 px-1 rounded",children:"0 0 1 * *"})," ","1st of month"]}),e.jsxs("button",{type:"button",onClick:()=>he(Le=>({...Le,cronExpression:"0 9 * * 1-5"})),className:"text-left hover:text-slate-900 hover:underline",children:[e.jsx("code",{className:"bg-slate-200 px-1 rounded",children:"0 9 * * 1-5"})," ","Weekdays 9:00"]})]})]}),e.jsx("div",{className:"bg-blue-50 rounded-lg p-3 text-sm",children:e.jsxs("p",{className:"text-blue-700",children:[e.jsx(Ra,{className:"w-4 h-4 inline-block mr-1.5 text-blue-500"}),"Expression:"," ",e.jsx("code",{className:"bg-blue-100 px-1 rounded",children:je.cronExpression})," ","(",je.timezone,")"]})})]})]})]}),e.jsxs(Ns,{children:[e.jsx(be,{variant:"outline",onClick:()=>ye(!1),children:"Cancel"}),e.jsx(be,{onClick:yt,disabled:Ze,className:"bg-slate-800 hover:bg-slate-700",children:Ze?e.jsxs(e.Fragment,{children:[e.jsx(He,{size:14,className:"animate-spin mr-2"}),"Saving..."]}):"Save Settings"})]})]})}),e.jsx(Mj,{isOpen:ke,onClose:()=>qe(!1),selectedPromptIds:Qe,trackedPrompts:G}),!a&&e.jsx("button",{onClick:pt.startManual,className:"fixed bottom-5 right-5 z-50 h-8 w-8 rounded-full bg-white border border-slate-200 shadow-md hover:shadow-lg hover:bg-slate-50 transition-all hover:scale-105 hidden sm:flex items-center justify-center",title:"View navigation guide","aria-label":"View navigation guide",children:e.jsx(Hs,{className:"h-4 w-4 text-slate-600"})}),!i&&e.jsx(oa,{steps:oj,run:pt.run,onComplete:pt.stopAndMarkCompleted,onSkip:pt.stopAndMarkCompleted})]})}const Dj=[{target:'[data-onboarding="page-tracking-intro"]',content:"Page Tracking monitors performance metrics for specific URLs on your site. Track clicks, impressions, CTR, and average position from Google Search Console data.",placement:"bottom",disableBeacon:!0},{target:'[data-onboarding="add-pages-button"]',content:"Add pages to track. Import from GSC top-performing pages, your sitemap, or enter URLs manually.",placement:"bottom",disableBeacon:!0},{target:'[data-onboarding="date-range-picker"]',content:"Select a date range to view performance history. Data is grouped by week for trend comparison.",placement:"bottom",disableBeacon:!0},{target:'[data-onboarding="page-tracking-table"]',content:"The performance table displays metrics per period. Each column represents a week with clicks, impressions, CTR, and position data.",placement:"top",disableBeacon:!0,spotlightClicks:!1,styles:{spotlight:{pointerEvents:"none"}}},{target:'[data-onboarding="refresh-pages-button"]',content:"Refresh to sync the latest data from Google Search Console. Requires GSC integration to be connected.",placement:"bottom",disableBeacon:!0}];async function Lj(t=!1){return await ot("/tracked-pages",{include_inactive:t})}async function zj(t){return await Je("/tracked-pages",{pages:t})}async function $j(t,s=!1){return await Ca("/tracked-pages",{data:{page_ids:t,hard_delete:s}})}function Do({visible:t,message:s="Loading...",zIndex:a=1e3,fixed:n=!1,progress:o}){return t?e.jsx("div",{className:`${n?"fixed":"absolute"} inset-0 flex items-center justify-center bg-slate-900/40 backdrop-blur-[2px] transition-opacity duration-200`,style:{zIndex:a},children:e.jsxs("div",{className:"flex flex-col items-center gap-4 bg-white rounded-xl shadow-xl px-8 py-6 border border-slate-200 min-w-[320px]",children:[e.jsx("div",{className:"relative",children:e.jsx("div",{className:"h-12 w-12 border-4 border-slate-200 border-t-slate-900 rounded-full animate-spin"})}),s&&e.jsx("div",{className:"text-sm font-semibold text-slate-900 text-center max-w-xs",children:s}),o&&o.total>0&&e.jsxs("div",{className:"w-full space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between text-xs text-slate-600",children:[e.jsxs("span",{children:[o.completed," / ",o.total," completed"]}),e.jsxs("span",{className:"font-semibold",children:[o.percentage,"%"]})]}),e.jsx("div",{className:"w-full bg-slate-200 rounded-full h-2 overflow-hidden",children:e.jsx("div",{className:"h-full bg-blue-600 transition-all duration-300 ease-out rounded-full",style:{width:`${o.percentage}%`}})})]})]})}):null}const Fj=365,dm=t=>{const s=t.getFullYear(),a=String(t.getMonth()+1).padStart(2,"0"),n=String(t.getDate()).padStart(2,"0");return`${s}-${a}
180-${n}`},Oj=t=>{const s=t.trim();return s?s.endsWith("/")?s.slice(0,-1):s:""},Bj=t=>{if(!t||!t.trim())return t;let s=t.trim();if(s.startsWith("sc-domain:"))return s;if(s.includes("://"))try{s=new URL(s).hostname}catch{s=s.replace(/^https?:\/\//,""),s=s.split("/")[0]}else s=s.split("/")[0],s=s.split("?")[0],s=s.split("#")[0];return s=s.toLowerCase(),s.startsWith("www.")&&(s=s.substring(4)),`sc-domain:${s}`};function mm({open:t,onOpenChange:s,siteUrl:a,existingUrls:n,onSuccess:o}){const{toast:i}=_t(),[l,c]=r.useState(()=>window.innerWidth<768);r.useEffect(()=>{const j=()=>c(window.innerWidth<768);return window.addEventListener("resize",j),()=>window.removeEventListener("resize",j)},[]);const[d,m]=r.useState("gsc"),[h,p]=r.useState([]),[f,b]=r.useState(!1),[y,x]=r.useState(""),[u,g]=r.useState(new Set),[w,_]=r.useState(1),[E]=r.useState(50),[N,S]=r.useState(""),[k,D]=r.useState(!1),[F,R]=r.useState(!1);r.useEffect(()=>{if(!t||!a)return;(async()=>{b(!0);try{const q=Bj(a),T=new Date,M=new Date(T);M.setDate(M.getDate()-(Fj-1));const B=((await Cw({site_url:q,start_date:dm(M),end_date:dm(T),search_type:"web"})).items||[]).map(ae=>({url:Oj(ae.key||""),clicks:ae.clicks||0,impressions:ae.impressions||0,selected:!1})).filter(ae=>ae.url.length>0).sort((ae,de)=>de.clicks-ae.clicks);p(B)}catch(q){console.error("Failed to load GSC pages:",q),i({title:"Failed to load pages",description:"Unable to fetch pages from Google Search Console"})}finally{b(!1)}})()},[t,a,i]),r.useEffect(()=>{t||(m("gsc"),x(""),g(new Set),S(""),D(!1),_(1))},[t]),r.useEffect(()=>{_(1)},[y]);const L=r.useMemo(()=>h.filter(j=>n.has(j.url)?!1:y?j.url.toLowerCase().includes(y.toLowerCase()):!0),[h,y,n]),$=r.useMemo(()=>{const j=(w-1)*E;return L.slice(j,j+E)},[L,w,E]),H=Math.ceil(L.length/E),K=r.useMemo(()=>N.trim()?N.split(/[\n,]/).map(j=>j.trim()).filter(j=>j.length>0).filter(j=>!n.has(j)):[],[N,n]),X=r.useCallback(j=>{g(q=>{const T=new Set(q);return T.has(j)?T.delete(j):T.add(j),T})},[]),V=r.useCallback(()=>{g(new Set(L.map(j=>j.url)))},[L]),P=r.useCallback(()=>{new Set($.map(j=>j.url)),g(j=>{const q=new Set(j);return $.every(M=>q.has(M.url))?$.forEach(M=>q.delete(M.url)):$.forEach(M=>q.add(M.url)),q})},[$]),A=r.useCallback(()=>{g(new Set)},[]),C=r.useMemo(()=>d==="gsc"?u.size:K.length,[d,u,K]),I=async()=>{if(C===0){i({title:"No pages selected",description:"Please select or enter at least one page URL"});return}R(!0);try{const j=[];d==="gsc"?u.forEach(T=>{j.push({url:T,source:"gsc",is_generated_by_rankgale:k})}):K.forEach(T=>{j.push({url:T,source:"manual",is_generated_by_rankgale:k})});const q=await zj(j);i({title:"Pages added",description:`Successfully added ${q.added} page(s) to tracking`}),await o(),s(!1)}catch(j){console.error("Failed to add pages:",j),i({title:"Failed to add pages",description:j?.response?.data?.detail||"An error occurred"})}finally{R(!1)}};return l&&t?e.jsxs("div",{className:"fixed inset-0 z-50 bg-white flex flex-col",children:[e.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b border-slate-200",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-base font-semibold text-slate-800",children:"Add Pages"}),e.jsx("p",{className:"text-xs text-slate-400",children:"Add pages to track performance"})]}),e.jsx("button",{onClick:()=>s(!1),className:"p-1.5 rounded-lg text-slate-400 hover:text-slate-600 hover:bg-slate-50",children:e.jsx(mt,{className:"w-5 h-5"})})]}),e.jsxs("div",{className:"flex border-b border-slate-200",children:[e.jsxs("button",{onClick:()=>m("gsc"),className:`flex-1 flex items-center justify-center gap-2 py-3 text-sm font-medium border-b-2 transition-colors ${d==="gsc"?"border-slate-800 text-slate-800":"border-transparent text-slate-500"}`,children:[e.jsx(Qt,{className:"w-4 h-4"}),"From GSC"]}),e.jsxs("button",{onClick:()=>m("manual"),className:`flex-1 flex items-center justify-center gap-2 py-3 text-sm font-medium border-b-2 transition-colors ${d==="manual"?"border-slate-800 text-slate-800":"border-transparent text-slate-500"}`,children:[e.jsx(is,{className:"w-4 h-4"}),"Manual"]})]}),e.jsx("div",{className:"flex-1 overflow-auto",children:d==="gsc"?e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsx("div",{className:"p-3 border-b border-slate-100",children:e.jsxs("div",{className:"relative",children:[e.jsx(Pt,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400"}),e.jsx(bt,{placeholder:"Search pages...",value:y,onChange:j=>x(j.target.value),className:"pl-9"})]})}),e.jsx("div",{className:"flex-1 overflow-auto",children:f?e.jsx("div",{className:"flex items-center justify-center h-48",children:e.jsx(He,{className:"w-6 h-6 text-slate-400 animate-spin"})}):L.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center h-48 text-center p-4",children:[e.jsx(Ss,{className:"w-8 h-8 text-slate-300 mb-2"}),e.jsx("p",{className:"text-sm text-slate-500",children:y?"No pages match your search":"No new pages available"})]}):e.jsx("div",{className:"divide-y divide-slate-100",children:$.map(j=>e.jsxs("div",{className:`flex items-center gap-3 px-4 py-3 ${u.has(j.url)?"bg-blue-50":""}`,onClick:()=>X(j.url),children:[e.jsx(Kt,{checked:u.has(j.url),onCheckedChange:()=>X(j.url)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm text-slate-700 truncate",children:j.url}),e.jsxs("p",{className:"text-xs text-slate-400",children:[j.clicks," 
180clicks • ",j.impressions," impressions"]})]}),u.has(j.url)&&e.jsx(Rs,{className:"w-4 h-4 text-blue-600"})]},j.url))})}),u.size>0&&e.jsxs("div",{className:"p-3 border-t border-slate-100 text-sm text-slate-600",children:[u.size," page(s) selected"]})]}):e.jsxs("div",{className:"p-4 h-full flex flex-col",children:[e.jsx("label",{className:"text-sm font-medium text-slate-700 mb-2",children:"Enter page URLs (one per line)"}),e.jsx("textarea",{className:"flex-1 w-full rounded-lg border border-slate-200 px-3 py-2 text-sm resize-none font-mono",placeholder:`https://example.com/page-1
181https://example.com/page-2`,value:N,onChange:j=>S(j.target.value)}),K.length>0&&e.jsxs("div",{className:"mt-2 text-sm text-slate-600",children:[K.length," URL(s) detected"]})]})}),e.jsx("div",{className:"px-4 py-3 bg-gradient-to-r from-purple-50 to-blue-50 border-t border-purple-100",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Kt,{checked:k,onCheckedChange:j=>D(j===!0)}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ks,{className:"w-4 h-4 text-purple-500"}),e.jsx("span",{className:"text-sm font-medium text-slate-700",children:"Generated by Rankgale"})]})]})}),e.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-t border-slate-200 bg-white",children:[e.jsx(be,{variant:"outline",onClick:()=>s(!1),children:"Cancel"}),e.jsx(be,{onClick:I,disabled:C===0||F,className:"gap-2",children:F?e.jsxs(e.Fragment,{children:[e.jsx(He,{className:"w-4 h-4 animate-spin"}),"Adding..."]}):e.jsxs(e.Fragment,{children:[e.jsx($t,{className:"w-4 h-4"}),"Add ",C," Page",C!==1?"s":""]})})]})]}):e.jsx(Ht,{open:t,onOpenChange:s,children:e.jsxs(qt,{className:"max-w-2xl max-h-[85vh] flex flex-col gap-2",children:[e.jsxs(Zt,{children:[e.jsxs(Yt,{className:"flex items-center gap-2",children:[e.jsx($t,{className:"w-5 h-5 text-blue-600"}),"Add Pages to Track"]}),e.jsx(Ds,{children:"Add pages from GSC or manually enter URLs to start tracking their performance."})]}),e.jsxs("div",{className:"flex items-center gap-1 bg-slate-100 rounded-lg p-1",children:[e.jsxs("button",{onClick:()=>m("gsc"),className:`flex-1 flex items-center justify-center gap-2 px-4 py-2 rounded-md text-sm font-medium transition-all ${d==="gsc"?"bg-white text-slate-900 shadow-sm":"text-slate-600 hover:text-slate-900"}`,children:[e.jsx(Qt,{className:"w-4 h-4"}),"Select from GSC"]}),e.jsxs("button",{onClick:()=>m("manual"),className:`flex-1 flex items-center justify-center gap-2 px-4 py-2 rounded-md text-sm font-medium transition-all ${d==="manual"?"bg-white text-slate-900 shadow-sm":"text-slate-600 hover:text-slate-900"}`,children:[e.jsx(is,{className:"w-4 h-4"}),"Manual URLs"]})]}),e.jsx("div",{className:"flex-1 min-h-0 flex flex-col",children:d==="gsc"?e.jsxs("div",{className:"flex flex-col flex-1 min-h-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3 flex-shrink-0",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Pt,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400"}),e.jsx(bt,{placeholder:"Search pages...",value:y,onChange:j=>x(j.target.value),className:"pl-9"})]}),e.jsx(be,{variant:"outline",size:"sm",onClick:P,disabled:$.length===0,children:"Select Page"}),e.jsx(be,{variant:"outline",size:"sm",onClick:V,disabled:L.length===0,children:"Select All"}),u.size>0&&e.jsx(be,{variant:"ghost",size:"sm",onClick:A,children:"Clear"})]}),e.jsxs("div",{className:"flex-1 min-h-0 flex flex-col border border-slate-200 rounded-lg overflow-hidden",children:[e.jsx("div",{className:"flex-1 overflow-auto",children:f?e.jsxs("div",{className:"flex items-center justify-center h-48",children:[e.jsx(He,{className:"w-6 h-6 text-slate-400 animate-spin"}),e.jsx("span",{className:"ml-2 text-sm text-slate-500",children:"Loading pages from GSC..."})]}):L.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center h-48 text-center",children:[e.jsx(Ss,{className:"w-8 h-8 text-slate-300 mb-2"}),e.jsx("p",{className:"text-sm text-slate-500",children:y?"No pages match your search":"No new pages available from GSC"}),!y&&e.jsx("p",{className:"mt-1 text-xs text-slate-400 max-w-md",children:"GSC only returns pages with impressions/clicks in the selected time window, and pages you already track are hidden here. Try adding URLs manually, or wait for more GSC data to accumulate."})]}):e.jsx("div",{className:"divide-y divide-slate-100",children:$.map(j=>e.jsxs("div",{className:`flex items-center gap-3 px-3 py-2.5 hover:bg-slate-50 cursor-pointer transition-colors ${u.has(j.url)?"bg-blue-50":""}`,onClick:()=>X(j.url),children:[e.jsx(Kt,{checked:u.has(j.url),onCheckedChange:()=>X(j.url)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm text-slate-700 truncate",children:j.url}),e.jsxs("div",{className:"flex items-center gap-3 mt-0.5",children:[e.jsxs("span",{className:"text-xs text-slate-400",children:[j.clicks.toLocaleStr
181ing()," clicks"]}),e.jsxs("span",{className:"text-xs text-slate-400",children:[j.impressions.toLocaleString()," impressions"]})]})]}),u.has(j.url)&&e.jsx(Rs,{className:"w-4 h-4 text-blue-600 flex-shrink-0"})]},j.url))})}),!f&&L.length>0&&e.jsxs("div",{className:"flex-shrink-0 flex items-center justify-between px-3 py-2.5 border-t border-slate-200 bg-white",children:[e.jsxs("div",{className:"text-xs text-slate-500",children:["Showing ",(w-1)*E+1,"-",Math.min(w*E,L.length)," ","of ",L.length," page",L.length!==1?"s":""]}),H>1&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(be,{variant:"ghost",size:"sm",onClick:()=>_(j=>Math.max(1,j-1)),disabled:w===1,className:"h-7 px-2",children:e.jsx(cn,{className:"w-4 h-4"})}),e.jsxs("div",{className:"text-xs text-slate-600 px-2 min-w-[80px] text-center",children:["Page ",w," / ",H]}),e.jsx(be,{variant:"ghost",size:"sm",onClick:()=>_(j=>Math.min(H,j+1)),disabled:w===H,className:"h-7 px-2",children:e.jsx(Qn,{className:"w-4 h-4"})})]})]})]}),u.size>0&&e.jsx("div",{className:"mt-2 text-sm text-slate-600 flex-shrink-0",children:e.jsxs(ls,{variant:"secondary",className:"bg-blue-50 text-blue-700",children:[u.size," page(s) selected"]})})]}):e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsx("div",{className:"mb-2",children:e.jsx("label",{className:"text-sm font-medium text-slate-700",children:"Enter page URLs (one per line or comma-separated)"})}),e.jsx("textarea",{className:"flex-1 min-h-[200px] w-full rounded-lg border border-slate-200 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-100 focus:border-blue-400 resize-none font-mono",placeholder:`https://example.com/page-1
182https://example.com/page-2
183https://example.com/page-3`,value:N,onChange:j=>S(j.target.value)}),K.length>0&&e.jsxs("div",{className:"mt-2 text-sm text-slate-600",children:[e.jsxs(ls,{variant:"secondary",className:"bg-orange-50 text-orange-700",children:[K.length," URL(s) detected"]}),e.jsx("span",{className:"ml-2 text-xs text-slate-400",children:'(will be tagged as "manual")'})]})]})}),e.jsxs("div",{className:"flex items-center gap-3 py-3 px-4 bg-gradient-to-r from-purple-50 to-blue-50 rounded-lg border border-purple-100",children:[e.jsx(Kt,{checked:k,onCheckedChange:j=>D(j)}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ks,{className:"w-4 h-4 text-purple-500"}),e.jsx("span",{className:"text-sm font-medium text-slate-700",children:"Generated by Rankgale"})]}),e.jsx("span",{className:"text-xs text-slate-500 ml-auto",children:"Mark these pages as AI-generated content"})]}),e.jsxs(Ns,{divider:!0,children:[e.jsx(be,{variant:"outline",onClick:()=>s(!1),children:"Cancel"}),e.jsx(be,{onClick:I,disabled:C===0||F,className:"gap-2",children:F?e.jsxs(e.Fragment,{children:[e.jsx(He,{className:"w-4 h-4 animate-spin"}),"Adding..."]}):e.jsxs(e.Fragment,{children:[e.jsx($t,{className:"w-4 h-4"}),"Add ",C," Page",C!==1?"s":""]})})]})]})})}function Uj(t){return t.checked?t.estimatingCredits?e.jsx("div",{className:"text-[11px] text-slate-500",children:"Estimating..."}):t.estimatedCreditsRange?e.jsxs("div",{className:"text-[11px] font-semibold text-amber-600",children:["Est. ",t.estimatedCreditsRange.min,"–",t.estimatedCreditsRange.max," ","credits"]}):e.jsx("div",{className:"text-[11px] text-slate-500",children:"Estimate unavailable"}):e.jsx("div",{className:"text-[11px] text-slate-400",children:"Optional"})}function Kj(t){return e.jsxs("label",{className:"flex items-center justify-between gap-3 rounded-lg border border-slate-200 bg-slate-50 px-3 py-2",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Kt,{checked:t.checked,disabled:!!t.disabled,onCheckedChange:s=>t.onCheckedChange(!!s)}),e.jsxs("div",{className:"leading-tight",children:[e.jsx("div",{className:"text-[12px] font-medium text-slate-800",children:t.label}),t.description&&e.jsx("div",{className:"text-[11px] text-slate-500 mt-0.5",children:t.description})]})]}),e.jsx("div",{className:"text-right",children:Uj({checked:t.checked,estimatingCredits:t.estimatingCredits,estimatedCreditsRange:t.estimatedCreditsRange,requiredMinimumBalance:t.requiredMinimumBalance})})]})}function Gj(t){const[s,a]=r.useState(!1),[n,o]=r.useState(null),[i,l]=r.useState(null);return r.useEffect(()=>{if(!t.isOpen)return;if(!t.enabled){o(null),l(null);return}if(t.urlCount<=0){o(null),l(null);return}let c=!0;return(async()=>{a(!0);try{const m=await Vi.estimateCredits({scenario:"worksheet_seo_analysis_generate",params:{url_count:Math.max(0,Number(t.urlC
183ount||0)),model:t.model||"gpt-5-mini",max_steps:t.maxSteps||12,include_title_content:t.includeTitleContent||!1,template_type:t.templateType||""}});if(!c)return;o({min:Number(m.estimated_min_credits||0),max:Number(m.estimated_max_credits||0)}),l(Number(m.required_minimum_balance||0))}catch(m){if(console.warn("⚠️ Failed to estimate SEO Analysis credits:",m),!c)return;o(null),l(null)}finally{if(!c)return;a(!1)}})(),()=>{c=!1}},[t.isOpen,t.enabled,t.urlCount,t.model,t.maxSteps,t.includeTitleContent,t.templateType]),{estimating:s,estimatedRange:n,requiredMinimumBalance:i}}function Wj({isOpen:t,onClose:s,selectedPageUrls:a,defaultCampaignName:n}){const{toast:o}=_t(),{confirm:i}=ia(),[l,c]=v.useState(1),[d,m]=v.useState("seo_analysis_shopify"),[h,p]=v.useState(""),[f,b]=v.useState(!0),[y,x]=v.useState(!1),[u,g]=v.useState(!1),[w,_]=v.useState(null),[E,N]=v.useState(""),[S,k]=v.useState(void 0),D=v.useMemo(()=>Ei.find(A=>A.id===d)||null,[d]);v.useEffect(()=>{t&&(c(1),m("seo_analysis_shopify"),k(void 0),b(!0),x(!1))},[t]);const F=d==="seo_content_webflow"||d==="seo_content_shopify",R=v.useMemo(()=>Va({rawContext:S??null}),[S]),L=Gj({isOpen:t,enabled:f,urlCount:a.length,model:"gpt-5-mini",maxSteps:12,includeTitleContent:F,templateType:F?d:void 0}),$=F?"Run analysis & generate content automatically":"Run analysis automatically",H="Progress will be shown in the worksheet.";v.useEffect(()=>{if(!t)return;if(n?.trim()){p(n.trim());return}const A=new Date,C=A.toLocaleString("en-US",{month:"short"}),I=A.getDate(),j=D?.name||"Optimize Existing Content";p(`${j} - ${C} ${I}`)},[t,n,D?.name,d]);const K=()=>{u||s()},X=!u&&h.trim().length>0&&a.length>0,V=async()=>{if(X){if(f){if(y)return;x(!0);try{if(!await Ji({confirm:i,estimatedRange:L.estimatedRange,requiredMinimumBalance:L.requiredMinimumBalance,toast:o}))return}finally{x(!1)}}g(!0),_("creating_campaign"),N("Starting...");try{const A=await cr.createWorksheetAndGenerateFromPages({source:{kind:"default_template",templateType:d},campaignSource:"page_tracking",campaignName:h.trim(),pageUrls:a,options:{generateTitleAndContent:f,runAnalysis:f,includeTitleContent:F&&f,titlePollingTimeoutMs:12e4,titlePollingIntervalMs:2e3,context:R,onProgress:(I,j)=>{_(I),j&&N(j)}}});try{localStorage.setItem("flowwriter.currentCampaign",JSON.stringify({id:A.campaignId,name:h.trim()}))}catch{}o({title:"✅ Worksheet created",description:f?F?"Pages filled. Analysis & content generation started.":"Pages filled. Analysis started.":"Pages filled. You can run from the table."}),s(),jt("table-new",{campaign:A.campaignId,view:A.viewId})}catch(A){console.error("❌ Failed to create worksheet:",A),o({title:"Create worksheet failed",description:A?.message||"Please try again."})}finally{g(!1)}}},P=[];return R.company&&P.push("Company"),R.knowledges.enabled&&P.push(`Knowledge (${R.knowledges.scope_ids?R.knowledges.scope_ids.length:"all"})`),R.competitors.enabled&&P.push(`Competitors (${R.competitors.scope_domains?R.competitors.scope_domains.length:"all"})`),l===1?e.jsxs("div",{className:`fixed inset-0 z-50 flex items-center justify-center ${t?"":"hidden"}`,children:[e.jsx("div",{className:"absolute inset-0 bg-black/20",onClick:K}),e.jsxs("div",{className:"relative bg-white rounded-2xl shadow-xl max-w-xl w-full mx-4 overflow-hidden",children:[e.jsx("div",{className:"px-6 py-5 border-b border-slate-100",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-[15px] font-semibold text-slate-800",children:"Add Reference"}),e.jsx("p",{className:"text-[12px] text-slate-400 mt-0.5",children:"Help AI create content that truly represents your brand"})]}),e.jsx("button",{onClick:K,className:"p-1.5 rounded-lg text-slate-400 hover:text-slate-600 hover:bg-slate-50 transition-colors",children:e.jsx(mt,{size:18})})]})}),e.jsx(Yi,{isOpen:t,onClose:K,onConfirm:()=>c(2),value:S,onChange:k}),e.jsxs("div",{className:"px-6 py-4 border-t border-slate-100 flex justify-between items-center bg-slate-50/50",children:[e.jsx("button",{onClick:K,className:"text-[13px] text-slate-500 hover:text-slate-700",children:"Cancel"}),e.jsxs("button",{onClick:()=>c(2),className:"px-5 py-2 bg-slate-800 text-white text-[13px] font-medium rounded-lg hover:bg-slate-700 flex items-center gap-2 transition-colors",children:["Continue",e.jsx(Ms,{size:14})]})]})]})]}):e.jsx(Ht,{open:t,onOpenChange:K,children:e.jsxs(qt,{className:"max-w-2xl",children:[e.jsxs("div",{className:"flex items-center gap-3 -mt-2 mb-4",children:[e.jsx("button",{onClick:()=>c(1),disabled:u,className:"p-1 text-slate-400 hover:text-slate-600 transition-colors disabled:opacity-50",children:e.jsx(cn,{size:18})}),e.jsxs("div",{children:[e.jsx(Yt,{className:"text-[15px] font-medium text-slate-800",children:"Choose Template"}),e.jsxs("p",{className:"text-[11px] text-slate-400",children:[a.length," page",a.length===1?"":"s"," selected"]})]})]}),P.length>0&&e.jsxs("div",{className:"px-3 py-2 bg-slate-50 rounded-lg border border-slate-100 flex items-center gap-2 mb-4",children:[e.jsx("span",{className:"text-[10px] text-slate-400",children:"Reference:"}),e.jsx("div",{className:"flex flex-wrap gap-1",children:P.map(A=>e.jsx("span",{className:"px-2 py-0.5 bg-slate-200 text-slate-600 text-[10px] rounded-full",children:A},A))}),e.jsx("button",{onClick:()=>c(1),disabled:u,className:"text-[10px] text-slate-500 hover:text-slate-700 ml-auto disabled:opacity-50",children:"Edit"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-[12px] font-medium text-slate-700 mb-3 block",children:"Choose a Template"}),e.jsx("div",{className:"grid grid-cols-3 gap-3",children:Ei.map(A=>{const C=d===A.id;return e.jsxs("button",{onClick:()=>m(A.id),disabled:u,className:`relative p-4 rounded-lg text-left transition-all border-2 ${C?"border-slate-900 bg-slate-50":"border-slate-200 bg-white hover:border-slate-300"} ${u?"opacity-50 cursor-not-allowed":""}`,children:[C&&e.jsx("div",{className:"absolute top-2 right-2 w-5 h-5 bg-slate-900 rounded-full flex items-center justify-center",children:e.jsx(wt,{size:12,className:"text-white"})}),e.jsx("div",{className:"text-[12px] font-medium text-slate-800 pr-6",children:A.name}),e.jsx("div",{className:"text-[10px] text-slate-500 mt-1.5 leading-relaxed",children:A.description})]},A.id)})})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-[11px] text-slate-500 mb-1.5 block",children:"Worksheet Name"}),e.jsx(bt,{value:h,onChange:A=>p(A.target.value),placeholder:"Enter worksheet name",disabled:u,className:"text-[12px]"})]}),e.jsx(Kj,{checked:f,disabled:u,onCheckedChange:b,estimatingCredits:L.estimating,estimatedCreditsRange:L.estimatedRange,requiredMinimumBalance:L.requiredMinimumBalance,label:$,description:H}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(be,{variant:"ghost",size:"sm",onClick:()=>c(1),disabled:u,children:"Back"}),e.jsx(be,{size:"sm",className:"bg-slate-900 hover:bg-slate-800 disabled:opacity-80 min-w-[140px]",onClick:V,disabled:!X,children:u?e.jsxs("span",{className:"inline-flex items-center gap-2",children:[e.jsx(He,{className:"w-4 h-4 animate-spin"}),E||"Creating..."]}):"Create Worksheet"})]})]})]})})}const lh="pageTracking_selectedSite",Vj=()=>{try{return localStorage.getItem(lh)}catch{return null}},Hr=t=>{try{localStorage.setItem(lh,t)}catch(s){console.error("Failed to save site to cache:",s)}},Hj=t=>{const s=new Date(Date.UTC(t.getFullYear(),t.getMonth(),t.getDate())),a=s.getUTCDay()||7;s.setUTCDate(s.getUTCDate()+4-a);const n=new Date(Date.UTC(s.getUTCFullYear(),0,1));return Math.ceil(((s.getTime()-n.getTime())/864e5+1)/7)},ch=t=>{const s=new Date(t),a=s.getDay(),n=s.getDate()-a+(a===0?-6:1);return new Date(s.setDate(n))},ws=t=>t.toISOString().split("T")[0],um=[{label:"THIS WEEK",value:{from:ws(ch(new Date)),to:ws(new Date)}},{label:"LAST 4 WEEKS",value:{from:ws(new Date(Date.now()-27*864e5)),to:ws(new Date)}},{label:"LAST 8 WEEKS",value:{from:ws(new Date(Date.now()-55*864e5)),to:ws(new Date)}},{label:"LAST 12 WEEKS",value:{from:ws(new Date(Date.now()-83*864e5)),to:ws(new Date)}},{label:"LAST 3 MONTHS",value:{from:ws(new Date(new Date().getFullYear(),new Date().getMonth()-3,1)),to:ws(new Date)}},{label:"LAST 6 MONTHS",value:{from:ws(new Date(new Date().getFullYear(),new Date().getMonth()-6,1)),to:ws(new Date)}},{label:"YTD",value:{from:ws(new Date(new Date().getFullYear(),0,1)),to:ws(new Date)}}],qj=()=>{const t=new Date,s=new Date(Date.now()-27*864e5);return{from:ws(s),to:ws(t)}},Yj=(t,s)=>{if(!t.from||!t.to)return[];const a=[],n=new Date(t.from),o=new Date(t.to);if(s==="weekly"){let i=ch(n);for(;i<=o;){const l=new Date(i);l.setDate(l.getDate()+6);const c=Hj(i),d=i.getFullYear(),m=`${d}-W${String(c).padStart(2,"0")}`;a.push({period:m,periodLabel:`Week ${c}, ${d}`,periodStart:ws(i),periodEnd:ws(l),clicks:0,impressions:0,ctr:0,position:0}),i=new Date(i),i.setDate(i.getDate()+7)}}else{let i=new Date(n.getFullYear(),n.getMonth(),1);for(;i<=o;){const l=new Date(i.getFullYear(),i.getMonth()+1,0),c=["January","February","March","April","May","June","July","August","September","October","November","December"],d=`${i.getFullYear()}
183-${String(i.getMonth()+1).padStart(2,"0")}`;a.push({period:d,periodLabel:`${c[i.getMonth()]} ${i.getFullYear()}`,periodStart:ws(i),periodEnd:ws(l),clicks:0,impressions:0,ctr:0,position:0}),i=new Date(i.getFullYear(),i.getMonth()+1,1)}}return a},fr=t=>t>=1e6?(t/1e6).toFixed(1)+"M":t>=1e3?(t/1e3).toFixed(1)+"K":t.toString(),xm=t=>{try{let s=t.replace(/^sc-domain:/,"").replace(/^https?:\/\//,"").replace(/^www\./,"").replace(/\/$/,"").toLowerCase();const a=s.indexOf("/");return a>0&&(s=s.substring(0,a)),s}catch{return t.toLowerCase()}},Jj=(t,s)=>{if(!t||t.length===0)return null;if(!s)return t[0].site_url;const a=xm(s),n=t.map(o=>{const i=xm(o.site_url);let l=0;if(i===a)l=100;else if(i.includes(a)||a.includes(i))l=80;else{const c=i.split(".").slice(-2).join("."),d=a.split(".").slice(-2).join(".");c===d&&(l=60)}return{site:o,score:l}});return n.sort((o,i)=>i.score-o.score),n[0].score===0?t[0].site_url:n[0].site.site_url};function dh(){const{toast:t}=_t(),[s,a]=r.useState(()=>window.innerWidth<768);r.useEffect(()=>{const Y=()=>a(window.innerWidth<768);return window.addEventListener("resize",Y),()=>window.removeEventListener("resize",Y)},[]);const[n,o]=r.useState(!1),[i,l]=r.useState(!0),[c,d]=r.useState({checkbox:40,url:200}),[m,h]=r.useState(null),p=r.useCallback((Y,xe)=>{Y.preventDefault(),Y.stopPropagation();const Ee="touches"in Y?Y.touches[0].clientX:Y.clientX,Ne=c[xe]||100;h({column:xe,startX:Ee,startWidth:Ne})},[c]);r.useEffect(()=>{if(!m)return;const Y=Ee=>{const Ce=("touches"in Ee?Ee.touches[0].clientX:Ee.clientX)-m.startX,De=Math.max(60,Math.min(400,m.startWidth+Ce));d(Ge=>({...Ge,[m.column]:De}))},xe=()=>{h(null)};return document.addEventListener("mousemove",Y),document.addEventListener("mouseup",xe),document.addEventListener("touchmove",Y),document.addEventListener("touchend",xe),()=>{document.removeEventListener("mousemove",Y),document.removeEventListener("mouseup",xe),document.removeEventListener("touchmove",Y),document.removeEventListener("touchend",xe)}},[m]),r.useEffect(()=>{const Y=Ne=>{o(Ne.detail??!n)},xe=()=>{pt()},Ee=()=>{ne(!0)};return window.addEventListener("mobile-filter-toggle",Y),window.addEventListener("mobile-refresh-click",xe),window.addEventListener("mobile-add-click",Ee),()=>{window.removeEventListener("mobile-filter-toggle",Y),window.removeEventListener("mobile-refresh-click",xe),window.removeEventListener("mobile-add-click",Ee)}},[n]);const[f,b]=r.useState(!1),[y,x]=r.useState(!1),[u,g]=r.useState({key:"",direction:null}),[w,_]=r.useState("weekly"),[E,N]=r.useState(qj),[S,k]=r.useState(""),[D,F]=r.useState(!1),[R,L]=r.useState(!1),[$,H]=r.useState(1),[K,X]=r.useState(100),[V,P]=r.useState(!1),[A,C]=r.useState(""),[I,j]=r.useState([]),[q,T]=r.useState(""),[M,Z]=r.useState(""),[B,ae]=r.useState(""),[de,fe]=r.useState(0),[se,z]=r.useState([]),[U,Q]=r.useState(!1),[me,le]=r.useState(!1),[O,ne]=r.useState(!1),ge=Zs(Us.page_tracking,{autoStart:!1}),[ze,Ke]=r.useState(!1),[ie,ve]=r.useState(new Set);r.useEffect(()=>{ie.size>0&&l(!1)},[ie.size]);const{confirm:we}=ia(),[Pe,Ae]=r.useState(new Map),ye=r.useRef(!1),Te=r.useRef(""),Ie=r.useRef(!1),Oe=r.useCallback(()=>{fe(Y=>Y+1)},[]);r.useEffect(()=>{let Y=!0;async function xe(){try{b(!0);const Ee=await bs.getGoogleAuthExistsCached({ttlMs:3e4});if(!Y)return;x(!!Ee.exists)}catch(Ee){console.error("⚠️ Failed to check GSC auth:",Ee),Y&&x(!1)}finally{Y&&b(!1)}}return xe(),()=>{Y=!1}},[]);const J=r.useCallback(()=>{x(!0)},[]),re=r.useCallback(()=>{Ie.current=!1,Te.current="",j([]),T(""),Ae(new Map)},[]);r.useEffect(()=>{if(!y||Ie.current)return;Ie.current=!0;let Y=!0;return(async()=>{P(!0),C("Loading GSC sites...");try{const[Ee,Ne]=await Promise.all([Ro(),Or().catch(()=>null)]);if(!Y)return;const Ce=Ee.items||[];if(j(Ce),Ne?.domain&&Z(Ne.domain),Ce.length>0){const De=Vj();if(De&&Ce.some(ee=>ee.site_url===De))T(De),Hr(De);else{const ee=Ne?.domain,Fe=Jj(Ce,ee);Fe?(T(Fe),Hr(Fe)):(T(Ce[0].site_url),Hr(Ce[0].site_url))}}}catch(Ee){console.error("Failed to load GSC sites:",Ee),Ie.current=!1}finally{Y&&(P(!1),C(""))}})(),()=>{Y=!1}},[y]);const Se=r.useCallback(async()=>{Q(!0);try{const xe=(await Lj()).pages||[];return z(xe),xe}catch(Y){return console.error("Failed to load tracked pages:",Y),t({title:"Failed to load tracked pages",description:"Unable to fetch your tracked pages"}),[]}finally{Q(!1),le(!0)}},[t]);r.useEffect(()=>{Se()},[Se]),r.useEffect(()=>{(async()=>{try{const{company:xe}=await Dn();xe?.url&&ae(xe.url)}catch(xe){console.error("Failed to load company info:",xe)}})()},[]);const je=r.useMemo(()=>new Set(se.map(Y=>Y.page_url)),[se]),he=r.useMemo(()=>{const Y=new Map;return se.forEach(xe=>Y.set(xe.page_url,xe)),Y},[se]);r.useEffect(()=>{if(!y||!q||!E.from||!E.to||se.length===0){Ae(new Map);return}const Y=w==="weekly"?"week":"month",xe=`${q}|${E.from}|${E.to}|${Y}|${de}`;if(ye.current||Te.current===xe)return;(async()=>{ye.current=!0,Te.current=xe,L(!0),P(!0),C("Loading page metrics from GSC...");try{const Ne=await Sw({site_url:q,start_date:E.from,end_date:E.to,search_type:"web",time_grouping:Y}),Ce=new Map;
183(Ne.items||[]).forEach(De=>{const Ge=String(De.key||""),ee=Ge.indexOf("|");if(ee<=0)return;const Fe=Ge.slice(0,ee),Xe=Ge.slice(ee+1);!Fe||!Xe||(Ce.has(Xe)||Ce.set(Xe,new Map),Ce.get(Xe).set(Fe,{clicks:De.clicks||0,impressions:De.impressions||0,ctr:De.ctr||0,position:De.position||0}))}),Ae(Ce)}catch(Ne){console.error("Failed to load page metrics:",Ne),t({title:"Failed to load page metrics",description:Ne.message}),Te.current=""}finally{L(!1),P(!1),C(""),ye.current=!1}})()},[y,q,E.from,E.to,w,de,se.length]);const Re=r.useMemo(()=>Yj(E,w),[E,w]),Me=r.useMemo(()=>{if(se.length===0)return[];Pe.size>0;const Y=[];return se.forEach(xe=>{const Ee=xe.page_url,Ne=Pe.get(Ee),Ce=Re.map(De=>{const Ge=Ne?.get(De.period);return{...De,clicks:Ge?.clicks??0,impressions:Ge?.impressions??0,ctr:Ge?.ctr??0,position:Ge?.position??0}});Y.push({id:xe.id,url:Ee,metrics:Ce})}),Y.sort((xe,Ee)=>{const Ne=xe.metrics.reduce((De,Ge)=>De+Ge.clicks,0);return Ee.metrics.reduce((De,Ge)=>De+Ge.clicks,0)-Ne}),Y},[Pe,Re,se]),Ze=r.useMemo(()=>S.trim()?Me.filter(Y=>Y.url.toLowerCase().includes(S.toLowerCase())):Me,[Me,S]),Be=Y=>{g(xe=>xe.key!==Y?{key:Y,direction:"asc"}:xe.direction==="asc"?{key:Y,direction:"desc"}:xe.direction==="desc"?{key:"",direction:null}:{key:Y,direction:"asc"})},et=(Y,xe=!1)=>{const Ee=xe?10:14;return u.key!==Y?e.jsx(dn,{size:Ee,className:"text-slate-400 opacity-50"}):u.direction==="asc"?e.jsx(Is,{size:Ee,className:"text-blue-600"}):u.direction==="desc"?e.jsx(Ws,{size:Ee,className:"text-blue-600"}):e.jsx(dn,{size:Ee,className:"text-slate-400 opacity-50"})},$e=r.useMemo(()=>{if(!u.key||!u.direction)return Ze;const Y=u.direction,xe=u.key,Ee=(De,Ge)=>{const ee=De==null,Fe=Ge==null;if(ee&&Fe)return 0;if(ee)return 1;if(Fe)return-1;if(typeof De=="number"&&typeof Ge=="number"){const It=De-Ge;return Y==="asc"?It:-It}const Xe=String(De),yt=String(Ge),ut=Xe.localeCompare(yt);return Y==="asc"?ut:-ut},Ne=(De,Ge,ee)=>{const Fe=De.metrics.find(Xe=>Xe.period===ee);return Fe&&Fe[Ge]||0},Ce=[...Ze];return Ce.sort((De,Ge)=>{if(xe==="url")return Ee(De.url,Ge.url);const ee=xe.match(/^(clicks|impressions|ctr|position)-(.+)$/);if(ee){const Fe=ee[1],Xe=ee[2];return Ee(Ne(De,Fe,Xe),Ne(Ge,Fe,Xe))}return 0}),Ce},[Ze,u]),ue=r.useMemo(()=>{const Y=($-1)*K;return $e.slice(Y,Y+K)},[$e,$,K]),[W,ke]=r.useState(30),qe=r.useMemo(()=>$e.slice(0,W),[$e,W]),Qe=r.useCallback(Y=>{const xe=Y.currentTarget;xe.scrollHeight-xe.scrollTop-xe.clientHeight<200&&ke(Ee=>Math.min(Ee+20,$e.length))},[$e.length]);r.useEffect(()=>{H(1),ke(30)},[S,E,w,u]),r.useEffect(()=>{ie.size>0&&l(!1)},[ie.size]);const ct=r.useMemo(()=>{const Y=se.length,xe=Me.reduce((Ge,ee)=>Ge+ee.metrics.reduce((Fe,Xe)=>Fe+Xe.clicks,0),0),Ee=Me.reduce((Ge,ee)=>Ge+ee.metrics.reduce((Fe,Xe)=>Fe+Xe.impressions,0),0);let Ne=0,Ce=0;Me.forEach(Ge=>{Ge.metrics.forEach(ee=>{ee.impressions>0&&(Ne+=ee.position*ee.impressions,Ce+=ee.impressions)})});const De=Ce>0?Ne/Ce:0;return{totalPages:Y,totalClicks:xe,totalImpressions:Ee,avgCtr:Ee>0?(xe/Ee*100).toFixed(2)+"%":"—",avgPosition:De>0?De.toFixed(1):"—"}},[Me,se.length]),pt=r.useCallback(()=>{y&&q&&E.from&&E.to&&(Oe(),t({title:"Refreshing data",description:"Fetching latest metrics from GSC"}))},[y,q,E.from,E.to,Oe,t]),At=r.useCallback(()=>{if($e.length===0){t({title:"Nothing to export",description:"No pages available for export"});return}try{const Y=["Page URL"];Y.push("Clicks");for(let Xe=1;Xe<Re.length;Xe++)Y.push(null);Y.push("Impressions");for(let Xe=1;Xe<Re.length;Xe++)Y.push(null);Y.push("CTR");for(let Xe=1;Xe<Re.length;Xe++)Y.push(null);Y.push("Position");for(let Xe=1;Xe<Re.length;Xe++)Y.push(null);const xe=[null];Re.forEach(Xe=>xe.push(Xe.period)),Re.forEach(Xe=>xe.push(Xe.period)),Re.forEach(Xe=>xe.push(Xe.period)),Re.forEach(Xe=>xe.push(Xe.period));const Ee=[Y,xe];$e.forEach(Xe=>{const yt=[Xe.url];Re.forEach(ut=>{const It=Xe.metrics.find(Ct=>Ct.period===ut.period);yt.push(It?.clicks||0)}),Re.forEach(ut=>{const It=Xe.metrics.find(Ct=>Ct.period===ut.period);yt.push(It?.impressions||0)}),Re.forEach(ut=>{const It=Xe.metrics.find(Ct=>Ct.period===ut.period);yt.push(((It?.ctr||0)*100).toFixed(2)+"%")}),Re.forEach(ut=>{const It=Xe.metrics.find(Ct=>Ct.period===ut.period);yt.push((It?.position||0).toFixed(1))}),Ee.push(yt)});const Ne=as.book_new(),Ce=as.aoa_to_sheet(Ee),De=[],Ge=Re.length;let ee=1;De.push({s:{r:0,c:ee},e:{r:0,c:ee+Ge-1}}),ee+=Ge,De.push({s:{r:0,c:ee},e:{r:0,c:ee+Ge-1}}),ee+=Ge,De.push({s:{r:0,c:ee},e:{r:0,c:ee+Ge-1}}),ee+=Ge,De.push({s:{r:0,c:ee},e:{r:0,c:ee+Ge-1}}),Ce["!merges"]=De,as.book_append_sheet(Ne,Ce,"Page Tracking");const Fe=`page_tracking_${w}_${E.from}_to_${E.to}.xlsx`;mi(Ne,Fe),t({title:"Export completed",description:`Exported ${$e.length} page(s) to Excel`})}catch(Y){console.error("Failed to export:",Y),t({title:"Export failed",description:Y?.message||"Unable to export page tracking data"})}},[$e,Re,E,w,t]),te=r.useCallback(Y=>{ve(xe=>{const Ee=new Set(xe);return Ee.has(Y)?Ee.delete(Y):Ee.add(Y),Ee})},[]),G=r.useCallback(()=>{const Y=s?qe:ue;ie.size===Y.length?ve(new Set):ve(new Set(Y.map(xe=>xe.id)))},[ue,qe,ie.size,s]);r.useCallback(async()=>
183{if(ie.size===0){t({title:"No pages selected",description:"Please select pages to delete"});return}if(se.filter(Ne=>ie.has(Ne.id)).map(Ne=>Ne.page_url),!(!await we({title:"Delete Pages?",message:`Are you sure you want to delete ${ie.size} page(s)? This action will remove all tracking data for these pages.`,confirmText:"Delete",cancelText:"Cancel",variant:"default"})||(await new Promise(Ne=>setTimeout(Ne,100)),!await we({title:"Confirm Deletion",message:`This action cannot be undone. Are you absolutely sure you want to permanently delete ${ie.size} page(s)?`,confirmText:"Yes, Delete Permanently",cancelText:"Cancel",variant:"danger"})))){P(!0),C(`Deleting ${ie.size} page(s)...`);try{await $j(Array.from(ie)),t({title:"Pages deleted",description:`Successfully deleted ${ie.size} page(s)`}),ve(new Set),Se()}catch(Ne){console.error("Failed to delete pages:",Ne),t({title:"Failed to delete pages",description:Ne?.response?.data?.detail||"An error occurred"})}finally{P(!1),C("")}}},[ie,se,t,Se,we]),r.useCallback(()=>{if(ie.size===0){t({title:"No pages selected",description:"Please select at least one page to generate content"});return}Ke(!0)},[ie.size,t]);const pe=r.useCallback(async()=>{const Y=se.length===0,Ee=(await Se()).length>0;Y&&Ee&&ge.startExternal(),q&&E.from&&E.to&&Oe()},[se.length,Se,ge,q,E.from,E.to,Oe]);if(me&&!R&&!U&&se.length===0)return e.jsxs("div",{className:"min-h-screen bg-slate-50",children:[e.jsx("div",{className:"bg-white border-b border-slate-200",children:e.jsx("div",{className:"max-w-7xl mx-auto px-6 py-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 bg-slate-100 rounded-xl flex items-center justify-center",children:e.jsx(Qt,{className:"w-5 h-5 text-slate-600"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-lg font-semibold text-slate-900",children:"Page Tracking"}),e.jsx("p",{className:"text-xs text-slate-500",children:"Monitor page visibility across search engines"})]})]})})}),e.jsx("div",{className:"max-w-[1600px] mx-auto px-6 py-6",children:e.jsx("div",{className:"bg-white rounded-xl border border-slate-200 p-12",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12",children:[e.jsx("div",{className:"w-16 h-16 rounded-full bg-slate-900 flex items-center justify-center mb-6",children:e.jsx(Qt,{className:"w-7 h-7 text-white"})}),e.jsx("h2",{className:"text-2xl font-semibold text-slate-900 mb-2",children:"Page Tracking"}),e.jsx("p",{className:"text-slate-500 text-center max-w-md mb-8",children:"Monitor and improve page visibility across search engines"}),e.jsxs(be,{onClick:()=>ne(!0),className:"gap-2 bg-slate-900 hover:bg-slate-800",children:["Add Pages",e.jsx($t,{className:"w-4 h-4"})]})]})})}),e.jsx(mm,{open:O,onOpenChange:ne,siteUrl:B||q,existingUrls:je,onSuccess:pe})]});const ce=se.length>0&&$e.length>0;return e.jsxs("div",{className:`h-full relative flex flex-col overflow-hidden ${s?"bg-white":"p-4 pb-20 bg-slate-50"}`,"data-onboarding":"page-tracking-intro",children:[e.jsx(Do,{visible:V,message:A,fixed:!1,zIndex:50}),s&&n&&e.jsxs("div",{className:"px-4 py-3 bg-white border-b border-gray-200",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Pt,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400"}),e.jsx(bt,{placeholder:"Search pages...",value:S,onChange:Y=>k(Y.target.value),className:"pl-9 pr-8 w-full",autoFocus:!0}),S&&e.jsx("button",{onClick:()=>k(""),className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 hover:bg-slate-100 rounded",children:e.jsx(mt,{className:"w-3 h-3 text-slate-400"})})]}),e.jsxs("div",{className:"mt-3 space-y-3",children:[I.length>1?e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-wider font-medium text-slate-400 mb-1",children:"Site"}),e.jsx("select",{className:"h-9 px-3 rounded-md border border-slate-200 bg-white text-sm w-full",value:q,disabled:!y||f,onChange:Y=>{const xe=Y.target.value;T(xe),Hr(xe)},children:I.map(Y=>e.jsx("option",{value:Y.site_url,children:Y.site_url.replace(/^sc-domain:/,"")},Y.site_url))})]}):q?e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-wider font-medium text-slate-400",children:"Site"}),e.jsx("div",{className:"text-xs text-slate-600 truncate max-w-[70%]",children:q.replace(/^sc-domain:/,"")})]}):null,e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-wider font-medium text-slate-400 mb-1",children:"Period"}),e.jsxs("div",{className:"flex items-center bg-slate-100 rounded-lg p-0.5",children:[e.jsx("button",{onClick:()=>_("weekly"),className:`flex-1 px-3 py-1.5 text-sm font-medium rounded-md transition-all ${w==="weekly"?"bg-white text-slate-900 shadow-sm":"text-slate-600 hover:text-slate-900"}`,children:"Weekly"}),e.jsx("button",{onClick:()=>_("monthly"),className:`flex-1 px-3 py-1.5 text-sm font-medium rounded-md transition-all ${w==="monthly"?"bg-white text-slate-900 shadow-sm":"text-slate-600 hover:text-slate-900"}`,children:"Monthly"})]})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-wider font-medium text-slate-400 mb-1",children:"Date range"}),e.jsx(Sa,{value:E,onChange:N,presets:um,placeholder:"Select date range",className:"w-full"})]})]})]}),e.jsx("div",{className:"mb-6 flex-shrink-0 hidden sm:block",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 bg-slate-100 rounded-xl flex items-center justify-center",children:e.jsx(is,{className:"w-5 h-5 text-slate-600"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-slate-900",children:"SEO Page Tracking"}),e.jsxs("p",{className:"text-sm text-slate-500",children:["Track GSC metrics for all pages | ",Re.length," ",w==="weekly"?"weeks":"months"]})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[I.length>1&&e.jsx("select",{className:"h-9 px-3 rounded-md border border-slate-200 bg-white text-sm",value:q,disabled:!y||f,onChange:Y=>{const xe=Y.target.value;T(xe),Hr(xe)},children:I.map(Y=>e.jsx("option",{value:Y.site_url,children:Y.site_url.replace(/^sc-domain:/,"")},Y.site_url))}),q&&I.length<=1&&e.jsxs("span",{className:"text-xs text-slate-500 bg-slate-100 px-2.5 py-1 rounded-full",children:["Site: ",q.replace(/^sc-domain:/,"")]})]})]})}),s&&Me.length>0&&e.jsxs("div",{className:"px-3 py-2 grid grid-cols-2 gap-2 flex-shrink-0",children:[e.jsxs("div",{className:"bg-slate-50 rounded-lg p-3",children:[e.jsx("div",{className:"text-[10px] text-slate-400 uppercase tracking-wider",children:"Pages"}),e.jsx("div",{className:"text-base font-semibold text-slate-800",children:se.length})]}),e.jsxs("div",{className:"bg-slate-50 rounded-lg p-3",children:[e.jsx("div",{className:"text-[10px] text-slate-400 uppercase tracking-wider",children:"Clicks"}),e.jsx("div",{className:"text-base font-semibold text-slate-800",children:fr(ct.totalClicks)})]}),e.jsxs("div",{className:"bg-slate-50 rounded-lg p-3",children:[e.jsx("div",{className:"text-[10px] text-slate-400 uppercase tracking-wider",children:"Impressions"}),e.jsx("div",{className:"text-base font-semibold text-slate-800",children:fr(ct.totalImpressions)})]}),e.jsxs("div",{className:"bg-slate-50 rounded-lg p-3",children:[e.jsx("div",{className:"text-[10px] text-slate-400 uppercase tracking-wider",children:"Avg Position"}),e.jsx("div",{className:"text-base font-semibold text-slate-800",children:ct.avgPosition})]})]}),!s&&Me.length>
1830&&e.jsxs("div",{className:"grid grid-cols-5 gap-4 mb-6 flex-shrink-0",children:[e.jsx("div",{className:"bg-white border border-slate-200 rounded-xl p-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-9 h-9 rounded-lg bg-slate-50 flex items-center justify-center",children:e.jsx(us,{size:16,className:"text-slate-500"})}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] text-slate-400 uppercase tracking-wider",children:"Tracked Pages"}),e.jsx("div",{className:"text-lg font-semibold text-slate-800",children:se.length})]})]})}),e.jsx("div",{className:"bg-white border border-slate-200 rounded-xl p-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-9 h-9 rounded-lg bg-slate-50 flex items-center justify-center",children:e.jsx(du,{size:16,className:"text-slate-500"})}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] text-slate-400 uppercase tracking-wider",children:"Clicks"}),e.jsx("div",{className:"text-lg font-semibold text-slate-800",children:fr(ct.totalClicks)})]})]})}),e.jsx("div",{className:"bg-white border border-slate-200 rounded-xl p-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-9 h-9 rounded-lg bg-slate-50 flex items-center justify-center",children:e.jsx(Ga,{size:16,className:"text-slate-500"})}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] text-slate-400 uppercase tracking-wider",children:"Impressions"}),e.jsx("div",{className:"text-lg font-semibold text-slate-800",children:fr(ct.totalImpressions)})]})]})}),e.jsx("div",{className:"bg-white border border-slate-200 rounded-xl p-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-9 h-9 rounded-lg bg-slate-50 flex items-center justify-center",children:e.jsx(Ma,{size:16,className:"text-slate-500"})}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] text-slate-400 uppercase tracking-wider",children:"Avg CTR"}),e.jsx("div",{className:"text-lg font-semibold text-slate-800",children:ct.avgCtr})]})]})}),e.jsx("div",{className:"bg-white border border-slate-200 rounded-xl p-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-9 h-9 rounded-lg bg-slate-50 flex items-center justify-center",children:e.jsx(Sn,{size:16,className:"text-slate-500"})}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] text-slate-400 uppercase tracking-wider",children:"Avg Position"}),e.jsx("div",{className:"text-lg font-semibold text-slate-800",children:ct.avgPosition})]})]})})]}),e.jsx("div",{className:"bg-white rounded-xl border border-slate-200 p-4 mb-4 flex-shrink-0 hidden sm:block",children:e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Pt,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400"}),e.jsx(bt,{placeholder:"Search pages...",value:S,onChange:Y=>k(Y.target.value),onFocus:()=>F(!0),onBlur:()=>F(!1),className:`pl-9 pr-8 w-56 transition-all ${D?"w-72 ring-2 ring-blue-100":""}`}),S&&e.jsx("button",{onClick:()=>k(""),className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 hover:bg-slate-100 rounded",children:e.jsx(mt,{className:"w-3 h-3 text-slate-400"})})]}),e.jsx("div",{className:"h-8 w-px bg-slate-200"}),e.jsxs("div",{className:"flex items-center bg-slate-100 rounded-lg p-0.5",children:[e.jsx("button",{onClick:()=>_("weekly"),className:`px-3 py-1.5 text-sm font-medium rounded-md transition-all ${w==="weekly"?"bg-white text-slate-900 shadow-sm":"text-slate-600 hover:text-slate-900"}`,children:"Weekly"}),e.jsx("button",{onClick:()=>_("monthly"),className:`px-3 py-1.5 text-sm font-medium rounded-md transition-all ${w==="monthly"?"bg-white text-slate-900 shadow-sm":"text-slate-600 hover:text-slate-900"}`,children:"Monthly"})]}),e.jsx("div",{"data-onboarding":"date-range-picker",children:e.jsx(Sa,{value:E,onChange:N,presets:um,placeholder:"Select date range",className:"w-64"})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(be,{size:"sm",className:"gap-1.5 bg-slate-900 hover:bg-slate-800 text-white",onClick:()=>ne(!0),"data-onboarding":"add-pages-button",children:["Add Pages",e.jsx($t,{className:"w-4 h-4"})]}),e.jsxs(be,{variant:"outline",size:"sm",className:"gap-1.5",onClick:At,disabled:!y||f||$e.length===0,children:[e.jsx(Vs,{className:"w-4 h-4"}),"Export"]}),e.jsxs(be,{variant:"outline",size:"sm",className:"gap-1.5",onClick:pt,disabled:!y||f||R,"data-onboarding":"refresh-pages-button",children:[e.jsx(kt,{className:`w-4 h-4 ${R?"animate-spin":""}`}),"Refresh"]})]})]})}),e.jsxs("div",{className:`bg-white overflow-hidden flex-1 flex flex-col min-h-0 relative ${s?"":"rounded-xl border border-slate-200"}`,"data-onboarding":"page-tracking-table",children:[e.jsxs("div",{className:`flex-1 overflow-auto min-h-0 relative h-full ${s&&ie.size>0?"pb-28":""}`,onScroll:s?Qe:void 0,children:[ce&&e.jsxs("table",{className:"min-w-full text-sm",style:s?{tableLayout:"fixed"}:void 0,children:[e.jsxs("thead",{className:`text-left text-slate-500 bg-slate-50 border-b border-slate-200 ${s?"sticky top-0 z-30":""}`,children:[e.jsxs("tr",{className:"border-b border-slate-200",children:[e.jsxs("th",{rowSpan:2,className:`px-3 py-3 align-middle relative group/resize ${s?"bg-slate-50":"w-10 sticky left-0 bg-slate-50 z-10"}`,style:s?{width:c.checkbox,minWidth:c.checkbox}:void 0,children:[e.jsx(Kt,{checked:ue.length>0&&ie.size===ue.length?!0:ie.size>0?"indeterminate":!1,onCheckedChange:G}),s&&e.jsx("div",{className:"absolute right-0 top-0 bottom-0 w-1 cursor-col-resize bg-transparent hover:bg-blue-400 transition-colors",onMouseDown:Y=>p(Y,"checkbox"),onTouchStart:Y=>p(Y,"checkbox")}
183)]}),e.jsxs("th",{rowSpan:2,className:`px-4 py-3 font-semibold text-slate-700 cursor-pointer hover:bg-slate-100 align-middle relative group/resize ${s?"bg-slate-50":"min-w-[300px] sticky left-10 bg-slate-50 z-10"}`,style:s?{width:c.url,minWidth:c.url}:void 0,onClick:()=>Be("url"),children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("span",{children:"Page URL"}),et("url")]}),s&&e.jsx("div",{className:"absolute right-0 top-0 bottom-0 w-1 cursor-col-resize bg-transparent hover:bg-blue-400 transition-colors",onMouseDown:Y=>{Y.stopPropagation(),p(Y,"url")},onTouchStart:Y=>{Y.stopPropagation(),p(Y,"url")}})]}),e.jsx("th",{colSpan:Re.length,className:"px-2 py-2 font-semibold text-slate-700 text-center border-l border-slate-200",children:"Clicks"}),e.jsx("th",{colSpan:Re.length,className:"px-2 py-2 font-semibold text-slate-700 text-center border-l border-slate-200",children:"Impressions"}),e.jsx("th",{colSpan:Re.length,className:"px-2 py-2 font-semibold text-slate-700 text-center border-l border-slate-200",children:"CTR"}),e.jsx("th",{colSpan:Re.length,className:"px-2 py-2 font-semibold text-slate-700 text-center border-l border-slate-200",children:"Position"})]}),e.jsxs("tr",{children:[Re.map((Y,xe)=>{const Ee=`clicks-${Y.period}`;return e.jsx("th",{className:`px-1 py-2 font-medium text-slate-500 text-center text-[11px] min-w-[50px] cursor-pointer hover:bg-slate-100 ${xe===0?"border-l border-slate-200":""}`,title:`Sort by Clicks ${Y.periodLabel}`,onClick:()=>Be(Ee),children:e.jsxs("div",{className:"flex items-center justify-center gap-0.5",children:[e.jsx("span",{children:Y.period}),et(Ee,!0)]})},`clicks-${Y.period}`)}),Re.map((Y,xe)=>{const Ee=`impressions-${Y.period}`;return e.jsx("th",{className:`px-1 py-2 font-medium text-slate-500 text-center text-[11px] min-w-[50px] cursor-pointer hover:bg-slate-100 ${xe===0?"border-l border-slate-200":""}`,title:`Sort by Impressions ${Y.periodLabel}`,onClick:()=>Be(Ee),children:e.jsxs("div",{className:"flex items-center justify-center gap-0.5",children:[e.jsx("span",{children:Y.period}),et(Ee,!0)]})},`impr-${Y.period}`)}),Re.map((Y,xe)=>{const Ee=`ctr-${Y.period}`;return e.jsx("th",{className:`px-1 py-2 font-medium text-slate-500 text-center text-[11px] min-w-[50px] cursor-pointer hover:bg-slate-100 ${xe===0?"border-l border-slate-200":""}`,title:`Sort by CTR ${Y.periodLabel}`,onClick:()=>Be(Ee),children:e.jsxs("div",{className:"flex items-center justify-center gap-0.5",children:[e.jsx("span",{children:Y.period}),et(Ee,!0)]})},`ctr-${Y.period}`)}),Re.map((Y,xe)=>{const Ee=`position-${Y.period}`;return e.jsx("th",{className:`px-1 py-2 font-medium text-slate-500 text-center text-[11px] min-w-[50px] cursor-pointer hover:bg-slate-100 ${xe===0?"border-l border-slate-200":""}`,title:`Sort by Position ${Y.periodLabel}`,onClick:()=>Be(Ee),children:e.jsxs("div",{className:"flex items-center justify-center gap-0.5",children:[e.jsx("span",{children:Y.period}),et(Ee,!0)]})},`pos-${Y.period}`)})]})]}),e.jsx("tbody",{className:"divide-y divide-slate-100 border-b border-gray-200",children:(s?qe:ue).map(Y=>{const xe=he.get(Y.url),Ee=ie.has(Y.id);return e.jsxs("tr",{className:`hover:bg-slate-50/50 transition-colors cursor-pointer ${Ee?"bg-blue-50/50":""}`,onClick:s?()=>te(Y.id):void 0,children:[e.jsx("td",{className:`px-3 py-3 ${s?"bg-white":"w-10 sticky left-0 bg-white z-10"}`,style:s?{width:c.checkbox,minWidth:c.checkbox}:void 0,children:e.jsx(Kt,{checked:Ee,onCheckedChange:()=>te(Y.id),onClick:Ne=>Ne.stopPropagation()})}),e.jsx("td",{className:`px-4 py-3 font-medium text-slate-900 ${s?"bg-white":"sticky left-10 bg-white z-10"}`,style:s?{width:c.url,minWidth:c.url}:void 0,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:s?"truncate":"truncate max-w-[250px]",title:Y.url,children:Y.url.replace(/^https?:\/\//,"")}),e.jsx("a",{href:Y.url,target:"_blank",rel:"noopener noreferrer",className:"text-slate-400 hover:text-blue-600 flex-shrink-0",children:e.jsx(ns,{className:"w-3 h-3"})}),xe?.source==="manual"&&e.jsx(ls,{variant:"secondary",className:"text-[10px] px-1.5 py-0 bg-orange-50 text-orange-600 border border-orange-100",children:"Manual"}),xe?.is_generated_by_rankgale&&e.jsxs(ls,{variant:"secondary",className:"text-[10px] px-1.5 py-0 bg-purple-50 text-purple-600 border border-purple-100 gap-0.5",children:[e.jsx(Ks,{className:"w-2.5 h-2.5"}),"Rankgale"]})]})}),Re.map((Ne,Ce)=>{const De=Y.metrics.find(ee=>ee.period===Ne.period),Ge=De&&(De.clicks>0||De.impressions>0);return e.jsx("td",{className:`px-2 py-3 text-center tabular-nums ${Ce===0?"border-l border-slate-100":""}`,children:e.jsx("span",{className:Ge?"text-slate-800 font-medium":"text-slate-400",children:fr(De?.clicks||0)})},`clicks-${Ne.period}`)}),Re.map((Ne,Ce)=>{const De=Y.metrics.find(ee=>ee.period===Ne.period),Ge=De&&(De.clicks>0||De.impressions>0);return e.jsx("td",{className:`px-2 py-3 text-center tabular-nums ${Ce===0?"border-l border-slate-100":""}`,children:e.jsx("span",{className:Ge?"text-slate-600":"text-slate-400",children:fr(De?.impressions||0)})},`impr-${Ne.period}`)}),Re.map((Ne,Ce)=>{const De=Y.metrics.find(ee=>ee.period===Ne.period),Ge=De&&(De.clicks>0||De.impressions>0);return e.jsx("td",{className:`px-2 py-3 text-center tabular-nums ${Ce===0?"border-l border-slate-100":""}`,children:e.jsxs("span",{className:Ge?"text-slate-600":"text-slate-400",children:[((De?.ctr||0)*100).toFixed(1),"%"]})},`ctr-${Ne.period}`)}),Re.map((Ne,Ce)=>{const De=Y.metrics.find(ee=>ee.period===Ne.period),Ge=De&&(De.clicks>0||De.impressions>0);return e.jsx("td",{className:`px-2 py-3 text-center tabular-nums ${Ce===0?"border-l border-slate-100":""}`,children:e.jsx("span",{className:Ge?"text-slate-600":"text-slate-400",children:(De?.position||0).toFixed(1)})},`pos-${Ne.period}`)})]},Y.id)})})]}),R&&!ce&&e.jsx("div",{className:"h-full min-h-[320px] flex items-center justify-center bg-white",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"w-16 h-16 bg-slate-100 rounded-full flex items-center justify-center mx-auto mb-4",children:e.jsx(kt,{className:"w-8 h-8 text-slate-400 animate-spin"})}),e.jsx("h3",{className:"text-lg font-medium text-slate-900 mb-1",children:"Loading page data..."})]})}),!R&&!U&&se.length===0&&e.jsx("div",{className:"h-full min-h-[320px] flex items-center justify-center bg-white",children:e.jsxs("div",{className:"text-center max-w-md",children:[e.jsx("div",{className:"w-20 h-20 bg-gradient-to-br from-blue-50 to-purple-50 rounded-2xl flex items-center justify-center mx-auto mb-6 border border-blue-100",children:e.jsx(Qt,{className:"w-10 h-10 text-blue-500"})}),e.jsx("h3",{className:"text-xl font-semibold text-slate-900 mb-2",children:"Start Tracking Your Pages"}),e.jsx("p",{className:"text-sm text-slate-500 mb-6 leading-relaxed",children:"Add pages from Google Search Console or enter URLs manually to track their SEO performance over time."}),e.jsxs(be,{size:"lg",className:"gap-2 bg-blue-600 hover:bg-blue-700 text-white",onClick:()=>ne(!0),children:[e.jsx($t,{className:"w-5 h-5"}),"Add Your First Pages"]})]})}),!R&&se.length>0&&$e.length===0&&e.jsx("div",{className:"h-full min-h-[320px] flex items-center justify-center bg-white",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"w-16 h-16 bg-slate-100 rounded-full flex items-center justify-center mx-auto mb-4",children:e.jsx(Pt,{className:"w-8 h-8 text-slate-400"})}),e.jsx("h3",{className:"text-lg font-medium text-slate-900 mb-1",children:"No pages found"}),e.jsx("p",{className:"text-sm text-slate-500 mb-4",children:S?"Try adjusting your search query":"No page data available for the selected date range"})]})})]}),!R&&$e.length>0&&!s&&e.jsx("div",{className:"flex-shrink-0 border-t border-slate-200",children:e.jsx(xn,{page:$,pageSize:K,total:$e.length,onPageChange:H,onPageSizeChange:X,onPageSizeChangeWithReset:Y=>{X(Y),H(1)},displayFormat:"range",maxPageSize:500})})]}),e.jsx(mm,{open:O,onOpenChange:ne,siteUrl:B||q,existingUrls:je,onSuccess:pe}),e.jsx(Wj,{isOpen:ze,onClose:()=>{Ke(!1),ve(new Set)},selectedPageUrls:Array.from(ie).map(Y=>
183se.find(Ee=>Ee.id===Y)?.page_url||"").filter(Y=>Y.length>0)}),!f&&e.jsx(_x,{visible:!y,onAuthorized:J,onComplete:re}),e.jsx("button",{onClick:ge.startManual,className:"fixed bottom-5 right-5 z-50 h-8 w-8 rounded-full bg-white border border-slate-200 shadow-md hover:shadow-lg hover:bg-slate-50 transition-all hover:scale-105 hidden sm:flex items-center justify-center",title:"View navigation guide","aria-label":"View navigation guide",children:e.jsx(Hs,{className:"h-4 w-4 text-slate-600"})}),e.jsx(oa,{steps:Dj,run:ge.run,onComplete:ge.stopAndMarkCompleted,onSkip:ge.stopAndMarkCompleted})]})}const Xj=[{target:'[data-onboarding="competitors-header"]',content:e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-semibold text-slate-900 mb-2",children:"Competitors Intelligence"}),e.jsx("p",{className:"text-sm text-slate-600",children:"This page provides a comprehensive analysis of your domain's competitive landscape. Data is sourced from third-party SEO databases and aggregated across your selected markets."})]}),placement:"bottom",disableBeacon:!0},{target:'[data-onboarding="competitors-table"]',content:e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-semibold text-slate-900 mb-2",children:"Competitor Table"}),e.jsx("p",{className:"text-sm text-slate-600 mb-2",children:"Detailed competitor data:"}),e.jsxs("ul",{className:"text-sm text-slate-600 space-y-1.5 list-disc list-inside",children:[e.jsxs("li",{children:[e.jsx("span",{className:"font-medium",children:"Ranked Keywords"})," - Total keywords the competitor ranks for"]}),e.jsxs("li",{children:[e.jsx("span",{className:"font-medium",children:"Shared Keywords"})," - Keywords both you and the competitor rank for"]}),e.jsxs("li",{children:[e.jsx("span",{className:"font-medium",children:"Traffic"})," - Estimated monthly organic traffic"]})]}),e.jsx("p",{className:"text-sm text-slate-600 mt-2",children:"Click a competitor row to analyze their keyword strategy in detail."})]}),placement:"bottom",disableBeacon:!0},{target:'[data-onboarding="competitors-add-btn"]',content:e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-semibold text-slate-900 mb-2",children:"Add Competitors"}),e.jsx("p",{className:"text-sm text-slate-600",children:"Manually add competitor domains to track. The system will fetch their SEO metrics and keyword data. You can also use AI discovery to automatically identify relevant competitors based on your domain."})]}),placement:"left",disableBeacon:!0}];function mh({marketReloadNonce:t,hideActions:s=!1}){const{toast:a}=_t(),n=t??0,[o,i]=r.useState(!0),[l,c]=r.useState(null),[d,m]=r.useState(null),h=r.useRef(null),[p,f]=r.useState(!1),b=Zs(Us.competitors),y=r.useCallback(async(N=!0)=>{try{N&&i(!0),N&&c(null);let S=ma();if(S.length===0&&!Tr()){if(!await Pr({timeout_ms:5e3}))return console.warn("⚠️ Markets not ready; skip loading competitors."),null;S=ma()}const k=$a(S),D=await wo(k);return m(D.aggregated),h.current=D.aggregated.sync_status,D.aggregated.sync_status}catch(S){return N?(console.error("❌ Failed to load competitors:",S),c(S.message||"Failed to load competitors data"),null):(console.warn("⚠️ Failed to refresh competitors (background):",S),h.current??"syncing")}finally{N&&i(!1)}},[]),x=Io({toast:a,onCompleted:async()=>{await y(!1)}}),u=qx({syncManager:x,loadAndGetSyncStatus:async()=>await y(!1)??(x.isRunning?"syncing":null),refreshAfterCompleted:async()=>{await y(!1)}});r.useEffect(()=>{y()},[y,n]);const g=r.useMemo(()=>d?.details?d.details:[],[d]),w=d?.last_synced_at?new Date(d.last_synced_at).toLocaleDateString("en-CA"):"Never",_=async N=>{if(N){x.startTask({taskId:N,etaText:"~1-5min"});return}u.startSyncAndPoll({etaText:"~1-5min"})};if(o)return e.jsx("div",{className:"h-full flex items-center justify-center",children:e.jsxs("div",{className:"text-center",children:[e.jsx(kt,{className:"h-8 w-8 animate-spin text-slate-400 mx-auto"}),e.jsx("p",{className:"mt-4 text-slate-600",children:"Loading competitors..."})]})});if(l)return e.jsx("div",{className:"h-full flex items-center justify-center",children:e.jsxs("div",{className:"text-center max-w-md",children:[e.jsx("div",{className:"w-12 h-12 bg-red-100 rounded-full flex items-center justify-center mx-auto mb-4",children:e.jsx("div",{className:"h-6 w-6 text-red-500"})}),e.jsx("h3",{className:"text-lg font-semibold text-slate-800 mb-2",children:"Unable to Load Data"}),e.jsx("p",{className:"text-slate-600",children:l})]})});const E=!d||g.length===0;return e.jsxs("div",{className:"h-full overflow-hidden relative flex flex-col",children:[e.jsx(oa,{steps:Xj,run:b.run,onComplete:b.stopAndMarkCompleted,onSkip:b.stopAndMarkCompleted}),e.jsxs("div",{className:"flex-1 flex flex-col px-0 sm:px-4 pt-4 pb-4 max-w-7xl mx-auto w-full min-h-0 overflow-hidden",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2 shrink-0 mb-4 px-4 sm:px-0","data-onboarding":"competitors-header",children:[e.jsx("h1",{className:"text-lg font-bold tracking-tight",children:"Competitors Intelligence"}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-slate-400",children:[e.jsx(ka,{size:12}),e.jsx("span",{className:"hidden sm:inline",children:"last refresh: "}),e.jsx("span",{children:w})]})]}),x.panel.phase!=="idle"&&e.jsx("div",{className:"bg-slate-50 sm:rounded-lg p-3 border-y sm:border border-slate-100 shrink-0 mb-4 mx-0 sm:mx-0",children:e.jsx(Mo,{state:x.panel})}),E?e.jsx("div",{className:"flex-1 flex items-center justify-center min-h-0",children:e.jsxs("div",{className:"text-center px-4",children:[e.jsx(Qs,{className:"h-10 w-10 text-slate-300 mx-auto mb-3"}),e.jsx("h3",{className:"text-base font-semibold text-slate-800 mb-2",children:"No Competitors Found"}),e.jsx("p",{className:"text-slate-600 mb-4 text-sm",children:"Add competitors to start analyzing your competitive landscape."}),!s&&e.jsxs(be,{onClick:()=>f(!0),disabled:x.isRunning,className:"flex items-center gap-2 bg-slate-900 hover:bg-slate-800",children:[e.jsx($t,{size:16}),"Add Competitors"]})]})}):e.jsx(e.Fragment,{children:e.jsx("div",{"data-onboarding":"competitors-landscape",children:e.jsx(Mx,{competitorsData:d,userDomain:d?.domain?{domain:d.domain,keywords:null,traffic:null,lastSyncedAt:d.last_synced_at??null}:null,onDataChange:()=>y(!1),onCompetitorsAdded:N=>{_(N)},onKeywordsSyncStarted:N=>{if(N){x.startTask({taskId:N,etaText:"~2-5 min"});return}x.startSync("~2-5 min")},hideActions:s})})})]}),e.jsx(Ix,{open:p,onOpenChange:f,existingCompetitors:g.map(N=>N.competitor),competitorsLimit:d?.competitors_limit||0,currentCount:d?.current_count||0,onSuccess:_}),!s&&e.jsx("button",{onClick:b.startManual,className:"fixed bottom-5 right-5 z-50 h-8 w-8 rounded-full bg-white border border-slate-200 shadow-md hover:shadow-lg hover:bg-slate-50 transition-all hover:scale-105 hidden sm:flex items-center justify-center",title:"View navigation guide","aria-label":"View navigation guide",children:e.jsx(Hs,{className:"h-4 w-4 text-slate-600"})})]})}const ds={async listKeywords(t){return await ot("/keywords/list",t)},async upsertKeywordsBatch(t){return await Je("/keywords/upsert_batch",t)},async batchDeleteKeywords(t){return await Je("/keywords/batch_delete",t)},async batchDeleteGroups(t){return await Je("/keyword_group/batch_delete",t)},async listGroups(t){return await ot("/keyword_group/list",t)},async listGroupsWithKeywords(t){return await ot("/keyword_group/list_with_keywords",t)},async getGroupDetail(t){return await ot("/keyword_group/get_detail",t)},async createGroup(t){return await Je("/keyword_group/create",t)},async updateGroup(t){return await Je("/keyword_group/update",t,{params:{group_id:t.group_id}})},async deleteGroup(t){return await Je("/keyword_group/delete",void 0,{params:t})},async addKeywordsToGroup(t){return await Je("/keyword_group/add_keywords",t)},async removeKeywordsFromGroup(t){return await Je("/keyword_group/remove_keywords",t)},async aiGroupKeywords(t){return await Je("/keyword_group/ai_group_keywords",t)},async getAIGroupTaskStatus(t){return await ot("/keyword_group/ai_group_task_status",t)},async updateGroupInsights(t){return await Je("/keyword_group/update_insights",{insights:t.insights},{params:{group_id:t.group_id}})},async generateGroupInsights(t){return await Je("/keyword_group/generate_insights",void 0,{params:{group_id:t.group_id}})}},Qj=Object.freeze(Object.defineProperty({__proto__:null,keywordResearchService:ds},Symbol.toStringTag,{value:"Module"}));function pl(t){return new Intl.NumberFormat("en-US").format(t)}function uh(t){const[s,a]=v.useState(!1),[n,o]=v.useState(t.rankedKeywordsLimit);v.useEffect(()=>{o(t.rankedKeywordsLimit)},[t.rankedKeywordsLimit]);const i=v.useCallback(()=>{o(t.rankedKeywordsLimit),a(!0)},[t.rankedKeywordsLimit]);return e.jsxs("div",{className:"flex items-center gap-2 sm:gap-3",children:[e.jsxs("button",{type:"button",onClick:i,className:"flex sm:hidden items-center gap-1.5 px-3 py-2 bg-slate-50 border border-slate-200 rounded-xl h-10 text-sm","data-onboarding":"keywords-gap-limit",title:`Ranked keywords limit: ${pl(t.rankedKeywordsLimit)}`,children:[e.jsx("span",{className:"font-semibold text-slate-800",children:pl(t.rankedKeywordsLimit)}),e.jsx(lc,{className:"w-4 h-4 text-slate-500"})]}),e.jsx("button",{type:"button",onClick:i,disabled:t.isSyncing||t.competitorsTrackedCount===0,className:"flex sm:hidden items-center justify-center w-10 h-10 text-slate-500 bg-slate-100 rounded-xl hover:bg-slate-200 hover:text-slate-700 disabled:opacity-50 transition-all",title:"Refresh","data-onboarding":"keywords-gap-refresh",children:e.jsx(kt,{className:`w-4 h-4 ${t.isSyncing?"animate-spin":""}`})}),e.jsxs("div",{className:"hidden sm:flex items-center gap-2 px-3 py-1.5 bg-slate-50 border border-slate-200 rounded-lg h-8","data-onboarding":"keywords-gap-limit",children:[e.jsx("span",{className:"text-sm text-slate-600",children:"Ranked keywords limit:"}),e.jsx("span",{className:"text-sm font-semibold text-slate-800",children:pl(t.rankedKeywordsLimit)}),e.jsx("button",{type:"button",onClick:i,className:"text-sm font-medium text-blue-600 hover:text-blue-700 hover:underline ml-1",children:"Increase"})]}),e.jsxs(be,{size:"sm",variant:"outline",onClick:i,disabled:t.isSyncing||t.competitorsTrackedCount===0,className:"hidden sm:flex h-8 bg-white",title:"Refresh competitors ranked keywords","data-onboarding":"keywords-gap-refresh",children:[e.jsx(kt,{className:t.isSyncing?"animate-spin":"",size:14}),e.jsx("span",{className:"ml-2",children:t.isSyncing?"Refreshing...":"Refresh"})]}),e.jsx(zc,{open:s,onOpenChange:a,mode:"ranked_keywords_only",keywordsLimit:n,onKeywordsLimitChange:o,onSaveSetting:async l=>{t.onRankedKeywordsLimitChange(l)},saveSettingText:"Save setting",isRunning:t.isSyncing,confirmText:"Save & Refresh",domains:[...t.selfDomain?.domain?[{domain:t.selfDomain.domain,lastSyncedAt:t.selfDomain.lastSyncedAt??null,isSelf:!0}
183]:[],...t.competitors.map(l=>({domain:l.domain,lastSyncedAt:l.lastSyncedAt}))],onConfirm:async l=>{a(!1);try{await t.onSyncCompetitorsRankedKeywords({domains:l.domains,forceSyncKeywords:l.forceSyncKeywords,includeSelf:l.includeSelf,keywordsLimit:l.keywordsLimit})}catch{}}})]})}function Zj(t){const s=t?.details||[];return s.length===0?null:s.reduce((a,n)=>a+(n.ranked_keywords_count||0),0)}function ev(t){if(t?.last_synced_at)return String(t.last_synced_at).trim();const s=t?.details||[];if(s.length===0)return null;let a=null,n=null;for(const o of s){const i=o?.last_synced_at?String(o.last_synced_at).trim():"";if(!i)continue;const l=Date.parse(i);Number.isFinite(l)&&(a===null||l>a)&&(a=l,n=i)}return n}const tv=({competitors:t,loading:s,selectedItem:a,onAddComplete:n,onRefreshCompetitors:o})=>{const{toast:i}=_t(),[l,c]=r.useState([]),[d,m]=r.useState(!1),[h,p]=r.useState(!1),[f,b]=r.useState(1),[y,x]=r.useState(()=>Ir()),u=a.actionTitle,g=a.description,w=Zj(t),_=t?.details?.length||0,E=ev(t);r.useEffect(()=>{if(E)try{localStorage.setItem("mobile_header_subtitle",`Last refresh: ${new Date(E).toLocaleDateString("en-CA")}`)}catch{}return()=>{try{localStorage.removeItem("mobile_header_subtitle")}catch{}}},[E]);const N=Io({toast:i,onCompleted:async()=>{try{await o()}catch(F){console.warn("⚠️ Failed to refresh after competitors sync:",F)}}});r.useEffect(()=>{let F=!0;return(async()=>{try{const $=(await Eo())?.competitor_ranked_keywords_limit;if(!F)return;typeof $=="number"&&(Rn($),x($))}catch(L){console.warn("⚠️ Failed to load ranked keywords limit:",L)}})(),()=>{F=!1}},[]),r.useEffect(()=>{let F=!1;return(async()=>{try{const L=await La(),$=Array.isArray(L?.markets)&&L.markets.length>0?L.markets.length:1;if(F)return;b(Math.max(1,Number($)||1))}catch(L){console.warn("⚠️ Failed to load track markets for credit estimate:",L),F||b(1)}})(),()=>{F=!0}},[]);const S=r.useCallback(async F=>{try{const L=(await Ao(F))?.competitor_ranked_keywords_limit??F;Rn(L),x(L),i({title:"Settings saved",description:`Competitor ranked keywords limit updated to Top ${L}.`})}catch(R){console.error("❌ Failed to save ranked keywords limit:",R),i({title:"Error",description:R?.message||"Failed to save settings"})}},[i]),k=r.useCallback(async F=>{const R=(F.domains||[]).map(H=>String(H).trim()).filter(Boolean);if(R.length===0&&!F.includeSelf){i({title:"No selection",description:"Please select at least one competitor to sync."});return}const{creditEstimateService:L}=await Bt(async()=>{const{creditEstimateService:H}=await Promise.resolve().then(()=>Ya);return{creditEstimateService:H}},void 0),{validateCreditBalance:$}=await Bt(async()=>{const{validateCreditBalance:H}=await Promise.resolve().then(()=>ua);return{validateCreditBalance:H}},void 0);try{const H=R.length+(F.includeSelf?1:0),K=await L.estimateCredits({scenario:"domainseo_batch_sync_competitors",params:{markets_count:f,targets_count:H,competitor_targets_count:R.length,keywords_limit:typeof F.keywordsLimit=="number"&&Number.isFinite(F.keywordsLimit)?F.keywordsLimit:y,sync_rank_overview:!1,sync_ranked_keywords:!0,force_sync_keywords:!!F.forceSyncKeywords}});if(!await $({estimatedRange:K?{min:K.estimated_min_credits,max:K.estimated_max_credits}:null,requiredMinimumBalance:K?.required_minimum_balance??null,toast:i}))return;const V=typeof F.keywordsLimit=="number"&&Number.isFinite(F.keywordsLimit)?F.keywordsLimit:y,P=await Er(R,F.forceSyncKeywords,V,!1,!0,!!F.includeSelf),A=P?.task_id?String(P.task_id):"";if(A){await N.startTask({taskId:A,etaText:"2-5 min"});return}await o(),i({title:"Sync started",description:"Competitors ranked keywords sync triggered."})}catch(H){console.error("❌ Failed to sync competitors ranked keywords:",H),i({title:"Error",description:H?.message||"Failed to sync competitors ranked keywords"})}},[f,o,y,N,i]),D=async()=>{if(l.length!==0){m(!0);try{const F=await ds.upsertKeywordsBatch({keywords:l}),R=F.added_count||0,L=F.existing_count||0;i({title:"Keywords added successfully",description:`${R} added, ${L} already existed`}),c([]),n()}catch(F){console.error("❌ Failed to add keywords:",F),i({title:"Failed to add keywords",de
183scription:"Please try again later"})}finally{m(!1)}}};return r.useEffect(()=>{l.length>0&&p(!1)},[l.length]),s?e.jsx("div",{className:"flex items-center justify-center h-64",children:e.jsxs("div",{className:"flex items-center gap-2 text-slate-500",children:[e.jsx(kt,{size:18,className:"animate-spin"}),e.jsx("span",{children:"Loading keywords data..."})]})}):e.jsxs("div",{className:"h-full flex flex-col min-h-0 bg-white sm:bg-transparent px-4",children:[e.jsxs("div",{className:"hidden sm:flex items-center justify-between mb-3 sm:mb-4","data-onboarding":"keywords-gap-header",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("h2",{className:"text-lg font-semibold text-slate-900",children:u}),e.jsx("p",{className:"text-sm text-slate-500 mt-0.5",children:g})]}),e.jsxs("div",{className:"flex items-center gap-2 sm:gap-3 shrink-0",children:[e.jsx(uh,{competitorsRankedKeywordsCount:w,competitorsTrackedCount:_,competitors:(t?.details||[]).map(F=>({domain:F.competitor,lastSyncedAt:F.last_synced_at||null})),selfDomain:t?.domain?{domain:t.domain,lastSyncedAt:t?.last_synced_at||null}:null,rankedKeywordsLimit:y,onRankedKeywordsLimitChange:F=>{S(F)},onSyncCompetitorsRankedKeywords:k,isSyncing:N.isRunning}),E&&e.jsxs("div",{className:"hidden sm:flex items-center gap-2 text-xs text-slate-400",children:[e.jsx(ka,{size:12}),e.jsxs("span",{children:["Last refresh:"," ",new Date(E).toLocaleDateString("en-CA")]})]})]})]}),N.panel.phase!=="idle"&&e.jsx("div",{className:"mb-3 shrink-0",children:e.jsx(Mo,{state:N.panel})}),e.jsx("div",{className:"flex-1 min-h-0","data-onboarding":"keywords-gap-table",children:e.jsx(Gi,{competitors:t?.details||[],userDomain:t?.domain||"You",selectedKeywords:l,onSelectedKeywordsChange:c,showOpportunities:!0,showSelectionActions:!1,onRefresh:()=>{k({domains:(t?.details||[]).map(F=>F.competitor),forceSyncKeywords:!1,includeSelf:!0})},isRefreshing:N.isRunning})}),e.jsx("div",{className:"hidden sm:block",children:e.jsx("div",{className:"absolute bottom-3 left-1/2 -translate-x-1/2 z-50 animate-in slide-in-from-bottom-4 fade-in duration-200 max-w-[calc(100vw-2rem)]","data-onboarding":"keywords-gap-actions",children:e.jsxs("div",{className:"flex items-center gap-3 px-4 py-2.5 bg-white border border-slate-200 rounded-full shadow-lg",children:[e.jsx("span",{className:"text-sm text-slate-500 max-w-[260px] md:max-w-[420px] truncate",children:l.length>0?e.jsxs("span",{children:[e.jsx("span",{className:"font-medium text-slate-800",children:l.length})," ","selected"]}):e.jsx("span",{children:"Select keywords to continue"})}),e.jsx("div",{className:"w-px h-5 bg-slate-200"}),e.jsx("button",{onClick:D,disabled:l.length===0||d,className:`flex items-center gap-1.5 px-4 py-1.5 text-sm font-medium rounded-lg transition-colors ${l.length===0||d?"bg-slate-200 text-slate-400 cursor-not-allowed":"bg-slate-900 text-white hover:bg-slate-800"}`,children:d?"Adding...":"Add to Target Keywords"})]})})}),e.jsxs("div",{className:`sm:hidden fixed bottom-0 left-0 right-0 z-50 bg-white shadow-[0_-8px_30px_rgba(0,0,0,0.12)] rounded-t-2xl transition-transform duration-300 ease-out border-t border-gray-100 ${l.length>0?h?"translate-y-[calc(100%-24px)]":"translate-y-0":"translate-y-full"}`,children:[e.jsx("div",{className:"w-full h-8 flex items-center justify-center cursor-pointer active:opacity-70",onClick:()=>p(!h),children:e.jsx("div",{className:"w-10 h-1 bg-gray-200 rounded-full"})}),e.jsx("div",{className:"px-5 pb-8 pt-1",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"text-xs text-gray-500 font-medium uppercase tracking-wide",children:"Selected"}),e.jsxs("div",{className:"flex items-baseline gap-1",children:[e.jsx("span",{className:"text-2xl font-bold text-gray-900",children:l.length}),e.jsx("span",{className:"text-sm text-gray-500",children:"keywords"})]})]}),e.jsxs("div",{className:"flex gap-3",children:[e.jsx("button",{onClick:()=>c([]),className:"px-4 py-2.5 text-sm font-medium text-gray-600 bg-gray-100 rounded-xl hover:bg-gray-200 active:bg-gray-300 transition-colors",children:"Clear"}),e.jsxs("button",{onClick:D,disabled:d,className:"px-5 py-2.5 bg-blue-600 text-white text-sm font-semibold rounded-xl shadow-lg shadow-blue-200 active:scale-95 transition-all flex items-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed",children:[e.jsx("span",{className:"text-lg leading-none",children:"+"}),d?"Adding...":"Add to List"]})]})]})})]}),l.length>0&&h&&e.jsx("div",{className:"sm:hidden fixed bottom-6 left-0 right-0 flex justify-center pointer-events-none animate-bounce z-50",children:e.jsx("span",{className:"bg-black/70 text-white text-[10px] px-2 py-1 rounded-full backdrop-blur-sm shadow-md",children:"Tap handle to open"})})]})},sv=({data:t,selectedIds:s,onToggleSelect:a,onSelectAll:n,searchKeyword:o})=>{const[i,l]=r.useState(1),[c,d]=r.useState(20),[m,h]=r.useState("created_at"),[p,f]=r.useState("desc"),[b,y]=r.useState(!1),[x,u]=r.useState(50),g=r.useRef(null),w=50,[_,E]=r.useState({keyword:200,added:120}),[N,S]=r.useState(null);r.useEffect(()=>{const P=()=>y(window.innerWidth<640);return P(),window.addEventListener("resize",P),()=>window.removeEventListener("resize",P)},[]);const k=r.useCallback((P,A)=>{P.preventDefault(),P.stopPropagation();const C="touches"in P?P.touches[0].clientX:P.clientX,I=_[A]||100;S({column:A,startX:C,startWidth:I})},[_]);r.useEffect(()=>{if(!N)return;const P=C=>{const j=("touches"in C?C.touches[0].clientX:C.clientX)-N.startX,q=Math.max(60,Math.min(400,N.startWidth+j));E(T=>({...T,[N.column]:q}))},A=()=>{S(null)};return document.addEventListener("mousemove",P),document.addEventListener("mouseup",A),document.addEventListener("touchmove",P),document.addEventListener("touchend",A),()=>{document.removeEventListener("mousemove",P),document.removeEventListener("mouseup",A),document.removeEventListener("touchmove",P),document.removeEventListener("touchend",A)}},[N]);const D=P=>{m===P?f(p==="asc"?"desc":"asc"):(h(P),f("desc")),l(1)},F=r.useMemo(()=>[...t].sort((P,A)=>{let C,I;if(m==="created_at")C=new Date(P.created_at).getTime(),I=new Date(A.created_at).getTime();else if(m==="keyword")C=P.keyword.toLowerCase(),I=A.keyword.toLowerCase();else return 0;return C<I?p==="asc"?-1:1:C>I?p==="asc"?1:-1:0}),[t,m,p]),R=r.useMemo(()=>F.slice(0,x),[F,x]),L=x<F.length,$=r.useCallback(()=>
183{if(!b||!g.current||!L)return;const{scrollTop:P,scrollHeight:A,clientHeight:C}=g.current;A-P-C<200&&u(I=>Math.min(I+w,F.length))},[b,L,F.length]),H=F.slice((i-1)*c,i*c),K=Math.ceil(F.length/c),X=F.length>0&&s.size===F.length,V=R.length>0&&R.every(P=>s.has(P.id));return t.length===0?e.jsx("div",{className:"flex-1 min-h-0 h-full flex items-center justify-center",children:e.jsxs("div",{className:"py-8 text-center text-slate-500",children:[e.jsx(us,{className:"mx-auto mb-3 text-slate-300",size:32}),e.jsx("p",{className:"text-sm",children:"No target keywords yet"}),e.jsx("p",{className:"text-xs text-slate-400 mt-1",children:"Add keywords from Keywords Gap to start"})]})}):e.jsxs("div",{className:"sm:bg-white sm:rounded-xl sm:shadow-sm sm:border sm:border-gray-200 flex flex-col h-full min-h-0 overflow-hidden relative bg-white",children:[e.jsxs("div",{ref:g,onScroll:$,className:Lt("flex-1 min-h-0 overflow-auto custom-scrollbar relative pb-28 sm:pb-0 bg-white",N&&"select-none cursor-col-resize"),children:[e.jsxs("table",{className:"w-full border-collapse text-left min-w-max",style:{tableLayout:"fixed"},children:[e.jsx("thead",{className:"bg-gray-50 sticky top-0 z-30 text-xs font-semibold text-gray-500 uppercase tracking-wider shadow-[0_1px_2px_rgba(0,0,0,0.05)]",children:e.jsxs("tr",{children:[e.jsx("th",{className:"sticky left-0 top-0 bg-gray-50 w-[40px] min-w-[40px] px-2 py-2 border-r border-gray-200 border-b z-20",children:e.jsx("div",{className:"flex items-center justify-center",children:e.jsx(Kt,{checked:b?V:X?!0:s.size>0?"indeterminate":!1,onCheckedChange:n,"aria-label":"Select all"})})}),e.jsxs("th",{className:"sticky bg-gray-50 px-3 py-2 border-b border-gray-200 shadow-[4px_0_8px_-4px_rgba(0,0,0,0.1)] z-10 relative group/resize cursor-pointer hover:text-indigo-600",style:{left:40},onClick:()=>D("keyword"),children:[e.jsxs("div",{className:"flex items-center gap-1",children:["Keyword",m==="keyword"&&(p==="desc"?e.jsx(Ws,{size:12}):e.jsx(Is,{size:12}))]}),e.jsx("div",{className:"absolute right-0 top-0 bottom-0 w-1 cursor-col-resize hover:bg-blue-400 active:bg-blue-500 opacity-0 group-hover/resize:opacity-100 transition-opacity",onMouseDown:P=>{P.stopPropagation(),k(P,"keyword")},onTouchStart:P=>{P.stopPropagation(),k(P,"keyword")}})]}),e.jsxs("th",{className:"px-2 py-2 cursor-pointer hover:text-indigo-600 border-b border-gray-200 relative group/resize",style:{width:_.added,minWidth:_.added},onClick:()=>D("created_at"),children:[e.jsxs("div",{className:"flex items-center gap-1",children:["Added",m==="created_at"&&(p==="desc"?e.jsx(Ws,{size:12}):e.jsx(Is,{size:12}))]}),e.jsx("div",{className:"absolute right-0 top-0 bottom-0 w-1 cursor-col-resize hover:bg-blue-400 active:bg-blue-500 opacity-0 group-hover/resize:opacity-100 transition-opacity",onMouseDown:P=>{P.stopPropagation(),k(P,"added")},onTouchStart:P=>{P.stopPropagation(),k(P,"added")}})]})]})}),e.jsx("tbody",{className:"divide-y divide-gray-100 border-b border-gray-200",children:(b?R:H).map(P=>{const A=s.has(P.id);return e.jsxs("tr",{onClick:()=>b&&a(P.id),className:Lt("transition-colors group",A?"bg-blue-50/50":"bg-white hover:bg-gray-50/50",b&&"cursor-pointer active:bg-gray-50"),children:[e.jsx("td",{className:"sticky left-0 bg-white group-hover:bg-gray-50 w-[40px] min-w-[40px] px-2 py-2 border-r border-gray-100 z-10",style:{backgroundColor:A?"rgb(239 246 255 / 0.5)":void 0},onClick:C=>{C.stopPropagation(),a(P.id)},children:e.jsx("div",{className:"flex items-center justify-center",children:e.jsx(Kt,{checked:A,onCheckedChange:()=>a(P.id)})})}),e.jsx("td",{className:"sticky bg-white group-hover:bg-gray-50 px-3 py-2 shadow-[4px_0_8px_-4px_rgba(0,0,0,0.05)] border-r border-gray-100 z-10",style:{left:40,backgroundColor:A?"rgb(239 246 255 / 0.5)":void 0},children:e.jsx("div",{className:"font-medium text-sm sm:text-xs text-gray-900 truncate",children:P.keyword})}),e.jsx("td",{className:"px-2 py-2 text-sm sm:text-xs text-gray-600",style:{width:_.added,minWidth:_.added},children:new Date(P.created_at).toLocaleDateString()})]},P.id)})})]}),b&&L&&e.jsx("div",{className:"flex items-center justify-center py-4 text-gray-400",children:e.jsx("span",{className:"text-sm",children:"Scroll for more..."})}),b&&!L&&F.length>0&&e.jsxs("div",{className:"text-center py-4 text-gray-400 text-sm",children:[F.length," keywords total"]}),b&&e.jsx("div",{className:"h-20"})]}),!b&&e.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-t border-gray-200 bg-white shrink-0",children:[e.jsxs("div",{className:"text-sm text-gray-500",children:[F.length," results"]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("select",{value:c,onChange:P=>{d(Number(P.target.value)),l(1)},className:"px-2 py-1 text-sm border border-gray-200 rounded-md bg-white",children:[20,50,100].map(P=>e.jsx("option",{value:P,children:P},P))}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("button",{onClick:()=>l(P=>
183Math.max(1,P-1)),disabled:i===1,className:"px-2 py-1 text-sm text-gray-600 hover:bg-gray-100 rounded disabled:opacity-50 disabled:cursor-not-allowed",children:"‹"}),e.jsxs("span",{className:"px-2 text-sm text-gray-600",children:[i," / ",K||1]}),e.jsx("button",{onClick:()=>l(P=>Math.min(K,P+1)),disabled:i>=K,className:"px-2 py-1 text-sm text-gray-600 hover:bg-gray-100 rounded disabled:opacity-50 disabled:cursor-not-allowed",children:"›"})]})]})]})]})},xh=({selectedCount:t,onDelete:s,actionLabel:a,onAction:n,showDelete:o=!0,"data-onboarding":i})=>e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"sm:hidden fixed bottom-0 left-0 right-0 z-50 animate-in slide-in-from-bottom-4 fade-in duration-200",children:e.jsxs("div",{className:"flex items-center justify-between px-4 py-3 bg-white/95 backdrop-blur-lg border-t border-gray-200 shadow-[0_-4px_20px_rgba(0,0,0,0.08)]","data-onboarding":i,children:[e.jsx("div",{className:"flex items-center",children:t>0?e.jsxs("span",{className:"text-sm text-gray-600",children:[e.jsx("span",{className:"font-semibold text-gray-900",children:t}),e.jsx("span",{className:"ml-1 text-gray-500",children:"selected"})]}):e.jsx("span",{className:"text-sm text-gray-400",children:"Select keywords"})}),e.jsxs("div",{className:"flex items-center gap-3",children:[o&&t>0&&e.jsx("button",{onClick:s,className:"flex items-center justify-center w-10 h-10 text-red-500 bg-red-50 rounded-xl hover:bg-red-100 transition-colors",title:"Clear selection",children:e.jsx(es,{className:"w-5 h-5"})}),e.jsxs("button",{onClick:n,disabled:t===0,"data-onboarding-action":"primary",className:`flex items-center gap-2 px-5 py-2.5 text-sm font-semibold rounded-xl transition-all ${t===0?"bg-gray-100 text-gray-400 cursor-not-allowed":"bg-gray-900 text-white hover:bg-gray-800 active:scale-[0.98]"}`,children:[e.jsx($t,{className:"w-4 h-4"}),e.jsx("span",{children:"Add"})]})]})]})}),e.jsx("div",{className:"hidden sm:block absolute bottom-3 left-1/2 -translate-x-1/2 z-50 animate-in slide-in-from-bottom-4 fade-in duration-200 max-w-[calc(100vw-2rem)]",children:e.jsxs("div",{className:"flex items-center gap-3 px-4 py-2.5 bg-white border border-slate-200 rounded-full shadow-lg","data-onboarding":i,children:[e.jsx("span",{className:"text-sm text-slate-500 max-w-[260px] md:max-w-[420px] truncate",children:t>0?e.jsxs("span",{children:[e.jsx("span",{className:"font-medium text-slate-800",children:t})," selected"]}):e.jsx("span",{children:"Select keywords to continue"})}),e.jsx("div",{className:"w-px h-5 bg-slate-200"}),e.jsxs("button",{onClick:n,disabled:t===0,"data-onboarding-action":"primary",className:`flex items-center gap-1.5 px-4 py-1.5 text-sm font-medium rounded-lg transition-colors ${t===0?"bg-slate-200 text-slate-400 cursor-not-allowed":"bg-slate-900 text-white hover:bg-slate-800"}`,children:[e.jsx(is,{className:"w-3.5 h-3.5"}),e.jsx("span",{children:a})]}),o&&e.jsxs("button",{onClick:s,disabled:t===0,className:`flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium rounded-lg border transition-colors ${t===0?"border-slate-200 text-slate-300 cursor-not-allowed":"border-red-200 text-red-600 hover:bg-red-50"}`,children:[e.jsx(es,{className:"w-3.5 h-3.5"}),e.jsx("span",{children:"Delete"})]})]})})]}),av=({isOpen:t,onClose:s,onAdd:a})=>{const[n,o]=r.useState(""),[i,l]=r.useState(!1),c=async()=>{const m=n.split(`
184`).map(h=>h.trim()).filter(h=>h.length>0);if(m.length!==0){l(!0);try{await a(m),o(""),s()}finally{l(!1)}}};if(!t)return null;const d=n.split(`
185`).map(m=>m.trim()).filter(m=>m.length>0).length;return e.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[e.jsx("div",{className:"absolute inset-0 bg-black/50",onClick:s}),e.jsxs("div",{className:"relative bg-white rounded-xl shadow-xl max-w-lg w-full mx-4",children:[e.jsxs("div",{className:"flex items-center justify-between px-5 py-4 border-b border-slate-200",children:[e.jsx("h2",{className:"text-base font-semibold text-slate-800",children:"Add Keywords"}),e.jsx("button",{onClick:s,className:"p-1 text-slate-400 hover:text-slate-600",children:e.jsx(mt,{size:18})})]}),e.jsxs("div",{className:"p-5",children:[e.jsx("p",{className:"text-sm text-slate-600 mb-3",children:"Enter keywords to track, one per line:"}),e.jsx("textarea",{value:n,onChange:m=>o(m.target.value),placeholder:`keyword 1
186keyword 2
187keyword 3`,className:"w-full h-48 px-3 py-2 text-sm border border-slate-200 rounded-lg resize-none focus:outline-none focus:ring-2 focus:ring-slate-200",autoFocus:!0}),e.jsxs("p",{className:"text-xs text-slate-400 mt-2",children:[d," keyword",d!==1?"s":""," to add"]})]}),e.jsxs("div",{className:"flex items-center justify-end gap-2 px-5 py-3 border-t border-slate-200 bg-slate-50",children:[e.jsx("button",{onClick:s,className:"px-4 py-2 text-sm text-slate-600 hover:text-slate-800",children:"Cancel"}),e.jsxs("button",{onClick:c,disabled:d===0||i,className:`px-4 py-2 text-sm font-medium rounded-lg flex items-center gap-1.5 ${d===0||i?"bg-slate-200 text-slate-400 cursor-not-allowed":"bg-slate-900 text-white hover:bg-slate-800"}`,children:[i&&e.jsx(kt,{size:14,className:"animate-spin"}),i?"Adding...":`Add ${d} Keyword${d!==1?"s":""}`]})]})]})]})},nv=({groups:t,setGroups:s,unassignedKeywords:a,setUnassignedKeywords:n,handleAddGroup:o,handleRemoveGroup:i,handleRenameGroup:l,handleAssignKeyword:c,handleUnassignKeyword:d,handleConfirmManualGroups:m,creating:h})=>{const[p,f]=r.useState(new Set),[b,y]=r.useState(0),x=_=>{f(E=>{const N=new Set(E);return N.has(_)?N.delete(_):N.add(_),N})},u=()=>
187{f(new Set(a))},g=()=>{f(new Set)},w=()=>{if(p.size===0)return;const _=Array.from(p);n(a.filter(N=>!p.has(N)));const E=[...t];E[b].keywords.push(..._),s(E),f(new Set)};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex-1 overflow-hidden flex min-h-[400px]",children:[e.jsxs("div",{className:"w-2/5 border-r border-slate-200 flex flex-col",children:[e.jsxs("div",{className:"px-4 py-2 border-b border-slate-100 bg-slate-50 flex items-center justify-between",children:[e.jsxs("span",{className:"text-xs font-medium text-slate-500",children:["Unassigned (",a.length,")"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[p.size>0&&e.jsxs("span",{className:"text-xs text-slate-500",children:[p.size," selected"]}),e.jsx("button",{onClick:u,className:"text-[10px] text-slate-500 hover:text-slate-700",children:"All"}),e.jsx("button",{onClick:g,className:"text-[10px] text-slate-500 hover:text-slate-700",children:"Clear"})]})]}),e.jsxs("div",{className:"flex-1 overflow-auto p-2","data-onboarding":"manual-unassigned-keywords",children:[e.jsx("div",{className:"flex flex-wrap gap-1",children:a.map(_=>{const E=p.has(_);return e.jsx("button",{onClick:()=>x(_),className:`px-2 py-1 rounded text-xs transition-colors ${E?"bg-slate-800 text-white":"bg-slate-100 text-slate-700 hover:bg-slate-200"}`,children:_},_)})}),a.length===0&&e.jsx("div",{className:"text-xs text-slate-400 text-center py-8",children:"All keywords assigned"})]}),e.jsx("div",{className:"px-3 py-2 border-t border-slate-100 bg-slate-50",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("select",{value:b,onChange:_=>y(Number(_.target.value)),className:"flex-1 px-2 py-1.5 text-xs border border-slate-200 rounded bg-white",children:t.map((_,E)=>e.jsx("option",{value:E,children:_.name},E))}),e.jsxs("button",{onClick:w,disabled:p.size===0,className:`px-3 py-1.5 text-xs font-medium rounded transition-colors ${p.size===0?"bg-slate-200 text-slate-400 cursor-not-allowed":"bg-slate-800 text-white hover:bg-slate-700"}`,"data-onboarding":"manual-add-selected-btn",children:["Add ",p.size]})]})})]}),e.jsxs("div",{className:"flex-1 flex flex-col",children:[e.jsxs("div",{className:"px-4 py-2 border-b border-slate-100 bg-slate-50 flex items-center justify-between",children:[e.jsxs("span",{className:"text-xs font-medium text-slate-500",children:["Groups (",t.length,")"]}),e.jsx("button",{onClick:o,className:"flex items-center gap-1 text-xs text-slate-600 hover:text-slate-800","data-onboarding":"manual-add-group-btn",children:"Add Group"})]}),e.jsx("div",{className:"flex-1 overflow-auto p-3 space-y-3",children:t.map((_,E)=>e.jsxs("div",{className:`border rounded-lg transition-colors ${b===E?"border-slate-400 bg-slate-50/50":"border-slate-200"}`,children:[e.jsxs("div",{className:"flex items-center justify-between px-3 py-2 border-b border-slate-100 bg-slate-50 cursor-pointer",onClick:()=>y(E),children:[e.jsxs("div",{className:"flex items-center gap-2 flex-1",children:[e.jsx("div",{className:`w-2 h-2 rounded-full ${b===E?"bg-slate-800":"bg-slate-300"}`}),e.jsx("input",{type:"text",value:_.name,onChange:N=>l(E,N.target.value),onClick:N=>N.stopPropagation(),className:"text-xs font-medium text-slate-700 bg-transparent border-none outline-none flex-1","data-onboarding":b===E?"manual-group-name-input":void 0}),e.jsx("span",{className:"text-[10px] text-slate-400",children:_.keywords.length})]}),t.length>1&&e.jsx("button",{onClick:N=>{N.stopPropagation(),i(E)},className:"p-1 text-slate-400 hover:text-red-500",children:e.jsx(mt,{size:12})})]}),e.jsx("div",{className:"p-2 min-h-[50px]",children:_.keywords.length===0?e.jsx("div",{className:"text-xs text-slate-400 text-center py-2",children:b===E?"Select keywords and click Add":"Click to select this group"}):e.jsx("div",{className:"flex flex-wrap gap-1",children:_.keywords.map(N=>e.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-1 bg-slate-100 rounded text-xs text-slate-700",children:[N,e.jsx("button",{onClick:()=>d(N,E),className:"text-slate-400 hover:text-slate-600",children:e.jsx(mt,{size:10})})]},N))})})]},E))})]})]}),e.jsxs("div",{className:"flex items-center justify-between px-5 py-3 border-t border-slate-200 bg-slate-50 flex-shrink-0",children:[e.jsxs("span",{className:"text-xs text-slate-500",children:[t.filter(_=>_.keywords.length>0).length," group(s) with keywords"]}),e.jsxs("button",{onClick:m,disabled:t.every(_=>_.keywords.length===0)||h,className:`px-4 py-1.5 text-xs font-medium rounded flex items-center gap-1.5 ${t.every(_=>_.keywords.length===0)||h?"bg-slate-200 text-slate-400 cursor-not-allowed":"bg-slate-900 text-white hover:bg-slate-800"}`,"data-onboarding":"manual-create-groups-btn",children:[h&&e.jsx(kt,{size:12,className:"animate-spin"}),h?"Creating...":"Create Groups & Continue"]})]})]})}
187,hh=({isOpen:t,onClose:s,selectedCount:a,selectedKeywords:n,onGenerateForEach:o,onGroupAndGenerate:i,onManualGroup:l})=>{const{toast:c}=_t(),{confirm:d}=ia(),[m,h]=r.useState("main"),[p,f]=r.useState("ai"),[b,y]=r.useState([{name:"Group 1",keywords:[]}]),[x,u]=r.useState(n),[g,w]=r.useState(!1),[_,E]=r.useState(void 0),N=r.useRef(void 0),[S,k]=r.useState("content_generation_keywords_only"),[D,F]=r.useState(!0),[R,L]=r.useState(!1),$=v.useMemo(()=>{const T=(n||[]).filter(Z=>typeof Z=="string"&&Z.trim().length>0).length,M=(n||[]).reduce((Z,B)=>{const ae=(B||"").trim();return Z+ae.length},0);return{group_count:T,total_keywords:T,total_keyword_chars:M}},[n]),H=v.useRef(t);v.useEffect(()=>{t&&!H.current&&(h("main"),f("ai"),y([{name:"Group 1",keywords:[]}]),u(n),w(!1),E(void 0),N.current=void 0,k("content_generation_keywords_only"),F(!0),L(!1)),H.current=t},[t,n]);const K=Bc({isOpen:t,enabled:m==="single_step2"&&D,templateType:S,groupCount:$.group_count,totalKeywords:$.total_keywords,totalKeywordChars:$.total_keyword_chars}),X=ta({enabled:t&&m==="grouping"&&p==="ai"&&$.total_keywords>0,scenario:"keyword_group_ai_group_keywords",params:{keyword_count:$.total_keywords,total_keyword_chars:$.total_keyword_chars,model:"gemini-3-pro-preview"}}),V=async()=>{if(!D)return!0;if(R)return!1;L(!0);try{return await Ji({confirm:d,estimatedRange:K.estimatedRange,requiredMinimumBalance:K.requiredMinimumBalance,toast:c})}finally{L(!1)}};if(!t)return null;const P=()=>{y([...b,{name:`Group ${b.length+1}`,keywords:[]}])},A=T=>{const M=b[T];u([...x,...M.keywords]),y(b.filter((Z,B)=>B!==T))},C=(T,M)=>{const Z=[...b];Z[T].name=M,y(Z)},I=(T,M)=>{u(x.filter(B=>B!==T));const Z=[...b];Z[M].keywords.push(T),y(Z)},j=(T,M)=>{const Z=[...b];
187Z[M].keywords=Z[M].keywords.filter(B=>B!==T),y(Z),u([...x,T])},q=async()=>{const T=b.filter(M=>M.keywords.length>0);if(T.length!==0){w(!0);try{for(const M of T){const Z=await ds.createGroup({name:M.name,description:`Manual group with ${M.keywords.length} keywords`});await ds.addKeywordsToGroup({group_id:Z.id,keywords:M.keywords})}c({title:"Groups Created",description:`Created ${T.length} group(s) with ${T.reduce((M,Z)=>M+Z.keywords.length,0)} keywords`}),l(T.flatMap(M=>M.keywords),Va({rawContext:_??null}))}catch(M){c({title:"Failed to create groups",description:M?.message||"Please try again later"})}finally{w(!1)}}};if(m==="main")return e.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[e.jsx("div",{className:"absolute inset-0 bg-black/50",onClick:s}),e.jsxs("div",{className:"relative bg-white rounded-xl shadow-xl max-w-md w-full mx-4","data-onboarding":"generate-content-modal",children:[e.jsxs("div",{className:"flex items-center justify-between px-5 py-3 border-b border-slate-200",children:[e.jsx("h2",{className:"text-sm font-semibold text-slate-800",children:"Generate Content"}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("span",{className:"text-[11px] text-slate-500",children:[a," keywords"]}),e.jsx("button",{onClick:s,className:"p-1 rounded text-slate-400 hover:text-slate-600 hover:bg-slate-100 transition-colors",children:e.jsx(mt,{size:16})})]})]}),e.jsxs("div",{className:"p-4 space-y-2","data-onboarding":"generate-content-choice-options",children:[e.jsxs("button",{onClick:()=>h("single_step1"),className:"w-full p-4 text-left rounded-lg border border-slate-200 hover:border-slate-300 hover:bg-slate-50 transition-all group","data-onboarding":"generate-content-single-option",children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx("span",{className:"text-[13px] font-medium text-slate-800",children:"One article per keyword"}),e.jsx(Ms,{size:14,className:"text-slate-300 group-hover:text-slate-500 transition-colors"})]}),e.jsxs("p",{className:"text-[11px] text-slate-500",children:["Create ",a," separate articles, one for each keyword"]})]}),e.jsxs("button",{onClick:()=>h("grouping"),className:"w-full p-4 text-left rounded-lg border border-slate-200 hover:border-slate-300 hover:bg-slate-50 transition-all group","data-onboarding":"generate-content-group-option",children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx("span",{className:"text-[13px] font-medium text-slate-800",children:"Group keywords first"}),e.jsx(Ms,{size:14,className:"text-slate-300 group-hover:text-slate-500 transition-colors"})]}),e.jsx("p",{className:"text-[11px] text-slate-500",children:"Cluster related keywords into topic groups, then generate"})]})]})]})]});if(m==="single_step1")return e.jsx(Yi,{isOpen:!0,onClose:s,onCancel:()=>h("main"),cancelText:"Back",confirmText:"Continue",onConfirm:()=>h("single_step2"),value:_,onChange:T=>{N.current=T,E(T)}});if(m==="single_step2"){const T=Va({rawContext:N.current??_??null}),Z=`${Mr.find(ae=>ae.id===S)?.name||"Content generation"} - ${new Date().toLocaleDateString("en-US",{month:"short",day:"numeric"})}`,B=[];return T.company&&B.push("Company"),T.knowledges.enabled&&B.push(`Knowledge (${T.knowledges.scope_ids?T.knowledges.scope_ids.length:"all"})`),T.competitors.enabled&&B.push(`Competitors (${T.competitors.scope_domains?T.competitors.scope_domains.length:"all"})`),e.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[e.jsx("div",{className:"absolute inset-0 bg-black/30",onClick:s}),e.jsxs("div",{className:"relative bg-white rounded-lg shadow-lg max-w-2xl w-full mx-4","data-onboarding":"single-keyword-template-modal",children:[e.jsxs("div",{className:"px-5 py-4 border-b border-slate-100 flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("button",{onClick:()=>h("single_step1"),className:"p-1 text-slate-400 hover:text-slate-600 transition-colors",children:e.jsx(cn,{size:18})}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-[15px] font-medium text-slate-800",children:"Choose Template"}),e.jsxs("p",{className:"text-[11px] text-slate-400",children:[a," keywords"]})]})]}),e.jsx("button",{onClick:s,className:"text-slate-400 hover:text-slate-600",children:e.jsx(mt,{size:16})})]}),B.length>0&&e.jsxs("div",{className:"px-5 py-2 bg-slate-50 border-b border-slate-100 flex items-center gap-2",children:[e.jsx("span",{className:"text-[10px] text-slate-400",children:"Reference:"}),e.jsx("div",{className:"flex flex-wrap gap-1",children:B.map(ae=>e.jsx("span",{className:"px-2 py-0.5 bg-slate-200 text-slate-600 text-[10px] rounded-full",children:ae},ae))}),e.jsx("button",{onClick:()=>h("single_step1"),className:"text-[10px] text-slate-500 hover:text-slate-700 ml-auto",children:"Edit"})]}),e.jsxs("div",{className:"px-5 py-4 space-y-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[12px] font-medium text-slate-700 mb-3",children:"Choose a Template"}),e.jsx("div",{className:"grid grid-cols-3 gap-3","data-onboarding":"single-keyword-template-grid",children:Mr.map(ae=>{const de=S===ae.id;return e.jsxs("button",{onClick:()=>k(ae.id),className:`relative p-4 rounded-lg text-left transition-all border-2 ${de?"border-slate-900 bg-slate-50":"border-slate-200 bg-white hover:border-slate-300"}`,children:[de&&e.jsx("div",{className:"absolute top-2 right-2 w-5 h-5 bg-slate-900 rounded-full flex items-center justify-center",children:e.jsx(wt,{size:12,className:"text-white"})}),e.jsx("div",{className:"text-[12px] font-medium text-slate-800 pr-6",children:ae.name.replace("Content generation ","")}),e.jsx("div",{className:"text-[10px] text-slate-500 mt-1.5 leading-relaxed",children:ae.description})]},ae.id)})})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] text-slate-500 mb-1.5",children:"Worksheet Name"}),e.jsx("input",{type:"text",defaultValue:Z,className:"w-full px-3 py-2 border border-slate-200 rounded-lg text-[12px] focus:outline-none focus:border-slate-400"})]}),e.jsx("div",{"data-onboarding":"single-keyword-title-content-option",children:e.jsx(Oc,{checked:D,disabled:R,onCheckedChange:F,estimatingCredits:K.estimating,estimatedCreditsRange:K.estimatedRange,requiredMinimumBalance:K.requiredMinimumBalance})})]}),e.jsxs("div",{className:"px-5 py-4 border-t border-slate-100 flex justify-end gap-2",children:[e.jsx("button",{onClick:()=>h("single_step1"),className:"px-4 py-2 text-[12px] text-slate-500 hover:text-slate-700",children:"Back"}),e.jsx("button",{onClick:async()=>{await V()&&o(S,T,D)},disabled:R,className:"px-5 py-2 bg-slate-900 text-white text-[12px] font-medium rounded-lg hover:bg-slate-800 disabled:opacity-60 disabled:cursor-not-allowed","data-onboarding":"single-keyword-generate-btn",children:"Generate Content"})]})]})]})}return e.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[e.jsx("div",{className:"absolute inset-0 bg-black/50",onClick:s}),e.jsxs("div",{className:`relative bg-white rounded-xl shadow-xl w-full mx-4 flex flex-col ${p==="manual"?"max-w-4xl max-h-[80vh]":"max-w-3xl"}`,"data-onboarding":"grouping-modal",children:[e.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-slate-200 flex-shrink-0",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("button",{onClick:()=>h("main"),className:"p-1 text-slate-400 hover:text-slate-600 transition-colors",children:e.jsx(cn,{size:18})}),e.jsx("h2",{className:"text-base font-semibold text-slate-800",children:"Group Keywords"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("span",{className:"text-sm text-slate-500",children:[a," keywords"]}),e.jsx("button",{onClick:s,className:"p-1.5 rounded-lg text-slate-400 hover:text-slate-600 hover:bg-slate-100 transition-colors",children:e.jsx(mt,{size:18})})]})]}),e.jsxs("div",{className:"flex border-b border-slate-200 flex-shrink-0",children:[e.jsxs("button",{onClick:()=>f("ai"),className:`flex-1 px-6 py-3 text-sm font-medium transition-colors relative ${p==="ai"?"text-slate-800":"text-slate-500 hover:text-slate-700"}`,"data-onboarding":"grouping-tab-ai","data-active":p==="ai"?"true":"false",children:["AI Grouping",p==="ai"&&e.jsx("div",{className:"absolute bottom-0 left-0 right-0 h-0.5 bg-slate-800"})]}),e.jsxs("button",{onClick:()=>f("manual"),className:`flex-1 px-6 py-3 text-sm font-medium transition-colors relative ${p==="manual"?"text-slate-800":"text-slate-500 hover:text-slate-700"}`,"data-onboarding":"grouping-tab-manual","data-active":p==="manual"?"true":"false",children:["Manual",p==="manual"&&e.jsx("div",{className:"absolute bottom-0 left-0 right-0 h-0.5 bg-slate-800"})]})]}),p==="ai"?e.jsx("div",{className:"p-6",children:e.jsxs("div",{className:"text-center py-8",children:[e.jsxs("p",{className:"text-sm text-slate-600 mb-5",children:["Let AI automatically cluster your ",a," keywords into topic groups"]}),e.jsx("div",{className:"mb-4 flex justify-center",children:e.jsxs("div",{className:"inline-flex items-center gap-2 px-3 py-1.5 rounded-lg bg-amber-50 border border-amber-200 text-[12px] text-amber-800",children:[e.jsx(vs,{className:"w-4 h-4 text-amber-600"}),X.estimating?e.jsxs("span",{className:"font-medium flex items-center gap-2",children:[e.jsx(He,{className:"w-4 h-4 animate-spin"}),"Estimating..."]}):X.estimatedRange?e.jsxs("span",{className:"font-medium",children:["Est. ",X.estimatedRange.min,"–",X.estimatedRange.max," credits"]}):e.jsx("span",{className:"font-medium",children:"Estimate unavailable"})]})}),e.jsx("button",{onClick:()=>i("ai",S,Va({rawContext:N.current??_??null}),!1),className:"px-5 py-2.5 bg-slate-900 text-white text-sm font-medium rounded-lg hover:bg-slate-800 transition-colors","data-onboarding":"ai-grouping-button",children:"Start AI Grouping"})]})}):e.jsx(nv,{groups:b,setGroups:y,unassignedKeywords:x,setUnassignedKeywords:u,handleAddGroup:P,handleRemoveGroup:A,handleRenameGroup:C,handleAssignKeyword:I,handleUnassignKeyword:j,handleConfirmManualGroups:q,creating:g})]})]})},gl=t=>String(Math.max(0,Math.floor(t))).padStart(2,"0"),rv=t=>{const s=Math.max(0,Math.floor(t)),a=Math.floor(s/3600),n=Math.floor(s%3600/60),o=s%60;return a>0?`${a}:${gl(n)}:${gl(o)}`:`${n}:${gl(o)}`},ph=({taskId:t,onComplete:s,onDismiss:a})=>{const[n,o]=r.useState(null),[i,l]=r.useState(!0),[c,d]=r.useState(null),[m,h]=r.useState(()=>Date.now()),[p,f]=r.useState(()=>Date.now()),b=v.useRef(!1);r.useEffect(()=>
187{h(Date.now()),f(Date.now()),b.current=!1},[t]),r.useEffect(()=>{let $=!0,H=null,K=!0,X=null;const V=async()=>{if(!(!$||!K))try{const P=await ds.getAIGroupTaskStatus({task_id:t});if(!$||!K)return;if(o(P),l(!1),d(null),P.status==="done"||P.status==="error"){K=!1,H&&(clearInterval(H),H=null),P.status==="done"&&s&&!b.current?(b.current=!0,X=setTimeout(()=>{$&&s&&(console.log("✅ Calling onComplete with result:",P),s(t,P))},1e3)):P.status==="error"&&s&&!b.current&&(b.current=!0,console.log("❌ Calling onComplete with error:",P),s(t,P));return}}catch(P){if(!$||!K)return;d(P.message||"Failed to fetch task status"),l(!1)}};return V(),K&&(H=setInterval(()=>{K&&V()},2e3)),()=>{$=!1,K=!1,H&&(clearInterval(H),H=null),X&&(clearTimeout(X),X=null)}},[t,s]),r.useEffect(()=>{if(n?.status==="processing"||i){const $=window.setInterval(()=>f(Date.now()),1e3);return()=>window.clearInterval($)}},[n?.status,i]);const y=()=>{a&&a(t)},x=(p-m)/1e3,u=rv(x),g=n?n.progress:0,w=n?n.total:0,_=w>0?Math.round(g/w*100):0,E=i?"processing":n?.status==="done"?"completed":n?.status==="error"?"error":"processing",N=3e4,S=Math.max(0,p-m),k=E==="processing"?Math.min(99,Math.max(1,Math.floor(S/N*99))):0,D=E==="completed"?100:E==="processing"?Math.min(99,Math.max(_,k)):_,F=E==="processing"?e.jsx(kt,{className:"w-4 h-4 text-slate-500 animate-spin"}):E==="completed"?e.jsx(Rs,{className:"w-4 h-4 text-emerald-600"}):e.jsx(Ja,{className:"w-4 h-4 text-amber-600"}),R=E==="processing"?"Grouping keywords in background":E==="completed"?"Grouping completed":"Grouping failed",L=n?.message||n?.current_step||(i?"Starting...":" ");return e.jsx("div",{className:"w-full bg-white border border-slate-200 rounded-lg px-3 py-2 shadow-sm",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-[170px] flex-1",children:[F,e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"text-[11px] font-semibold text-slate-800 truncate",children:R}),e.jsx("div",{className:"text-[10px] text-slate-500 truncate",children:c||L})]})]}),e.jsx("div",{className:"flex-1 min-w-[160px]",children:e.jsx("div",{className:"w-full bg-slate-200 rounded-full h-2 overflow-hidden",children:e.jsx("div",{className:"h-full bg-blue-600 transition-all duration-300 ease-out rounded-full",style:{width:`${D}%`}})})}),e.jsxs("div",{className:"flex items-center gap-3 text-[10px] text-slate-500 flex-shrink-0",children:[E!=="processing"&&w>0&&e.jsxs("span",{className:"whitespace-nowrap",children:[g,"/",w," (",D,"%)"]}),E==="processing"&&e.jsxs("span",{className:"whitespace-nowrap",children:[D,"%"]}),e.jsxs("span",{className:"flex items-center gap-1 whitespace-nowrap",children:[e.jsx(Ra,{className:"w-3.5 h-3.5 text-slate-400"}),u]}),a&&e.jsx("button",{onClick:y,className:"p-0.5 hover:bg-slate-100 rounded transition-colors","aria-label":"Dismiss",children:e.jsx(mt,{className:"w-3.5 h-3.5 text-slate-400"})})]})]})})};function Yl(t){switch(t){case"creating_campaign":return"Creating worksheet...";case"creating_rows":return"Creating rows...";case"generating_title":return"Generating titles...";case"generating_content":return"Generating content...";case"completed":return"Completed.";default:return"Working..."}}function gh(){const[t,s]=r.useState({isRunning:!1,step:null,message:""}),a=r.useRef(!0);r.useEffect(()=>(a.current=!0,()=>{a.current=!1}),[]);const n=r.useCallback(d=>{a.current&&s(d)},[]),o=r.useCallback(d=>{n(()=>({isRunning:!0,step:"creating_campaign",message:d?.trim()||"Creating worksheet..."}))},[n]),i=r.useCallback(()=>{n(()=>({isRunning:!1,step:null,message:""}))},[n]),l=r.useCallback((d,m)=>{n(h=>({...h,isRunning:!0,step:d,message:(m?.trim()||Yl(d)).trim()}))},[n]),c=r.useMemo(()=>(t.message||Yl(t.step)).trim(),[t.message,t.step]);return{isRunning:t.isRunning,step:t.step,message:c,begin:o,end:i,onProgress:l}}const ov=({onNavigateToGroups:t,targetKeywords:s,loading:a,searchKeyword:n,onSearchChange:o,onRefresh:i,onGroupKeywords:l})=>{const{toast:c}=_t(),{confirm:d}=ia(),m=gh(),[h,p]=r.useState(new Set),[f,b]=r.useState(!1),[y,x]=r.useState(!1),[u,g]=r.useState(!1),[w,_]=r.useState(!1),[E,N]=r.useState(null),[S,k]=r.useState(!1),[D,F]=r.useState(!0);r.useEffect(()=>{const I=T=>{k(T.detail)},j=()=>{i()},q=()=>{x(!0)};return window.addEventListener("mobile-filter-toggle",I),window.addEventListener("mobile-refresh-click",j),window.addEventListener("mobile-add-click",q),()=>{window.removeEventListener("mobile-filter-toggle",I),window.removeEventListener("mobile-refresh-click",j),window.removeEventListener("mobile-add-click",q)}},[i]),r.useEffect(()=>{h.size>0&&F(!1)},[h.size]);const R=async I=>{try{const j=await ds.upsertKeywordsBatch({keywords:I});c({title:"Keywords added",description:`${j.added_count} added, ${j.existing_count} already existed`}),i()}catch(j){throw console.error("❌ Failed to add keywords:",j),c({title:"Failed to add keywords",de
187scription:"Please try again later"}),j}},L=I=>{p(j=>{const q=new Set(j);return q.has(I)?q.delete(I):q.add(I),q})},$=()=>{h.size===s.length?p(new Set):p(new Set(s.map(I=>I.id)))},H=I=>{const j=Mr.find(Z=>Z.id===I)?.name||"Content generation",q=new Date,T=q.toLocaleString("en-US",{month:"short"}),M=q.getDate();return`${j} - ${T} ${M}`},K=async(I,j,q)=>{const T=s.filter(M=>h.has(M.id)).map(M=>M.keyword);if(T.length===0){c({title:"No keywords selected",description:"Please select keywords to generate content"});return}b(!1),_(!0),m.begin("Creating worksheet...");try{const M=H(I),Z=T.map((ae,de)=>({id:`kw-${de+1}`,name:ae,keywords:[{keyword:ae}]})),B=await cr.createWorksheetAndGenerateFromGroups({source:{kind:"content_generation_template",templateType:I},campaignSource:"keywords_research",campaignName:M,groups:Z,options:{generateTitleAndContent:q,titlePollingTimeoutMs:12e4,titlePollingIntervalMs:2e3,context:j,onProgress:m.onProgress}});try{localStorage.setItem("flowwriter.currentCampaign",JSON.stringify({id:B.campaignId,name:M}))}catch{}c({title:"✅ Worksheet created",description:q?"Keywords filled. Title & content generation started.":"Keywords filled. You can run generation from the table."}),p(new Set),jt("table-new",{campaign:B.campaignId,view:B.viewId})}catch(M){console.error("❌ Failed to create worksheet and generate:",M),c({title:"Create & generate failed",description:M?.message||"Please try again."})}finally{_(!1),m.end()}},X=async(I,j,q,T)=>{const M=s.filter(Z=>h.has(Z.id)).map(Z=>Z.keyword);if(M.length===0){c({title:"No keywords selected",description:"Please select keywords to group"});return}b(!1);try{const Z=await l(M,I);if(Z&&typeof Z=="object"&&"isAsync"in Z&&Z.isAsync){N(Z.taskId),_(!0);return}const B=Z;if(!B||B.length===0)throw new Error("No groups were created.");await V(B,j,q,T)}catch(Z){console.error("❌ Failed to group keywords:",Z),c({title:"Create & generate failed",description:Z?.message||"Please try again later"}),_(!1)}},V=async(I,j,q,T)=>{_(!0),m.begin("Creating worksheet...");try{const Z=(await Promise.all(I.map(de=>ds.getGroupDetail({group_id:de.id})))).map(de=>({id:de.id,name:de.name,keywords:(de.keywords||[]).map(fe=>({keyword:fe.keyword}))})),B=H(j),ae=await cr.createWorksheetAndGenerateFromGroups({source:{kind:"content_generation_template",templateType:j},campaignName:B,groups:Z,options:{generateTitleAndContent:T,titlePollingTimeoutMs:12e4,titlePollingIntervalMs:2e3,context:q,onProgress:m.onProgress}});try{localStorage.setItem("flowwriter.currentCampaign",JSON.stringify({id:ae.campaignId,name:B}))}catch{}c({title:"✅ Worksheet created",description:T?"Groups filled. Title & content generation started.":"Groups filled. You can run generation from the table."}),p(new Set),jt("table-new",{campaign:ae.campaignId,view:ae.viewId})}catch(M){console.error("❌ Failed to create worksheet:",M),c({title:"Create & generate failed",description:M?.message||"Please try again later"})}finally{_(!1),m.end()}},P=v.useCallback(async(I,j)=>{if(j.status==="done"){const q=j.all_groups||j.groups_created||[],T=q.length>0,M=j.keywords_added||0,Z=j.groups_created_count||0,B=j.groups_updated_count||0;let ae="✅ AI Groups Processed",de="";if(Z>0&&B>0?de=`Created ${Z} groups and updated ${B} groups${M>0?` with ${M} keywords`:""}`:Z>
1870?de=`Created ${Z} groups${M>0?` with ${M} keywords`:""}`:B>0?de=`Updated ${B} groups${M>0?` with ${M} keywords`:""}`:M>0?de=`Processed ${M} keywords`:de="Grouping completed",c({title:ae,description:de}),i(),T){const fe=q.map(se=>se.id);try{sessionStorage.setItem("ai_group_selected_ids",JSON.stringify(fe))}catch(se){console.warn("⚠️ Failed to store group IDs in sessionStorage:",se)}}else try{sessionStorage.removeItem("ai_group_selected_ids")}catch{}setTimeout(()=>{N(null),_(!1),console.log("🚀 Navigating to keywords_group page"),t()},1500)}else j.status==="error"&&(c({title:"Failed to create AI groups",description:j.error||"Please try again later"}),N(null),_(!1))},[c,i,t]),A=()=>{N(null),_(!1)},C=async()=>{if(h.size===0||u)return;const I=h.size;if(await d({title:"Delete keywords",message:`You are about to delete ${I} keyword(s). This action cannot be undone.`,confirmText:"Delete",cancelText:"Cancel",variant:"danger"})){g(!0);try{const q=Array.from(h),T=await ds.batchDeleteKeywords({keyword_ids:q});p(new Set),c({title:"Keywords deleted",description:`Deleted ${T.deleted_count} keyword(s), failed ${T.failed_count}`}),i()}catch(q){console.error("❌ Failed to delete keywords:",q),c({title:"Failed to delete keywords",description:"Please try again later"})}finally{g(!1)}}};return u?e.jsx("div",{className:"flex items-center justify-center h-64",children:e.jsxs("div",{className:"flex items-center gap-2 text-slate-500",children:[e.jsx(kt,{size:18,className:"animate-spin"}),e.jsx("span",{children:"Deleting keywords..."})]})}):e.jsxs("div",{className:"h-full flex flex-col min-h-0 bg-white sm:bg-transparent px-4",children:[e.jsx(Do,{visible:m.isRunning,message:m.message,fixed:!0,zIndex:9999}),e.jsxs("div",{className:"hidden sm:flex items-center justify-between mb-4","data-onboarding":"target-keywords-header",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("h2",{className:"text-lg font-semibold text-slate-900",children:"Target Keywords"}),e.jsx("p",{className:"text-sm text-slate-500 mt-0.5",children:"Keywords you've collected and want to create content for."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(be,{size:"sm",onClick:()=>x(!0),children:[e.jsx($t,{size:14,className:"mr-1"}),"Add Keywords"]}),e.jsxs(be,{variant:"outline",size:"sm",onClick:i,disabled:u,className:"text-slate-500 hover:text-slate-700 bg-white",children:[e.jsx(kt,{size:14,className:"mr-1"}),"Refresh"]})]})]}),e.jsx("div",{className:Lt("sm:hidden overflow-hidden transition-all duration-300 ease-in-out bg-gray-50",S?"max-h-20 opacity-100 border-b border-gray-200":"max-h-0 opacity-0"),children:e.jsx("div",{className:"p-4",children:e.jsxs("div",{className:"relative",children:[e.jsx(Pt,{className:"absolute left-3 top-2.5 w-4 h-4 text-gray-400"}),e.jsx("input",{type:"text",placeholder:"Search keywords...",className:"w-full pl-9 pr-4 py-2 bg-white border border-gray-200 rounded-lg text-sm focus:outline-none focus:border-blue-500 focus:ring-1 focus:ring-blue-500",value:n||"",onChange:I=>o?.(I.target.value)})]})})}),o&&e.jsx("div",{className:"hidden sm:block mb-4 max-w-[400px]",children:e.jsxs("div",{className:"relative",children:[e.jsx(Pt,{className:"absolute left-3 top-1/2 -translate-y-1/2 text-slate-400",size:16}),e.jsx(bt,{placeholder:"Search keywords...",className:"pl-9 bg-white border-slate-200",value:n||"",onChange:I=>o(I.target.value)})]})}),E&&e.jsx("div",{className:"mb-4",children:e.jsx(ph,{taskId:E,onComplete:P,onDismiss:A})}),e.jsxs("div",{className:"flex-1 min-h-0 relative","data-onboarding":"target-keywords-table",children:[a&&e.jsx("div",{className:"absolute inset-0 z-10 flex items-center justify-center bg-white/50 backdrop-blur-[1px]",children:e.jsxs("div",{className:"flex items-center gap-2 text-slate-500",children:[e.jsx(kt,{size:18,className:"animate-spin"}),e.jsx("span",{children:"Loading target keywords..."})]})}),e.jsx(sv,{data:s,selectedIds:h,onToggleSelect:L,onSelectAll:$,searchKeyword:n})]}),e.jsx("div",{className:"hidden sm:block",children:e.jsx(xh,{selectedCount:h.size,onDelete:C,actionLabel:"Generate Content",onAction:()=>b(!0),"data-onboarding":"target-keywords-actions"})}),e.jsxs("div",{className:`sm:hidden fixed bottom-0 left-0 right-0 z-50 bg-white shadow-[0_-8px_30px_rgba(0,0,0,0.12)] rounded-t-2xl transition-transform duration-300 ease-out border-t border-gray-100 ${h.size>0?D?"translate-y-[calc(100%-24px)]":"translate-y-0":"translate-y-full"}`,children:[e.jsx("div",{className:"w-full h-8 flex items-center justify-center cursor-pointer active:opacity-70",onClick:()=>F(!D),children:e.jsx("div",{className:"w-10 h-1 bg-gray-200 rounded-full"})}),e.jsx("div",{className:"px-5 pb-8 pt-1",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"text-xs text-gray-500 font-medium uppercase tracking-wide",children:"Selected"}),e.jsxs("div",{className:"flex items-baseline gap-1",children:[e.jsx("span",{className:"text-2xl font-bold text-gray-900",children:h.size}),e.jsx("span",{className:"text-sm text-gray-500",children:"keywords"})]})]}),e.jsxs("div",{className:"flex gap-3",children:[e.jsx("button",{onClick:()=>p(new Set),className:"px-4 py-2.5 text-sm font-medium text-gray-600 bg-gray-100 rounded-xl hover:bg-gray-200 active:bg-gray-300 transition-colors",children:"Clear"}),e.jsxs("button",{onClick:()=>b(!0),className:"px-5 py-2.5 bg-blue-600 text-white text-sm font-semibold rounded-xl shadow-lg shadow-blue-200 active:scale-95 transition-all flex items-center gap-2",children:[e.jsx("span",{className:"text-lg leading-none",children:"+"}),"Generate"]})]})]})})]}),h.size>0&&D&&e.jsx("div",{className:"sm:hidden fixed bottom-6 left-0 right-0 flex justify-center pointer-events-none animate-bounce z-50",children:e.jsx("span",{className:"bg-black/70 text-white text-[10px] px-2 py-1 rounded-full backdrop-blur-sm shadow-md",children:"Tap handle to open"})}),e.jsx(hh,{isOpen:f,onClose:()=>b(!1),selectedCount:h.size,selectedKeywords:s.filter(I=>h.has(I.id)).map(I=>I.keyword),onGenerateForEach:K,onGroupAndGenerate:X,onManualGroup:async(I,j)=>{b(!1),p(new Set),t()}}),e.jsx(av,{isOpen:y,onClose:()=>x(!1),onAdd:R})]})};function iv(t){return t.trim().toLowerCase()}function lv(t,s,a){const n=s.id?.trim();if(n)return`${t}:${n}`;const o=s.keyword?.trim();return o?`${t}:kw:${iv(o)}:${a}`:`${t}:kw:empty:${a}`}const cv=({data:t,selectedIds:s,onToggleSelect:a,onSelectAll:n,onAddKeyword:o,onRemoveKeyword:i,pagination:l})=>{const[c,d]=r.useState(!1),[m,h]=r.useState(50),p=r.useRef(null),f=50,[b,y]=r.useState({groupName:180,keywords:300}),[x,u]=r.useState(null);r.useEffect(()=>{const D=()=>d(window.innerWidth<640);return D(),window.addEventListener("resize",D),()=>window.removeEventListener("resize",D)},[]);const g=r.useCallback((D,F)=>{D.preventDefault(),D.stopPropagation();const R="touches"in D?D.touches[0].clientX:D.clientX,L=b[F]||100;u({column:F,startX:R,startWidth:L})},[b]);r.useEffect(()=>{if(!x)return;const D=R=>{const $=("touches"in R?R.touches[0].clientX:R.clientX)-x.startX,H=Math.max(80,Math.min(500,x.startWidth+$));y(K=>({...K,[x.column]:H}))},F=()=>{u(null)};return document.addEventListener("mousemove",D),document.addEventListener("mouseup",F),document.addEventListener("touchmove",D),document.addEventListener("touchend",F),()=>{document.removeEventListener("mousemove",D),document.removeEventListener("mouseup",F),document.removeEventListener("touchmove",D),document.removeEventListener("touchend",F)}},[x]);const w=r.useMemo(()=>t.slice(0,m),[t,m]),_=m<t.length,E=r.useCallback(()=>
187{if(!c||!p.current||!_)return;const{scrollTop:D,scrollHeight:F,clientHeight:R}=p.current;F-D-R<200&&h(L=>Math.min(L+f,t.length))},[c,_,t.length]),N=t.length>0&&t.every(D=>s.has(D.id)),S=w.length>0&&w.every(D=>s.has(D.id)),k=Math.ceil(l.total/l.pageSize);return t.length===0?e.jsx("div",{className:"flex-1 min-h-0 h-full flex items-center justify-center",children:e.jsxs("div",{className:"py-8 text-center text-slate-500",children:[e.jsx(qa,{className:"mx-auto mb-3 text-slate-300",size:32}),e.jsx("p",{className:"text-sm",children:"No keyword groups yet"}),e.jsx("p",{className:"text-xs text-slate-400 mt-1",children:"Group keywords from Target Keywords to start"})]})}):e.jsxs("div",{className:"sm:bg-white sm:rounded-xl sm:shadow-sm sm:border sm:border-gray-200 flex flex-col h-full min-h-0 overflow-hidden relative bg-white",children:[e.jsxs("div",{ref:p,onScroll:E,className:Lt("flex-1 min-h-0 overflow-auto custom-scrollbar relative pb-28 sm:pb-0 bg-white",x&&"select-none cursor-col-resize"),children:[e.jsxs("table",{className:"w-full border-collapse text-left min-w-max",style:{tableLayout:"fixed"},children:[e.jsx("thead",{className:"bg-gray-50 sticky top-0 z-30 text-xs font-semibold text-gray-500 uppercase tracking-wider shadow-[0_1px_2px_rgba(0,0,0,0.05)]",children:e.jsxs("tr",{children:[e.jsx("th",{className:"sticky left-0 top-0 bg-gray-50 w-[40px] min-w-[40px] px-2 py-2 border-r border-gray-200 border-b z-20",children:e.jsx("div",{className:"flex items-center justify-center",children:e.jsx(Kt,{checked:c?S:N?!0:s.size>0?"indeterminate":!1,onCheckedChange:n,"aria-label":"Select all"})})}),e.jsxs("th",{className:"sticky bg-gray-50 px-3 py-2 border-b border-gray-200 shadow-[4px_0_8px_-4px_rgba(0,0,0,0.1)] z-10 relative group/resize",style:{left:40,width:b.groupName,minWidth:b.groupName},children:["Group Name",e.jsx("div",{className:"absolute right-0 top-0 bottom-0 w-1 cursor-col-resize hover:bg-blue-400 active:bg-blue-500 opacity-0 group-hover/resize:opacity-100 transition-opacity",onMouseDown:D=>g(D,"groupName"),onTouchStart:D=>g(D,"groupName")})]}),e.jsxs("th",{className:"px-2 py-2 border-b border-gray-200 relative group/resize",children:["Keywords",e.jsx("div",{className:"absolute right-0 top-0 bottom-0 w-1 cursor-col-resize hover:bg-blue-400 active:bg-blue-500 opacity-0 group-hover/resize:opacity-100 transition-opacity",onMouseDown:D=>g(D,"keywords"),onTouchStart:D=>g(D,"keywords")})]}),e.jsx("th",{className:"w-[50px] min-w-[50px] px-2 py-2 border-b border-gray-200"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-100 border-b border-gray-200",children:(c?w:t).map(D=>{const F=s.has(D.id),R=D.keywords||[];return e.jsxs("tr",{onClick:()=>c&&a(D.id),className:Lt("transition-colors group",F?"bg-blue-50/50":"bg-white hover:bg-gray-50/50",c&&"cursor-pointer active:bg-gray-50"),children:[e.jsx("td",{className:"sticky left-0 bg-white group-hover:bg-gray-50 w-[40px] min-w-[40px] px-2 py-2 border-r border-gray-100 z-10",style:{backgroundColor:F?"rgb(239 246 255 / 0.5)":void 0},onClick:L=>{L.stopPropagation(),a(D.id)},children:e.jsx("div",{className:"flex items-center justify-center",children:e.jsx(Kt,{checked:F,onCheckedChange:()=>a(D.id)})})}),e.jsx("td",{className:"sticky bg-white group-hover:bg-gray-50 px-3 py-2 shadow-[4px_0_8px_-4px_rgba(0,0,0,0.05)] border-r border-gray-100 z-10",style:{left:40,backgroundColor:F?"rgb(239 246 255 / 0.5)":void 0,width:b.groupName,minWidth:b.groupName,maxWidth:b.groupName},children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(qa,{size:14,className:"text-slate-400 flex-shrink-0"}),e.jsx("span",{className:"font-medium text-sm sm:text-xs text-gray-900 truncate",children:D.name})]})}),e.jsx("td",{className:"px-2 py-2",children:R.length===0?e.jsx("p",{className:"text-xs text-slate-400 italic",children:"No keywords"}):e.jsx("div",{className:"flex flex-wrap gap-1.5",children:R.map((L,$)=>e.jsxs("div",{className:"inline-flex items-center gap-1 px-2 py-0.5 bg-slate-100 border border-slate-200 rounded text-xs text-slate-700 group/chip",onClick:H=>H.stopPropagation(),children:[e.jsx("span",{children:L.keyword}),e.jsx("button",{onClick:H=>{H.stopPropagation(),i(D.id,L.keyword)},className:"p-0.5 rounded opacity-0 group-hover/chip:opacity-100 hover:bg-slate-200 text-slate-400 hover:text-red-500 transition-opacity",title:"Remove keyword",children:e.jsx(mt,{size:10})})]},lv(D.id,L,$)))})}),e.jsx("td",{className:"px-2 py-2",onClick:L=>L.stopPropagation(),children:e.jsx("button",{onClick:()=>o(D.id),className:"p-1 rounded hover:bg-slate-100 text-slate-400 hover:text-slate-600",title:"Add keywords",children:e.jsx($t,{size:14})})})]},D.id)})})]}),c&&_&&e.jsx("div",{className:"flex items-center justify-center py-4 text-gray-400",children:e.jsx("span",{className:"text-sm",children:"Scroll for more..."})}),c&&!_&&t.length>0&&e.jsxs("div",{className:"text-center py-4 text-gray-400 text-sm",children:[l.total," groups total"]}),c&&e.jsx("div",{className:"h-20"})]}),!c&&e.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-t border-gray-200 bg-white shrink-0",children:[e.jsxs("div",{className:"text-sm text-gray-500",children:[l.total," results"]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("select",{value:l.pageSize,onChange:D=>l.onPageSizeChange(Number(D.target.value)),className:"px-2 py-1 text-sm border border-gray-200 rounded-md bg-white",children:[20,50,100].map(D=>e.jsx("option",{value:D,children:D},D))}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("button",{onClick:()=>l.onPageChange(Math.max(1,l.currentPage-1)),disabled:l.currentPage===1,className:"px-2 py-1 text-sm text-gray-600 hover:bg-gray-100 rounded disabled:opacity-50 disabled:cursor-not-allowed",children:"‹"}),e.jsxs("span",{className:"px-2 text-sm text-gray-600",children:[l.currentPage," / ",k||1]}),e.jsx("button",{onClick:()=>l.onPageChange(Math.min(k,l.currentPage+1)),disabled:l.currentPage>=k,className:"px-2 py-1 text-sm text-gray-600 hover:bg-gray-100 rounded disabled:opacity-50 disabled:cursor-not-allowed",children:"›"})]})]})]})]})},dv=({isOpen:t,groupId:s,groupName:a,onClose:n,onAdd:o})=>{const[i,l]=r.useState("");
187if(!t)return null;const c=()=>{const d=i.split(/[\n,]/).map(m=>m.trim()).filter(m=>m.length>0);d.length>0&&(o(s,d),l(""),n())};return e.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[e.jsx("div",{className:"absolute inset-0 bg-black/30",onClick:n}),e.jsxs("div",{className:"relative bg-white rounded-lg shadow-xl w-full max-w-md p-5",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsxs("h3",{className:"text-base font-semibold text-slate-800",children:['Add Keywords to "',a,'"']}),e.jsx("button",{onClick:n,className:"text-slate-400 hover:text-slate-600",children:e.jsx(mt,{size:18})})]}),e.jsx("textarea",{value:i,onChange:d=>l(d.target.value),placeholder:"Enter keywords, one per line or comma-separated",className:"w-full h-32 px-3 py-2 border border-slate-200 rounded-lg text-sm resize-none focus:outline-none focus:ring-2 focus:ring-blue-500",autoFocus:!0}),e.jsxs("div",{className:"flex justify-end gap-2 mt-4",children:[e.jsx(be,{variant:"ghost",size:"sm",onClick:n,children:"Cancel"}),e.jsx(be,{size:"sm",onClick:c,disabled:i.trim().length===0,className:"bg-slate-900 hover:bg-slate-800 text-white",children:"Add Keywords"})]})]})]})},mv=({isOpen:t,onClose:s,onConfirm:a,selectedCount:n,totalKeywords:o,totalKeywordChars:i,itemType:l="groups"})=>{const{toast:c}=_t(),{confirm:d}=ia(),[m,h]=r.useState(1),[p,f]=r.useState(void 0),b=r.useRef(void 0),[y,x]=r.useState(Xr[0]?.id||""),[u,g]=r.useState(!0),[w,_]=r.useState(!1);v.useEffect(()=>{t&&(h(1),x(Xr[0]?.id||""),f(void 0),b.current=void 0,g(!0),_(!1))},[t]);const E=v.useMemo(()=>Va({rawContext:b.current??p??null}),[p]),N=v.useMemo(()=>{const D=[];if(E.company&&D.push("Company"),E.knowledges.enabled){const F=E.knowledges.scope_ids?.length;D.push(F?`${F} Knowledge Base${F>1?"s":""}`:"Knowledge")}if(E.competitors.enabled){const F=E.competitors.scope_domains?.length;D.push(F?`${F} Competitor${F>1?"s":""}`:"Competitors")}return D},[E]),S=Bc({isOpen:t,enabled:m===2&&u,templateType:y,groupCount:n,totalKeywords:o,totalKeywordChars:i});if(!t)return null;if(m===1)return e.jsx(Yi,{isOpen:t,onClose:s,value:p,onChange:D=>{b.current=D,f(D)},onConfirm:()=>h(2)});const k=async()=>{if(!u)return!0;if(w)return!1;_(!0);try{return await Ji({confirm:d,estimatedRange:S.estimatedRange,requiredMinimumBalance:S.requiredMinimumBalance,toast:c})}finally{_(!1)}};return e.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[e.jsx("div",{className:"absolute inset-0 bg-black/30",onClick:s}),e.jsxs("div",{className:"relative bg-white rounded-lg shadow-lg max-w-2xl w-full mx-4","data-onboarding":"context-modal",children:[e.jsxs("div",{className:"px-5 py-4 border-b border-slate-100 flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("button",{onClick:()=>h(1),className:"p-1 text-slate-400 hover:text-slate-600 transition-colors",children:e.jsx(cn,{size:18})}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-[15px] font-medium text-slate-800",children:"Choose Template"}),e.jsxs("p",{className:"text-[11px] text-slate-400",children:[n," ",l]})]})]}),e.jsx("button",{onClick:s,className:"text-slate-400 hover:text-slate-600",children:e.jsx(mt,{size:16})})]}),N.length>0&&e.jsxs("div",{className:"px-5 py-2 bg-slate-50 border-b border-slate-100 flex items-center gap-2",children:[e.jsx("span",{className:"text-[10px] text-slate-400",children:"Reference:"}),e.jsx("div",{className:"flex flex-wrap gap-1",children:N.map(D=>e.jsx("span",{className:"px-2 py-0.5 bg-slate-200 text-slate-600 text-[10px] rounded-full",children:D},D))}),e.jsx("button",{onClick:()=>h(1),className:"text-[10px] text-slate-500 hover:text-slate-700 ml-auto",children:"Edit"})]}),e.jsxs("div",{className:"px-5 py-4 space-y-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[12px] font-medium text-slate-700 mb-3",children:"Choose a Template"}),e.jsx("div",{className:"grid grid-cols-3 gap-3","data-onboarding":"context-modal-template-grid",children:Xr.map(D=>{const F=y===D.id;return e.jsxs("button",{onClick:()=>x(D.id),className:`relative p-4 rounded-lg text-left transition-all border-2 ${F?"border-slate-900 bg-slate-50":"border-slate-200 bg-white hover:border-slate-300"}`,children:[F&&e.jsx("div",{className:"absolute top-2 right-2 w-5 h-5 bg-slate-900 rounded-full flex items-center justify-center",children:e.jsx(wt,{size:12,className:"text-white"})}),e.jsx("div",{className:"text-[12px] font-medium text-slate-800 pr-6",children:D.name.replace("Content generation ","")}),e.jsx("div",{className:"text-[10px] text-slate-500 mt-1.5 leading-relaxed",children:D.description})]},D.id)})})]}),e.jsx("div",{"data-onboarding":"context-modal-title-content-option",children:e.jsx(Oc,{checked:u,onCheckedChange:g,estimatingCredits:S.estimating,estimatedCreditsRange:S.estimatedRange,requiredMinimumBalance:S.requiredMinimumBalance})})]}),e.jsx("div",{className:"px-5 py-4 border-t border-slate-100 flex justify-end gap-2",children:e.jsxs("button",{onClick:async()=>{await k()&&a({context:E,templateId:y||Xr[0].id,generateTitleAndContent:u})},disabled:w,className:"px-5 py-2 bg-slate-900 text-white text-[12px] font-medium rounded-lg hover:bg-slate-800 disabled:opacity-60 disabled:cursor-not-allowed flex items-center gap-2 transition-colors","data-onboarding":"context-modal-generate-btn",children:["Generate Content",e.jsx(Ms,{size:14})]})})]})]})},uv=({searchKeyword:t,debouncedSearchKeyword:s,onSearchChange:a,onRefresh:n,additionalGroups:o,hideActionBar:i=!1})=>{const{toast:l}=_t(),{confirm:c}=ia(),d=gh(),[m,h]=r.useState([]),[p,f]=r.useState(!0),[b,y]=r.useState(new Set),[x,u]=r.useState(!1),[g,w]=r.useState(!1),[_,E]=r.useState(""),[N,S]=r.useState(""),[k,D]=r.useState(!1),[F,R]=r.useState(1),[L,$]=r.useState(20),[H,K]=r.useState(0),[X,V]=r.useState(!1),[P,A]=r.useState(!0),C=r.useMemo(()=>!o||o.length===0?m:[...o,...m],[o,m]);r.useEffect(()=>{const Q=le=>{V(le.detail)},me=()=>{se()};return window.addEventListener("mobile-filter-toggle",Q),window.addEventListener("mobile-refresh-click",me),()=>{window.removeEventListener("mobile-filter-toggle",Q),window.removeEventListener("mobile-refresh-click",me)}},[]),r.useEffect(()=>{b.size>0&&A(!1)},[b.size]);const I=r.useCallback(()=>{y(new Set)},[]),j=r.useCallback(async(Q,me,le)=>{f(!0);try{const O=me??1,ne=le??20,ge=await ds.listGroupsWithKeywords({keyword:Q||void 0,page:O,page_size:ne}),ze=ge.items||[],Ke=Number.isFinite(ge.total)?ge.total:ze.length,ie=Ke>0?Math.max(1,Math.ceil(Ke/ne)):1;if(ze.length===0&&Ke>0&&O>ie){console.log("🔁 Adjusting keyword groups page:",{from:O,to:ie,total:Ke,pageSize:ne}),R(ie);return}h(ze),K(Ke);const ve=new Set(ze.map(Pe=>Pe.id));let we=null;try{const Pe=sessionStorage.getItem("ai_group_selected_ids");if(Pe){const Ae=JSON.parse(Pe);if(Array.isArray(Ae)&&Ae.length>0){const ye=Ae.filter(Te=>ze.some(Ie=>Ie.id===Te));ye.length>0&&(we=ye),sessionStorage.removeItem("ai_group_selected_ids")}else sessionStorage.removeItem("ai_group_selected_ids")}}catch(Pe){console.warn("⚠️ Failed to read group IDs from sessionStorage:",Pe);
187try{sessionStorage.removeItem("ai_group_selected_ids")}catch{}}y(Pe=>we&&we.length>0?new Set(we):new Set(Array.from(Pe).filter(Ae=>ve.has(Ae))))}catch(O){console.error("❌ Failed to load keyword groups:",O),l({title:"Failed to load groups",description:"Please try again later"})}finally{f(!1)}},[l]);r.useEffect(()=>{R(1),I()},[s,I]),r.useEffect(()=>{j(s,F,L)},[j,s,F,L]);const q=Q=>{y(me=>{const le=new Set(me);return le.has(Q)?le.delete(Q):le.add(Q),le})},T=()=>{y(Q=>{const me=new Set(Q),le=C.map(ne=>ne.id);return le.length>0&&le.every(ne=>me.has(ne))?le.forEach(ne=>me.delete(ne)):le.forEach(ne=>me.add(ne)),me})},M=()=>{D(!0)},Z=Q=>{const me=C.filter(ie=>b.has(ie.id));if(me.length===0){l({title:"No groups selected",description:"Please select groups to generate content"});return}const le=Q.templateId||"content_generation",O=Xr.find(ie=>ie.id===le)?.name||"Content generation",ne=new Date,ge=ne.toLocaleString("en-US",{month:"short"}),ze=ne.getDate(),Ke=`${O} - ${ge} ${ze}`;D(!1),(async()=>{d.begin("Creating worksheet...");try{const ie=await cr.createWorksheetAndGenerateFromGroups({source:{kind:"content_generation_template",templateType:le},campaignSource:"keywords_research",campaignName:Ke,groups:me.map(ve=>({id:ve.id,name:ve.name,keywords:(ve.keywords||[]).map(we=>({keyword:we.keyword}))})),options:{generateTitleAndContent:Q.generateTitleAndContent,titlePollingTimeoutMs:12e4,titlePollingIntervalMs:2e3,context:Q.context,onProgress:d.onProgress}});try{localStorage.setItem("flowwriter.currentCampaign",JSON.stringify({id:ie.campaignId,name:Ke}))}catch{}l({title:"✅ Worksheet created",description:Q.generateTitleAndContent?"Groups filled. Title & content generation started.":"Groups filled. You can run generation from the table."}),jt("table-new",{campaign:ie.campaignId,view:ie.viewId})}catch(ie){console.error("❌ Failed to create worksheet and generate:",ie),l({title:"Create & generate failed",description:ie?.message||"Please try again."})}finally{d.end()}})()},B=async()=>{if(b.size===0||x)return;const Q=b.size;if(await c({title:"Delete groups",message:`You are about to delete ${Q} group(s). This action cannot be undone.`,confirmText:"Delete",cancelText:"Cancel",variant:"danger"})){u(!0);try{const le=Array.from(b),O=await ds.batchDeleteGroups({group_ids:le});l({title:O.failed_count>0?"Groups deleted (partial)":"Groups deleted",description:O.failed_count>0?`${O.deleted_count} deleted, ${O.failed_count} failed`:`${O.deleted_count} group(s) deleted successfully`}),I(),j(s,F,L),n()}catch(le){console.error("❌ Failed to delete groups:",le),l({title:"Failed to delete groups",description:"Please try again later"})}finally{u(!1)}}},ae=Q=>{const me=C.find(le=>le.id===Q);me&&(E(Q),S(me.name),w(!0))},de=async(Q,me)=>{try{await ds.addKeywordsToGroup({group_id:Q,keywords:me}),l({title:"Keywords added",description:`${me.length} keyword(s) added to group`}),j(s,F,L)}catch(le){console.error("❌ Failed to add keywords:",le),l({title:"Failed to add keywords",description:"Please try again later"})}},fe=async(Q,me)=>{try{await ds.removeKeywordsFromGroup({group_id:Q,keywords:[me]}),l({title:"Keyword removed",description:`"${me}" removed from group`}),j(s,F,L)}catch(le){console.error("❌ Failed to remove keyword:",le),l({title:"Failed to remove keyword",description:"Please try again later"})}},se=()=>{j(s,F,L),n()},z=Q=>{I(),R(Q)},U=Q=>{I(),$(Q),R(1)};return e.jsxs("div",{className:"h-full flex flex-col min-h-0 bg-white sm:bg-transparent px-4",children:[e.jsx(Do,{visible:d.isRunning,message:d.message,fixed:!0,zIndex:9999}),e.jsxs("div",{className:"hidden sm:flex items-center justify-between mb-4","data-onboarding":"keywords-group-header",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("h2",{className:"text-lg font-semibold text-slate-800",children:"Keywords Group"}),e.jsx("p",{className:"text-sm text-slate-500 mt-0.5",children:"View and manage grouped keywords for content creation."})]}),e.jsxs(be,{variant:"outline",size:"sm",onClick:se,disabled:x,className:"bg-white",children:[e.jsx(kt,{size:14,className:"mr-1"}),"Refresh"]})]}),e.jsx("div",{className:Lt("sm:hidden overflow-hidden transition-all duration-300 ease-in-out bg-gray-50",X?"max-h-20 opacity-100 border-b border-gray-200":"max-h-0 opacity-0"),children:e.jsx("div",{className:"p-4",children:e.jsxs("div",{className:"relative",children:[e.jsx(Pt,{className:"absolute left-3 top-2.5 w-4 h-4 text-gray-400"}),e.jsx("input",{type:"text",placeholder:"Search groups or keywords...",className:"w-full pl-9 pr-4 py-2 bg-white border border-gray-200 rounded-lg text-sm focus:outline-none focus:border-blue-500 focus:ring-1 focus:ring-blue-500",value:t||"",onChange:Q=>a?.(Q.target.value)})]})})}),a&&e.jsx("div",{className:"hidden sm:block mb-4 max-w-[400px]",children:e.jsxs("div",{className:"relative",children:[e.jsx(Pt,{className:"absolute left-3 top-1/2 -translate-y-1/2 text-slate-400",size:16}),e.jsx(bt,{placeholder:"Search groups or keywords...",className:"pl-9 bg-white border-slate-200",value:t||"",onChange:Q=>a(Q.target.value)})]})}),e.jsxs("div",{className:"flex-1 min-h-0 relative","data-onboarding":"keywords-group-table",children:[e.jsx("div",{className:"absolute left-0 right-0 top-0 h-[220px] pointer-events-none","data-onboarding":"keywords-group-table-spotlight","aria-hidden":"true"}),p&&e.jsx("div",{className:"absolute inset-0 z-10 flex items-center justify-center bg-white/50 backdrop-blur-[1px]",children:e.jsxs("div",{className:"flex items-center gap-2 text-slate-500",children:[e.jsx(kt,{size:18,className:"animate-spin"}),e.jsx("span",{children:"Loading keyword groups..."})]})}),e.jsx(cv,{data:C,selectedIds:b,onToggleSelect:q,onSelectAll:T,onAddKeyword:ae,onRemoveKeyword:fe,pagination:{currentPage:F,pageSize:L,total:H+(o?.length||0),onPageChange:z,onPageSizeChange:U}})]}),!i&&e.jsx("div",{className:"hidden sm:block",children:e.jsx(xh,{selectedCount:b.size,onDelete:B,actionLabel:"Generate Content",onAction:M,"data-onboarding":"keywords-group-actions"})}),!i&&e.jsxs("div",{className:`sm:hidden fixed bottom-0 left-0 right-0 z-50 bg-white shadow-[0_-8px_30px_rgba(0,0,0,0.12)] rounded-t-2xl transition-transform duration-300 ease-out border-t border-gray-100 ${b.size>0?P?"translate-y-[calc(100%-24px)]":"translate-y-0":"translate-y-full"}`,children:[e.jsx("div",{className:"w-full h-8 flex items-center justify-center cursor-pointer active:opacity-70",onClick:()=>A(!P),children:e.jsx("div",{className:"w-10 h-1 bg-gray-200 rounded-full"})}),e.jsx("div",{className:"px-5 pb-8 pt-1",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"text-xs text-gray-500 font-medium uppercase tracking-wide",children:"Selected"}),e.jsxs("div",{className:"flex items-baseline gap-1",children:[e.jsx("span",{className:"text-2xl font-bold text-gray-900",children:b.size}),e.jsx("span",{className:"text-sm text-gray-500",children:"groups"})]})]}),e.jsxs("div",{className:"flex gap-3",children:[e.jsx("button",{onClick:I,className:"px-4 py-2.5 text-sm font-medium text-gray-600 bg-gray-100 rounded-xl hover:bg-gray-200 active:bg-gray-300 transition-colors",children:"Clear"}),e.jsxs("button",{onClick:M,className:"px-5 py-2.5 bg-blue-600 text-white text-sm font-semibold rounded-xl shadow-lg shadow-blue-200 active:scale-95 transition-all flex items-center gap-2",children:[e.jsx("span",{className:"text-lg leading-none",children:"+"}),"Generate"]})]})]})})]}),!i&&b.size>0&&P&&e.jsx("div",{className:"sm:hidden fixed bottom-6 left-0 right-0 flex justify-center pointer-events-none animate-bounce z-50",children:e.jsx("span",{className:"bg-black/70 text-white text-[10px] px-2 py-1 rounded-full backdrop-blur-sm shadow-md",children:"Tap handle to open"})}),e.jsx(dv,{isOpen:g,groupId:_,groupName:N,onClose:()=>w(!1),onAdd:de}),e.jsx(mv,{isOpen:k,onClose:()=>D(!1),onConfirm:Z,selectedCount:b.size,totalKeywords:C.filter(Q=>b.has(Q.id)).reduce((Q,me)=>Q+(me.keywords||[]).length,0),totalKeywordChars:C.filter(Q=>b.has(Q.id)).reduce((Q,me)=>{const le=(me.keywords||[]).reduce((O,ne)=>{const ge=(ne.keyword||"").trim();return O+ge.length},0);return Q+le},0),itemType:"groups"})]})},xv=()=>e.jsx("div",{className:"w-6 h-6 rounded flex items-center justify-center bg-gray-200 flex-shrink-0",children:e.jsx(Zn,{className:"w-3.5 h-3.5 text-gray-600"})});function hv(t){switch(t){case"seo":return"keywords_research";case"geo":return"geo_prompt";case"page":return"page_tracking"}}
187function pv(t){return{id:t.id,name:t.name,campaignId:t.id,createdAt:t.created_at}}function gv(t){const s=new Date,a=new Date(s.getFullYear(),s.getMonth(),s.getDate()),n=new Date(a.getTime()-10080*60*1e3),o=new Date(a.getTime()-720*60*60*1e3),i={Today:[],"Previous 7 days":[],"Previous 30 days":[],Earlier:[]};return t.forEach(l=>{const c=l.createdAt?new Date(l.createdAt):new Date(0);c>=a?i.Today.push(l):c>=n?i["Previous 7 days"].push(l):c>=o?i["Previous 30 days"].push(l):i.Earlier.push(l)}),i}const fl=({workflowType:t})=>{const[s,a]=r.useState("list"),[n,o]=r.useState("asc"),[i,l]=r.useState(!1),[c,d]=r.useState(""),[m,h]=r.useState([]);r.useEffect(()=>{let y=!0;return(async()=>{l(!0),d("");try{const u=await lr({source:hv(t),page:1,page_size:200});if(!y)return;const g=Array.isArray(u.items)?u.items:[];h(g.map(pv))}catch(u){if(console.error("❌ Failed to load related worksheets:",u),!y)return;d(u?.message||"Please try again."),h([])}finally{if(!y)return;l(!1)}})(),()=>{y=!1}},[t]);const p=r.useMemo(()=>[...m].sort((y,x)=>{const u=y.name.toLowerCase(),g=x.name.toLowerCase();return n==="asc"?u.localeCompare(g):g.localeCompare(u)}),[m,n]),f=r.useMemo(()=>gv(p),[p]),b=y=>{(async()=>{try{if(y.viewId){jt("table-new",{campaign:y.campaignId,view:y.viewId});return}const u=((await Wt.listViewConfigs({campaign_id:y.campaignId})).items||[])[0]?.id;jt("table-new",{campaign:y.campaignId,...u?{view:u}:{}})}catch(x){console.warn("⚠️ Failed to open worksheet view; navigating anyway:",x),jt("table-new",{campaign:y.campaignId})}})()};return e.jsxs("div",{className:"h-full flex flex-col bg-white",children:[e.jsx("div",{className:"px-4 sm:px-2 pt-4 pb-3 sm:pb-4 flex-shrink-0",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("h2",{className:"text-lg font-semibold text-slate-900",children:"Related Worksheets"}),e.jsx("p",{className:"hidden sm:block text-sm text-slate-500 mt-0.5",children:"Worksheets created from this workflow"})]}),!i&&m.length>0&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("button",{onClick:()=>a("list"),className:`flex items-center justify-center w-9 h-9 sm:w-8 sm:h-8 rounded-lg sm:rounded hover:bg-gray-100 transition-colors ${s==="list"?"bg-gray-100 text-gray-700":"text-gray-400"}`,title:"List view",children:e.jsx(_o,{className:"w-4 h-4 sm:w-5 sm:h-5"})}),e.jsx("button",{onClick:()=>a("grid"),className:`flex items-center justify-center w-9 h-9 sm:w-8 sm:h-8 rounded-lg sm:rounded hover:bg-gray-100 transition-colors ${s==="grid"?"bg-gray-100 text-gray-700":"text-gray-400"}`,title:"Grid view",children:e.jsx(uu,{className:"w-4 h-4 sm:w-5 sm:h-5"})}),e.jsx("button",{onClick:()=>o(n==="asc"?"desc":"asc"),className:"flex items-center justify-center w-9 h-9 sm:w-8 sm:h-8 rounded-lg sm:rounded hover:bg-gray-100 transition-colors text-gray-500",title:n==="asc"?"Sort Z to A":"Sort A to Z",children:n==="asc"?e.jsx(xu,{className:"w-4 h-4 sm:w-5 sm:h-5"}):e.jsx(hu,{className:"w-4 h-4 sm:w-5 sm:h-5"})})]})]})}),e.jsx("div",{className:"flex-1 overflow-y-auto px-4 sm:px-2 pb-4",children:i?e.jsxs("div",{className:"text-center py-12",children:[e.jsx("div",{className:"w-16 h-16 rounded-full bg-gray-100 flex items-center justify-center mx-auto mb-4",children:e.jsx(ln,{className:"h-8 w-8 text-gray-400"})}),e.jsx("h3",{className:"text-base font-medium text-gray-700 mb-2",children:"Loading..."}),e.jsx("p",{className:"text-sm text-gray-500 max-w-sm mx-auto",children:"Fetching related worksheets"})]}):c?e.jsxs("div",{className:"text-center py-12",children:[e.jsx("div",{className:"w-16 h-16 rounded-full bg-gray-100 flex items-center justify-center mx-auto mb-4",children:e.jsx(ln,{className:"h-8 w-8 text-gray-400"})}),e.jsx("h3",{className:"text-base font-medium text-gray-700 mb-2",children:"Failed to load"}),e.jsx("p",{className:"text-sm text-gray-500 max-w-sm mx-auto",children:c})]}):m.length===0?e.jsxs("div",{className:"text-center py-12",children:[e.jsx("div",{className:"w-16 h-16 rounded-full bg-gray-100 flex items-center justify-center mx-auto mb-4",children:e.jsx(ln,{className:"h-8 w-8 text-gray-400"})}),e.jsx("h3",{className:"text-base font-medium text-gray-700 mb-2",children:"No worksheets yet"}),e.jsx("p",{className:"text-sm text-gray-500 max-w-sm mx-auto",children:"Worksheets created from this workflow will appear here"})]}):s==="list"?e.jsx("div",{className:"space-y-4",children:Object.entries(f).map(([y,x])=>x.length===0?null:e.jsxs("div",{children:[e.jsx("h3",{className:"text-xs font-medium text-gray-500 mb-2 sm:px-2",children:y}),e.jsx("div",{className:"space-y-0.5",children:x.map(u=>e.jsxs("div",{onClick:()=>b(u),className:"flex items-center gap-3 px-2 sm:px-2 py-3 sm:py-2.5 rounded-xl sm:rounded hover:bg-gray-50 active:bg-gray-100 cursor-pointer transition-colors",children:[e.jsx(xv,{}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsx("span",{className:"text-sm text-gray-800 line-clamp-1",children:u.name})}),e.jsx("button",{onClick:g=>g.stopPropagation(),className:"p-1.5 sm:p-1 rounded-lg sm:rounded hover:bg-gray-100 text-gray-400",children:e.jsx(En,{className:"w-4 h-4"})})]},u.id))})]},y))}):e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 ga
187p-3 sm:gap-4",children:p.map(y=>e.jsxs("div",{onClick:()=>b(y),className:"group relative bg-white border border-gray-200 rounded-xl sm:rounded-lg p-3 sm:p-4 hover:border-gray-300 hover:shadow-sm active:bg-gray-50 cursor-pointer transition-all",children:[e.jsx("div",{className:"absolute top-2 right-2",children:e.jsx("button",{onClick:x=>x.stopPropagation(),className:"p-1.5 sm:p-1 rounded-lg sm:rounded hover:bg-gray-100 text-gray-400 sm:opacity-0 sm:group-hover:opacity-100 transition-opacity",children:e.jsx(En,{className:"w-4 h-4"})})}),e.jsx("div",{className:"w-full aspect-[4/3] bg-gray-50 rounded-lg sm:rounded border border-gray-100 mb-2 sm:mb-3 flex items-center justify-center",children:e.jsx(Zn,{className:"w-6 h-6 sm:w-8 sm:h-8 text-gray-300"})}),e.jsx("p",{className:"text-xs sm:text-sm text-gray-800 truncate",title:y.name,children:y.name})]},y.id))})})]})};function fv(t){return!!t&&t instanceof HTMLElement}function fh(t){try{const s=t.getBoundingClientRect();return s.width>0&&s.height>0}catch{return!1}}function yv(){const t=document.querySelector('[data-onboarding="cell-detail-panel"]');if(!t||!fh(t))return 0;const s=t.getBoundingClientRect(),a=Math.round(s.width);return Number.isFinite(a)&&a>0?a:0}function bv(){return{top:12,right:12+yv(),bottom:12,left:12}}function hm(t,s){let a=t.parentElement;for(;a&&a!==document.body;){const n=window.getComputedStyle(a),o=s==="x"?n.overflowX||n.overflow:n.overflowY||n.overflow;if((o==="auto"||o==="scroll"||o==="overlay")&&(s==="x"&&a.scrollWidth>a.clientWidth||s==="y"&&a.scrollHeight>a.clientHeight))return a;a=a.parentElement}return null}function wv(t){const s=bv();try{t.scrollIntoView({behavior:"auto",block:"center",inline:"center"})}catch{}const a=t.getBoundingClientRect(),n=window.innerWidth-s.right,o=s.left,i=window.innerHeight-s.bottom,l=s.top,c=a.right-n,d=o-a.left,m=a.bottom-i,h=l-a.top,p=c>0?c+8:d>0?-(d+8):0;if(p!==0){const b=hm(t,"x");b?b.scrollLeft+=p:typeof window.scrollBy=="function"&&window.scrollBy({left:p,top:0,behavior:"auto"})}const f=m>0?m+8:h>0?-(h+8):0;if(f!==0){const b=hm(t,"y");b?b.scrollTop+=f:typeof window.scrollBy=="function"&&window.scrollBy({left:0,top:f,behavior:"auto"})}}async function jv(t,s){const a=s?.maxRetries,n=s?.intervalMs;for(let o=0;o<a;o++){const i=document.querySelector(t);if(fv(i)&&document.body.contains(i)&&fh(i))return i;await new Promise(l=>setTimeout(l,n))}return null}const vv=({continuous:t,index:s,step:a,backProps:n,closeProps:o,primaryProps:i,skipProps:l,tooltipProps:c,isLastStep:d,isInteractive:m,actionHint:h,isLastPhase:p=!0})=>{const f=c?.style;return e.jsxs("div",{...c,className:"bg-white rounded-xl shadow-2xl border border-gray-100 max-w-md",style:{padding:"20px",...f||{}},children:[e.jsx("div",{className:"mb-4",children:a.content}),m&&h&&e.jsx("div",{className:"bg-slate-100 border border-slate-300 rounded-lg p-3 mb-4",children:e.jsx("p",{className:"text-sm text-slate-700 font-medium",children:h})}),e.jsxs("div",{className:"flex items-center justify-between pt-2 border-t border-gray-100",children:[e.jsx("div",{children:!d&&e.jsx("button",{...l,className:"text-sm text-gray-400 hover:text-gray-600 transition-colors",children:"Skip tour"})}),e.jsxs("div",{className:"flex items-center gap-2",children:[s>0&&e.jsx("button",{...n,className:"px-4 py-2 text-sm text-gray-600 hover:text-gray-800 transition-colors",children:"Back"}),e.jsx("button",{...i,className:"px-4 py-2 text-sm font-medium text-white bg-slate-900 hover:bg-slate-800 rounded-lg transition-colors",children:d&&p?"Finish":"Next"})]})]})]})};function Uc({steps:t,run:s,onComplete:a,onSkip:n,startDelay:o=300,isLastPhase:i=!0,onStepChange:l}){const[c,d]=r.useState(!1),[m,h]=r.useState(0),[p,f]=r.useState(!1),b=r.useRef(null),y=r.useRef(null),x=r.useRef(-1),u=r.useRef(0),g=r.useRef(!1),w=r.useCallback((S,k)=>{if(!g.current){g.current=!0;try{console.log("🧭 [Onboarding] Finishing tour:",{reason:S,stepIndex:m,detail:k})}catch{}d(!1),setTimeout(()=>{try{S==="complete"?a?.():n?.()}finally{g.current=!1,u.current=0}},0)}},[a,n,m]);r.useEffect(()=>{if(s){const S=setTimeout(()=>{d(!0),h(0),u.current=0,g.current=!1},o);return()=>clearTimeout(S)}else d(!1),u.current=0,g.current=!1},[s,o]),r.useEffect(()=>{c&&m!==x.current&&t[m]&&(x.current=m,l?.(m,t[m]))},[c,m,t,l]),r.useEffect(()=>{if(!c)return;const S=t[m],k=typeof S?.target=="string"?S.target:null;if(!k||k==="body")return;let D=!1;return(async()=>{try{f(!0);const F=await jv(k,{maxRetries:40,intervalMs:50});if(D)return;F?(console.log("🧭 [Onboarding] Preparing step target (scroll into view):",{stepIndex:m,selector:k}),wv(F),await new Promise(R=>requestAnimationFrame(()=>R(null))),await new Promise(R=>requestAnimationFrame(()=>R(null)))):console.warn("⚠️ [Onboarding] Step target not ready for scroll prepare:",{stepIndex:m,selector:k})}catch(F){console.warn("⚠️ [Onboarding] Failed to prepare step target:",F)}finally{D||f(!1)}})(),()=>{D=!0}},[c,m,t]),r.useEffect(()=>{if(!y.current){const S=document.createElement("style");S.textContent=`
188        @keyframes onboarding-pulse {
189          0%, 100% {
190            box-shadow: 0 0 0 0 rgba(99, 102, 241, 0.7);
191          }
192          50% {
193            box-shadow: 0 0 0 8px rgba(99, 102, 241, 0);
194          }
195        }
196        .onboarding-interactive-target {
197          animation: onboarding-pulse 1.5s ease-in-out infinite;
198          position: relative;
199          z-index: 10000;
200        }
201        .onboarding-interactive-target::after {
202          content: '';
203          position: absolute;
204          inset: -4px;
205          border: 2px dashed rgba(99, 102, 241, 0.5);
206          border-radius: inherit;
207          pointer-events: none;
208        }
209      `,document.head.appendChild(S),y.current=S}return()=>{y.current&&(y.current.remove(),y.current=null)}},[]);const _=t[m],E=_?.interactive===!0;_?.interactionType,r.useEffect(()=>{if(!c||!E||!_)return;const S=typeof _.target=="string"?_.target:null;if(!S||S==="body")return;const D=(_.interactionType||"click")==="dblclick"?"dblclick":"pointerdown",F=P=>{if(!P)return 0;const A=Array.from(document.querySelectorAll(P));let C=0;for(const I of A)I instanceof HTMLElement&&(I.classList.add("onboarding-interactive-target"),C+=1);return C},R=()=>{const P=F(S),C=(_.pulseTargets||[]).filter(I=>
209typeof I=="string"&&I.trim().length>0).reduce((I,j)=>I+F(j),0);return P+C>0},L=()=>{const P=[S,...(_.pulseTargets||[]).filter(A=>typeof A=="string"&&A.trim().length>0)];for(const A of P){const C=Array.from(document.querySelectorAll(A));for(const I of C)I instanceof HTMLElement&&I.classList.remove("onboarding-interactive-target")}},$=()=>{const P=new KeyboardEvent("keydown",{key:"Escape",code:"Escape",keyCode:27,which:27,bubbles:!0,cancelable:!0});document.dispatchEvent(P),document.querySelectorAll('[data-radix-portal], .fixed.inset-0, [role="dialog"]').forEach(C=>{const I=C.querySelector("[data-radix-overlay-backdrop], .bg-black\\/50, .bg-black\\/80");I&&I instanceof HTMLElement&&I.click()})},H=P=>{const A=P.target;if(!!A&&(A.closest?.(S)!=null||A.matches?.(S)===!0)){try{const j=A.closest?.(S);if(j instanceof HTMLButtonElement&&j.disabled)return}catch{}console.log(`[InteractiveOnboarding] Target ${D}, advancing to step ${m+1}`),L(),_.keepOpenAfterInteraction===!0?setTimeout(()=>{m+1<t.length?h(m+1):(d(!1),a?.())},800):setTimeout(()=>{$(),setTimeout(()=>{m+1<t.length?h(m+1):w("complete",{source:"interaction_end"})},200)},600)}};let K=0;const X=20,V=()=>R()?(document.addEventListener(D,H,!0),b.current=H,!0):!1;if(!V()){const P=setInterval(()=>{K++,(V()||K>=X)&&clearInterval(P)},100);return()=>{clearInterval(P),L(),b.current&&(document.removeEventListener(D,b.current,!0),b.current=null)}}return()=>{L(),b.current&&(document.removeEventListener(D,b.current,!0),b.current=null)}},[c,m,E,_,t,w]);const N=r.useCallback(S=>{const{status:k,type:D,action:F,index:R}=S;if(console.log("[InteractiveOnboarding] Callback:",{type:D,action:F,index:R,stepIndex:m,status:k}),k===nn.FINISHED||k===nn.SKIPPED){w(k===nn.FINISHED?"complete":"skip",{source:"joyride_status",status:k});return}if(D===ja.STEP_AFTER)if(F===Ka.NEXT){const L=t[m];if(L?.interactive===!0&&L?.autoTriggerOnNext===!0){const K=typeof L.target=="string"?L.target:null;if(K&&K!=="body"){const X=document.querySelector(K);if(X){const V=L.interactionType||"click";console.log("🧭 Auto-triggering target on Next:",{selector:K,interaction:V});try{V==="dblclick"?X.dispatchEvent(new MouseEvent("dblclick",{bubbles:!0,cancelable:!0,view:window})):X.click?.()}catch(P){console.warn("⚠️ Failed to auto-trigger target on Next:",P)}}console.warn("⚠️ Auto-trigger target not found on Next:",K)}}const H=m+1;if(H<t.length){if(L?.interactive){const K=typeof L.target=="string"?L.target:null,X=L?.pulseTargets||[],V=[K,...Array.isArray(X)?X:[]].filter(P=>typeof P=="string"&&P&&P!=="body");for(const P of V){const A=Array.from(document.querySelectorAll(P));for(const C of A)C instanceof HTMLElement&&C.classList.remove("onboarding-interactive-target")}}h(H)}else w("complete",{source:"next_end"})}else F===Ka.PREV?h(Math.max(0,m-1)):F===Ka.CLOSE&&w("skip",{source:"close"});if(D===ja.TARGET_NOT_FOUND){const L=t[m]?.target,$=m+1;if(u.current+=1,console.warn("[InteractiveOnboarding] Target not found:",{stepIndex:m,target:L,notFoundCount:u.current}),$>=t.length){w("skip",{source:"target_not_found_end",target:L});return}if(u.current>=5){w("skip",{source:"target_not_found_limit",target:L});return}setTimeout(()=>h($),350);return}D===ja.TOOLTIP&&(u.current=0)},[w,m,t]);return c?e.jsx(ic,{steps:t,run:c&&!p,stepIndex:m,continuous:!0,showProgress:!1,showSkipButton:!0,disableCloseOnEsc:!1,disableOverlayClose:!0,callback:N,spotlightClicks:!0,scrollToFirstStep:!1,disableScrolling:!0,disableScrollParentFix:!0,tooltipComponent:S=>e.jsx(vv,{...S,isInteractive:t[m]?.interactive,actionHint:t[m]?.actionHint,isLastPhase:i}),floaterProps:{disableAnimation:!1,styles:{arrow:{color:"#fff"},floater:{filter:"none"}}},spotlightPadding:8,styles:{options:{zIndex:10001,arrowColor:"#fff"},overlay:{backgroundColor:"rgba(0, 0, 0, 0.5)"},spotlight:{borderRadius:"8px"}},locale:{back:"Back",close:"Close",last:"Finish",next:"Next",skip:"Skip tour"}}):null}const pm=[{target:"body",content:e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-semibold text-slate-900 mb-2",children:"Workflow"}),e.jsx("p",{className:"text-sm text-slate-600 mb-3",children:"This is your content creation workspace. Based on your current performance data, Workflow helps you identify opportunities and take targeted actions to improve your visibility in search engines and AI responses."}),e.jsx("p",{className:"text-sm text-slate-600",children:"Select a workflow category to view data and generate optimized content."})]}),placement:"center",disableBeacon:!0},{target:'[data-onboarding="workflow-sidebar"]',content:e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-semibold text-slate-900 mb-2",children:"Workflow Sidebar"}),e.jsx("p",{className:"text-sm text-slate-600",children:"The sidebar organizes content creation into categories. Select any item to view its data and available actions in the main panel."})]}),placement:"right",disableBeacon:!0},{target:'[data-onboarding="workflow-competitors"]',content:e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-semibold text-slate-900 mb-2",children:"Competitors"}),e.jsx("p",{className:"text-sm text-slate-600",children:"Monitor your competitors across selected markets and compare changes over time."})]}),placement:"right",disableBeacon:!0},{target:'[data-onboarding="workflow-keyword-gap"]',content:e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-semibold text-slate-900 mb-2",children:"Keyword Gap"}),e.jsx("p",{className:"text-sm text-slate-600 mb-2",children:"SEO content creation workflow with three stages:"}),e.jsxs("ul",{className:"text-sm text-slate-600 space-y-1.5",children:[e.jsxs("li",{children:[e.jsx("span",{className:"font-medium",children:"Keywords Gap"})," - View keywords your competitors rank for but you don't. Select keywords and add them to Target Keywords."]}),e.jsxs("li",{children:[e.jsx("span",{className:"font-medium",children:"Target Keywords"})," - All keywords you've collected from various sources. Generate content directly or group them first."]}),e.jsxs("li",{children:[e.jsx("span",{className:"font-medium",children:"Keywords Group"})," - AI-grouped keywords by topic. Generate content for multiple related keywords at once."]})]})]}),placement:"right",disableBeacon:!0},{target:'[data-onboarding="workflow-ai-visibility"]',content:e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-semibold text-slate-900 mb-2",children:"AI Visibility"}),e.jsx("p",{className:"text-sm text-slate-600 mb-2",children:"Track your brand visibility in AI-generated search results (GEO/AEO):"}),e.jsx("ul",{className:"text-sm text-slate-600 space-y-1.5",children:e.jsxs("li",{children:[e.jsx("span",{className:"font-medium",children:"Prompt Tracking"})," - Add prompts that potential customers might ask AI assistants. Monitor whether your brand appears in the AI-generated responses and track competitor mentions."]})})]}),placement:"right",disableBeacon:!0},{target:'[data-onboarding="workflow-content-optimization"]',content:e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-semibold text-slate-900 mb-2",children:"Content Optimization"}),e.jsx("p",{className:"text-sm text-slate-600 mb-2",children:"Optimize your existing published content:"}),e.jsx("ul",{className:"text-sm text-slate-600 space-y-1.5",children:e.jsxs("li",{children:[e.jsx("span",{className:"font-medium",children:"Page Tracking"}
209)," - Add URLs of your published pages. Track their keyword rankings over time and generate optimized content updates based on performance data."]})})]}),placement:"right",disableBeacon:!0},{target:'[data-onboarding="workflow-main-panel"]',content:e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-semibold text-slate-900 mb-2",children:"Main Panel"}),e.jsx("p",{className:"text-sm text-slate-600",children:"The main panel displays data for the selected workflow item. Use the table to select items, then click action buttons to add keywords, generate content, or perform other operations."})]}),placement:"left-start",disableBeacon:!0,floaterProps:{disableAnimation:!0,options:{positionFixed:!0,modifiers:{computeStyle:{gpuAcceleration:!1},preventOverflow:{enabled:!0,boundariesElement:"viewport",padding:8},flip:{enabled:!0,boundariesElement:"viewport"}}}}}],Nv=[{target:"body",content:e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-semibold text-slate-900 mb-2",children:"Keywords Research Workflow"}),e.jsx("p",{className:"text-sm text-slate-600 mb-3",children:"Welcome to the Keywords Research workflow! This is a 3-step process to help you discover, organize, and generate content for keywords."}),e.jsxs("div",{className:"bg-slate-50 border border-slate-200 rounded-lg p-3",children:[e.jsx("p",{className:"text-xs text-slate-500 mb-2 font-medium",children:"The 3 Steps:"}),e.jsxs("ol",{className:"text-xs text-slate-600 space-y-1 list-decimal list-inside",children:[e.jsxs("li",{children:[e.jsx("span",{className:"font-medium",children:"Keywords Gap"})," - Find keywords your competitors rank for"]}),e.jsxs("li",{children:[e.jsx("span",{className:"font-medium",children:"Target Keywords"})," - Collect and organize your keywords"]}),e.jsxs("li",{children:[e.jsx("span",{className:"font-medium",children:"Keywords Group"})," - Group keywords by topic for content"]})]})]})]}),placement:"center",disableBeacon:!0},{target:'[data-onboarding="keywords-gap-header"]',content:e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-semibold text-slate-900 mb-2",children:"Step 1: Keywords Gap"}),e.jsx("p",{className:"text-sm text-slate-600 mb-2",children:"This table shows keywords that your competitors rank for, but you don't. These are opportunities to create new content."}),e.jsx("p",{className:"text-sm text-slate-600",children:"The table is sorted by search volume - higher volume keywords appear first."})]}),placement:"bottom",disableBeacon:!0},{target:'[data-onboarding="keywords-gap-quick-select"]',content:e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-semibold text-slate-900 mb-2",children:"Quick Select Keywords"}),e.jsx("p",{className:"text-sm text-slate-600 mb-2",children:"This button helps you quickly select high-potential keywords based on opportunity scores."}),e.jsx("p",{className:"text-sm text-slate-600 mb-2",children:`We've automatically selected 10 keywords for you. Click "Next" to continue.`}),e.jsx("div",{className:"bg-slate-50 border border-slate-200 rounded-lg p-3 mt-2",children:e.jsx("p",{className:"text-xs text-slate-600 font-medium",children:'10 keywords selected. Click "Next" to proceed.'})})]}),placement:"bottom",disableBeacon:!0},{target:'[data-onboarding="keywords-gap-actions"] [data-onboarding-action="primary"]',content:e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-semibold text-slate-900 mb-2",children:"Add to Target Keywords"}),e.jsx("p",{className:"text-sm text-slate-600 mb-2",children:'Great! Keywords have been selected for you. Now click "Add to Target Keywords" to save them to your target list.'}),e.jsx("p",{className:"text-sm text-slate-600 mb-2",children:"This will move these keywords to your Target Keywords collection and take you to the next step."}),e.jsx("div",{className:"bg-slate-50 border border-slate-200 rounded-lg p-3 mt-2",children:e.jsx("p",{className:"text-xs text-slate-600 font-medium",children:'Click "Add to Target Keywords" to continue'})})]}),placement:"top-end",disableBeacon:!0,interactive:!0,actionHint:"Click 'Add to Target Keywords' to proceed to the next step",autoTriggerOnNext:!0}],kv=[{target:"body",content:e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-semibold text-slate-900 mb-2",children:"Step 2: Target Keywords"}),e.jsx("p",{className:"text-sm text-slate-600 mb-3",children:"This is your collection of target keywords. Keywords can come from Keywords Gap analysis, manual input, or other sources."}),e.jsx("p",{className:"text-sm text-slate-600",children:"From here, you can either generate content directly for each keyword, or group them by topic first."})]}),placement:"center",disableBeacon:!0},{target:'[data-onboarding="target-keywords-header"]',content:e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-semibold text-slate-900 mb-2",children:"Target Keywords"}),e.jsx("p",{className:"text-sm text-slate-600",children:"Your collected keywords are shown here. You can add more keywords manually, search through your list, or select keywords to take action."})]}),placement:"bottom",disableBeacon:!0},{target:'[data-onboarding="target-keywords-table"]',content:e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-semibold text-slate-900 mb-2",children:"Select Keywords"}),e.jsx("p",{className:"text-sm text-slate-600 mb-2",children:"Select the keywords you want to create content for. You can select all or pick specific keywords."}),e.jsx("div",{className:"bg-slate-50 border border-slate-200 rounded-lg p-3 mt-2",children:e.jsx("p",{className:"text-xs text-slate-600 font-medium",children:"Select keywords by clicking the checkboxes"})})]}),placement:"bottom",disableBeacon:!0,interactive:!0,actionHint:"Select keywords by clicking the checkboxes"},{target:'[data-onboarding="target-keywords-actions"]',content:e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-semibold text-slate-900 mb-2",children:"Generate Content"}),e.jsx("p",{className:"text-sm text-slate-600 mb-2",children:`Click "Generate Content" to open the content generation options. You'll be able to choose:`}),e.jsxs("ul",{className:"text-sm text-slate-600 space-y-1 list-disc list-inside",children:[e.jsx("li",{children:"Generate content for each keyword directly"}),e.jsx("li",{children:"Group keywords first, then generate content"})]}),e.jsx("div",{className:"bg-slate-50 border border-slate-200 rounded-lg p-3 mt-2",children:e.jsx("p",{className:"text-xs text-slate-600 font-medium",children:'Click "Generate Content" to continue'})})]}),placement:"top",disableBeacon:!0,interactive:!0,actionHint:"Click 'Generate Content' to open generation options",keepOpenAfterInteraction:!0,autoTriggerOnNext:!0}],_v=[{target:'[data-onboarding="generate-content-modal"]',content:e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-semibold text-slate-900 mb-2",children:"Content Generation Options"}),e.jsx("p",{className:"text-sm text-slate-600 mb-3",children:"Choose how you want to organize your content:"}),e.jsxs("ul",{className:"text-sm text-slate-600 space-y-2",children:[e.jsxs("li",{children:[e.jsx("span",{className:"font-medium",children:"Generate for Each"})," - Create one article per keyword. Best for distinct topics."]}),e.jsxs("li",{children:[e.jsx("span",{className:"font-medium",children:"Group First"})," - Let AI cluster related keywords together. Best for comprehensive guides."]})]})]}),placement:"center",disableBeacon:!0},{target:'[data-onboarding="generate-content-choice-options"]',content:e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-semibold text-slate-900 mb-2",children:"Choose Your Path"}),e.jsx("p",{className:"text-sm text-slate-600 mb-2",children:"Click one of the two options in the modal:"}),e.jsx("div",{className:"bg-slate-50 border border-slate-200 rounded-lg p-3 mt-2",children:e.jsx("p",{className:"text-xs text-slate-600 font-medium",children:"Click either option to continue"})})]}),placement:"bottom",disableBeacon:!0,interactive:!0,actionHint:"Click one of the options to continue",keepOpenAfterInteraction:!0,spotlightPadding:4,pulseTargets:['[data-onboarding="generate-content-single-option"]','[data-onboarding="generate-content-group-option"]']}],Cv=[{target:'[data-onboarding="context-reference-modal"]',content:e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-semibold text-slate-900 mb-2",children:"Add Reference (Optional)"}),e.jsxs("p",{className:"text-sm text-slate-600",children:["Add reference context to help the AI generate content that matches your brand. You can click"," ",e.jsx("span",{className:"font-medium",children:"Continue"})," or"," ",e.jsx("span",{className:"font-medium",children:"Back"})," at any time."]})]}),placement:"bottom",disableBeacon:!0},{target:'[data-onboarding="context-reference-continue-btn"]',content:e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-semibold text-slate-900 mb-2",children:"Continue"}),e.jsx("p",{className:"text-sm text-slate-600",children:'Click \\"Continue\\" to proceed to template selection.'})]}),placement:"top",disableBeacon:!0,interactive:!0,actionHint:"Click 'Continue' to proceed",keepOpenAfterInteraction:!0,autoTriggerOnNext:!0}],Sv=[{target:'[data-onboarding="single-keyword-template-modal"]',content:e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-semibold text-slate-900 mb-2",children:"Choose Template"}),e.jsx("p",{className:"text-sm text-slate-600",children:"Select a template and generation options for one-article-per-keyword."})]}),placement:"bottom",disableBeacon:!0},{target:'[data-onboarding="single-keyword-template-grid"]',content:e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-semibold text-slate-900 mb-2",children:"Pick a Template"}),e.jsx("p",{className:"text-sm text-slate-600",children:"Choose the template that best matches your goal."})]}),placement:"top",disableBeacon:!0},{target:'[data-onboarding="single-keyword-generate-btn"]',content:e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-semibold text-slate-900 mb-2",children:"Generate Content"}),e.jsx("p",{className:"text-sm text-slate-600",children:'Click \\"Generate Content\\" to create your worksheet and start generation.'})]}),placement:"top",disableBeacon:!0,interactive:!0,actionHint:"Click 'Generate Content' to start generation",keepOpenAfterInteraction:!0,autoTriggerOnNext:!0}],Ev=[{target:'[data-onboarding="grouping-modal"]',content:e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-semibold text-slate-900 mb-2",children:"Grouping Options"}),e.jsx("p",{className:"text-sm text-slate-600 mb-3",children:"You can choose between two grouping methods:"}),e.jsxs("ul",{className:"text-sm text-slate-600 space-y-2",children:[e.jsxs("li",{children:[e.jsx("span",{className:"font-medium",children:"AI Grouping"})," - Let AI automatically cluster related keywords into topic groups."]}),e.jsxs("li",{children:[e.jsx("span",{className:"font-medium",children:"Manual"})," - Create and organize groups yourself for full control."]})]})]}),placement:"bottom",disableBeacon:!0,interactive:!0,keepOpenAfterInteraction:!0,actionHint:"Click 'Continue' to proceed",pulseTargets:['[data-onboarding="context-reference-continue-btn"]']},{target:'[data-onboarding="ai-grouping-button"]',content:e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-semibold text-slate-900 mb-2",children:"Start AI Grouping"}),e.jsx("p",{className:"text-sm text-slate-600 mb-2",children:'Click "Start AI Grouping" to let AI analyze your keywords and create topic groups automatically.'}),e.jsx("div",{className:"bg-slate-50 border border-slate-200 rounded-lg p-3 mt-2",children:e.jsx("p",{className:"text-xs text-slate-600 font-medium",children:'Click "Start AI Grouping" to continue'})})]}),placement:"top",disableBeacon:!0,interactive:!0,actionHint:"Click 'Start AI Grouping' to create keyword groups",autoTriggerOnNext:!0}],Av=[{target:'[data-onboarding="grouping-modal"]',content:e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-semibold text-slate-900 mb-2",children:"Manual Grouping"}),e.jsx("p",{className:"text-sm text-slate-600",children:"In Manual mode, you create groups and assign ke
209ywords yourself."})]}),placement:"bottom",disableBeacon:!0},{target:'[data-onboarding="manual-unassigned-keywords"]',content:e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-semibold text-slate-900 mb-2",children:"Select Keywords"}),e.jsx("p",{className:"text-sm text-slate-600",children:"Select one or more keyword chips. When you're ready, click Next."})]}),placement:"bottom",disableBeacon:!0},{target:'[data-onboarding="manual-add-selected-btn"]',content:e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-semibold text-slate-900 mb-2",children:"Add to Group"}),e.jsx("p",{className:"text-sm text-slate-600",children:"Click “Add” to assign the selected keywords to the active group."})]}),placement:"top",disableBeacon:!0,interactive:!0,keepOpenAfterInteraction:!0,autoTriggerOnNext:!0,actionHint:"Click 'Add' to assign keywords"},{target:'[data-onboarding="manual-group-name-input"]',content:e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-semibold text-slate-900 mb-2",children:"Name Your Group"}),e.jsx("p",{className:"text-sm text-slate-600",children:"Click the group name to rename it (optional), then click Next."})]}),placement:"bottom",disableBeacon:!0},{target:'[data-onboarding="manual-create-groups-btn"]',content:e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-semibold text-slate-900 mb-2",children:"Create Groups"}),e.jsx("p",{className:"text-sm text-slate-600",children:"After assigning keywords to groups, click “Create Groups & Continue” to create the groups and proceed."})]}),placement:"top",disableBeacon:!0,interactive:!0,keepOpenAfterInteraction:!0,actionHint:"Click 'Create Groups & Continue' to proceed",autoTriggerOnNext:!0}],Tv=[{target:"body",content:e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-semibold text-slate-900 mb-2",children:"Step 3: Keywords Group"}),e.jsx("p",{className:"text-sm text-slate-600 mb-3",children:"Your keywords have been organized into topic groups. Each group represents a cluster of related keywords that can be used to create a single comprehensive article."}),e.jsx("p",{className:"text-sm text-slate-600",children:"Select groups and generate content to create your articles."})]}),placement:"center",disableBeacon:!0},{target:'[data-onboarding="keywords-group-header"]',content:e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-semibold text-slate-900 mb-2",children:"Keywords Group"}),e.jsx("p",{className:"text-sm text-slate-600",children:"Each group shows the group name and the keywords it contains. Groups are automatically named based on the main topic."})]}),placement:"bottom",disableBeacon:!0},{target:'[data-onboarding="keywords-group-table-spotlight"]',content:e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-semibold text-slate-900 mb-2",children:"Select Groups"}),e.jsx("p",{className:"text-sm text-slate-600 mb-2",children:"Your newly created groups are already selected. You can see the keywords for each group directly in the table."}),e.jsx("p",{className:"text-sm text-slate-600",children:"Review the keywords and keep the groups you want to generate content for selected."})]}),placement:"top",disableBeacon:!0},{target:'[data-onboarding="keywords-group-actions"] [data-onboarding-action="primary"]',content:e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-semibold text-slate-900 mb-2",children:"Generate Content"}),e.jsx("p",{className:"text-sm text-slate-600 mb-2",children:'Click "Generate Content" to choose your references and template before generating articles for your selected groups.'}),e.jsx("div",{className:"bg-slate-50 border border-slate-200 rounded-lg p-3 mt-2",children:e.jsx("p",{className:"text-xs text-slate-600 font-medium",children:'Click "Generate Content" to continue'})})]}),placement:"top",disableBeacon:!0,interactive:!0,actionHint:"Click 'Generate Content' to choose references and a template",keepOpenAfterInteraction:!0,autoTriggerOnNext:!0},{target:'[data-onboarding="context-reference-modal"]',content:e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-semibold text-slate-900 mb-2",children:"Add Reference (Optional)"}),e.jsx("p",{className:"text-sm text-slate-600 mb-2",children:"Add reference context to help the AI generate content that matches your brand."}),e.jsxs("ul",{className:"text-sm text-slate-600 space-y-1 list-disc list-inside",children:[e.jsxs("li",{children:[e.jsx("span",{className:"font-medium",children:"Company"})," - Your business info"]}),e.jsxs("li",{children:[e.jsx("span",{className:"font-medium",children:"Knowledge"})," - Your docs and guides"]}),e.jsxs("li",{children:[e.jsx("span",{className:"font-medium",children:"Competitors"})," - Reference pages"]})]})]}),placement:"bottom",disableBeacon:!0},{target:'[data-onboarding="context-reference-continue-btn"]',content:e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-semibold text-slate-900 mb-2",children:"Continue to Template Selection"}),e.jsx("p",{className:"text-sm text-slate-600",children:'Click "Continue" to choose a template and generation options.'})]}),placement:"top",disableBeacon:!0,interactive:!0,actionHint:"Click 'Continue' to proceed",keepOpenAfterInteraction:!0,autoTriggerOnNext:!0},{target:'[data-onboarding="context-modal"]',content:e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-semibold text-slate-900 mb-2",children:"Choose Template"}),e.jsx("p",{className:"text-sm text-slate-600",children:"Select a template for how your grouped keywords will be turned into articles."})]}),placement:"bottom",disableBeacon:!0},{target:'[data-onboarding="context-modal-template-grid"]',content:e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-semibold text-slate-900 mb-2",children:"Pick a Template"}),e.jsx("p",{className:"text-sm text-slate-600",children:"Choose the template that best matches your goal (e.g., guide, landing page, comparison)."})]}),placement:"top",disableBeacon:!0},{target:'[data-onboarding="context-modal-title-content-option"]',content:e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-semibold text-slate-900 mb-2",children:"Auto-generate Title & Content"}),e.jsx("p",{className:"text-sm text-slate-600",children:"Enable this to generate titles and content automatically after the worksheet is created."})]}),placement:"top",disableBeacon:!0},{target:'[data-onboarding="context-modal-generate-btn"]',content:e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-semibold text-slate-900 mb-2",children:"Generate Content"}),e.jsx("p",{className:"text-sm text-slate-600 mb-2",children:'Click "Generate Content" to create your worksheet and start generation.'}),e.jsx("div",{className:"bg-slate-50 border border-slate-200 rounded-lg p-3 mt-2",children:e.jsx("p",{className:"text-xs text-slate-600 font-medium",children:'Click "Generate Content" to finish'})})]}),placement:"top",disableBeacon:!0,interactive:!0,actionHint:"Click 'Generate Content' to start generation",keepOpenAfterInteraction:!0,autoTriggerOnNext:!0}],Pv=[{target:'[data-onboarding="context-modal"]',content:e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-semibold text-slate-900 mb-2",children:"Choose Template"}),e.jsx("p",{className:"text-sm text-slate-600",children:"Select a template for how your grouped keywords will be turned into articles."})]}),placement:"bottom",disableBeacon:!0},{target:'[data-onboarding="context-modal-template-grid"]',content:e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-semibold text-slate-900 mb-2",children:"Pick a Template"}),e.jsx("p",{className:"text-sm text-slate-600",children:"Choose the template that best matches your goal (e.g., guide, landing page, comparison)."})]}),placement:"top",disableBeacon:!0},{target:'[data-onboarding="context-modal-title-content-option"]',content:e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-semibold text-slate-900 mb-2",children:"Auto-generate Title & Content"}),e.jsx("p",{className:"text-sm text-slate-600",children:"Enable this to generate titles and content automatically after the worksheet is created."})]}),placement:"top",disableBeacon:!0},{target:'[data-onboarding="context-modal-generate-btn"]',content:e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-semibold text-slate-900 mb-2",children:"Generate Content"}),e.jsx("p",{className:"text-sm text-slate-600",children:"Click “Generate Content” to create the worksheet and start generation."})]}),placement:"top",disableBeacon:!0,interactive:!0,actionHint:"Click 'Generate Content' to start generation",keepOpenAfterInteraction:!0,autoTriggerOnNext:!0}],Iv=t=>[{id:"competitors_context",name:"Competitors",icon:Qs,expanded:!0,items:[{id:"competitors_intelligence",name:"Competitors Intelligence",icon:Qs,description:"Analyze your competitive landscape across selected markets and monitor changes over time.",actionTitle:"Competitors Intelligence",actionDescription:"Understand your competitors and track opportunities.",benefits:["Compare performance across competitors","Track changes over time","Discover new competitor opportunities"],actionLabel:"View Competitors",dataType:"competitors",workflowType:"seo"}]}
209,{id:"seo_content",name:"Keywords Research",icon:Pt,expanded:!0,items:[{id:"competitors_keywords",name:"Keywords Gap",icon:Pt,count:t.keywords_gap_count,description:"Identify keyword gaps from competitors and add to Target Keywords for content creation.",actionTitle:"Keywords Gap",actionDescription:"Find keyword opportunities from competitor analysis.",benefits:["Discover competitor keyword gaps","Find high volume, low competition keywords","Identify quick win opportunities"],actionLabel:"Add to Target Keywords",dataType:"keywords",workflowType:"seo"},{id:"target_keywords",name:"Target Keywords",icon:us,count:t.target_keywords_count,description:"Keywords you've collected and want to create content for.",actionTitle:"Target Keywords",actionDescription:"Manage your target keywords before generating content.",benefits:["Centralized keyword management","Track keywords from multiple sources","Ready for content generation"],actionLabel:"Generate Content",dataType:"keywords",workflowType:"seo"},{id:"keywords_group",name:"Keywords Group",icon:qa,count:t.keyword_groups_count,description:"AI-grouped keywords by topic for efficient content creation.",actionTitle:"Keywords Group",actionDescription:"Generate content from grouped keywords.",benefits:["Topic-clustered content strategy","Efficient batch content creation","Better internal linking opportunities"],actionLabel:"Generate Content",dataType:"groups",workflowType:"seo"},{id:"seo_related_worksheets",name:"Related Worksheets",icon:on,count:t.seo_related_worksheets_count,description:"View worksheets created from Keywords Research workflow.",actionTitle:"Related Worksheets",actionDescription:"Worksheets generated from keyword research.",benefits:["Quick access to generated content","Track content creation progress","Manage related worksheets"],actionLabel:"View Worksheets",dataType:"keywords",workflowType:"seo"}]},{id:"prompt_content",name:"AI Visibility",icon:is,expanded:!0,items:[{id:"prompt_tracking",name:"Prompt Tracking",icon:is,count:t.prompt_tracking_count,description:"Track and optimize your AI prompts for GEO/AEO visibility.",actionTitle:"Prompt Tracking",actionDescription:"Monitor your brand visibility in AI-generated responses.",benefits:["Track AI citations and mentions","Monitor competitor visibility","Optimize content for AI responses"],actionLabel:"View Prompts",dataType:"prompts",workflowType:"geo"},{id:"geo_related_worksheets",name:"Related Worksheets",icon:on,count:t.geo_related_worksheets_count,description:"View worksheets created from AI Visibility workflow.",actionTitle:"Related Worksheets",actionDescription:"Worksheets generated from prompt tracking.",benefits:["Quick access to generated content","Track content creation progress","Manage related worksheets"],actionLabel:"View Worksheets",dataType:"prompts",workflowType:"geo"}]},{id:"optimization_content",name:"Content Optimization",icon:_r,expanded:!0,items:[{id:"page_tracking",name:"Page Tracking",icon:Qt,count:t.page_tracking_count,description:"Track and optimize your existing pages for better SEO performance.",actionTitle:"Page Tracking",actionDescription:"Monitor your page rankings and optimize content.",benefits:["Track page rankings over time","Identify optimization opportunities","Monitor content performance"],actionLabel:"View Pages",dataType:"prompts",workflowType:"page"},{id:"page_related_worksheets",name:"Related Worksheets",icon:on,count:t.page_related_worksheets_count,description:"View worksheets created from Content Optimization workflow.",actionTitle:"Related Worksheets",actionDescription:"Worksheets generated from page optimization.",benefits:["Quick access to generated content","Track content creation progress","Manage related worksheets"],actionLabel:"View Worksheets",dataType:"prompts",workflowType:"page"}]}],gm=({categories:t,selectedItem:s,onSelect:a})=>e.jsx("div",{className:"px-3",children:e.jsx("div",{className:"space-y-5",children:t.map(n=>e.jsx(Rv,{category:n,selectedItem:s,onSelect:a},n.id))})}),Mv=t=>{switch(t){case"competitors_context":return"workflow-competitors";case"seo_content":return"workflow-keyword-gap";case"prompt_content":return"workflow-ai-visibility";case"optimization_content":return"workflow-content-optimization";default:return}},Rv=({category:t,selectedItem:s,onSelect:a})=>{const n=Mv(t.id);return e.jsxs("div",{"data-onboarding":n,children:[e.jsx("div",{className:"text-[9px] font-medium text-slate-400 uppercase tracking-wide mb-2",children:t.name}),e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"absolute left-[10px] top-3 bottom-3 w-[2px] bg-slate-200 rounded-full"}),e.jsx("div",{className:"space-y-2",children:t.items.map(o=>{const i=s===o.id;return e.jsxs("button",{onClick:()=>a(o.id),className:`pl-1.5 w-full flex items-center gap-4 py-2.5 pr-3 rounded-lg transition-all text-left group ${i?"bg-slate-100/80":"hover:bg-slate-50"}`,children:[e.jsx("div",{className:"relative z-10 flex-shrink-0",children:e.jsx("div",{className:`w-3 h-3 rounded-full border-2 transition-all ${i?"bg-slate-800 border-slate-800 scale-110":"bg-white border-slate-300 group-hover:border-slate-400"}`})}),e.jsxs("div",{className:"flex-1 flex items-center justify-between min-w-0",children:[e.jsx("span",{className:`text-[11px] truncate ${i?"font-medium text-slate-900":"text-slate-600 group-hover:text-slate-800"}`,children:o.name}),o.count!==void 0&&e.jsx("span",{className:`text-[10px] flex-shrink-0 ml-3 tabular-nums ${i?"text-slate-600":"text-slate-400"}`,children:o.count})]})]},o.id)})})]})]})},Dv=({item:t})=>e.jsxs("div",{className:"h-full flex flex-col p-4",children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("h2",{className:"text-lg font-semibold text-slate-800",children:t.actionTitle}),e.jsx("p",{className:"text-sm text-slate-500",children:t.description})]}),e.jsx("div",{className:"flex-1 min-h-0 overflow-auto pb-15",children:e.jsxs("div",{className:"text-sm text-slate-500",children:["Content for ",t.name," coming soon..."]})})]}),Lv=t=>["competitors_keywords","target_keywords","keywords_group"].includes(t),zv={competitors_keywords:"keywords_gap",target_keywords:"target_keywords",keywords_group:"keywords_group"};function $v(){const{toast:t}=_t(),[s,a]=r.useState(()=>Tr()),[n,o]=r.useState(0),[i,l]=r.useState(!1),[c,d]=r.useState(()=>{try{const we=localStorage.getItem("workflow_fab_position");if(we)return JSON.parse(we)}catch{}return{x:12,y:64}}),[m,h]=r.useState(!1);v.useRef(null);const p=Zs(Us.workflow_first_visit,{autoStart:!1}),f=Zs(Us.keywords_research_workflow,{autoStart:!1}),[b,y]=r.useState(null),x=Zs(Us.workflow,{autoStart:!1}),u=we=>
209{try{const Pe=(we||"/").split("/").filter(Boolean);return Pe[0]==="app"&&Pe[1]==="workflow"&&Pe[2]||null}catch{return null}},g=r.useCallback((we,Pe={})=>{try{const Ae=`/app/workflow/${we}`;window.location.pathname!==Ae&&(Pe.replace?window.history.replaceState({},"",Ae):window.history.pushState({},"",Ae),window.dispatchEvent(new PopStateEvent("popstate")))}catch{}},[]),[w,_]=r.useState(()=>{const we=u(window.location.pathname);if(we)return we;try{const Ae=new URLSearchParams(window.location.search).get("item");if(Ae)return Ae}catch{}return"competitors_keywords"}),E=v.useRef(w);r.useEffect(()=>{E.current=w},[w]);const N=r.useCallback(async({name:we,predicate:Pe,timeoutMs:Ae,intervalMs:ye})=>await new Promise(Te=>{const Ie=Date.now(),Oe=window.setInterval(()=>{try{if(Pe()){window.clearInterval(Oe),Te(!0);return}}catch(J){console.warn(`⚠️ waitForCondition(${we}) predicate error:`,J)}Date.now()-Ie>=Ae&&(window.clearInterval(Oe),Te(!1))},ye)}),[]),S=r.useCallback(async we=>{if(f.stop(),!await N({name:`grouping_navigate_to_keywords_group_${we}`,predicate:()=>{const ye=window.location.pathname||"";return E.current==="keywords_group"||ye.includes("/app/workflow/keywords_group")},timeoutMs:we==="ai"?18e4:2e4,intervalMs:120})){t({title:"Grouping is still in progress",description:"Please wait until grouping completes, then continue."});return}y("keywords_group"),await N({name:"keywords_group_dom_ready_after_grouping",predicate:()=>document.querySelector('[data-onboarding="keywords-group-header"]')!==null,timeoutMs:2e4,intervalMs:120})&&f.startExternal({force:!0})},[f,t,N]);r.useEffect(()=>{oi.isCompleted(Us.workflow_first_visit)||p.startExternal({force:!0})},[p]);const k=r.useCallback(()=>{p.stopAndMarkCompleted(),_("competitors_keywords"),g("competitors_keywords"),setTimeout(()=>{y("keywords_gap"),f.startExternal({force:!0})},80)},[p,f,g]),D=r.useCallback(()=>{if(b==="keywords_gap"){const we=document.querySelector('[data-onboarding-action="primary"]');we&&!we.disabled&&(console.log("🧭 Triggering Keywords Gap primary CTA via helper click"),we.click()),f.stop(),setTimeout(()=>{y("target_keywords"),_("target_keywords"),g("target_keywords"),(async()=>{await N({name:"target_keywords_dom_ready",predicate:()=>document.querySelector('[data-onboarding="target-keywords-table"]')!==null,timeoutMs:2e4,intervalMs:80})&&f.startExternal({force:!0})})().catch(()=>{})},120)}else if(b==="target_keywords"){if(document.querySelector('[data-onboarding="generate-content-modal"]')!==null||document.querySelector('[data-onboarding="grouping-modal"]')!==null)console.log("🧭 Generate Content modal already open; skipping helper click");else{const Pe=document.querySelector('[data-onboarding-action="primary"]');Pe&&!Pe.disabled&&(console.log("🧭 Opening Generate Content modal via helper click"),Pe.click())}f.stop(),(async()=>{await N({name:"generate_content_modal_dom_ready",predicate:()=>document.querySelector('[data-onboarding="generate-content-modal"]')!==null,timeoutMs:6e3,intervalMs:50})&&(y("generate_content_modal"),f.startExternal({force:!0}))})().catch(()=>{})}else if(b==="generate_content_modal"){f.stop();const we=document.querySelector('[data-onboarding="grouping-modal"]');if(document.querySelector('[data-onboarding="context-reference-modal"]')){console.log("🧭 Detected single-keyword flow; switching onboarding phase"),y("single_keyword_context"),setTimeout(()=>{f.startExternal({force:!0})},60);return}if(!we){console.log("🧭 No option selected yet; restarting choice step"),t({title:"Choose an option",description:"Please click one of the options to continue."}),setTimeout(()=>{y("generate_content_modal"),f.startExternal({force:!0})},80);return}console.log("🧭 Grouping view active; continuing"),y("ai_grouping_modal");const Ae=()=>{document.querySelector('[data-onboarding="grouping-modal"]')?f.startExternal({force:!0}):setTimeout(Ae,80)};setTimeout(Ae,160)}else if(b==="single_keyword_context"){const we=document.querySelector('[data-onboarding="single-keyword-template-modal"]');f.stop(),y("single_keyword_template");const Pe=()=>{document.querySelector('[data-onboarding="single-keyword-template-modal"]')?f.startExternal({force:!0}):setTimeout(Pe,80)};if(!we){const Ae=document.querySelector('[data-onboarding="context-reference-continue-btn"]');Ae&&!Ae.disabled&&(console.log("🧭 Continuing to template selection via helper click"),Ae.click())}setTimeout(Pe,160)}else if(b==="single_keyword_template"){const we=document.querySelector('[data-onboarding="single-keyword-generate-btn"]');we&&!we.disabled&&(console.log("🧭 Starting single-keyword generation via helper click"),we.click()),f.stopAndMarkCompleted(),y(null)}else if(b==="ai_grouping_modal"){const we=document.querySelector('[data-onboarding="ai-grouping-button"]');we?(console.log("🤖 Starting AI grouping via onboarding helper click"),we.click()):console.log("✅ AI grouping already started (button not found; modal likely closed)"),S("ai")}else if(b==="manual_grouping_modal"){console.log("🧭 Manual grouping onboarding phase completed; waiting for create action/navigation");return}else f.stopAndMarkCompleted(),y(null)},[b,f,g,S]),F=r.useCallback(()=>{const we=new KeyboardEvent("keydown",{key:"Escape",code:"Escape",keyCode:27,which:27,bubbles:!0});document.dispatchEvent(we),f.stopAndMarkCompleted(),y(null)},[f]),R=r.useCallback(we=>{const Pe=zv[we];Pe&&(y(Pe),f.startExternal({force:!0}))},[f]),L=r.useMemo(()=>
209{if(!b)return[];switch(b){case"keywords_gap":return Nv;case"target_keywords":return kv;case"generate_content_modal":return _v;case"ai_grouping_modal":return Ev;case"manual_grouping_modal":return Av;case"keywords_group":return Tv;case"keywords_group_template":return Pv;case"single_keyword_context":return Cv;case"single_keyword_template":return Sv;default:return[]}},[b]);r.useEffect(()=>{if(!f.run||b!=="ai_grouping_modal"&&b!=="manual_grouping_modal")return;let we=!1;const Pe=Ae=>{if(we)return;const ye=Ae.target;if(!ye)return;const Te=ye.closest?.('[data-onboarding="ai-grouping-button"]')!=null,Ie=ye.closest?.('[data-onboarding="grouping-tab-manual"]')!=null,Oe=ye.closest?.('[data-onboarding="grouping-tab-ai"]')!=null,J=ye.closest?.('[data-onboarding="manual-create-groups-btn"]')!=null;if(b==="ai_grouping_modal"){if(Ie){we=!0,console.log("🧭 Grouping modal: Manual tab clicked; switching tutorial phase"),f.stop(),setTimeout(()=>{y("manual_grouping_modal"),f.startExternal({force:!0})},80);return}if(Te){we=!0,console.log("🧭 Grouping modal: AI start clicked; waiting for navigation"),S("ai");return}}if(b==="manual_grouping_modal"){if(Oe){we=!0,console.log("🧭 Grouping modal: AI tab clicked; switching tutorial phase"),f.stop(),setTimeout(()=>{y("ai_grouping_modal"),f.startExternal({force:!0})},80);return}if(J){const re=ye.closest?.('[data-onboarding="manual-create-groups-btn"]');if(re&&re.disabled)return;we=!0,console.log("🧭 Grouping modal: Manual create clicked; waiting for navigation"),S("manual");return}}};return document.addEventListener("click",Pe,!0),()=>document.removeEventListener("click",Pe,!0)},[b,f,S]),r.useEffect(()=>{if(!f.run||b!=="generate_content_modal")return;let we=!1,Pe=!1,Ae=0;const ye=180,Te=()=>{if(we||Pe)return;Ae+=1;const Oe=document.querySelector('[data-onboarding="grouping-modal"]'),J=document.querySelector('[data-onboarding="context-reference-modal"]');if(Oe){Pe=!0,console.log("🧭 Detected grouping modal; switching onboarding phase"),f.stop(),setTimeout(()=>{we||(y("ai_grouping_modal"),f.startExternal({force:!0}))},150);return}if(J){Pe=!0,console.log("🧭 Detected single-keyword context modal; switching onboarding phase"),f.stop(),setTimeout(()=>{we||(y("single_keyword_context"),f.startExternal({force:!0}))},150);return}Ae>=ye&&(we=!0)},Ie=window.setInterval(Te,50);return Te(),()=>{we=!0,window.clearInterval(Ie)}},[b,f]),r.useEffect(()=>{if(!f.run||b!=="single_keyword_context")return;let we=!1,Pe=!1,Ae=0;const ye=180,Te=()=>{if(we||Pe)return;if(Ae+=1,document.querySelector('[data-onboarding="single-keyword-template-modal"]')){Pe=!0,console.log("🧭 Detected single-keyword template modal; switching onboarding phase"),f.stop(),setTimeout(()=>{we||(y("single_keyword_template"),f.startExternal({force:!0}))},150);return}Ae>=ye&&(we=!0)},Ie=window.setInterval(Te,50);return Te(),()=>{we=!0,window.clearInterval(Ie)}},[b,f]),r.useEffect(()=>{if(!f.run||b!=="single_keyword_context")return;let we=!1;const Pe=Ae=>{if(we)return;const ye=Ae.target;if(!ye)return;const Te=ye.closest?.('[data-onboarding="context-reference-continue-btn"]')!=null,Ie=ye.closest?.('[data-onboarding="context-reference-back-btn"]')!=null;if(!(!Te&&!Ie)){if(we=!0,Ie){console.log("🧭 ContextReference: Back clicked; returning to choice step"),f.stop(),(async()=>{await N({name:"generate_content_modal_ready_after_back",predicate:()=>document.querySelector('[data-onboarding="generate-content-modal"]')!==null,timeoutMs:6e3,intervalMs:50})&&(y("generate_content_modal"),f.startExternal({force:!0}))})().catch(()=>{});return}console.log("🧭 ContextReference: Continue clicked; advancing to single keyword template step"),f.stop(),(async()=>{await N({name:"single_keyword_template_ready_after_continue",predicate:()=>document.querySelector('[data-onboarding="single-keyword-template-modal"]')!==null,timeoutMs:1e4,intervalMs:50})&&(y("single_keyword_template"),f.startExternal({force:!0}))})().catch(()=>{})}};return document.addEventListener("click",Pe,!0),()=>{document.removeEventListener("click",Pe,!0)}},[b,f,N]),r.useEffect(()=>{if(!f.run||b!=="keywords_group")return;let we=!1;const Pe=Ae=>{if(we)return;const ye=Ae.target;!ye||!(ye.closest?.('[data-onboarding="context-reference-continue-btn"]')!=null)||(we=!0,console.log("🧭 Keywords Group: Continue clicked; switching to template onboarding"),f.stop(),(async()=>{await N({name:"keywords_group_template_ready_after_continue",predicate:()=>document.querySelector('[data-onboarding="context-modal"]')!==null,timeoutMs:1e4,intervalMs:50})&&(y("keywords_group_template"),f.startExternal({force:!0}))})().catch(()=>{}))};return document.addEventListener("click",Pe,!0),()=>document.removeEventListener("click",Pe,!0)},[b,f,N]),r.useEffect(()=>{const we=()=>{const Pe=u(window.location.pathname);if(Pe){_(Pe);return}try{const ye=new URLSearchParams(window.location.search).get("item");if(ye){g(ye,{replace:!0});return}
209const Te=(window.location.pathname||"/").split("/").filter(Boolean);Te[0]==="app"&&Te[1]==="workflow"&&!Te[2]&&g(E.current||"competitors_keywords",{replace:!0})}catch{}};return we(),window.addEventListener("popstate",we),()=>window.removeEventListener("popstate",we)},[g]),r.useEffect(()=>{a(Tr());const we=mr(),Pe=Pc(Ae=>{Ae.scope_key===we&&a(!!Ae.ready)});return()=>{try{Pe()}catch{}}},[]),r.useEffect(()=>{const we=Oi(()=>{o(Ae=>Ae+1)}),Pe=So(()=>{o(Ae=>Ae+1)});return()=>{try{we()}catch{}try{Pe()}catch{}}},[]);const[$,H]=r.useState(null),[K,X]=r.useState(!1),[V,P]=r.useState([]),[A,C]=r.useState(!1),[I,j]=r.useState(""),[q,T]=r.useState(""),[M,Z]=r.useState([]),[B,ae]=r.useState(""),[de,fe]=r.useState("");r.useEffect(()=>{const we=setTimeout(()=>{T(I)},1e3);return()=>clearTimeout(we)},[I]),r.useEffect(()=>{const we=setTimeout(()=>{fe(B)},1e3);return()=>clearTimeout(we)},[B]);const se=v.useRef({panelId:null,fired:!1}),[z,U]=r.useState({keywords_gap_count:0,target_keywords_count:0,keyword_groups_count:0,prompt_tracking_count:0,page_tracking_count:0,seo_related_worksheets_count:0,geo_related_worksheets_count:0,page_related_worksheets_count:0}),Q=r.useCallback(async()=>{try{const we=await kc();U(we)}catch(we){console.error("❌ Failed to load workflow counts:",we)}},[]),me=r.useCallback(async we=>{C(!0);try{const Ae=((await ds.listKeywords({keyword:we||void 0,page:1,page_size:1e3})).items||[]).map(ye=>
209({id:ye.id,keyword:ye.keyword,created_at:ye.created_at}));P(Ae)}catch(Pe){console.error("❌ Failed to load target keywords:",Pe)}finally{C(!1)}},[]),le=r.useCallback(async()=>{try{const we=await ds.listGroups({page:1,page_size:1e3});Z(we.items||[])}catch(we){console.error("❌ Failed to load keyword groups:",we)}},[]);r.useEffect(()=>{Q()},[Q]),r.useEffect(()=>{w==="target_keywords"&&me(q)},[q,w,me]);const O=r.useCallback(async(we,Pe)=>{if(Pe==="ai")try{const{creditEstimateService:Ae}=await Bt(async()=>{const{creditEstimateService:J}=await Promise.resolve().then(()=>Ya);return{creditEstimateService:J}},void 0),{validateCreditBalance:ye}=await Bt(async()=>{const{validateCreditBalance:J}=await Promise.resolve().then(()=>ua);return{validateCreditBalance:J}},void 0),Te=await Ae.estimateCredits({scenario:"keyword_group_ai_group_keywords",params:{keyword_count:we.length,total_keyword_chars:we.reduce((J,re)=>J+re.length,0)}});if(!await ye({estimatedRange:Te?{min:Te.estimated_min_credits,max:Te.estimated_max_credits}:null,requiredMinimumBalance:Te?.required_minimum_balance??null,toast:t}))throw new Error("Insufficient credits");return{taskId:(await ds.aiGroupKeywords({keywords:we.map(J=>({keyword:J,source:"tracked"}))})).task_id,isAsync:!0}}catch(Ae){throw t({title:"Failed to start AI grouping",description:Ae?.message||"Please try again later"}),Ae}try{const Ae=`Group ${new Date().toLocaleDateString("en-CA")}`,ye=await ds.createGroup({name:Ae,description:`Manual group with ${we.length} keywords`});return await ds.addKeywordsToGroup({group_id:ye.id,keywords:we}),t({title:"Group Created",description:`Created "${Ae}" with ${we.length} keywords`}),await Promise.all([le(),Q()]),[{id:ye.id,name:Ae}]}catch(Ae){throw t({title:"Failed to create group",description:Ae?.message||"Please try again later"}),Ae}},[t,le,Q]),ne=r.useMemo(()=>Iv(z),[z]),ge=r.useMemo(()=>ne.flatMap(we=>we.items).find(we=>we.id===w),[ne,w]),ze=()=>{_("keywords_group"),g("keywords_group")},Ke=r.useCallback(async()=>{X(!0);try{if(ma().length===0&&!await Pr({timeout_ms:5e3})){console.warn("⚠️ Markets not ready; skip loading competitors."),X(!1);return}const Pe=await Tn();H(Pe)}catch(we){console.error("❌ Failed to load competitors:",we)}finally{X(!1)}},[]);r.useEffect(()=>{se.current.panelId!==w&&(se.current.panelId=w,se.current.fired=!1);const we=(Pe,Ae,ye)=>{se.current.fired||Pe&&(se.current.fired=!0,Ae())};if(w==="competitors_keywords"){we(!K&&!$,Ke);return}if(w==="target_keywords"){we(V.length===0&&!A,me);return}if(w==="keywords_group"){we(M.length===0,le);return}},[w,$,K,V.length,A,M.length,Ke,me,le]);const ie=()=>{if(!ge)return e.jsx("div",{className:"flex-1 flex items-center justify-center text-slate-400",children:"Select an item to view details"});switch(ge.id){case"competitors_intelligence":return e.jsx(mh,{marketReloadNonce:n});case"competitors_keywords":return e.jsx(tv,{competitors:$,loading:K,selectedItem:{actionTitle:ge.actionTitle,description:ge.description},onRefreshCompetitors:async()=>{await Promise.all([Ke(),Q()])},onAddComplete:()=>{Q(),_("target_keywords"),g("target_keywords")}});case"target_keywords":return e.jsx(ov,{onNavigateToGroups:ze,targetKeywords:V,loading:A,searchKeyword:I,onSearchChange:j,onRefresh:async()=>{await Promise.all([me(q),Q()])},onGroupKeywords:O});case"keywords_group":return e.jsx(uv,{searchKeyword:B,debouncedSearchKeyword:de,onSearchChange:ae,onRefresh:async()=>{await Promise.all([le(),Q()])}});case"prompt_tracking":return e.jsx(ih,{});case"page_tracking":return e.jsx(dh,{});case"seo_related_worksheets":return e.jsx(fl,{workflowType:"seo"});case"geo_related_worksheets":return e.jsx(fl,{workflowType:"geo"});case"page_related_worksheets":return e.jsx(fl,{workflowType:"page"});default:return e.jsx(Dv,{item:ge})}},ve=Lv(w);return e.jsxs("div",{className:"flex h-full bg-white relative",children:[e.jsx(oa,{steps:pm,run:p.run,onComplete:k,onSkip:k}),f.run&&L.length>0&&e.jsx(Uc,{steps:L,run:f.run,onComplete:D,onSkip:F,isLastPhase:b==="keywords_group"||b==="single_keyword_template",startDelay:80,onStepChange:(we,Pe)=>{b==="keywords_gap"&&Pe.target==='[data-onboarding="keywords-gap-quick-select"]'&&setTimeout(()=>{const Ae=document.querySelector('[data-onboarding="keywords-gap-table"]');if(Ae){const ye=Ae.querySelectorAll('td button[role="checkbox"][aria-checked="false"]'),Te=Math.min(10,ye.length);for(let Ie=0;Ie<Te;Ie++)setTimeout(()=>{ye[Ie].click()},Ie*50)}},400),b==="target_keywords"&&we===2&&setTimeout(()=>{const Ae=document.querySelector('[data-onboarding="target-keywords-table"]');if(Ae){const ye=Ae.querySelectorAll('td button[role="checkbox"][aria-checked="false"]');for(let Te=0;Te<ye.length;Te++)setTimeout(()=>{ye[Te].click()},Te*50)}},400),b==="keywords_group"&&Pe.target==='[data-onboarding="keywords-group-table-spotlight"]'&&we===2&&setTimeout(()=>{const Ae=document.querySelector('[data-onboarding="keywords-group-table"]');if(Ae){const ye=Ae.querySelectorAll('td button[role="checkbox"][aria-checked="false"]');for(let Te=0;Te<ye.length;Te++)setTimeout(()=>{ye[Te].click()},Te*50)}},400)}}
209),!ve&&e.jsx(oa,{steps:pm,run:x.run,onComplete:x.stopAndMarkCompleted,onSkip:x.stopAndMarkCompleted}),e.jsx("button",{onClick:()=>{ve?R(w):x.startManual()},className:"fixed bottom-5 right-5 z-50 h-8 w-8 rounded-full bg-white border border-slate-200 shadow-md hover:shadow-lg hover:bg-slate-50 transition-all hover:scale-105 hidden sm:flex items-center justify-center",title:ve?"View Keywords Research guide":"View workflow guide","aria-label":ve?"View Keywords Research guide":"View workflow guide",children:e.jsx(Hs,{className:"h-4 w-4 text-slate-600"})}),i&&e.jsx("div",{className:"fixed inset-0 z-[60] bg-black/40 backdrop-blur-sm md:hidden",onClick:()=>l(!1),children:e.jsxs("div",{className:"absolute left-0 right-0 bottom-0 max-h-[70vh] bg-white rounded-t-2xl shadow-2xl flex flex-col animate-in slide-in-from-bottom duration-300",onClick:we=>we.stopPropagation(),children:[e.jsx("div",{className:"flex justify-center pt-3 pb-1 shrink-0",children:e.jsx("div",{className:"w-10 h-1 bg-slate-300 rounded-full"})}),e.jsxs("div",{className:"flex items-center justify-between px-5 py-2 border-b border-slate-100 shrink-0",children:[e.jsx("span",{className:"text-base font-semibold text-slate-900",children:"Switch Step"}),e.jsx("button",{onClick:()=>l(!1),className:"flex items-center justify-center w-8 h-8 text-slate-400 hover:text-slate-600 hover:bg-slate-100 rounded-full transition-colors",children:e.jsx(mt,{size:18})})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto overscroll-contain py-2 px-2 pb-safe",children:[e.jsx(gm,{categories:ne,selectedItem:w,onSelect:we=>{_(we),g(we),l(!1)}}),e.jsx("div",{className:"h-6"})]})]})}),e.jsxs("div",{className:"hidden md:flex w-52 border-r border-slate-200/60 flex-col bg-slate-50/30","data-onboarding":"workflow-sidebar",children:[e.jsx("div",{className:"h-12 flex items-center px-4 border-b border-slate-200/60",children:e.jsx("h1",{className:"text-[15px] font-semibold text-slate-800",children:"Workflow"})}),e.jsx("div",{className:"flex-1 overflow-y-auto py-5 space-y-6",children:e.jsx(gm,{categories:ne,selectedItem:w,onSelect:we=>{_(we),g(we)}})})]}),e.jsxs("div",{className:"flex-1 flex flex-col bg-white sm:bg-slate-50 overflow-hidden relative min-h-0","data-onboarding":"workflow-main-panel",children:[(w==="competitors_keywords"||w==="competitors_intelligence")&&e.jsx("div",{className:"hidden sm:block shrink-0 bg-white border-b border-slate-200/60",children:e.jsx("div",{className:"px-4 py-2 flex items-center gap-3 overflow-x-auto",children:e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx("div",{className:"text-[12px] font-semibold text-slate-700 whitespace-nowrap",children:"Markets:"}),e.jsx(Bi,{})]})})}),e.jsx("div",{className:"flex-1 min-h-0 overflow-hidden",children:ie()})]})]})}const Fv=[{target:'[data-onboarding="company-header"]',content:e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-semibold text-slate-900 mb-2",children:"Company Info"}),e.jsx("p",{className:"text-sm text-slate-600",children:"This page displays your company profile extracted from your website. The information here is used as context for AI-generated content to ensure brand consistency and relevance."})]}),placement:"bottom",disableBeacon:!0},{target:'[data-onboarding="company-reanalyze"]',content:e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-semibold text-slate-900 mb-2",children:"Re-analyze"}),e.jsx("p",{className:"text-sm text-slate-600",children:"Click to re-analyze your website and update the company profile. Use this when your website content has changed significantly or if the initial analysis needs improvement."})]}),placement:"bottom",disableBeacon:!0},{target:'[data-onboarding="company-profile"]',content:e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-semibold text-slate-900 mb-2",children:"Company Profile"}),e.jsx("p",{className:"text-sm text-slate-600 mb-2",children:"Your company's core information:"}),e.jsxs("ul",{className:"text-sm text-slate-600 space-y-1.5 list-disc list-inside",children:[e.jsxs("li",{children:[e.jsx("span",{className:"font-medium",children:"Company Name"})," - Used in generated content and branding"]}),e.jsxs("li",{children:[e.jsx("span",{className:"font-medium",children:"Domain"})," - Your website URL for reference"]}),e.jsxs("li",{children:[e.jsx("span",{className:"font-medium",children:"About"})," - Company description used as AI context"]})]})]}),placement:"right",disableBeacon:!0},{target:'[data-onboarding="company-edit"]',content:e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-semibold text-slate-900 mb-2",children:"Edit Information"}),e.jsx("p",{className:"text-sm text-slate-600",children:"Click Edit to manually update your company name and description. A detailed, accurate description improves the quality of AI-generated SEO content by providing better context."})]}),placement:"left",disableBeacon:!0}];function Ov(){const{toast:t}=_t(),[s,a]=r.useState(!0),[n,o]=r.useState(null),[i,l]=r.useState(null),c=Zs(Us.company),d=()=>"company",[m,h]=r.useState(d());r.useEffect(()=>{const k=()=>{h(d())};return window.addEventListener("popstate",k),()=>window.removeEventListener("popstate",k)},[]);const[p,f]=r.useState(!1),[b,y]=r.useState(""),[x,u]=r.useState(""),[g,w]=r.useState(!1),[_,E]=r.useState("");r.useEffect(()=>{(async()=>{a(!0);try{const{company:k}=await Dn();if(!k||!k.url)return;const D={name:k.name||new URL(k.url).hostname.replace(/^www\./,"").split(".")[0],domain:new URL(k.url).hostname,homepage:k.url,description:k.about||"",extracted_keywords:[],content_analysis:{word_count:k.word_count||0,heading_count:k.heading_count||0,link_count:k.link_count||0,paragraph_count:k.paragraph_count||0,image_count:k.image_count||0,language_detected:k.language_detected||"EN",content_type:k.content_type||"business_website"},analysis_metadata:{analysis_time:k.analysis_time||new Date().toISOString(),processing_time_seconds:k.processing_time_seconds||0,total_results_processed:0,successful_results:0,ai_model_used:k.ai_model_used||"gemini-3-pro",url_analyzed:k.url,keywords_extracted_count:0,content_length:k.content_length||0,extraction_method:k.extraction_method||"ai"}};o(D),E(k.id),y(k.name||""),u(k.about||""),l(k.competitor_analysis_insights||null)}catch(k){console.error("❌ Failed to load company data:",k)}finally{a(!1)}})()},[]);async function N(){if(!_){t({title:"Error",description:"Company ID not found"});return}w(!0);try{const k=await Iu({company_id:_,name:b.trim()||void 0,about:x.trim()||void 0});if(n){const D={...n,name:k.name||n.name,description:k.about||""};o(D)}f(!1),t({title:"Saved",description:"Company information updated successfully"})}catch(k){console.error("Save error:",k),t({title:"Error",description:k?.message||"Failed to save. Please try again."})}finally{w(!1)}}
209function S(){n&&(y(n.name||""),u(n.description||"")),f(!1)}return s?e.jsx("div",{className:"h-full flex items-center justify-center",children:e.jsxs("div",{className:"text-center",children:[e.jsx(He,{className:"h-8 w-8 animate-spin text-slate-400 mx-auto"}),e.jsx("p",{className:"mt-4 text-slate-600",children:"Loading company data..."})]})}):e.jsxs("div",{className:"p-6 max-w-5xl mx-auto space-y-6 relative",children:[e.jsx(oa,{steps:Fv,run:c.run,onComplete:c.stopAndMarkCompleted,onSkip:c.stopAndMarkCompleted}),e.jsx("div",{className:"hidden sm:flex items-center justify-between","data-onboarding":"company-header",children:e.jsxs("div",{children:[e.jsx("h1",{className:"text-3xl font-bold tracking-tight",children:"Company Info"}),e.jsx("p",{className:"text-slate-600 mt-2",children:"Your company information"})]})}),n&&e.jsx(xs,{className:"rounded-2xl border-0 shadow-sm","data-onboarding":"company-profile",children:p?e.jsxs(e.Fragment,{children:[e.jsx(Bs,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-12 w-12 rounded-xl bg-slate-100 flex items-center justify-center",children:e.jsx(an,{className:"h-6 w-6 text-slate-700"})}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-semibold",children:"Edit Company Information"}),e.jsx("p",{className:"text-sm text-slate-600 mt-1",children:"Update your company name and description"})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(be,{variant:"outline",size:"sm",onClick:S,disabled:g,children:"Cancel"}),e.jsxs(be,{size:"sm",onClick:N,disabled:g,children:[g&&e.jsx(He,{className:"mr-2 h-4 w-4 animate-spin"}),e.jsx(pu,{className:"mr-2 h-4 w-4"}),"Save Changes"]})]})]})}),e.jsxs(fs,{className:"space-y-8 py-8",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(Gt,{htmlFor:"company-name",className:"text-base font-semibold",children:"Company Name"}),e.jsx("p",{className:"text-sm text-slate-500 mt-2",children:"The official name of your company"})]}),e.jsx(bt,{id:"company-name",value:b,onChange:k=>y(k.target.value),placeholder:"Enter company name",className:"h-14 text-lg px-4"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(Gt,{htmlFor:"company-about",className:"text-base font-semibold",children:"About Company"}),e.jsx("p",{className:"text-sm text-slate-500 mt-2",children:"A brief description of what your company does and what makes it unique"})]}),e.jsx("textarea",{id:"company-about",value:x,onChange:k=>u(k.target.value),placeholder:`Enter company description... 
210
211Describe your company's mission, products, services, and what sets you apart from competitors.`,rows:12,maxLength:2e3,className:"w-full p-5 text-base leading-relaxed border border-slate-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-slate-900 focus:border-transparent resize-y"}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("p",{className:"text-sm text-slate-500",children:[x.length," / 2000 characters"]}),e.jsx("p",{className:"text-xs text-slate-400",children:"Tip: A detailed description helps with better SEO"})]})]}),e.jsx("div",{className:"pt-6 border-t",children:e.jsxs("p",{className:"text-sm text-slate-600",children:[e.jsx("span",{className:"font-medium",children:"Website:"})," ",e.jsxs("a",{href:n.homepage,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:underline inline-flex items-center gap-1",children:[n.domain,e.jsx(ns,{className:"h-3 w-3"})]})]})})]})]}):e.jsxs(e.Fragment,{children:[e.jsx(Bs,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-12 w-12 rounded-xl bg-slate-100 flex items-center justify-center",children:e.jsx(an,{className:"h-6 w-6 text-slate-700"})}),e.jsxs("div",{children:[e.jsx(Xs,{children:n.name||n.domain}),e.jsx(Br,{className:"mt-1",children:e.jsxs("a",{href:n.homepage,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:underline flex items-center gap-1",children:[n.domain,e.jsx(ns,{className:"h-3 w-3"})]})})]})]}),e.jsxs(be,{variant:"outline",size:"sm",onClick:()=>f(!0),"data-onboarding":"company-edit",children:[e.jsx(Ua,{className:"mr-2 h-4 w-4"}),"Edit"]})]})}),e.jsx(fs,{className:"space-y-6",children:e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-semibold mb-2",children:"About"}),e.jsx("pre",{className:"text-sm text-slate-600 leading-relaxed whitespace-pre-wrap break-words",children:n.description||"No description available"})]})})]})}),e.jsx("button",{onClick:c.startManual,className:"fixed bottom-5 right-5 z-50 h-8 w-8 rounded-full bg-white border border-slate-200 shadow-md hover:shadow-lg hover:bg-slate-50 transition-all hover:scale-105 hidden sm:flex items-center justify-center",title:"View navigation guide","aria-label":"View navigation guide",children:e.jsx(Hs,{className:"h-4 w-4 text-slate-600"})})]})}const Bv=[{target:'[data-onboarding="blank-spreadsheet-btn"]',content:e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-semibold text-slate-900 mb-2",children:"Create a Blank Table"}),e.jsx("p",{className:"text-sm text-slate-600 mb-2",children:"Start with an empty table and define your own column structure. Suitable for custom workflows."})]}),placement:"bottom",disableBeacon:!0,interactive:!0,actionHint:"Click to create a blank table"},{target:'[data-onboarding="system-template-cards"]',content:e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-semibold text-slate-900 mb-2",children:"Use a Template"}),e.jsx("p",{className:"text-sm text-slate-600 mb-2",children:"Pre-configured tables with AI columns ready to use:"}),e.jsxs("ul",{className:"text-sm text-slate-600 space-y-1 list-disc list-inside",children:[e.jsxs("li",{children:[e.jsx("span",{className:"font-medium",children:"Create New Content"})," - Generate SEO content from keywords"]}),e.jsxs("li",{children:[e.jsx("span",{className:"font-medium",children:"Optimize Existing"})," - Improve published pages"]})]})]}),placement:"bottom",disableBeacon:!0,interactive:!0,actionHint:"Click on a template to use it"},{target:'[data-onboarding="first-worksheet-item"]',content:e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-semibold text-slate-900 mb-2",children:"Qu
211ick Reference"}),e.jsxs("ul",{className:"text-sm text-slate-600 space-y-1.5",children:[e.jsx("li",{children:"Right-click a table to rename or delete"}),e.jsx("li",{children:"Save tables as templates for reuse"}),e.jsxs("li",{children:["Click ",e.jsx("span",{className:"font-medium",children:"?"})," to restart this guide"]})]})]}),placement:"right",disableBeacon:!0,interactive:!1}],fm="onboarding:table:completed";function Uv(t={}){const{delay:s=500,isLoading:a=!1}=t,[n,o]=r.useState(!1),[i,l]=r.useState(()=>{try{return localStorage.getItem(fm)==="true"}catch{return!1}});r.useEffect(()=>{if(a||i)return;const h=setTimeout(()=>{o(!0)},s);return()=>clearTimeout(h)},[a,i,s]);const c=r.useCallback(()=>{o(!0)},[]),d=r.useCallback(()=>{o(!1)},[]),m=r.useCallback(()=>{o(!1),l(!0);try{localStorage.setItem(fm,"true")}catch{}},[]);return r.useEffect(()=>{const h=()=>{console.log("[useTableOnboarding] Restarting onboarding via HelpButton"),o(!0)};return window.addEventListener("restartTableOnboarding",h),()=>{window.removeEventListener("restartTableOnboarding",h)}},[]),{runOnboarding:n,startOnboarding:c,stopOnboarding:d,completeOnboarding:m,isCompleted:i}}const ym="onboarding:worksheets:completed";function Kv(t={}){const{isLoading:s=!1,delay:a=300}=t,[n,o]=r.useState(!1),[i,l]=r.useState(()=>{try{return localStorage.getItem(ym)==="true"}catch{return!1}});r.useEffect(()=>{if(s||i)return;const h=setTimeout(()=>{o(!0)},a);return()=>clearTimeout(h)},[s,i,a]);const c=r.useCallback(()=>{o(!0)},[]),d=r.useCallback(()=>{o(!1)},[]),m=r.useCallback(()=>{o(!1),l(!0);try{localStorage.setItem(ym,"true")}catch{}},[]);return r.useEffect(()=>{const h=()=>{console.log("[useWorksheetsOnboarding] Restarting onboarding via HelpButton"),o(!0)};return window.addEventListener("restartWorksheetsOnboarding",h),()=>{window.removeEventListener("restartWorksheetsOnboarding",h)}},[]),{runOnboarding:n,startOnboarding:c,stopOnboarding:d,completeOnboarding:m,isCompleted:i}}const Ko=[{id:"seo_content_webflow",name:"Create New Content (Webflow)",description:"Analyze pages and generate optimized content for Webflow",previewBg:"from-emerald-50 to-emerald-100"},{id:"seo_content_shopify",name:"Create New Content (Shopify)",description:"Analyze pages and generate optimized content for Shopify",previewBg:"from-emerald-50 to-emerald-100"},{id:"seo_analysis_shopify",name:"Optimize Existing Content",description:"Analyze and optimize SEO performance with AI",previewBg:"from-blue-50 to-blue-100"},{id:"content_refresh",name:"Content Refresh",description:"Analyze pages and generate refreshed content with keyword optimization",previewBg:"from-purple-50 to-purple-100"}];function Gv(t){const s=new Date,a=s.toLocaleString("en-US",{month:"short"}),n=s.getDate();return`${{seo_content_webflow:"Create New Content",seo_content_shopify:"Create New Content",seo_analysis_shopify:"Optimize Existing Content",content_refresh:"Content Refresh"}[t]} - ${a} ${n}`}function Wv(t){if(!t)return"--";const s=new Date(t);return(new Date().getTime()-s.getTime())/(1e3*60*60)<24?s.toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0}):s.toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"})}function Vv(t){const s=new Date,a=new Date(s.getFullYear(),s.getMonth(),s.getDate()),n=new Date(a.getTime()-10080*60*1e3),o=new Date(a.getTime()-720*60*60*1e3),i={Today:[],"Previous 7 days":[],"Previous 30 days":[],Earlier:[]};return t.forEach(l=>{const c=l.createdAt?new Date(l.createdAt):new Date(0);c>=a?i.Today.push(l):c>=n?i["Previous 7 days"].push(l):c>=o?i["Previous 30 days"].push(l):i.Earlier.push(l)}),i}function bm({onRename:t,onDelete:s}){const[a,n]=r.useState(!1),o=r.useRef(null);return r.useEffect(()=>{const i=l=>{o.current&&!o.current.contains(l.target)&&n(!1)};return a&&document.addEventListener("mousedown",i),()=>document.removeEventListener("mousedown",i)},[a]),e.jsxs("div",{className:"relative",ref:o,children:[e.jsx("button",{onClick:i=>{i.stopPropagation(),n(!a)},className:"p-2 rounded-full hover:bg-gray-100 transition-colors",children:e.jsx(En,{className:"h-5 w-5 text-gray-500"})}),a&&e.jsxs("div",{className:"absolute right-0 top-full mt-1 w-48 bg-white rounded-md shadow-lg border border-gray-200 py-2 z-50",children:[e.jsx("button",{onClick:i=>{i.stopPropagation(),n(!1),t()},className:"w-full px-4 py-2 text-left text-sm text-gray-700 hover:bg-gray-100",children:"Rename"}),e.jsx("button",{onClick:i=>{i.stopPropagation(),n(!1),s()},className:"w-full px-4 py-2 text-left text-sm text-gray-700 hover:bg-gray-100",children:"Remove"})]})]})}function Hv(){const{toast:t}=_t(),[s,a]=r.useState([]),[n,o]=r.useState(!1),[i,l]=r.useState(!1),[c,d]=r.useState(!1),[m,h]=r.useState(!1),[p,f]=r.useState(!1);r.useEffect(()=>{const ue=()=>l(window.innerWidth<640);return ue(),window.addEventListener("resize",ue),()=>window.removeEventListener("resize",ue)},[]);const{runOnboarding:b,startOnboarding:y,completeOnboarding:x}=Kv({isLoading:n,hasWorksheets:s.length>0});r.useEffect(()=>{const ue=()=>{y()};return window.addEventListener("restartWorksheetsOnboarding",ue),()=>{window.removeEventListener("restartWorksheetsOnboarding",ue)}},[y]);const[u,g]=r.useState(null),[w,_]=r.useState(!1),[E,N]=r.useState(null),[S,k]=r.useState(""),[D,F]=r.useState("list"),[R,L]=r.useState("asc"),[$,H]=r.useState([]),[K,X]=r.useState(!1),[V,P]=r.useState(null),[A,C]=r.useState(null),I=r.useRef(null),j=r.useRef(null),[q,T]=r.useState(1),[M]=r.useState(12),[Z,B]=r.useState(!0),[ae,de]=r.useState(!1),[fe,se]=r.useState(!1),[z,U]=r.useState(1),[Q]=r.useState(12),[me,le]=r.useState(1),[O,ne]=r.useState(0),[ge,ze]=r.useState([]);function Ke(ue){return{id:ue.id,name:ue.name,description:ue.description||"",keywordCount:ue.keyword_count||0,groupCount:ue.group_count||0,contentCount:ue.content_count||0}}async function ie(){o(!0);try{const W=((await lr({page:1,page_size:1e3})).items||[]).map(Ke);a(W)}
211catch(ue){t({title:"Failed to load worksheets",description:ue?.message||"Please try again later"})}finally{o(!1)}}async function ve(){X(!0);try{const ue=await io({page:1,page_size:M}),W=ue.items||[];H(W),T(1);const ke=typeof ue.total_pages=="number"&&ue.total_pages>0?ue.total_pages:1;B(1<ke)}catch(ue){console.error("Failed to load user templates:",ue),H([]),B(!1),T(1)}finally{X(!1)}}async function we(){if(!(K||ae||!Z)){de(!0);try{const ue=q+1,W=await io({page:ue,page_size:M}),ke=W.items||[];H(Qe=>{const ct=new Set(Qe.map(At=>At.id)),pt=[...Qe];for(const At of ke)ct.has(At.id)||pt.push(At);return pt}),T(ue);const qe=typeof W.total_pages=="number"&&W.total_pages>0?W.total_pages:ue;B(ue<qe)}catch(ue){console.error("Failed to load more user templates:",ue),B(!1)}finally{de(!1)}}}async function Pe(ue){try{const W=await io({page:ue,page_size:Q});ze(W.items||[]),ne(typeof W.total=="number"?W.total:0),le(typeof W.total_pages=="number"&&W.total_pages>0?W.total_pages:1)}catch(W){console.error("Failed to load gallery templates:",W),ze([]),ne(0),le(1)}}r.useEffect(()=>{ie(),ve()},[]),r.useEffect(()=>{const ue=I.current,W=j.current;if(!ue||!W)return;const ke=new IntersectionObserver(qe=>{const Qe=qe[0];Qe&&Qe.isIntersecting&&we()},{root:ue,rootMargin:"0px 240px 0px 0px",threshold:.1});return ke.observe(W),()=>ke.disconnect()},[K,ae,Z,q,M]),r.useEffect(()=>{fe&&Pe(z)},[fe,z,Q]);const Ae=r.useMemo(()=>[...s].sort((W,ke)=>{const qe=W.name.localeCompare(ke.name);return R==="asc"?qe:-qe}),[s,R]),ye=r.useMemo(()=>Vv(Ae),[Ae]);function Te(ue){const W=new Set(s.map(qe=>qe.name.toLowerCase()));if(!W.has(ue.toLowerCase()))return ue;let ke=1;for(;W.has(`${ue} (${ke})`.toLowerCase());)ke++;return`${ue} (${ke})`}async function Ie(){_(!0);try{const ue=new Date,W=`Untitled spreadsheet - ${ue.toLocaleString("en-US",{month:"short"})} ${ue.getDate()}`,ke=Te(W),qe=await No({name:ke,template_type:"none"}),Qe=Ke(qe);try{const ct=await Wt.createViewConfig({campaign_id:Qe.id,view_name:"table",table_type:"custom",is_default:!0,is_shared:!1});await Vt.createColumn({campaign_id:Qe.id,table_type:ct.view_system_name||ct.view_name||"table",view_config_id:ct.id,name:"Text",type:"text",width:240,is_visible:!0})}catch(ct){console.error("Failed to initialize blank table view/column:",ct),t({title:"Created worksheet, but failed to initialize table",description:"Please refresh or create a view manually."})}try{localStorage.setItem("flowwriter.currentCampaign",JSON.stringify({id:Qe.id,name:Qe.name}))}catch{}jt("table-new",{campaign:Qe.id})}catch(ue){t({title:"Failed to create worksheet",description:ue?.message||"Please try again"})}finally{_(!1)}}async function Oe(ue){g(ue);try{const W=Gv(ue),ke=Te(W),qe=await No({name:ke,template_type:ue}),Qe=Ke(qe);try{localStorage.setItem("flowwriter.currentCampaign",JSON.stringify({id:Qe.id,name:Qe.name}))}catch{}jt("table-new",{campaign:Qe.id})}catch(W){t({title:"Failed to create worksheet",description:W?.message||"Please try again"})}finally{g(null)}}function J(ue){try{localStorage.setItem("flowwriter.currentCampaign",JSON.stringify({id:ue.id,name:ue.name}))}catch{}
211jt("table-new",{campaign:ue.id})}async function re(ue){if(confirm("Are you sure you want to delete this worksheet?"))try{await sw([ue]),t({title:"Worksheet deleted",description:"The worksheet has been deleted successfully"}),await ie()}catch(W){t({title:"Failed to delete worksheet",description:W?.message||"Please try again later"})}}async function Se(ue){if(!S.trim()){N(null);return}try{await Cx(ue,{name:S.trim()}),a(W=>W.map(ke=>ke.id===ue?{...ke,name:S.trim()}:ke))}catch(W){t({title:"Failed to rename worksheet",description:W?.message||"Please try again"})}finally{N(null),k("")}}function je(ue){N(ue.id),k(ue.name)}async function he(ue){P(ue.id);try{const W=new Date,ke=`${ue.name} - ${W.toLocaleString("en-US",{month:"short"})} ${W.getDate()}`,qe=Te(ke),Qe=await $c({template_id:ue.id,campaign_name:qe});try{localStorage.setItem("flowwriter.currentCampaign",JSON.stringify({id:Qe.campaign_id,name:Qe.campaign_name}))}catch{}jt("table-new",{campaign:Qe.campaign_id})}catch(W){t({title:"Failed to apply template",description:W?.message||"Please try again"})}finally{P(null)}}async function Re(ue,W){if(W.stopPropagation(),!!confirm("Are you sure you want to delete this template?")){C(ue);try{await Vw(ue),t({title:"Template deleted",description:"The template has been deleted successfully"}),await ve()}catch(ke){t({title:"Failed to delete template",description:ke?.message||"Please try again later"})}finally{C(null)}}}const Me=()=>e.jsx("div",{className:"w-6 h-6 rounded flex items-center justify-center bg-gray-200 flex-shrink-0",children:e.jsx(Zn,{className:"w-3.5 h-3.5 text-gray-600"})}),Ze=({worksheet:ue})=>e.jsxs("div",{onClick:()=>J(ue),className:"flex items-center gap-4 px-4 py-4 active:bg-gray-50 transition-colors border-b border-gray-100 last:border-0 cursor-pointer",children:[e.jsx("div",{className:"flex-shrink-0",children:e.jsx(ln,{className:"w-9 h-9 text-slate-600"})}),e.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[E===ue.id?e.jsx("input",{type:"text",value:S,onChange:W=>k(W.target.value),onBlur:()=>Se(ue.id),onKeyDown:W=>{W.key==="Enter"&&Se(ue.id),W.key==="Escape"&&(N(null),k(""))},onClick:W=>W.stopPropagation(),className:"text-[16px] font-medium text-gray-900 bg-white border border-gray-400 rounded px-2 py-1 outline-none w-full",autoFocus:!0}):e.jsx("h3",{className:"text-[16px] font-medium text-gray-900 truncate",children:ue.name}),e.jsxs("div",{className:"text-xs text-gray-500",children:["Modified ",Wv(ue.updatedAt||ue.createdAt)]})]}),e.jsx("button",{onClick:W=>{W.stopPropagation(),confirm(`Delete "${ue.name}"?`)&&re(ue.id)},className:"p-2 -mr-2 text-gray-500 active:bg-gray-200 rounded-full",children:e.jsx(En,{className:"w-5 h-5"})})]}),Be=()=>c?e.jsxs("div",{className:"fixed inset-0 z-40 flex items-end justify-center",children:[e.jsx("div",{className:"absolute inset-0 bg-black/40 backdrop-blur-[2px]",onClick:()=>d(!1)}),e.jsxs("div",{className:"bg-white w-full rounded-t-2xl relative z-50 p-6 pb-10 flex flex-col gap-2 animate-in slide-in-from-bottom duration-200",children:[e.jsx("div",{className:"w-12 h-1 bg-gray-200 rounded-full mx-auto mb-4"}),e.jsx("h3",{className:"text-center text-base font-medium text-gray-800 mb-4",children:"Create new"}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("button",{onClick:()=>{d(!1),Ie()},disabled:w,className:"flex flex-col items-center gap-3 p-5 bg-gray-50 rounded-2xl border border-gray-100 active:bg-slate-100 active:border-slate-200 transition-colors",children:[e.jsx("div",{className:"w-12 h-12 rounded-full bg-white shadow-sm flex items-center justify-center border border-gray-100",children:w?e.jsx("div",{className:"animate-spin rounded-full h-6 w-6 border-2 border-gray-300 border-t-slate-600"}):e.jsx($t,{className:"w-7 h-7 text-slate-600"})}),e.jsx("span",{className:"text-sm font-medium text-gray-700",children:"New Spreadsheet"})]}),e.jsxs("button",{onClick:()=>{d(!1),h(!0)},className:"flex flex-col items-center gap-3 p-5 bg-gray-50 rounded-2xl border border-gray-100 active:bg-slate-100 active:border-slate-200 transition-colors",children:[e.jsx("div",{className:"w-12 h-12 rounded-full bg-white shadow-sm flex items-center justify-center border border-gray-100",children:e.jsx(gu,{className:"w-6 h-6 text-slate-600"})}),e.jsx("span",{className:"text-sm font-medium text-gray-700",children:"Choose Template"})]})]}),e.jsx("button",{onClick:()=>d(!1),className:"mt-4 py-3 text-gray-500 font-medium text-sm w-full active:bg-gray-50 rounded-lg",children:"Cancel"})]})]}):null,et=({name:ue,onClick:W,isLoading:ke=!1})=>e.jsxs("div",{onClick:ke?void 0:W,className:`flex flex-col gap-2 group cursor-pointer ${ke?"opacity-50 pointer-events-none":""}`,children:[e.jsxs("div",{className:"aspect-[3/4] rounded-xl bg-gray-100 border border-gray-200 overflow-hidden relative shadow-sm group-active:shadow-md transition-all",children:[e.jsx("div",{className:"absolute top-0 left-0 right-0 h-4 bg-gray-200/50"}),e.jsxs("div",{className:"p-3 pt-6 flex flex-col gap-2 opacity-60",children:[e.jsx("div",{className:"h-2 w-1/2 bg-gray-300 rounded-full"}),e.jsx("div",{className:"h-2 w-3/4 bg-gray-300 rounded-full"}),e.jsx("div",{className:"h-2 w-full bg-gray-300 rounded-full"}),e.jsx("div",{className:"mt-4 flex gap-2",children:e.jsx("div",{className:"h-16 w-full bg-white border border-gray-200 rounded"})})]}),e.jsx("div",{className:"absolute bottom-0 left-0 right-0 h-1.5 bg-slate-500 opacity-80"}),ke&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-white/50",children:e.jsx("div",{className:"animate-spin rounded-full h-6 w-6 border-2 border-gray-300 border-t-slate-600"})})]}),e.jsx("span",{className:"text-sm font-medium text-gray-700 text-center px-1 truncate",children:ue})]}),$e=()=>m?e.jsxs("div",{className:"fixed inset-0 z-50 bg-white animate-in slide-in-from-bottom duration-300 flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-gray-100 flex items-center gap-3 bg-white sticky top-0 z-10",children:[e.jsx("button",{onClick:()=>h(!1),className:"p-2 -ml-2 hover:bg-gray-100 rounded-full",children:e.jsx(un,{className:"w-6 h-6 text-gray-600"})}),e.jsx("h2",{className:"text-lg font-normal text-gray-800",children:"Template gallery"})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto p-4",children:[e.jsx("h3",{className:"text-xs font-bold text-gray-500 uppercase tracking-wider mb-4 px-1",children:"System Templates"}),e.jsxs("div",{className:"grid grid-cols-2 gap-x-4 gap-y-6",children:[e.jsx(et,{name:"Blank Spreadsheet",onClick:()=>{h(!1),Ie()},isLoading:w}),Ko.map(ue=>e.jsx(et,{name:ue.name,onClick:()=>{h(!1),Oe(ue.id)},isLoading:u===ue.id},ue.id))]}),$.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-xs font-bold text-gray-500 uppercase tracking-wider mt-8 mb-4 px-1",children:"Your Templates"}),e.jsx("div",{className:"grid grid-cols-2 gap-x-4 gap-y-6 pb-8",children:$.map(ue=>e.jsx(et,{name:ue.name,onClick:()=>{h(!1),he(ue)},isLoading:V===ue.id},ue.id))})]})]})]}):null;return i?e.jsxs("div",{className:"min-h-screen bg-white font-sans text-gray-900 flex flex-col relative",children:[e.jsxs("div",{className:"px-4 py-3 flex items-center justify-between text-sm text-gray-500 border-b border-gray-100 sticky top-0 bg-white z-10",children:[e.jsx("span",{className:"font-medium text-gray-700",children:"My Spreadsheets"}),e.jsxs("button",{onClick:()=>f(!p),className:"flex items-center gap-1 text-gray-500",children:[R==="asc"?"A-Z":"Z-A"," ",e.jsx(Gs,{className:"w-4 h-4"})]})]}),p&&e.jsxs("div",{className:"absolute top-12 right-4 bg-white border border-gray-200 rounded-lg shadow-lg z-20 py-1",children:[e.jsx("button",{onClick:()=>{L("asc"),f(!1)},className:`w-full px-4 py-2 text-left text-sm ${R==="asc"?"bg-gray-100 text-gray-900":"text-gray-700"}`,children:"Name A-Z"}),e.jsx("button",{onClick:()=>{L("desc"),f(!1)},className:`w-full px-4 py-2 text-left text-sm ${R==="desc"?"bg-gray-100 text-gray-900":"text-gray-700"}`,children:"Name Z-A"})]}),e.jsx("div",{className:"flex-1 pb-24 overflow-y-auto",children:n?e.jsx("div",{className:"flex items-center justify-center py-20",children:e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-2 border-gray-300 border-t-slate-600"})}):s.length===0?e.jsxs("div",{className:"text-center py-16 px-4",children:[e.jsx("div",{className:"w-16 h-16 rounded-full bg-gray-100 flex items-center justify-center mx-auto mb-4",children:e.jsx(ln,{className:"h-8 w-8 text-gray-400"})}),e.jsx("h3",{className:"text-base font-medium text-gray-700 mb-2",children:"No spreadsheets yet"}),e.jsx("p",{className:"text-sm text-gray-500 max-w-xs mx-auto",children:"Tap the + button to create your first spreadsheet"})]}):Ae.map(ue=>e.jsx(Ze,{worksheet:ue},ue.id))}),e.jsx("button",{onClick:()=>d(!0),className:"fixed bottom-8 right-6 w-14 h-14 bg-gray-100 rounded-2xl shadow-[0_4px_10px_rgba(0,0,0,0.15)] flex items-center justify-center active:scale-90 transition-transform z-30 border border-white",children:e.jsx($t,{className:"w-8 h-8 text-slate-600"})}),e.jsx(Be,{}),e.jsx($e,{})]}):e.jsxs("div",{className:"h-screen bg-white flex flex-col overflow-hidden",children:[!i&&e.jsx(Uc,{steps:Bv,run:b,onComplete:x,onSkip:x}),e.jsx("div",{className:"bg-[#F8F9FA] border-b border-gray-200 px-6 py-5 flex-shrink-0",children:e.jsxs("div",{className:"max-w-5xl mx-auto",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("h2",{className:"text-sm font-medium text-gray-600",children:"Start a new spreadsheet"}),e.jsx("button",{className:"text-sm text-gray-500 hover:bg-gray-200 px-3 py-1.5 rounded",onClick:()=>{U(1),se(!0)},"data-onboarding":"template-gallery-btn",children:"Template gallery"})]}),e.jsxs("div",{className:"flex gap-4",children:[e.jsxs("button",{onClick:Ie,disabled:w,className:"flex-shrink-0 group","data-onboarding":"blank-spreadsheet-btn",children:[e.jsx("div",{className:"w-[160px] h-[120px] rounded-md border border-gray-300 bg-white flex items-center justify-center mb-2 group-hover:border-gray-400 transition-colors relative overflow-hidden",children:w?e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-2 border-gray-300 border-t-gray-500"}):e.jsx($t,{className:"w-14 h-14 text-gray-400 stroke-[1.5]"})}),e.jsx("p",{className:"text-sm text-gray-600 text-center",children:"Blank spreadsheet"})]}),e.jsxs("div",{ref:I,className:"flex gap-4 overflow-x-auto pb-2 flex-1","data-onboarding":"system-template-cards",children:[Ko.map(ue=>e.jsxs("button",{onClick:()=>Oe(ue.id),disabled:u!==null,className:"flex-shrink-0 group",children:[e.jsx("div",{className:"w-[160px] h-[120px] rounded-md border border-gray-300 bg-white flex flex-col items-center justify-center mb-2 group-hover:border-gray-400 transition-colors relative overflow-hidden",children:u===ue.id?e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-2 border-gray-300 border-t-gray-500"}):e.jsx(e.Fragment,{children:e.jsxs("div",{className:"w-[140px] h-[90px] bg-white rounded border border-gray-200 overflow-hidden",children:[e.jsx("div",{className:"h-5 bg-gray-50 border-b border-gray-200 flex items-center px-2",children:e.jsx("div",{className:"text-[8px] font-medium text-gray-500 truncate",children:ue.name})}),e.jsx("div",{className:"p-1",children:e.jsx("div",{className:"grid grid-cols-3 gap-0.5",children:[...Array(9)].map((W,ke)=>e.jsx("div",{className:`h-2 rounded-sm ${ke<3?"bg-gray-200":"bg-gray-100"}`},ke))})})]})})}),e.jsx("p",{className:"text-sm text-gray-600 text-center truncate w-[160px]",children:ue.name})]},ue.id)),$.map(ue=>e.jsxs("div",{onClick:()=>{V===null&&A===null&&he(ue)},className:`flex-shrink-0 group relative cursor-pointer ${V!==null||A!==null?"opacity-50 pointer-events-none":""}`,children:[e.jsx("div",{className:"w-[160px] h-[120px] rounded-md border border-gray-300 bg-white flex flex-col items-center justify-center mb-2 group-hover:border-gray-400 transition-colors relative overflow-hidden",children:V===ue.id?e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-2 border-gray-300 border-t-gray-500"}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"absolute top-2 left-2 flex gap-1",children:[e.jsx("span",{className:"px-1.5 py-0.5 text-[9px] font-medium bg-green-100 text-green-700 rounded",children:"Custom"}),ue.is_multi_view&&e.jsxs("span",{className:"px-1.5 py-0.5 text-[9px] font-medium bg-purple-100 text-purple-700 rounded flex items-center gap-0.5",children:[e.jsx(qa,{className:"w-2.5 h-2.5"}),"Multi"]})]}),e.jsx("button",{onClick:W=>Re(ue.id,W),className:"absolute top-2 right-2 p-1 rounded hover:bg-red-100 text-gray-400 hover:text-red-600 transition-colors opacity-0 group-hover:opacity-100",title:"Delete template",children:A===ue.id?e.jsx("div",{className:"animate-spin rounded-full h-3 w-3 border border-gray-300 border-t-gray-500"}):e.jsx(es,{className:"w-3.5 h-3.5"})}),e.jsxs("div",{className:"w-[140px] h-[90px] bg-white rounded border border-gray-200 overflow-hidden",children:[e.jsx("div",{className:"h-5 bg-gray-50 border-b border-gray-200 flex items-center px-2",children:e.jsx("div",{className:"text-[8px] font-medium text-gray-500 truncate",children:ue.name})}),e.jsx("div",{className:"p-1",children:e.jsx("div",{className:"grid grid-cols-3 gap-0.5",children:[...Array(9)].map((W,ke)=>e.jsx("div",{className:`h-2 rounded-sm ${ke<3?"bg-gray-200":"bg-gray-100"}`},ke))})})]})]})}),e.jsxs("div",{className:"flex items-center justify-center gap-2 w-[160px]",children:[e.jsx("p",{className:"text-sm text-gray-600 truncate",children:ue.name}),ue.view_count>0&&e.jsxs("span",{className:"text-[10px] text-gray-400 flex-shrink-0",children:[ue.view_count," view",ue.view_count>1?"s":""]})]})]},ue.id)),e.jsx("div",{ref:j,className:"w-1 h-1 flex-shrink-0"}),ae&&e.jsxs("div",{className:"flex-shrink-0 w-[160px]",children:[e.jsx("div",{className:"w-[160px] h-[120px] rounded-md border border-gray-300 bg-white flex items-center justify-center mb-2",children:e.jsx("div",{className:"animate-spin rounded-full h-6 w-6 border-2 border-gray-300 border-t-gray-500"})}),e.jsx("p",{className:"text-sm text-gray-400 text-center",children:"Loading..."})]})]})]})]})}),fe&&e.jsxs("div",{className:"fixed inset-0 z-[9999]",children:[e.jsx("div",{className:"absolute inset-0 bg-black/30",onClick:()=>se(!1)}),e.jsxs("div",{className:"absolute top-1/2 left-1/2 w-[min(1000px,calc(100vw-32px))] max-h-[min(780px,calc(100vh-32px))] -translate-x-1/2 -translate-y-1/2 bg-white rounded-lg shadow-2xl border border-gray-200 overflow-hidden",children:[e.jsxs("div",{className:"px-6 py-4 border-b border-gray-200 flex items-center justify-between bg-gray-50",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-semibold text-gray-900",children:"Template gallery"}),e.jsx("div",{className:"text-xs text-gray-500",children:"System templates + your saved templates (paginated)"})]}),e.jsx("button",{className:"p-2 rounded hover:bg-gray-200 text-gray-600",onClick:()=>se(!1),title:"Close",children:"✕"})]}),e.jsxs("div",{className:"p-6 space-y-6 overflow-auto max-h-[calc(min(780px,calc(100vh-32px))-64px)]",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("div",{className:"text-sm font-medium text-gray-800",children:"System templates"}),e.jsxs("div",{className:"text-xs text-gray-500",children:[Ko.length," items"]})]}),e.jsx("div",{className:"flex gap-4 flex-wrap",children:Ko.map(ue=>e.jsxs("button",{onClick:()=>Oe(ue.id),disabled:u!==null,className:"flex-shrink-0 group",children:[e.jsx("div",{className:"w-[160px] h-[120px] rounded-md border border-gray-300 bg-white flex flex-col items-center justify-center mb-2 group-hover:border-gray-400 transition-colors relative overflow-hidden",children:u===ue.id?e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-2 border-gray-300 border-t-gray-500"}):e.jsxs("div",{className:"w-[140px] h-[90px] bg-white rounded border border-gray-200 overflow-hidden",children:[e.jsx("div",{className:"h-5 bg-gray-50 border-b border-gray-200 flex items-center px-2",children:e.jsx("div",{className:"text-[8px] font-medium text-gray-500 truncate",children:ue.name})}),e.jsx("div",{className:"p-1",children:e.jsx("div",{className:"grid grid-cols-3 gap-0.5",children:[...Array(9)].map((W,ke)=>e.jsx("div",{className:`h-2 rounded-sm ${ke<3?"bg-gray-200":"bg-gray-100"}`},ke))})})]})
211}),e.jsx("p",{className:"text-sm text-gray-600 text-center truncate w-[160px]",children:ue.name})]},`gallery-system-${ue.id}`))})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("div",{className:"text-sm font-medium text-gray-800",children:"Your templates"}),e.jsxs("div",{className:"text-xs text-gray-500",children:[O," items • Page ",z," /"," ",me]})]}),e.jsx("div",{className:"flex gap-4 flex-wrap",children:ge.map(ue=>e.jsxs("div",{onClick:()=>{V===null&&A===null&&he(ue)},className:`flex-shrink-0 group relative cursor-pointer ${V!==null||A!==null?"opacity-50 pointer-events-none":""}`,children:[e.jsx("div",{className:"w-[160px] h-[120px] rounded-md border border-gray-300 bg-white flex flex-col items-center justify-center mb-2 group-hover:border-gray-400 transition-colors relative overflow-hidden",children:V===ue.id?e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-2 border-gray-300 border-t-gray-500"}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"absolute top-2 left-2 flex gap-1",children:[e.jsx("span",{className:"px-1.5 py-0.5 text-[9px] font-medium bg-green-100 text-green-700 rounded",children:"Custom"}),ue.is_multi_view&&e.jsxs("span",{className:"px-1.5 py-0.5 text-[9px] font-medium bg-purple-100 text-purple-700 rounded flex items-center gap-0.5",children:[e.jsx(qa,{className:"w-2.5 h-2.5"}),"Multi"]})]}),e.jsx("button",{onClick:W=>Re(ue.id,W),className:"absolute top-2 right-2 p-1 rounded hover:bg-red-100 text-gray-400 hover:text-red-600 transition-colors opacity-0 group-hover:opacity-100",title:"Delete template",children:A===ue.id?e.jsx("div",{className:"animate-spin rounded-full h-3 w-3 border border-gray-300 border-t-gray-500"}):e.jsx(es,{className:"w-3.5 h-3.5"})}),e.jsxs("div",{className:"w-[140px] h-[90px] bg-white rounded border border-gray-200 overflow-hidden",children:[e.jsx("div",{className:"h-5 bg-gray-50 border-b border-gray-200 flex items-center px-2",children:e.jsx("div",{className:"text-[8px] font-medium text-gray-500 truncate",children:ue.name})}),e.jsx("div",{className:"p-1",children:e.jsx("div",{className:"grid grid-cols-3 gap-0.5",children:[...Array(9)].map((W,ke)=>e.jsx("div",{className:`h-2 rounded-sm ${ke<3?"bg-gray-200":"bg-gray-100"}`},ke))})})]})]})}),e.jsxs("div",{className:"flex items-center justify-center gap-2 w-[160px]",children:[e.jsx("p",{className:"text-sm text-gray-600 truncate",children:ue.name}),ue.view_count>0&&e.jsxs("span",{className:"text-[10px] text-gray-400 flex-shrink-0",children:[ue.view_count," view",ue.view_count>1?"s":""]})]})]}
211,`gallery-user-${ue.id}`))}),e.jsxs("div",{className:"mt-4 flex items-center justify-between",children:[e.jsxs("div",{className:"text-xs text-gray-500",children:["Showing ",(z-1)*Q+1,"-",Math.min(z*Q,O)," of"," ",O]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{className:"px-3 py-1.5 text-sm border border-gray-200 rounded hover:bg-gray-50 disabled:opacity-50",disabled:z<=1,onClick:()=>U(ue=>Math.max(1,ue-1)),children:"Prev"}),e.jsx("button",{className:"px-3 py-1.5 text-sm border border-gray-200 rounded hover:bg-gray-50 disabled:opacity-50",disabled:z>=me,onClick:()=>U(ue=>Math.min(me,ue+1)),children:"Next"})]})]})]})]})]})]}),e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsxs("div",{className:"max-w-5xl mx-auto h-full flex flex-col",children:[s.length>0&&e.jsx("div",{className:"px-6 pt-4 pb-4 flex-shrink-0",children:e.jsxs("div",{className:"flex items-center justify-end gap-1",children:[e.jsx("button",{onClick:()=>F("list"),className:`p-2 rounded hover:bg-gray-100 transition-colors ${D==="list"?"bg-gray-100 text-gray-700":"text-gray-400"}`,title:"List view",children:e.jsx(_o,{className:"w-5 h-5"})}),e.jsx("button",{onClick:()=>F("grid"),className:`p-2 rounded hover:bg-gray-100 transition-colors ${D==="grid"?"bg-gray-100 text-gray-700":"text-gray-400"}`,title:"Grid view",children:e.jsx(uu,{className:"w-5 h-5"})}),e.jsx("button",{onClick:()=>L(R==="asc"?"desc":"asc"),className:"p-2 rounded hover:bg-gray-100 transition-colors text-gray-500",title:R==="asc"?"Sort Z to A":"Sort A to Z",children:R==="asc"?e.jsx(xu,{className:"w-5 h-5"}):e.jsx(hu,{className:"w-5 h-5"})})]})}),e.jsx("div",{className:"flex-1 overflow-y-auto px-6 pb-4",children:n?e.jsx("div",{className:"flex items-center justify-center py-20",children:e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-2 border-gray-300 border-t-gray-500"})}):s.length===0?e.jsxs("div",{className:"py-8",children:[b&&e.jsxs("div",{className:"mb-6",children:[e.jsx("h3",{className:"text-xs font-medium text-gray-500 mb-2 px-2",children:"Earlier"}),e.jsxs("div",{"data-onboarding":"first-worksheet-item",className:"flex items-center gap-3 px-2 py-2.5 rounded hover:bg-gray-50",children:[e.jsx(Me,{}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsx("span",{className:"text-sm text-gray-800",children:"Untitled spreadsheet"})}),e.jsx("button",{className:"p-1 rounded hover:bg-gray-100 text-gray-400",children:e.jsx(En,{className:"w-4 h-4"})})]})]}),e.jsxs("div",{className:"text-center py-12",children:[e.jsx("div",{className:"w-16 h-16 rounded-full bg-gray-100 flex items-center justify-center mx-auto mb-4",children:e.jsx(ln,{className:"h-8 w-8 text-gray-400"})}),e.jsx("h3",{className:"text-base font-medium text-gray-700 mb-2",children:"No spreadsheets yet"}),e.jsx("p",{className:"text-sm text-gray-500 max-w-sm mx-auto",children:"Create a blank spreadsheet or use one of the templates above to get started"})]})]}):D==="list"?e.jsx("div",{className:"space-y-4",children:Object.entries(ye).map(([ue,W])=>W.length===0?null:e.jsxs("div",{children:[e.jsx("h3",{className:"text-xs font-medium text-gray-500 mb-2 px-2",children:ue}),e.jsx("div",{className:"space-y-0.5",children:W.map((ke,qe)=>e.jsxs("div",{onClick:()=>J(ke),className:"flex items-center gap-3 px-2 py-2.5 rounded hover:bg-gray-50 cursor-pointer",...qe===0?{"data-onboarding":"first-worksheet-item"}:{},children:[e.jsx(Me,{}),e.jsx("div",{className:"flex-1 min-w-0",children:E===ke.id?e.jsx("input",{type:"text",value:S,onChange:Qe=>k(Qe.target.value),onBlur:()=>Se(ke.id),onKeyDown:Qe=>{Qe.key==="Enter"&&Se(ke.id),Qe.key==="Escape"&&(N(null),k(""))},onClick:Qe=>Qe.stopPropagation(),className:"text-sm text-gray-900 bg-white border border-gray-400 rounded px-2 py-1 outline-none w-full max-w-md",autoFocus:!0}):e.jsx("span",{className:"text-sm text-gray-800",children:ke.name})}),e.jsx(bm,{onRename:()=>je(ke),onDelete:()=>re(ke.id)})]},ke.id))})]},ue))}):e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-4",children:Ae.map(ue=>e.jsxs("div",{onClick:()=>J(ue),className:"group relative bg-white border border-gray-200 rounded-lg p-4 hover:border-gray-300 hover:shadow-sm cursor-pointer transition-all",children:[e.jsx("div",{className:"absolute top-2 right-2",children:e.jsx(bm,{onRename:()=>je(ue),onDelete:()=>re(ue.id)})}),e.jsx("div",{className:"w-full aspect-[4/3] bg-gray-50 rounded border border-gray-100 mb-3 flex items-center justify-center",children:e.jsx(Zn,{className:"w-8 h-8 text-gray-300"})}),E===ue.id?e.jsx("input",{type:"text",value:S,onChange:W=>k(W.target.value),onBlur:()=>Se(ue.id),onKeyDown:W=>{W.key==="Enter"&&Se(ue.id),W.key==="Escape"&&(N(null),k(""))},onClick:W=>W.stopPropagation(),className:"text-sm text-gray-900 bg-white border border-gray-400 rounded px-2 py-1 outline-none w-full",autoFocus:!0}):e.jsx("p",{className:"text-sm text-gray-800 truncate",title:ue.name,children:ue.name})]},ue.id))})})]})})]})}const qv=[{target:'[data-onboarding="keywords-gap-header"]',content:e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-semibold text-slate-900 mb-2",children:"Keywords Gap"}),e.jsx("p",{className:"text-sm text-slate-600",children:"Identify keyword opportunities by anal
211yzing gaps between your domain and competitors. Keywords shown here are ranked by competitors but not by you, representing potential growth opportunities."})]}),placement:"bottom",disableBeacon:!0},{target:'[data-onboarding="keywords-gap-limit"]',content:e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-semibold text-slate-900 mb-2",children:"Ranked Keywords Limit"}),e.jsx("p",{className:"text-sm text-slate-600 mb-2",children:"Controls the maximum number of keywords fetched per competitor. This setting affects data completeness and credit consumption."}),e.jsxs("ul",{className:"text-sm text-slate-600 space-y-1.5 list-disc list-inside",children:[e.jsx("li",{children:"Higher limits provide more comprehensive gap analysis"}),e.jsx("li",{children:'Click "Increase" to adjust before refreshing data'})]})]}),placement:"bottom",disableBeacon:!0},{target:'[data-onboarding="keywords-gap-refresh"]',content:e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-semibold text-slate-900 mb-2",children:"Refresh Data"}),e.jsx("p",{className:"text-sm text-slate-600",children:"Sync the latest ranked keywords from competitors. Select specific competitors to refresh or update all at once. Data freshness impacts gap analysis accuracy."})]}),placement:"bottom",disableBeacon:!0},{target:'[data-onboarding="keywords-gap-quick-select"]',content:e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-semibold text-slate-900 mb-2",children:"Quick Select"}),e.jsx("p",{className:"text-sm text-slate-600 mb-2",children:"Quickly filter and select keywords based on predefined criteria:"}),e.jsxs("ul",{className:"text-sm text-slate-600 space-y-1.5 list-disc list-inside",children:[e.jsxs("li",{children:[e.jsx("span",{className:"font-medium",children:"Competitor has, you don't"})," - Keywords competitors rank for but you don't"]}),e.jsxs("li",{children:[e.jsx("span",{className:"font-medium",children:"Competitor outranks you"})," - Keywords where competitors have better positions"]}),e.jsxs("li",{children:[e.jsx("span",{className:"font-medium",children:"Volume thresholds"})," - Filter by monthly search volume"]})]}),e.jsx("p",{className:"text-sm text-slate-600 mt-2",children:"The badge shows the number of keywords matching current filters."})]}),placement:"bottom-start",disableBeacon:!0},{target:'[data-onboarding="keywords-gap-actions"]',content:e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-semibold text-slate-900 mb-2",children:"Add to Target Keywords"}),e.jsx("p",{className:"text-sm text-slate-600 mb-2",children:"After selecting keywords from the table:"}),e.jsxs("ul",{className:"text-sm text-slate-600 space-y-1.5 list-disc list-inside",children:[e.jsxs("li",{children:[e.jsx("span",{className:"font-medium",children:"Add to Target Keywords"})," - Save selected keywords to your target list for tracking and content generation"]}),e.jsx("li",{children:"Keywords can then be grouped, prioritized, and used to generate SEO content"})]})]}),placement:"top",disableBeacon:!0}];function Yv(t){return(t||[]).map(s=>typeof s=="string"?s.trim():"").filter(Boolean).reduce((s,a)=>s+a.length,0)}function Jv(t){if(t.length===0)return"";if(t.length===1)return t[0];const s=t[0].toLowerCase();let a="";for(let n=0;n<s.length;n++){const o=s[n];if(t.every(i=>i.toLowerCase()[n]===o))a+=o;else break}if(a.length>0){const n=a.trim();if(n.length>2)return n}return""}function Xv(t){if(t.length===0)return"";if(t.length===1)return t[0];const s=t[0].toLowerCase();let a="";for(let n=1;n<=s.length;n++){const o=s[s.length-n];if(t.every(i=>i.toLowerCase()[i.length-n]===o))a=o+a;else break}if(a.length>0){const n=a.trim();if(n.length>2)return n}return""}function Qv(t){if(t.length===0)return[];const s=new Map;t.forEach(o=>{o.toLowerCase().split(/\s+/).forEach(l=>{l.length>2&&s.set(l,(s.get(l)||0)+1)})});const a=Math.max(1,Math.ceil(t.length*.3)),n=[];return s.forEach((o,i)=>{o>=a&&n.push(i)}),n.sort((o,i)=>(s.get(i)||0)-(s.get(o)||0))}function Zv(t=[]){if(t.length===0)return`Untitled Group ${new Date().toLocaleDateString("en-US",{month:"short",day:"numeric"})}`;const s=t.map(m=>m.trim()).filter(m=>m.length>0),a=s.length,n=s.slice(0,10);if(n.length===0)return`Untitled Group ${new Date().toLocaleDateString("en-US",{month:"short",day:"numeric"})}`;if(a<=2){const m=s.join(" & ");return m.length>50?m.substring(0,47)+"...":m}const o=Jv(n);if(o.length>2)return`${o.charAt(0).toUpperCase()+o.slice(1)} Keywords (${a})`;const i=Xv(n);if(i.length>2)return`${i.charAt(0).toUpperCase()+i.slice(1)} Keywords (${a})`;const l=Qv(n);if(l.length>0){const m=l[0];return`${m.charAt(0).toUpperCase()+m.slice(1)} Keywords (${a})`}const c=s[0];if(a<=3){const m=s.join(", ");return m.length>50?m.substring(0,47)+"...":m}return`${c.length>20?c.substring(0,17)+"...":c} & ${a-1} more`}function eN({isOpen:t,onClose:s,groupName:a,onGroupNameChange:n,onStartManualGroup:o,onStartAIGroup:i,isGeneratingAI:l=!1,keywords:c=[]}){v.useEffect(()=>{t&&!a.trim()&&n(Zv(c))},[t,a,c,n]);const d=v.useMemo(()=>(c||[]).filter(f=>typeof f=="string"&&f.trim()).length,[c]),m=v.useMemo(()=>Yv(c),[c]),h=ta({enabled:t&&d>0,scenario:"keyword_group_ai_group_keywords",params:{keyword_count:d,total_keyword_chars:m,model:"gemini-3-pro-preview"}}),p=()=>{l||(s(),n(""))};return e.jsx(Ht,{open:t,onOpenChange:p,children:e.jsxs(qt,{className:"max-w-md",children:[e.jsx(Zt,{children:e.jsx(Yt,{className:"text-base font-semibold text-slate-800",children:"Create Keyword Group"})}),e.jsxs("div",{className:"space-y-4 py-2",children:[e.jsxs("div",{className:Lt("p-4 border rounded-xl transition-all relative overflow-hidden",l?"bg-indigo-50/50 border-indigo-200 shadow-sm":"bg-white border-slate-200 hover:border-indigo-300 hover:shadow-md group/ai"),children:[e.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[e.jsx("div",{className:Lt("w-10 h-10 rounded-lg flex items-center justify-center shrink-0 transition-colors",l?"bg-indigo-100":"bg-slate-100 group-hover/ai:bg-indigo-50"),children:l?e.jsx(He,{className:"animate-spin text-indigo-600",size:20}):e.jsx(Wh,{size:20,className:"text-slate-600 group-hover/ai:text-indigo-600"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"text-sm font-semibold text-slate-800",children:l?"Analyzing & Grouping...":"AI Auto-Group"}),e.jsx("div",{className:"text-xs text-slate-500 mt-0.5",children:l?"This may take a few moments ✨":"Automatically organize selected keywords into logical groups"})]})]}),e.jsx("div",{className:"mb-4 flex items-center justify-center",children:e.jsxs("div",{className:"inline-flex items-center gap-2 px-3 py-1.5 rounded-lg bg-amber-50 border border-amber-200 text-[12px] text-amber-800",children:[e.jsx(vs,{className:"w-4 h-4 text-amber-600"}),h.estimating?e.jsx("span",{className:"font-medium",children:"Estimating..."}):h.estimatedRange?e.jsxs("span",{className:"font-medium",children:["Est. ",h.estimatedRange.min,"–",h.estimatedRange.max," ","credits"]}):e.jsx("span",{className:"font-medium",children:"Estimate unavailable"})]})}),e.jsx(be,{onClick:i,disabled:l,className:Lt("w-full h-10 font-medium transition-all",l?"bg-indigo-100 text-indigo-400":"bg-indigo-600 hover:bg-indigo-700 text-white shadow-sm shadow-indigo-200"),children:l?e.jsxs(e.Fragment,{children:[e.jsx(He,{className:"mr-2 h-4 w-4 animate-spin"}),"Processing"]}):"Generate with AI"})]}),e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"absolute inset-0 flex items-center",children:e.jsx("div",{className:"w-full border-t border-slate-100"})}),e.jsx("div",{className:"relative flex justify-center text-[10px] font-bold uppercase tracking-widest",children:e.jsx("span",{className:"bg-white px-3 text-slate-400",children:"or"})})]}),e.jsxs("div",{className:Lt("p-4 border border-slate-200 rounded-xl bg-white transition-all",l?"opacity-50 pointer-events-none":"hover:border-slate-300 hover:shadow-sm"),children:[e.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg bg-slate-100 flex items-center justify-center shrink-0",children:e.jsx($t,{size:20,className:"text-slate-600"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"text-sm font-semibold text-slate-800",children:"Single Group"}),e.jsxs("div",{className:"text-xs text-slate-500 mt-0.5",children:["Combine all ",c.length," keywords into a single group"]})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(bt,{placeholder:"Group name",value:a,onChange:f=>n(f.target.value),className:"h-10 text-sm focus-visible:ring-slate-400",disabled:l}),e.jsx(be,{className:"bg-slate-800 hover:bg-slate-900 text-white h-10 px-5 shrink-0 font-medium",onClick:o,disabled:!a.trim()||l,children:"Create"})]})]})]}),e.jsx("div",{className:"mt-2 flex justify-end",children:e.jsx(be,{variant:"ghost",size:"sm",onClick:p,disabled:l,className:"text-slate-400 hover:text-slate-600",children:"Cancel"})})]})})}function tN({isOpen:t,onClose:s,selectedKeywords:a,defaultCampaignName:n}){const{toast:o}=_t(),{confirm:i}=ia(),[l,c]=v.useState("content_generation_keywords_only"),[d,m]=v.useState(""),[h,p]=v.useState(!1),[f,b]=v.useState(!1),[y,x]=v.useState(null),[u,g]=v.useState(""),[w,_]=v.useState(!1),[E,N]=v.useState(null),[S,k]=v.useState(null),D=v.useMemo(()=>Mr.find(K=>K.id===l)||null,[l]),F=v.useMemo(()=>a.map((K,X)=>({id:`keyword-${X}`,name:K,keywords:[{keyword:K}]})),[a]),R=v.useMemo(()=>{const K=a.length,X=a.length,V=a.reduce((P,A)=>P+A.length,0);return{group_count:K,total_keywords:X,total_keyword_chars:V}},[a]);v.useEffect(()=>{if(!t)return;if(!h){N(null);return}if(R.group_count<=0){N(null);return}let K=!0;return(async()=>{_(!0);try{const V=await Vi.estimateCredits({scenario:"worksheet_content_generation_title_content",params:{template_type:l,group_count:R.group_count,total_keywords:R.total_keywords,total_keyword_chars:R.total_keyword_chars}});if(!K)return;N({min:Number(V.estimated_min_credits||0),max:Number(V.estimated_max_credits||0)}),k(Number(V.required_minimum_balance||0))}catch(V){if(console.warn("⚠️ Failed to estimate credits:",V),!K)return;N(null),k(null)}finally{if(!K)return;_(!1)}})(),()=>{K=!1}},[t,h,l,R.group_count,R.total_keywords,R.total_keyword_chars]),v.useEffect(()=>{if(!t)return;if(n?.trim()){m(n.trim());return}const K=D?.name;m(Vx(K))},[t,n,D?.name]);const L=()=>{f||s()},$=!f&&d.trim().length>0&&a.length>0,H=async()=>
211{if($){if(h){const K=E?.min??0,X=E?.max??0,V=S??0;if(!await i({title:"Confirm credit usage",message:`This will start generating title and content automatically.
212
213Estimated cost: ${K}–${X} credits.
214`+(V>0?`Required minimum balance: ${V} credits.
215
216`:`
217`)+"Do you want to continue?",confirmText:"Continue",cancelText:"Cancel"}))return}b(!0),x("creating_campaign"),g("Starting...");try{const K=await cr.createWorksheetAndGenerateFromGroups({source:{kind:"content_generation_template",templateType:l},campaignSource:"keywords_research",campaignName:d.trim(),groups:F,options:{generateTitleAndContent:h,titlePollingTimeoutMs:12e4,titlePollingIntervalMs:2e3,onProgress:(X,V)=>{x(X),V&&g(V)}}});try{localStorage.setItem("flowwriter.currentCampaign",JSON.stringify({id:K.campaignId,name:d.trim()}))}catch{}o({title:"✅ Worksheet created",description:h?"Keywords filled. Title & content generation started.":"Keywords filled. You can run generation from the table."}),s(),jt("table-new",{campaign:K.campaignId,view:K.viewId})}catch(K){console.error("❌ Failed to create worksheet and generate:",K
217),o({title:"Create & generate failed",description:K?.message||"Please try again."})}finally{b(!1)}}};return e.jsx(Ht,{open:t,onOpenChange:L,children:e.jsxs(qt,{className:"max-w-2xl",children:[e.jsx(Zt,{children:e.jsx(Yt,{className:"text-base font-semibold text-slate-800",children:"Generate Content from Keywords"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"rounded-lg border border-slate-200 bg-slate-50 px-4 py-3",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-9 h-9 rounded-lg bg-white border border-slate-200 flex items-center justify-center shrink-0",children:e.jsx(ln,{size:16,className:"text-slate-600"})}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"text-sm font-medium text-slate-800",children:[a.length," keyword",a.length===1?"":"s"," selected"]}),e.jsx("div",{className:"text-xs text-slate-500 mt-0.5",children:"Each keyword will become one row in the worksheet."})]})]})}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium text-slate-800 mb-3 block",children:"Choose a Template"}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-3",children:Mr.map(K=>{const X=l===K.id;return e.jsxs("button",{type:"button",onClick:()=>c(K.id),disabled:f,className:["relative text-left rounded-xl border transition-all duration-200 overflow-hidden group h-full flex flex-col",X?"border-indigo-600 ring-1 ring-indigo-600 shadow-sm bg-indigo-50/10":"border-slate-200 hover:border-slate-300 hover:shadow-sm bg-white",f?"opacity-60 cursor-not-allowed":"cursor-pointer"].join(" "),children:[e.jsx("div",{className:`h-2 absolute top-0 left-0 right-0 bg-gradient-to-r ${K.previewBg}`}),e.jsxs("div",{className:"p-4 pt-5 flex-1 flex flex-col",children:[e.jsx("div",{className:`text-sm font-semibold mb-1 ${X?"text-indigo-900":"text-slate-800"}`,children:K.name}),e.jsx("div",{className:"text-xs text-slate-500 leading-relaxed",children:K.description})]}),X&&e.jsx("div",{className:"absolute top-3 right-3 text-indigo-600",children:e.jsx("div",{className:"w-4 h-4 rounded-full bg-indigo-600 text-white flex items-center justify-center",children:e.jsx("svg",{width:"10",height:"8",viewBox:"0 0 10 8",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:e.jsx("path",{d:"M1 4L3.5 6.5L9 1",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})})})]},K.id)})})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-slate-600 mb-1.5 block",children:"Worksheet Name"}),e.jsx(bt,{value:d,onChange:K=>m(K.target.value),placeholder:"Enter worksheet name",disabled:f})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(be,{variant:"ghost",size:"sm",onClick:L,disabled:f,children:"Cancel"}),e.jsx(be,{size:"sm",className:"bg-indigo-600 hover:bg-indigo-700 disabled:opacity-80 min-w-[140px]",onClick:H,disabled:!$,children:f?e.jsxs("span",{className:"inline-flex items-center gap-2",children:[e.jsx(He,{className:"w-4 h-4 animate-spin"}),u||"Creating..."]}):"Create & Generate"})]})]})]})})}function sN(t){const s=t?.details||[];return s.length===0?null:s.reduce((a,n)=>a+(n.ranked_keywords_count||0),0)}function wm({marketReloadNonce:t}){const{toast:s}=_t(),a=t??0,[n,o]=r.useState(1),[i,l]=r.useState(()=>typeof window<"u"&&new URLSearchParams(window.location.search).get("view")==="groups"?"groups":"gap_analysis");r.useEffect(()=>{if(typeof window<"u"){const M=new URL(window.location.href);i==="groups"?M.searchParams.set("view","groups"):M.searchParams.delete("view"),window.history.pushState({},"",M.toString())}},[i]);const[c,d]=r.useState(null),[m,h]=r.useState(()=>Ir()),[p,f]=r.useState([]),[b,y]=r.useState(!1),[x,u]=r.useState(!1),[g,w]=r.useState(!1),_=Zs(Us.keyword_research),[E,N]=r.useState(""),[S,k]=r.useState(!1),[D,F]=r.useState(!1),[R,L]=r.useState(0),$=sN(c),H=c?.details?.length||0,K=r.useCallback(async()=>{try{const M=ma(),Z=M.length>0?$a(M):null,B=Z?await wo(Z).then(ae=>ae.aggregated):await Tn();d(B)}catch(M){console.error("❌ Failed to load data:",M)}},[]),X=r.useCallback(async()=>{try{const M=ma(),Z=M.length>0?$a(M):null,B=Z?await wo(Z).then(ae=>ae.aggregated):await Tn();d(B)}catch(M){console.error("❌ Failed to refresh competitors data:",M)}},[]);r.useEffect(()=>{K()}
217,[K,a]),r.useEffect(()=>{if(c?.last_synced_at)try{localStorage.setItem("mobile_header_subtitle",`Last refresh: ${new Date(c.last_synced_at).toLocaleDateString("en-CA")}`)}catch{}return()=>{try{localStorage.removeItem("mobile_header_subtitle")}catch{}}},[c?.last_synced_at]),r.useEffect(()=>{p.length>0&&w(!1)},[p.length]),r.useEffect(()=>{let M=!0;return(async()=>{try{const ae=(await Eo())?.competitor_ranked_keywords_limit;if(!M)return;typeof ae=="number"&&(Rn(ae),h(ae))}catch(B){console.warn("⚠️ Failed to load ranked keywords limit:",B)}})(),()=>{M=!1}},[]);const V=r.useCallback(async M=>{try{const B=(await Ao(M))?.competitor_ranked_keywords_limit??M;Rn(B),h(B),s({title:"Settings saved",description:`Competitor ranked keywords limit updated to Top ${B}.`})}catch(Z){console.error("❌ Failed to save ranked keywords limit:",Z),s({title:"Error",description:Z?.message||"Failed to save settings"})}},[s]),P=Io({toast:s,onCompleted:async()=>{await X(),L(M=>M+1)}});r.useEffect(()=>{let M=!1;return(async()=>{try{const B=await La(),ae=Array.isArray(B?.markets)&&B.markets.length>0?B.markets.length:1;if(M)return;o(Math.max(1,Number(ae)||1))}catch(B){console.warn("⚠️ Failed to load track markets for credit estimate:",B),M||o(1)}})(),()=>{M=!0}},[]);const A=r.useCallback(async M=>{const Z=(M.domains||[]).map(de=>String(de).trim()).filter(Boolean);if(Z.length===0&&!M.includeSelf){s({title:"No selection",description:"Please select at least one competitor to sync."});return}const{creditEstimateService:B}=await Bt(async()=>{const{creditEstimateService:de}=await Promise.resolve().then(()=>Ya);return{creditEstimateService:de}},void 0),{validateCreditBalance:ae}=await Bt(async()=>{const{validateCreditBalance:de}=await Promise.resolve().then(()=>ua);return{validateCreditBalance:de}},void 0);try{const de=typeof M.keywordsLimit=="number"&&Number.isFinite(M.keywordsLimit)?M.keywordsLimit:m,fe=Z.length+(M.includeSelf?1:0),se=await B.estimateCredits({scenario:"domainseo_batch_sync_competitors",params:{markets_count:n,targets_count:fe,competitor_targets_count:Z.length,keywords_limit:de,sync_rank_overview:!1,sync_ranked_keywords:!0,force_sync_keywords:!!M.forceSyncKeywords}});if(!await ae({estimatedRange:se?{min:se.estimated_min_credits,max:se.estimated_max_credits}:null,requiredMinimumBalance:se?.required_minimum_balance??null,toast:s}))return;const U=await Er(Z,M.forceSyncKeywords,de,!1,!0,!!M.includeSelf),Q=U?.task_id?String(U.task_id):"";Q?await P.startTask({taskId:Q,etaText:"2-5 min"}):(await X(),L(me=>me+1),s({title:"Sync started",description:"Competitors ranked keywords sync triggered."}))}catch(de){console.error("❌ Failed to sync competitors ranked keywords:",de),s({title:"Error",description:de?.message||"Failed to sync competitors ranked keywords"})}},[n,m,X,P,s]),[C,I]=r.useState(!1),j=r.useCallback(async()=>{if(p.length!==0){I(!0);try{const M=await ds.upsertKeywordsBatch({keywords:p}),Z=M.added_count||0,B=M.existing_count||0;s({title:"Keywords added successfully",description:`${Z} added, ${B} already existed`}),f([]),jt("workflow",{item:"target_keywords"})}catch(M){console.error("Failed to add keywords:",M),s({title:"Failed to add keywords",description:"Please try again later"})}finally{I(!1)}}},[p,s]);r.useCallback(()=>{p.length!==0&&u(!0)},[p.length]),r.useCallback(()=>{p.length!==0&&(N(""),y(!0))},[p.length]);const q=async()=>{if(!E.trim()||p.length===0)return;const M=p;k(!0);try{const B=[];for(let de=0;de<M.length;de+=1e3){const fe=M.slice(de,de+1e3),z=((await ds.upsertKeywordsBatch({keywords:fe})).items||[]).map(U=>U.keyword).filter(U=>U);B.push(...z)}if(B.length===0){console.error("❌ No keywords were created");return}const ae=await ds.createGroup({name:E.trim()});await ds.addKeywordsToGroup({group_id:ae.id,keywords:B}),y(!1),N(""),p.length>0&&f([]),l("groups"),s({title:"Group created",description:`Created "${ae.name}" with ${B.length} keywords.`})}catch(Z){console.error("❌ Failed to create group:",Z),s({title:"Error",description:"Failed to create group"})}finally{k(!1)}},T=async()=>{if(p.length===0)return;const M=p;y(!1),F(!0);try{const{creditEstimateService:Z}=await Bt(async()=>{const{creditEstimateService:se}=await Promise.resolve().then(()=>Ya);return{creditEstimateService:se}},void 0),{validateCreditBalance:B}=await Bt(async()=>{const{validateCreditBalance:se}=await Promise.resolve().then(()=>ua);return{validateCreditBalance:se}},void 0),ae=await Z.estimateCredits({scenario:"keyword_group_ai_group_keywords",params:{keyword_count:M.length,total_keyword_chars:M.reduce((se,z)=>se+z.length,0)}});if(!await B({estimatedRange:ae?{min:ae.estimated_min_credits,max:ae.estimated_max_credits}:null,requiredMinimumBalance:ae?.required_minimum_balance??null,toast:s})){F(!1);return}(await ds.aiGroupKeywords({keywords:M.map(se=>({keyword:se,source:"manual"}))})).task_id&&(await K(),p.length>0&&f([]),l("groups"),s({title:"AI Grouping complete",description:"Keywords have been organized into groups."}))}catch(Z){console.error("❌ Failed to generate AI groups:",Z),s({title:"Error",description:"Failed to generate AI groups"})}finally{F(!1)}};return e.jsxs("div",{className:"h-full flex flex-col sm:p-4 sm:sp
217ace-y-4 overflow-hidden relative",children:[e.jsx(oa,{steps:qv,run:_.run,onComplete:_.stopAndMarkCompleted,onSkip:_.stopAndMarkCompleted}),e.jsx("div",{className:"flex-1 min-h-0 flex flex-col",children:e.jsxs("div",{className:"h-full flex flex-col animate-in fade-in duration-300 relative",children:[e.jsx("div",{className:"hidden sm:flex items-center justify-end mb-3 shrink-0","data-onboarding":"keywords-gap-header",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(uh,{competitorsRankedKeywordsCount:$,competitorsTrackedCount:H,competitors:(c?.details||[]).map(M=>({domain:M.competitor,lastSyncedAt:M.last_synced_at||null})),selfDomain:c?.domain?{domain:c.domain,lastSyncedAt:c?.last_synced_at||null}:null,rankedKeywordsLimit:m,onRankedKeywordsLimitChange:M=>{V(M)},onSyncCompetitorsRankedKeywords:A,isSyncing:P.isRunning}),c?.last_synced_at&&e.jsxs("div",{className:"flex items-center gap-2 text-xs text-slate-400",children:[e.jsx(ka,{size:12}),e.jsxs("span",{children:["last refresh:"," ",new Date(c.last_synced_at).toLocaleDateString("en-CA")]})]})]})}),P.panel.phase!=="idle"&&e.jsx("div",{className:"mb-3 shrink-0 sm:px-0 px-3",children:e.jsx(Mo,{state:P.panel})}),e.jsx("div",{"data-onboarding":"keywords-gap-table",className:"overflow-hidden flex-1 min-h-0",children:e.jsx(Gi,{competitors:c?.details||[],userDomain:c?.domain||"You",selectedKeywords:p,onSelectedKeywordsChange:f,dataRefreshKey:R,lastRefreshDate:c?.last_synced_at||null,onRefresh:()=>{A({domains:(c?.details||[]).map(M=>M.competitor),forceSyncKeywords:!1,includeSelf:!0})},isRefreshing:P.isRunning})}),e.jsx("div",{className:"hidden sm:block fixed bottom-6 left-1/2 -translate-x-1/2 z-50 animate-in slide-in-from-bottom-4 fade-in duration-200","data-onboarding":"keywords-gap-actions",children:e.jsxs("div",{className:"bg-white/95 backdrop-blur-sm text-slate-900 px-5 py-3 rounded-full shadow-[0_8px_30px_rgb(0,0,0,0.12)] border border-slate-200/60 flex items-center gap-4 flex-nowrap whitespace-nowrap",children:[e.jsx("span",{className:"text-sm font-medium pl-1 text-slate-700",children:p.length>0?e.jsxs(e.Fragment,{children:[p.length," selected"]}):e.jsx("span",{className:"text-slate-400",children:"Select keywords to continue"})}),e.jsx("div",{className:"h-4 w-px bg-slate-200"}),e.jsx(be,{onClick:j,disabled:p.length===0||C,size:"sm",className:`bg-slate-900 hover:bg-slate-800 text-white border-0 h-8 rounded-full px-4 shadow-sm ${p.length===0||C?"opacity-50 cursor-not-allowed":""}`,children:C?"Adding...":"Add to Target Keywords"}),p.length>0&&e.jsxs("button",{onClick:()=>f([]),className:"text-slate-400 hover:text-slate-600 transition-colors p-1",children:[e.jsx("span",{className:"sr-only",children:"Clear selection"}),e.jsx(mt,{size:16})]})]})}),e.jsxs("div",{className:`sm:hidden fixed bottom-0 left-0 right-0 z-50 bg-white shadow-[0_-8px_30px_rgba(0,0,0,0.12)] rounded-t-2xl transition-transform duration-300 ease-out border-t border-gray-100 ${p.length>0?g?"translate-y-[calc(100%-24px)]":"translate-y-0":"translate-y-full"}`,children:[e.jsx("div",{className:"w-full h-8 flex items-center justify-center cursor-pointer active:opacity-70",onClick:()=>w(!g),children:e.jsx("div",{className:"w-10 h-1 bg-gray-200 rounded-full"})}),e.jsx("div",{className:"px-5 pb-8 pt-1",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"text-xs text-gray-500 font-medium uppercase tracking-wide",children:"Selected"}),e.jsxs("div",{className:"flex items-baseline gap-1",children:[e.jsx("span",{className:"text-2xl font-bold text-gray-900",children:p.length}),e.jsx("span",{className:"text-sm text-gray-500",children:"keywords"})]})]}),e.jsxs("div",{className:"flex gap-3",children:[e.jsx("button",{onClick:()=>f([]),className:"px-4 py-2.5 text-sm font-medium text-gray-600 bg-gray-100 rounded-xl hover:bg-gray-200 active:bg-gray-300 transition-colors",children:"Clear"}),e.jsxs("button",{onClick:j,disabled:C,className:"px-5 py-2.5 bg-blue-600 text-white text-sm font-semibold rounded-xl shadow-lg shadow-blue-200 active:scale-95 transition-all flex items-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed",children:[e.jsx("span",{className:"text-lg leading-none",children:"+"}),C?"Adding...":"Add to List"]})]})]})})]}),p.length>0&&g&&e.jsx("div",{className:"sm:hidden fixed bottom-6 left-0 right-0 flex justify-center pointer-events-none animate-bounce z-50",children:e.jsx("span",{className:"bg-black/70 text-white text-[10px] px-2 py-1 rounded-full backdrop-blur-sm shadow-md",children:"Tap handle to open"})})]})}),e.jsx(eN,{isOpen:b,onClose:()=>y(!1),groupName:E,onGroupNameChange:N,onStartManualGroup:q,onStartAIGroup:T,isGeneratingAI:D,keywords:p}),e.jsx(tN,{isOpen:x,onClose:()=>u(!1),selectedKeywords:p}),e.jsx("button",{onClick:_.startManual,className:"fixed bottom-3 right-3 z-50 h-8 w-8 rounded-full bg-white border border-slate-200 shadow-md hover:shadow-lg hover:bg-slate-50 transition-all hover:scale-105 hidden sm:flex items-center justify-center",title:"View navigation guide","aria-label":"View navigation guide",children:e.jsx(Hs,{className:"h-4 w-4 text-slate-600"})})]})}function yh({open:t,onOpenChange:s,kbs:a,initialKbId:n,lockKbSelection:o,lockedKbName:i,disableOutsideClose:l,onCompleted:c}){const{toast:d}=_t(),[m,h]=v.useState(n||""),[p,f]=v.useState([]),[b,y]=v.useState("auto"),[x,u]=v.useState(1e3),[g,w]=v.useState(!1),[_,E]=v.useState(null),[N,S]=v.useState(!1),[k,D]=v.useState(!1),[F,R]=v.useState([]),[L,$]=v.useState(null),H=v.useRef(null),K=v.useRef({created:0,failed:0}),[X,V]=v.useState([]),[P,A]=v.useState(1),[C]=v.useState(10),[I,j]=v.useState(0),[q,T]=v.useState(""),[M,Z]=v.useState(!1),B=v.useCallback(async()=>{const O=m||n;if(!O){V([]),j(0);return}try{Z(!0);const ne=await co(O,P,C,q);V(ne.items||[]),j(ne.total||0)}catch(ne){console.error("Failed to load documents:",ne),V([]),j(0)}finally{Z(!1)}},[m,n,P,C,q]);v.useEffect(()=>{if(!t||!(m||n))return;const O=setTimeout(()=>{B()},300);return()=>clearTimeout(O)},[t,m,n,P,q,B]),v.useEffect(()=>{t&&(m||n)&&(A(1),T(""))},[t,m,n]),v.useEffect(()=>{t?(h(n||""),f([]),y("auto"),u(1e3),E(null),D(!1),$(null),R([]),K.current={created:0,failed:0},A(1),T("")):H.current&&(window.clearInterval(H.current),H.current=null)},[t,n]),v.useEffect(()=>{N||k||R(O=>{const ne=[];for(let ge=0;ge<p.length;ge++)ne.push(O[ge]??"pending");return ne})},[p,N,k]);function ae(O){if(!O)return;const ne=Array.from(O),ge=[],ze=new Set(p.map(Ke=>
217`${Ke.name}:${Ke.size}:${Ke.lastModified}`));for(const Ke of ne){const ie=`${Ke.name}:${Ke.size}:${Ke.lastModified}`;if(ze.has(ie)||(ge.push(Ke),ze.add(ie)),p.length+ge.length>=10)break}ge.length>0&&f(Ke=>[...Ke,...ge].slice(0,10))}function de(O){N||k||f(ne=>ne.filter((ge,ze)=>ze!==O))}function fe(O){O.preventDefault(),O.stopPropagation(),O.type==="dragenter"||O.type==="dragover"?w(!0):O.type==="dragleave"&&w(!1)}function se(O){O.preventDefault(),O.stopPropagation(),w(!1),O.dataTransfer.files&&O.dataTransfer.files.length>0&&ae(O.dataTransfer.files)}function z(O){if(!Number.isFinite(O)||O<=0)return"0 KB";const ne=O/1024,ge=ne/1024,ze=ge/1024,Ke=(ie,ve)=>{const we=Math.max(ve==="KB"?.1:.01,ie),Pe=we<10?1:0;return`${we.toFixed(Pe)} ${ve}`};return ze>=1?Ke(ze,"GB"):ge>=1?Ke(ge,"MB"):Ke(ne,"KB")}function U(O){return O==="success"?e.jsx(ls,{className:"bg-green-50 text-green-700 border border-green-100",children:"Done"}):O==="failed"?e.jsx(ls,{className:"bg-red-50 text-red-700 border border-red-100",children:"Failed"}):O==="uploading"?e.jsx(ls,{className:"bg-blue-50 text-blue-700 border border-blue-100",children:"Uploading"}):e.jsx(ls,{className:"bg-slate-50 text-slate-600 border border-slate-100",children:"Pending"})}const Q=v.useMemo(()=>o&&i?i:a.find(ne=>ne.id===(m||n))?.name||"",[a,m,n,o,i]);async function me(){const O=m||n;if(!(!O||p.length===0))try{S(!0),R(()=>{if(p.length===0)return[];const Ke=p.map(()=>"pending");return Ke[0]="uploading",Ke}),K.current={created:0,failed:0};const ge=(await jj(O,p,{chunk_mode:b,chunk_size:b==="fixed_size"?x:void 0})).task_id;E(ge),D(!0),H.current&&(window.clearInterval(H.current),H.current=null);const ze=window.setInterval(async()=>{try{const Ke=await vj(ge);if($({status:Ke.status,progress:Ke.progress,total:Ke.total,created:Ke.created,failed:Ke.failed,error:Ke.error}),R(ie=>{const ve=[...ie],we=K.current.created,Pe=K.current.failed,Ae=Math.max(0,Ke.created-we),ye=Math.max(0,Ke.failed-Pe);K.current={created:Ke.created,failed:Ke.failed};const Te=(Ie,Oe)=>{let J=Oe;for(let re=0;re<ve.length&&J>0;re++)(ve[re]==="pending"||ve[re]==="uploading")&&(ve[re]=Ie,J-=1)};if(Te("success",Ae),Te("failed",ye),Ke.status==="running"){const Ie=ve.findIndex(Oe=>Oe==="pending");if(Ie>=0){for(let Oe=0;Oe<ve.length;Oe++)ve[Oe]==="uploading"&&(ve[Oe]="pending");ve[Ie]="uploading"}else for(let Oe=0;Oe<ve.length;Oe++)ve[Oe]==="uploading"&&(ve[Oe]="pending")}else for(let Ie=0;Ie<ve.length;Ie++)ve[Ie]==="uploading"&&(ve[Ie]="pending");return ve}),Ke.status==="done"){window.clearInterval(ze),H.current=null,D(!1),s(!1);try{await c?.(),(m||n)&&await B()}catch{}}Ke.status==="error"&&(window.clearInterval(ze),H.current=null,D(!1))}catch{window.clearInterval(ze),H.current=null,D(!1)}},2e3);H.current=ze}catch(ne){console.error("[KbBatchUpload] upload failed:",ne),d({title:"Upload failed",description:ne?.message||"An unexpected error occurred while uploading files."}),D(!1),R([]),$(null)}finally{S(!1)}}const le=N||k;return e.jsx(Ht,{open:t,onOpenChange:s,children:e.jsxs(qt,{closeOnOutside:!l,children:[e.jsx(Zt,{children:e.jsx(Yt,{children:"bulk upload documents"})}),e.jsxs("div",{className:"space-y-6 py-4",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4 bg-slate-50/50 p-4 rounded-xl border border-slate-100",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Gt,{className:"text-xs uppercase tracking-wider text-slate-500 font-bold",children:"Target Knowledge Base"}),o?e.jsx("div",{className:"h-10 px-3 rounded-lg border border-slate-200 bg-white flex items-center text-sm text-slate-600",children:Q}):e.jsxs(nr,{value:m,onValueChange:h,className:"w-full",children:[e.jsx(rr,{className:"w-full bg-white",children:e.jsx("span",{className:"truncate",children:a.find(O=>O.id===m)?.name||"Select Knowledge Base"})}),e.jsx(or,{children:a.map(O=>e.jsx(_s,{value:O.id,children:O.name},O.id))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Gt,{className:"text-xs uppercase tracking-wider text-slate-500 font-bold",children:"Chunk Split"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(nr,{value:b,onValueChange:O=>y(O),className:"flex-1",children:[e.jsx(rr,{className:"w-full bg-white",children:e.jsx("span",{className:"truncate",children:b==="auto"?"Auto Mode":"Fixed Size"})}),e.jsxs(or,{children:[e.jsx(_s,{value:"auto",children:"Auto Mode"}),e.jsx(_s,{value:"fixed_size",children:"Fixed Size"})]})]}),b==="fixed_size"&&e.jsx(bt,{type:"number",className:"w-24 h-10 bg-white",placeholder:"Size",value:x,disabled:le,onChange:O=>u(parseInt(O.target.value||"1000",10))})]})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(Gt,{className:"text-xs uppercase tracking-wider text-slate-500 font-bold px-1",children:"Upload Documents"}),e.jsxs("div",{className:`relative flex flex-col items-center justify-center p-8 border-2 border-dashed rounded-2xl transition-all cursor-pointer ${g?"border-blue-500 bg-blue-50/50 scale-[1.01] shadow-inner":"border-slate-200 hover:border-slate-300 hover:bg-slate-50/50 bg-white"} ${le?"opacity-50 cursor-not-allowed":""}`,onDragEnter:fe,onDragOver:fe,onDragLeave:fe,onDrop:se,onClick:()=>!le&&document.getElementById("kb-batch-file-input")?.click(),children:[e.jsx("div",{className:"p-3 bg-slate-50 rounded-2xl mb-3 group-hover:scale-110 transition-transform",children:e.jsx(Vh,{
217className:`w-8 h-8 ${g?"text-blue-500":"text-slate-400"}`})}),e.jsx("div",{className:"text-sm font-semibold text-slate-900",children:"Click or drag files here to upload"}),e.jsx("p",{className:"text-xs text-slate-400 mt-1",children:"PDF, DOCX, TXT, MD • Up to 10 files"}),e.jsx("input",{id:"kb-batch-file-input",type:"file",multiple:!0,accept:".pdf,.txt,.docx,.md,.markdown",className:"hidden",onChange:O=>ae(O.target.files),disabled:le})]})]}),p.length>0&&e.jsxs("div",{className:"space-y-2 animate-in fade-in slide-in-from-top-2 duration-300",children:[e.jsxs("div",{className:"flex items-center justify-between px-1",children:[e.jsxs("span",{className:"text-xs font-bold text-slate-500 uppercase tracking-wider",children:["Selected (",p.length,"/10)"]}),e.jsx(be,{variant:"ghost",size:"sm",className:"h-6 text-[10px] text-slate-400 hover:text-red-500",onClick:()=>f([]),disabled:le,children:"Clear All"})]}),e.jsx("div",{className:"grid grid-cols-1 gap-2 max-h-[200px] overflow-y-auto pr-1 custom-scrollbar",children:p.map((O,ne)=>e.jsxs("div",{className:"flex items-center justify-between px-3 py-2 bg-slate-50 border border-slate-100 rounded-lg group hover:border-slate-200 transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0 flex-1",children:[e.jsx(is,{className:"w-3.5 h-3.5 text-slate-400 shrink-0"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"truncate text-xs font-medium text-slate-700",children:O.name}),e.jsx("div",{className:"text-[10px] text-slate-400",children:z(O.size)})]})]}),e.jsxs("div",{className:"flex items-center gap-2 ml-2 shrink-0",children:[U(F[ne]??"pending"),e.jsx("button",{className:"p-1 rounded-md text-slate-300 hover:text-red-500 hover:bg-white opacity-0 group-hover:opacity-100 transition-all",onClick:ge=>{ge.stopPropagation(),de(ne)},disabled:le,children:e.jsx(mt,{className:"w-3.5 h-3.5"})})]})]},`${O.name}-${O.size}-${O.lastModified}`))})]}),(m||n)&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between px-1",children:[e.jsxs(Gt,{className:"text-xs uppercase tracking-wider text-slate-500 font-bold",children:["Existing Documents (",I,")"]}),e.jsxs("div",{className:"relative w-48",children:[e.jsx(Pt,{className:"absolute left-2 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-slate-400"}),e.jsx(bt,{value:q,onChange:O=>{T(O.target.value),A(1)},placeholder:"Search documents...",className:"h-8 pl-8 text-xs bg-white border-slate-200"})]})]}),M?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(He,{className:"w-5 h-5 animate-spin text-slate-400"})}):X.length>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"grid grid-cols-1 gap-2 max-h-[200px] overflow-y-auto pr-1 custom-scrollbar border border-slate-100 rounded-lg p-2 bg-slate-50/50",children:X.map(O=>e.jsxs("div",{className:"flex items-center justify-between px-3 py-2 bg-white border border-slate-100 rounded-lg hover:border-slate-200 transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0 flex-1",children:[e.jsx(is,{className:"w-3.5 h-3.5 text-slate-400 shrink-0"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"truncate text-xs font-medium text-slate-700",children:O.file_name}),e.jsxs("div",{className:"text-[10px] text-slate-400",children:[O.chunk_count!==void 0?`${O.chunk_count} chunks`:"",O.file_size?` • ${z(O.file_size)}`:""]})]})]}),O.status==="completed"&&e.jsx(Rs,{className:"w-3.5 h-3.5 text-green-600 shrink-0"}),O.status==="processing"&&e.jsx(He,{className:"w-3.5 h-3.5 animate-spin text-blue-600 shrink-0"}),O.status==="failed"&&e.jsx(Ss,{className:"w-3.5 h-3.5 text-red-600 shrink-0"})]},O.id))}),I>0&&e.jsx("div",{className:"flex justify-center",children:e.jsx(xn,{page:P,pageSize:C,total:I,onPageChange:A,onPageSizeChange:()=>{},maxPageSize:C})})]}):e.jsx("div",{className:"text-center py-6 text-sm text-slate-400 border border-slate-100 rounded-lg bg-slate-50/50",children:q?"No documents found":"No documents yet"})]}),L&&e.jsxs("div",{className:"rounded-xl border border-slate-200 bg-white p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium text-slate-800",children:[L.status==="running"?e.jsx(He,{className:"w-4 h-4 animate-spin text-slate-500"}):L.status==="done"?e.jsx(Rs,{className:"w-4 h-4 text-green-600"}):e.jsx(Ss,{className:"w-4 h-4 text-red-600"}),e.jsx("span",{className:"capitalize",children:L.status})]}),e.jsxs("div",{className:"text-xs text-slate-500",children:[L.progress,"/",L.total," • ",L.created," done",L.failed?` • ${L.failed} failed`:""]})]}),e.jsx("div",{className:"h-2 w-full rounded-full bg-slate-100 overflow-hidden",children:e.jsx("div",{className:"h-2 bg-slate-500 rounded-full transition-all",style:{width:`${Math.min(100,Math.max(0,L.progress/(L.total||1)*100))}%`}})}),L.error&&e.jsx("div",{className:"text-xs text-red-700 bg-red-50 p-2 rounded-lg border border-red-100",children:L.error})]})]}),e.jsxs(Ns,{children:[e.jsx(be,{variant:"outline",onClick:()=>s(!1),disabled:N||k,children:"Cancel"}),e.jsx(be,{onClick:me,disabled:(o?!n:!m)||p.length===0||N||k,children:N||k?"Running...":"Start"})]})]})})}function aN({kbId:t,kbName:s,onOpenDocument:a,onBack:n}){const{toast:o}=_t(),[i,l]=v.useState([]),[c,d]=v.useState(1),[m,h]=v.useState(20),[p,f]=v.useState(0),[b,y]=v.useState(!1),[x,u]=v.useState(new Set),[g,w]=v.useState(!1),[_,E]=v.useState({key:"updated_at",direction:"desc"}),[N,S]=v.useState(null),k=j=>{j.preventDefault(),S({x:j.clientX,y:j.clientY})},D=v.useCallback(async()=>{try{const j=await co(t,c,m);l(j.items),f(j.total),u(new Set)}catch(j){console.error("Failed to load documents:",j),o({title:"Error",description:"Failed to load documents. Please try again later."})}},[t,c,m,o]);v.useEffect(()=>{D()},[D]),v.useEffect(()=>{const j=()=>S(null);return window.addEventListener("click",j),()=>window.removeEventListener("click",j)},[]);function F(j){const q=/[\\/:*?"<>|]/g;return j.trim().replace(q,"_")}function R(j,q){const T=F(j);if(!q)return T;const M=q.startsWith(".")?q:`.${q}`;return T.toLowerCase().endsWith(M.toLowerCase())?T:`${T}${M}`}async function L(j,q){try{const T=await fetch(j);if(!T.ok)throw new Error(`HTTP ${T.status}`);const M=await T.blob();Ar({filename:q,blob:M})}catch{window.open(j,"_blank")}}async function $(j,q){try{let T=q.download_url,M=q.file_name;if(!T){const B=await _j(j,q.id);T=B.url,M=B.file_name||M}const Z=R(M||"document",q.file_type);await L(T,Z)}catch(T){console.error(T),alert("Failed to download file")}}async function H(){if(!(x.size===0||!confirm(`Are you sure you want to delete ${x.size} document(s)?`)))try{w(!0);const q=Array.from(x);await Promise.allSettled(q.map(T=>om(t,T))),o({title:"Deleted",description:`${x.size} document(s) deleted successfully`}),await D()}catch(q){console.error("Failed to delete documents:",q),o({title:"Error",description:"Failed to delete documents. Please try again later."})}finally{w(!1)}}async function K(j){if(confirm(`Are you sure you want to delete "${j.file_name}"?`))try{await om(t,j.id),o({title:"Deleted",description:"Document deleted successfully"}),await D()}catch(q){console.error("Failed to delete document:",q),o({title:"Error",description:"Failed to delete document"})}}function X(j,q){u(T=>{const M=new Set(T);return q?M.add(j):M.delete(j),M})}function V(j){u(j?new Set(i.map(q=>q.id)):new Set)}const P=v.useMemo(()=>{let j=[...i];return _&&j.sort((q,T)=>{const M=(q[_.key]||"").toString().toLowerCase(),Z=(T[_.key]||"").toString().toLowerCase();return M<Z?_.direction==="asc"?-1:1:M>Z?_.direction==="asc"?1:-1:0}),j},[i,_]),A=j=>{let q="asc";_&&_.key===j&&_.direction==="asc"&&(q="desc"),E({key:j,direction:q})},C=(j,q)=>{j.preventDefault(),j.stopPropagation(),S({x:j.clientX,y:j.clientY,doc:q})},I=()=>
217{if(!N)return null;const{x:j,y:q,doc:T}=N;return Ha.createPortal(e.jsx("div",{className:"fixed z-[999] w-56 rounded-md border border-slate-200 bg-white shadow-md py-1 text-sm font-medium text-slate-700 animate-in fade-in zoom-in-95 duration-100",style:{top:q,left:j},onClick:M=>M.stopPropagation(),children:T?e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"flex w-full items-center px-3 py-2 hover:bg-slate-100 text-left",onClick:()=>{a?a(T):ai(t,T.id),S(null)},children:[e.jsx(ns,{className:"mr-2 h-4 w-4 text-slate-500"}),"Open"]}),e.jsx("div",{className:"my-1 border-b border-slate-100"}),e.jsxs("button",{className:"flex w-full items-center px-3 py-2 hover:bg-slate-100 text-left",onClick:()=>{$(t,T),S(null)},children:[e.jsx(Vs,{className:"mr-2 h-4 w-4 text-slate-500"}),"Download"]}),e.jsxs("button",{className:"flex w-full items-center px-3 py-2 hover:bg-slate-100 text-left text-red-600",onClick:()=>{K(T),S(null)},children:[e.jsx(es,{className:"mr-2 h-4 w-4"}),"Delete"]})]}):e.jsxs("button",{className:"flex w-full items-center px-3 py-2 hover:bg-slate-100 text-left",onClick:()=>{y(!0),S(null)},children:[e.jsx(Gn,{className:"mr-2 h-4 w-4 text-slate-500"}),"Upload"]})}),document.body)};return e.jsxs("div",{className:"flex flex-col h-full bg-white",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-0 px-6 pt-2 pb-2 flex-none",children:[e.jsxs(be,{variant:"outline",size:"sm",onClick:()=>y(!0),className:"h-9",children:[e.jsx(Gn,{className:"mr-2 h-4 w-4"}),"Upload"]}),e.jsxs(be,{variant:"outline",size:"sm",className:"h-9 text-red-600 border-red-200 hover:bg-red-50 disabled:opacity-50",onClick:H,disabled:x.size===0||g,children:[e.jsx(es,{className:"mr-2 h-4 w-4"}),"Delete (",x.size,")"]})]}),e.jsx(yh,{open:b,onOpenChange:j=>{y(j)},kbs:[],initialKbId:t,lockKbSelection:!0,lockedKbName:s,disableOutsideClose:!0,onCompleted:async()=>{await D()}}),e.jsxs("div",{className:"flex-1 overflow-hidden relative flex flex-col",children:[e.jsxs("div",{className:"flex-1 overflow-auto",onContextMenu:k,children:[e.jsxs("table",{className:"min-w-full text-sm",children:[e.jsx("thead",{className:"text-left text-slate-500 border-b border-slate-200 sticky top-0 bg-white z-10 shadow-[0_1px_0_0_#e2e8f0]",children:e.jsxs("tr",{children:[e.jsx("th",{className:"py-3 px-4 w-10 bg-white",children:e.jsx("input",{type:"checkbox","aria-label":"Select all",checked:i.length>0&&x.size===i.length,onChange:j=>V(j.target.checked),className:"rounded border-slate-300"})}),e.jsx("th",{className:"py-3 px-4 bg-white cursor-pointer hover:bg-slate-50 transition-colors select-none",onClick:()=>A("file_name"),children:e.jsxs("div",{className:"flex items-center gap-1",children:["File name",_?.key==="file_name"&&(_.direction==="asc"?e.jsx(Is,{className:"h-3 w-3"}):e.jsx(Ws,{className:"h-3 w-3"}))]})}),e.jsx("th",{className:"py-3 px-4 bg-white",children:"Type"}),e.jsx("th",{className:"py-3 px-4 bg-white cursor-pointer hover:bg-slate-50 transition-colors select-none",onClick:()=>A("chunk_count"),children:e.jsxs("div",{className:"flex items-center gap-1",children:["Chunks",_?.key==="chunk_count"&&(_.direction==="asc"?e.jsx(Is,{className:"h-3 w-3"}):e.jsx(Ws,{className:"h-3 w-3"}))]})}),e.jsx("th",{className:"py-3 px-4 bg-white cursor-pointer hover:bg-slate-50 transition-colors select-none",onClick:()=>A("updated_at"),children:e.jsxs("div",{className:"flex items-center gap-1",children:["Updated",_?.key==="updated_at"&&(_.direction==="asc"?e.jsx(Is,{className:"h-3 w-3"}):e.jsx(Ws,{className:"h-3 w-3"}))]})}),e.jsx("th",{className:"py-3 px-4 w-20 bg-white sticky right-0 z-20 shadow-[-1px_0_0_0_#f1f5f9]",children:e.jsx("div",{className:"flex justify-end pr-2",children:e.jsx(lc,{className:"h-4 w-4 text-slate-400"})})})]})}),e.jsx("tbody",{children:P.map(j=>e.jsxs("tr",{className:"hover:bg-slate-50 transition-colors cursor-pointer border-b border-slate-50 group",onDoubleClick:()=>{a?a(j):ai(t,j.id)},onContextMenu:q=>C(q,j),onClick:q=>{},children:[e.jsx("td",{className:"py-3 px-4",onClick:q=>q.stopPropagation(),children:e.jsx("input",{type:"checkbox","aria-label":"Select row",checked:x.has(j.id),onChange:q=>X(j.id,q.target.checked),className:"rounded border-slate-300"})}),e.jsx("td",{className:"py-3 px-4 font-medium text-slate-800",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(is,{className:"h-4 w-4 text-slate-400"}),j.file_name]})}),e.jsx("td",{className:"py-3 px-4 text-slate-500",children:j.file_type}),e.jsx("td",{className:"py-3 px-4 text-slate-500",children:j.chunk_count}),e.jsx("td",{className:"py-3 px-4 text-slate-500",children:j.updated_at||""}),e.jsx("td",{className:"py-3 px-4 w-20 text-right sticky right-0 bg-white group-hover:bg-slate-50 shadow-[-1px_0_0_0_#f1f5f9] transition-colors",onClick:q=>q.stopPropagation(),children:e.jsxs(Pn,{children:[e.jsx(In,{unstyled:!0,className:"w-8 h-8 p-0 border-none hover:bg-slate-200 rounded-full flex items-center justify-center text-slate-500 transition-colors ml-auto",children:e.jsx(En,{className:"h-4 w-4"})}),e.jsxs(Mn,{align:"right",children:[e.jsx(js,{value:"open",onClick:()=>{a?a(j):ai(t,j.id)},children:e.jsxs("div",{className:"flex items-center",children:[e.jsx(ns,{className:"mr-2 h-4 w-4 text-slate-500"})," ","Open"]})}),e.jsx(js,{value:"download",onClick:()=>$(t,j),children:e.jsxs("div",{className:"flex items-center",children:[e.jsx(Vs,{className:"mr-2 h-4 w-4 text-slate-500"})," ","Download"]})}),e.jsx("div",{className:"my-1 border-b border-slate-100"}),e.jsx(js,{value:"delete",onClick:()=>K(j),children:e.jsxs("div",{className:"flex items-center text-red-600",children:[e.jsx(es,{className:"mr-2 h-4 w-4"})," Delete"]})})]})]})})]},j.id))})]}),i.length===0&&e.jsx("div",{className:"py-12 text-center text-slate-400",children:"No documents yet. Upload to start indexing."})]}),e.jsx("div",{className:"flex-none p-4 border-t border-slate-100 bg-white",children:e.jsx(xn,{page:c,pageSize:m,total:p,onPageChange:d,onPageSizeChange:h,maxPageSize:100})})]}),e.jsx(I,{})]})}function bh({x:t,y:s,children:a,className:n=""}){return Ha.createPortal(e.jsx("div",{className:`fixed z-[999] rounded-md border border-slate-200 bg-white shadow-md py-1 text-sm font-medium text-slate-700 animate-in fade-in zoom-in-95 duration-100 ${n||"w-56"}
217`,style:{top:s,left:t},onClick:o=>o.stopPropagation(),children:a}),document.body)}function ba({children:t,onClick:s,className:a="",danger:n=!1}){return e.jsx("button",{className:`flex w-full items-center px-3 py-2 hover:bg-slate-100 text-left ${n?"text-red-600":""} ${a}`,onClick:s,children:t})}function Ti(){return e.jsx("div",{className:"my-1 border-b border-slate-100"})}function nN({kbId:t,document:s,onBack:a}){const{toast:n}=_t(),[o,i]=v.useState([]),[l,c]=v.useState(1),[d,m]=v.useState(20),[h,p]=v.useState(0),[f,b]=v.useState(""),[y,x]=v.useState(new Set),[u,g]=v.useState({}),[w,_]=v.useState({}),[E,N]=v.useState({}),[S,k]=v.useState(!1),D=v.useRef({}),[F,R]=v.useState(null);function L(B){return ae=>{D.current[B]=ae,ae&&$(ae)}}function $(B){B.style.height="auto",B.style.height=`${B.scrollHeight}px`}function H(B){const ae=D.current[B];ae&&$(ae)}const K=v.useCallback(async()=>{try{const B=await Nj(t,s.id,l,d,f.trim()||void 0);i(B.items),p(B.total)}catch(B){console.error(B),n({title:"Error",description:"Failed to load chunks"})}},[t,s.id,l,d,f,n]);v.useEffect(()=>{K()},[K]),v.useEffect(()=>{const B=()=>R(null);return window.addEventListener("click",B),()=>window.removeEventListener("click",B)},[]);const X=v.useMemo(()=>o.length===0?!1:o.every(B=>y.has(B.id)),[o,y]);function V(B){x(ae=>{const de=new Set(ae);return de.has(B)?de.delete(B):de.add(B),de})}function P(){x(B=>{const ae=new Set(B);return X?o.forEach(de=>ae.delete(de.id)):o.forEach(de=>ae.add(de.id)),ae})}function A(B){g(ae=>({...ae,[B.id]:!0})),N(ae=>({...ae,[B.id]:B.content})),setTimeout(()=>H(B.id),0),R(null)}function C(B){g(ae=>({...ae,[B]:!1})),N(ae=>{const{[B]:de,...fe}=ae;return fe})}async function I(B){const ae=E[B]??"";_(de=>({...de,[B]:!0}));try{const de=await kj({kb_id:t,chunk_id:B,content:ae});i(fe=>fe.map(se=>se.id===B?{...se,content:de.content}:se)),g(fe=>({...fe,[B]:!1})),N(fe=>{const{[B]:se,...z}=fe;return z}),n({title:"Saved",description:"Chunk updated successfully"})}catch{n({title:"Error",description:"Failed to save chunk"})}finally{_(de=>({...de,[B]:!1}))}}async function j(B){if(confirm("Are you sure you want to delete this paragraph?"))try{await rm(t,B),i(ae=>ae.filter(de=>de.id!==B)),p(ae=>Math.max(0,ae-1)),n({title:"Deleted",description:"Chunk deleted successfully"})}catch{n({title:"Error",description:"Failed to delete chunk"})}}async function q(){if(!(y.size===0||!confirm(`Are you sure you want to delete ${y.size} selected paragraph(s)?`))){k(!0);try{const ae=Array.from(y),de=await Promise.allSettled(ae.map(z=>rm(t,z))),fe=ae.filter((z,U)=>de[U].status==="fulfilled"),se=de.length-fe.length;se>0?n({title:"Warning",description:`Some deletes failed (${se}). The rest were deleted.`}):n({title:"Deleted",description:`Deleted ${fe.length} paragraphs.`}),fe.length>0&&(i(z=>z.filter(U=>!fe.includes(U.id))),x(z=>new Set),p(z=>Math.max(0,z-fe.length)),setTimeout(()=>{o.length-fe.length===0&&l>1?c(z=>Math.max(1,z-1)):K()},0))}catch{n({title:"Error",description:"Failed to delete selected paragraphs."})}finally{k(!1)}}}const T=B=>{B.preventDefault(),R({x:B.clientX,y:B.clientY,type:"global"})},M=(B,ae)=>{B.preventDefault(),B.stopPropagation(),R({x:B.clientX,y:B.clientY,type:"chunk",chunk:ae})},Z=()=>{if(!F)return null;const{x:B,y:ae,type:de,chunk:fe}=F;return e.jsxs(bh,{x:B,y:ae,className:"w-48",children:[de==="global"&&e.jsxs(e.Fragment,{children:[e.jsx(ba,{onClick:()=>{K(),R(null)},children:"Refresh"}),e.jsx(Ti,{}),e.jsx(ba,{onClick:()=>{P(),R(null)},children:X?"Deselect all":"Select all"})]}),de==="chunk"&&fe&&e.jsxs(e.Fragment,{children:[e.jsxs(ba,{onClick:()=>A(fe),children:[e.jsx(Ua,{className:"mr-2 h-4 w-4 text-slate-500"}),"Edit"]}),e.jsx(Ti,{}),e.jsxs(ba,{danger:!0,onClick:()=>{j(fe.id),R(null)},children:[e.jsx(es,{className:"mr-2 h-4 w-4"}),"Delete"]})]})]})};return e.jsxs("div",{className:"p-6 min-h-full",onContextMenu:T,children:[e.jsxs("div",{className:"sticky top-0 bg-white z-10 p-3 flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-4 flex-1",children:[e.jsxs("label",{className:"flex items-center gap-2 text-sm text-slate-700 cursor-pointer select-none",children:[e.jsx("input",{type:"checkbox",checked:X,onChange:P,className:"rounded border-slate-300"}),"Select all"]}),e.jsxs("div",{className:"relative w-64",children:[e.jsx(Pt,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400"}),e.jsx(bt,{value:f,onChange:B=>b(B.target.value),onKeyDown:B=>{B.key==="Enter"&&(c(1),K())},placeholder:"Search content...",className:"pl-9 h-8 bg-slate-50 border-transparent focus:bg-white focus:border-slate-300 transition-all rounded-full"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"text-xs text-slate-400 mr-2",children:[h," paragraphs"]}),e.jsx(be,{variant:"outline",size:"sm",className:"text-red-600 border-red-200 hover:bg-red-50 h-8",disabled:y.size===0||S,onClick:q,children:S?"Deleting...":`Delete selected (${y.size})`})]})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:o.map(B=>{const ae=!!u[B.id],de=!!w[B.id],fe=E[B.id]??B.content;return e.jsxs(xs,{className:"p-3 space-y-2 hover:shadow-md transition-shadow cursor-default",onContextMenu:se=>M(se,B),children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"checkbox",checked:y.has(B.id),onChange:()=>V(B.id),className:"rounded border-slate-300",onClick:se=>se.stopPropagation()}),e.jsxs("div",{className:"text-xs text-slate-500 font-mono bg-slate-100 px-1 rounded",children:["#",B.chunk_index]})]}),e.jsxs("div",{className:"flex gap-2",children:[!ae&&e.jsx(be,{size:"sm",variant:"ghost",className:"h-6 px-2 text-slate-500",onClick:()=>A(B),disabled:de,children:"Edit"}),ae&&e.jsxs(e.Fragment,{children:[e.jsx(be,{size:"sm",variant:"ghost",className:"h-6 px-2",onClick:()=>C(B.id),disabled:de,children:"Cancel"}),e.jsx(be,{size:"sm",className:"h-6 px-2",onClick:()=>I(B.id),disabled:de,children:de?"Saving...":"Save"})]})]})]}),!ae&&e.jsx("div",{className:"text-sm whitespace-pre-wrap text-slate-700 max-h-[300px] overflow-auto leading-relaxed",children:B.content}),ae&&e.jsx("textarea",{ref:L(B.id),className:"w-full text-sm bg-white rounded border border-slate-300 p-2 outline-none focus:ring-2 focus:ring-slate-200 resize-none overflow-hidden leading-relaxed",rows:3,value:fe,onChange:se=>{N(z=>({...z,[B.id]:se.target.value})),requestAnimationFrame(()=>H(B.id))}})]},B.id)})}),o.length===0&&e.jsx("div",{className:"py-12 text-center text-slate-400",children:"No content chunks found."}),e.jsx("div",{className:"mt-6 pb-8",children:e.jsx(xn,{page:l,pageSize:d,total:h,onPageChange:c,onPageSizeChange:m,maxPageSize:200})}),e.jsx(Z,{})]})}const rN=[{target:'[data-onboarding="knowledge-header"]',content:e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-semibold text-slate-900 mb-2",children:"Knowledge Base"}),e.jsx("p",{className:"text-sm text-slate-600",children:"Store and organize documents that provide context for AI content generation. Documents uploaded here can be referenced when generating SEO content to improve accuracy and relevance."})]}),placement:"bottom",disableBeacon:!0},{target:'[data-onboarding="knowledge-new-folder"]',content:e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-semibold text-slate-900 mb-2",children:"New Folder"}),e.jsx("p",{className:"text-sm text-slate-600",children:"Create folders to organize your documents by topic, product, or category. Well-organized folders help you quickly find and reference relevant context during content generation."})]}),placement:"bottom",disableBeacon:!0},{target:'[data-onboarding="knowledge-upload"]',content:e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-semibold text-slate-900 mb-2",children:"File Upload"}),e.jsx("p",{className:"text-sm text-slate-600 mb-2",children:"Upload documents to use as AI context:"}),e.jsxs("ul",{className:"text-sm text-slate-600 space-y-1.5 list-disc list-inside",children:[e.jsx("li",{children:"Product documentation and specifications"}),e.jsx("li",{children:"Brand guidelines and style guides"}),e.jsx("li",{children:"Research reports and whitepapers"}),e.jsx("li",{children:"FAQ documents and knowledge articles"})]})]}),placement:"bottom",disableBeacon:!0},{target:"body",content:e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-semibold text-slate-900 mb-2",children:"Folder List"}),e.jsx("p",{className:"text-sm text-slate-600 mb-2",children:"Your knowledge folders with key information:"}),e.jsxs("ul",{className:"text-sm text-slate-600 space-y-1.5 list-disc list-inside",children:[e.jsxs("li",{children:[e.jsx("span",{className:"font-medium",children:"Name"})," - Folder identifier"]}),e.jsxs("li",{children:[e.jsx("span",{className:"font-medium",children:"Description"})," - Brief summary of contents"]}),e.jsxs("li",{children:[e.jsx("span",{className:"font-medium",children:"Documents"})," - Number of files in folder"]})]}),e.jsx("p",{className:"text-sm text-slate-600 mt-2",children:"Double-click to open a folder. Right-click for more options."})]}),placement:"center",disableBeacon:!0}];function oN(){const{toast:t}=_t(),[s,a]=v.useState([]),[n,o]=v.useState(1),[i,l]=v.useState(20),[c,d]=v.useState(0),[m,h]=v.useState(!1),[p,f]=v.useState(""),[b,y]=v.useState(""),[x,u]=v.useState(()=>rd()),[g,w]=v.useState(null),[_,E]=v.useState({}),[N,S]=v.useState(""),[k,D]=v.useState(!1),[F,R]=v.useState(!1),[L,$]=v.useState(""),[H,K]=v.useState(!1),[X,V]=v.useState(!1),[P,A]=v.useState(!1),[C,I]=v.useState(!1),[j,q]=v.useState(!0),T=v.useRef(null),M=v.useRef(null),Z=Zs(Us.knowledge),[B,ae]=v.useState(!1),[de,fe]=v.useState(""),[se,z]=v.useState(""),[U,Q]=v.useState(!1),[me,le]=v.useState(""),[O,ne]=v.useState(""),[ge,ze]=v.useState({key:"created_at",direction:"desc"}),[Ke,ie]=v.useState(null),ve=v.useCallback(async()=>{try{h(!0);const W=ge?.key,ke=ge?.direction||"desc",qe=await am(n,i,N.trim()||void 0,W,ke);a(qe.items),d(qe.total),q(qe.items.length<qe.total);const Qe={};await Promise.all(qe.items.map(async ct=>{try{const pt=await co(ct.id,1,1);Qe[ct.id]=pt.total}catch{Qe[ct.id]=0}
217})),E(Qe)}catch(W){console.error("Failed to load knowledge bases:",W),t({title:"Error",description:"Failed to load knowledge bases. Please try again later."})}finally{h(!1)}},[n,i,N,ge,t]);v.useEffect(()=>{ve()},[ve]),v.useEffect(()=>{const W=()=>K(window.innerWidth<640);return W(),window.addEventListener("resize",W),()=>window.removeEventListener("resize",W)},[]),v.useEffect(()=>{const W=qe=>{const Qe=typeof qe?.detail=="boolean"?qe.detail:!1;V(Qe),Qe&&A(!1)},ke=()=>{A(!0),V(!1)};return window.addEventListener("mobile-filter-toggle",W),window.addEventListener("mobile-add-click",ke),()=>{window.removeEventListener("mobile-filter-toggle",W),window.removeEventListener("mobile-add-click",ke)}},[]),v.useEffect(()=>{const W=()=>{u(rd())};return window.addEventListener("popstate",W),()=>window.removeEventListener("popstate",W)},[]),v.useEffect(()=>{x.kbId&&x.docId?we(x.kbId,x.docId):w(null)},[x.kbId,x.docId]),v.useEffect(()=>{const W=()=>ie(null);return window.addEventListener("click",W),()=>window.removeEventListener("click",W)},[]);async function we(W,ke){try{const ct=(await co(W,1,1e3)).items.find(pt=>pt.id===ke);ct?w(ct):(t({title:"Document not found",description:"The document you are looking for does not exist."}),Qa(W))}catch(qe){console.error("Failed to load document:",qe),t({title:"Failed to load document",description:"Please try again later."}),x.kbId&&Qa(x.kbId)}}const Pe=s,Ae=W=>{let ke="asc";ge&&ge.key===W&&ge.direction==="asc"&&(ke="desc"),ze({key:W,direction:ke})};function ye(W){if(!W)return"";try{return new Date(W).toLocaleDateString("en-US",{year:"numeric",month:"short",day:"numeric"})}catch{return W}}const Te=x.docId?"document":x.kbId?"detail":"list",Ie=x.kbId||"",Oe=s.find(W=>W.id===Ie)?.name,J=H&&Te==="list"&&!m&&!C&&j,re=v.useCallback(async()=>{if(J)try{I(!0);const W=n+1,ke=ge?.key,qe=ge?.direction||"desc",Qe=await am(W,i,N.trim()||void 0,ke,qe);a(pt=>{const At=new Set(pt.map(G=>G.id)),te=[...pt];for(const G of Qe.items)At.has(G.id)||te.push(G);return te}),o(W),d(Qe.total),q(W*i<Qe.total);const ct={};await Promise.all(Qe.items.map(async pt=>{try{const At=await co(pt.id,1,1);ct[pt.id]=At.total}catch{ct[pt.id]=0}})),E(pt=>({...pt,...ct}))}catch(W){console.warn("Failed to load more knowledge bases:",W),q(!1)}finally{I(!1)}},[J,n,i,N,ge]);v.useEffect(()=>{if(!H||Te!=="list")return;const W=T.current,ke=M.current;if(!W||!ke)return;const qe=new IntersectionObserver(Qe=>{Qe[0]?.isIntersecting&&re()},{root:W,rootMargin:"0px 0px 240px 0px",threshold:.1});return qe.observe(ke),()=>qe.disconnect()},[H,Te,re]);async function Se(){if(p.trim())try{const W=await bj({name:p.trim(),description:b.trim()||void 0});f(""),y(""),R(!1),o(1),await ve(),Qa(W.id)}catch(W){console.error("Failed to create knowledge base:",W),t({title:"Failed to create folder",description:W?.message||"Please try again later"})}}function je(W,ke){fe(W),z(ke),ae(!0)}function he(W,ke){le(W),ne(ke||""),Q(!0)}async function Re(){if(me)try{await nm({kb_id:me,description:O.trim()}),a(W=>W.map(ke=>ke.id===me?{...ke,description:O.trim()}:ke)),t({title:"Description updated",description:"Folder description has been updated successfully"}),Q(!1)}catch(W){console.error("Failed to update description:",W),t({title:"Failed to update description",description:W?.message||"Please try again later"})}}async function Me(){!se.trim()||!de||(await Ze(de,se.trim()),ae(!1))}async function Ze(W,ke){if(ke.trim())try{await nm({kb_id:W,name:ke}),a(qe=>qe.map(Qe=>Qe.id===W?{...Qe,name:ke}:Qe)),t({title:"Folder updated",description:"Name has been updated successfully"})}catch(qe){console.error("Failed to update knowledge base:",qe),t({title:"Failed to update folder",description:qe?.message||"Please try again later"})}}async function Be(W){if(window.confirm("Are you sure you want to move this folder to trash?"))try{await wj(W),t({title:"Folder deleted",description:"The folder has been moved to trash"}),await ve(),Ie===W&&Gr()}catch(ke){console.error("Failed to delete knowledge base:",ke),t({title:"Failed to delete folder",description:ke?.message||"Please try again later"})}}const et=W=>{W.target.closest("tr")||(W.preventDefault(),ie({x:W.clientX,y:W.clientY,type:"global"}))},$e=(W,ke)=>{W.preventDefault(),W.stopPropagation(),ie({x:W.clientX,y:W.clientY,type:"item",kb:ke})},ue=()=>{if(!Ke)return null;const{x:W,y:ke,type:qe,kb:Qe}=Ke;return e.jsxs(bh,{x:W,y:ke,className:"w-56",children:[qe==="global"&&e.jsxs(e.Fragment,{children:[e.jsxs(ba,{onClick:()=>{R(!0),ie(null)},children:[e.jsx(Jo,{className:"mr-2 h-4 w-4 text-slate-500"}),"New folder"]}),e.jsx(Ti,{}),e.jsxs(ba,{onClick:()=>{$(Ie||""),D(!0),ie(null)},children:[e.jsx(Gn,{className:"mr-2 h-4 w-4 text-slate-500"}),"File upload"]}),e.jsxs(ba,{onClick:()=>{$(Ie||""),D(!0),ie(null)},children:[e.jsx(Xo,{className:"mr-2 h-4 w-4 text-slate-500"}),"Folder upload"]})]}),qe==="item"&&Qe&&e.jsxs(e.Fragment,{children:[e.jsxs(ba,{onClick:()=>{Qa(Qe.id),ie(null)},children:[e.jsx(ns,{className:"mr-2 h-4 w-4 text-slate-500"}),"Open"]}),e.jsxs(ba,{onClick:()=>{je(Qe.id,Qe.name),ie(null)},children:[e.jsx(Ua,{className:"mr-2 h-4 w-4 text-slate-500"}),"Rename"]}),e.jsxs(ba,{onClick:()=>{he(Qe.id,Qe.description||""),ie(null)},children:[e.jsx(is,{className:"mr-2 h-4 w-4 text-slate-500"}),"Edit description"]}),e.jsx(Ti,{}),e.jsxs(ba,{onClick:()=>{t({title:"Download",description:"Download folder as zip is not supported yet."}),ie(null)},children:[e.jsx(Vs,{className:"mr-2 h-4 w-4 text-slate-500"}),"Download"]}),e.jsxs(ba,{danger:!0,onClick:()=>{Be(Qe.id),ie(null)},children:[e.jsx(es,{className:"mr-2 h-4 w-4"}),"Move to trash"]})]})]})};return e.jsxs("div",{className:"h-full flex flex-col bg-white relative",children:[!H&&e.jsx(oa,{steps:rN,run:Z.run,onComplete:Z.stopAndMarkCompleted,onSkip:Z.stopAndMarkCompleted}),e.jsxs("div",{className:"hidden sm:block flex-none px-6 pt-4 pb-2 border-b border-slate-100",children:[e.jsx("div",{className:"flex items-center justify-between h-8 mb-4","data-onboarding":"knowledge-header",children:e.jsxs("div",{className:"flex items-center flex-nowrap text-lg text-slate-600 min-w-0 flex-1 mr-4",children:[e.jsx("div",{className:"flex items-center flex-shrink-0",children:e.jsx("span",{className:"hover:underline cursor-pointer px-1 whitespace-nowrap",onClick:()=>Gr(),children:"Knowledge"})}),Te!=="list"&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"mx-1 text-slate-400 flex-shrink-0",children:"/"}),e.jsx("div",{className:"flex items-center min-w-0",children:Te==="detail"?e.jsxs(Pn,{children:[e.jsx(In,{unstyled:!0,className:"flex items-center gap-1 px-2 py-1 rounded hover:bg-slate-100 text-slate-800 font-medium cursor-pointer transition-colors min-w-0 max-w-full",children:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"truncate",children:Oe||"Loading..."}),e.jsx(Gs,{className:"h-4 w-4 text-slate-500 flex-shrink-0"})]})}),e.jsxs(Mn,{align:"left",className:"w-56",children:[e.jsx(js,{value:"rename",onClick:()=>{Oe&&je(Ie,Oe)},children:e.jsxs("div",{className:"flex items-center",children:[e.jsx(Ua,{className:"mr-2 h-4 w-4 text-slate-500"})," ","Rename"]})}),e.jsx(js,{value:"edit-desc",onClick:()=>{const W=s.find(ke=>ke.id===Ie);W&&he(Ie,W.description||"")},children:e.jsxs("div",{className:"flex items-center",children:[e.jsx(is,{className:"mr-2 h-4 w-4 text-slate-500"})," ","Edit description"]})}),e.jsx("div",{className:"my-1 border-b border-slate-100"}),e.jsx(js,{value:"upload-file",onClick:()=>{$(Ie),D(!0)},children:e.jsxs("div",{className:"flex items-center",children:[e.jsx(Gn,{className:"mr-2 h-4 w-4 text-slate-500"})," ","File upload"]})}),e.jsx("div",{className:"my-1 border-b border-slate-100"}),e.jsx(js,{value:"delete",onClick:()=>Be(Ie),children:e.jsxs("div",{className:"flex items-center text-red-600",children:[e.jsx(es,{className:"mr-2 h-4 w-4"})," Move to trash"]})})]})]}):e.jsx("span",{className:"hover:underline cursor-pointer px-1 truncate",onClick:()=>Qa(Ie),children:Oe||"Detail"})})]}),Te==="document"&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"mx-1 text-slate-400 flex-shrink-0",children:"/"}),e.jsx("span",{className:"font-medium text-slate-800 px-1 truncate",children:g?.file_name||"Document"})]})]})}),Te==="list"&&e.jsxs("div",{className:"flex items-center justify-between pb-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(be,{variant:"outline",size:"sm",className:"h-9 px-4 bg-white hover:bg-slate-50 text-slate-700 border-slate-200",onClick:()=>R(!0),"data-onboarding":"knowledge-new-folder",children:[e.jsx(Jo,{className:"mr-2 h-4 w-4"}),"New folder"]}),e.jsxs(be,{variant:"outline",size:"sm",className:"h-9 px-4 bg-white hover:bg-slate-50 text-slate-700 border-slate-200",onClick:()=>{$(""),D(!0)},"data-onboarding":"knowledge-upload",children:[e.jsx(Gn,{className:"mr-2 h-4 w-4"}),"File upload"]}),e.jsxs(be,{variant:"outline",size:"sm",className:"h-9 px-4 bg-white hover:bg-slate-50 text-slate-700 border-slate-200",onClick:()=>{$(""),D(!0)},children:[e.jsx(Xo,{className:"mr-2 h-4 w-4"}),"Folder upload"]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(Pt,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400"}),e.jsx(bt,{value:N,onChange:W=>S(W.target.value),onKeyDown:W=>{W.key==="Enter"&&ve()},placeholder:"Search in Drive",className:"pl-9 w-64 h-9 bg-slate-50 border-transparent focus:bg-white focus:border-slate-300 transition-all rounded-full"})]})]})]}),H&&Te!=="list"&&e.jsx("div",{className:"flex-none px-4 py-3 border-b border-slate-100 bg-white",children:e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx("button",{type:"button",onClick:()=>
217{if(Te==="document"&&x.kbId){Qa(x.kbId);return}Gr()},className:"h-9 w-9 -ml-1 rounded-full hover:bg-slate-100 text-slate-600 flex items-center justify-center","aria-label":"Back",children:e.jsx(un,{className:"h-4 w-4"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-sm font-semibold text-slate-800 truncate",children:Te==="detail"?Oe||"Folder":g?.file_name||"Document"}),e.jsx("div",{className:"text-[11px] text-slate-400 truncate",children:"Knowledge"})]})]})}),H&&Te==="list"&&X&&e.jsx("div",{className:"flex-none px-4 py-3 border-b border-slate-100 bg-white",children:e.jsxs("div",{className:"relative",children:[e.jsx(Pt,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400"}),e.jsx(bt,{value:N,onChange:W=>S(W.target.value),onKeyDown:W=>{W.key==="Enter"&&(o(1),ve())},placeholder:"Search folders",className:"pl-9 w-full h-10 bg-slate-50 border-transparent focus:bg-white focus:border-slate-300 transition-all rounded-full"})]})}),e.jsxs("div",{className:"flex-1 overflow-hidden relative flex flex-col bg-white",onContextMenu:Te==="list"?et:void 0,children:[Te==="list"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex-1 overflow-auto",ref:T,"data-onboarding":"knowledge-table",children:[e.jsxs("table",{className:"min-w-full text-sm",children:[e.jsx("thead",{className:"text-left text-slate-500 border-b border-slate-200 sticky top-0 bg-white z-10 shadow-[0_1px_0_0_#e2e8f0]",children:e.jsxs("tr",{children:[e.jsx("th",{className:"py-3 px-4 font-medium w-48 bg-white cursor-pointer hover:bg-slate-50 transition-colors select-none",onClick:()=>Ae("name"),children:e.jsxs("div",{className:"flex items-center gap-1",children:["Name",ge?.key==="name"&&(ge.direction==="asc"?e.jsx(Is,{className:"h-3 w-3"}):e.jsx(Ws,{className:"h-3 w-3"}))]})}),e.jsx("th",{className:"py-3 px-4 font-medium w-64 bg-white",children:"Description"}),e.jsx("th",{className:"py-3 px-4 font-medium w-32 bg-white cursor-pointer hover:bg-slate-50 transition-colors select-none",onClick:()=>Ae("document_count"),children:e.jsxs("div",{className:"flex items-center gap-1",children:["Documents",ge?.key==="document_count"&&(ge.direction==="asc"?e.jsx(Is,{className:"h-3 w-3"}):e.jsx(Ws,{className:"h-3 w-3"}))]})}),e.jsx("th",{className:"py-3 px-4 font-medium w-40 bg-white cursor-pointer hover:bg-slate-50 transition-colors select-none",onClick:()=>Ae("updated_at"),children:e.jsxs("div",{className:"flex items-center gap-1",children:["Updated",ge?.key==="updated_at"&&(ge.direction==="asc"?e.jsx(Is,{className:"h-3 w-3"}):e.jsx(Ws,{className:"h-3 w-3"}))]})}),e.jsx("th",{className:"py-3 px-4 font-medium w-20 bg-white sticky right-0 z-20 shadow-[-1px_0_0_0_#f1f5f9]",children:e.jsx("div",{className:"flex justify-end pr-2",children:e.jsx(lc,{className:"h-4 w-4 text-slate-400"})})})]})}),e.jsx("tbody",{children:Pe.map(W=>e.jsxs("tr",{className:"hover:bg-slate-50 transition-colors cursor-pointer group border-b border-slate-50",onDoubleClick:()=>Qa(W.id),onContextMenu:ke=>$e(ke,W),children:[e.jsx("td",{className:"py-3 px-4 font-medium text-slate-900 w-48",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(nu,{className:"h-5 w-5 text-slate-500 fill-slate-500/20 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:W.name})]})}),e.jsx("td",{className:"py-3 px-4 text-slate-500 w-64",children:e.jsx("span",{className:"truncate block max-w-lg",children:W.description})}),e.jsx("td",{className:"py-3 px-4 text-slate-500 w-32",children:_[W.id]??0}),e.jsx("td",{className:"py-3 px-4 text-slate-500 w-40",children:ye(W.updated_at)}),e.jsx("td",{className:"py-3 px-4 w-20 text-right sticky right-0 bg-white group-hover:bg-slate-50 shadow-[-1px_0_0_0_#f1f5f9] transition-colors",onClick:ke=>ke.stopPropagation(),children:e.jsxs(Pn,{children:[e.jsx(In,{unstyled:!0,className:"w-8 h-8 p-0 border-none hover:bg-slate-200 rounded-full flex items-center justify-center text-slate-500 transition-colors ml-auto",children:e.jsx(En,{className:"h-4 w-4"})}),e.jsxs(Mn,{align:"right",children:[e.jsx(js,{value:"open",onClick:()=>Qa(W.id),children:e.jsxs("div",{className:"flex items-center",children:[e.jsx(ns,{className:"mr-2 h-4 w-4 text-slate-500"})," ","Open"]})}),e.jsx(js,{value:"rename",onClick:()=>je(W.id,W.name),children:e.jsxs("div",{className:"flex items-center",children:[e.jsx(Ua,{className:"mr-2 h-4 w-4 text-slate-500"})," ","Rename"]})}),e.jsx(js,{value:"edit-desc",onClick:()=>he(W.id,W.description||""),children:e.jsxs("div",{className:"flex items-center",children:[e.jsx(is,{className:"mr-2 h-4 w-4 text-slate-500"})," ","Edit description"]})}),e.jsx("div",{className:"my-1 border-b border-slate-100"}),e.jsx(js,{value:"download",onClick:()=>t({title:"Download",description:"Not supported yet."}),children:e.jsxs("div",{className:"flex items-center",children:[e.jsx(Vs,{className:"mr-2 h-4 w-4 text-slate-500"})," ","Download"]})}),e.jsx("div",{className:"my-1 border-b border-slate-100"}),e.jsx(js,{value:"delete",onClick:()=>Be(W.id),children:e.jsxs("div",{className:"flex items-center text-red-600",children:[e.jsx(es,{className:"mr-2 h-4 w-4"})," Move to trash"]})})]})]})})]},W.id))})]}),H&&e.jsx("div",{ref:M,className:"h-12 flex items-center justify-center",children:C&&e.jsx("div",{className:"text-xs text-slate-400",children:"Loading..."})}),s.length===0&&e.jsxs("div",{className:"py-12 text-center max-w-2xl mx-auto",children:[e.jsx("div",{className:"text-slate-300 mb-4",children:e.jsx(Hh,{className:"h-12 w-12 mx-auto 
217stroke-1"})}),e.jsx("h3",{className:"text-lg font-semibold text-slate-900 mb-2",children:"No folders yet"}),e.jsx("p",{className:"text-sm text-slate-500 mb-6",children:"Create a folder to organize your documents and help AI generate more professional SEO content"})]})]}),e.jsx("div",{className:"hidden sm:block flex-none border-t border-slate-100 bg-white",children:e.jsx(xn,{page:n,pageSize:i,total:c,onPageChange:o,onPageSizeChange:l,maxPageSize:100})})]}),Te==="detail"&&Ie&&e.jsx(aN,{kbId:Ie,kbName:Oe,onOpenDocument:W=>{ai(Ie,W.id)},onBack:()=>{Gr()}}),Te==="document"&&Ie&&g&&e.jsx("div",{className:"h-full overflow-auto",children:e.jsx(nN,{kbId:Ie,document:g,onBack:()=>{x.kbId?Qa(x.kbId):Gr()}})})]}),e.jsx(Ht,{open:F,onOpenChange:R,children:e.jsxs(qt,{children:[e.jsx(Zt,{children:e.jsx(Yt,{children:"Create new folder"})}),e.jsxs("div",{className:"grid grid-cols-1 gap-3",children:[e.jsxs("div",{children:[e.jsx(Gt,{children:"Name"}),e.jsx(bt,{value:p,onChange:W=>f(W.target.value),placeholder:"Folder name"})]}),e.jsxs("div",{children:[e.jsx(Gt,{children:"Description"}),e.jsx(Js,{value:b,onChange:W=>y(W.target.value),placeholder:"Description (optional)"})]})]}),e.jsxs(Ns,{children:[e.jsx(be,{variant:"outline",onClick:()=>R(!1),children:"Cancel"}),e.jsx(be,{onClick:Se,disabled:!p.trim(),children:"Create"})]})]})}),e.jsx(Ht,{open:B,onOpenChange:ae,children:e.jsxs(qt,{children:[e.jsx(Zt,{children:e.jsx(Yt,{children:"Rename folder"})}),e.jsx("div",{className:"grid grid-cols-1 gap-3 py-2",children:e.jsxs("div",{children:[e.jsx(Gt,{children:"Name"}),e.jsx(bt,{value:se,onChange:W=>z(W.target.value),placeholder:"Folder name",onKeyDown:W=>{W.key==="Enter"&&Me()}})]})}),e.jsxs(Ns,{children:[e.jsx(be,{variant:"outline",onClick:()=>ae(!1),children:"Cancel"}),e.jsx(be,{onClick:Me,disabled:!se.trim(),children:"Save"})]})]})}),e.jsx(Ht,{open:U,onOpenChange:Q,children:e.jsxs(qt,{children:[e.jsx(Zt,{children:e.jsx(Yt,{children:"Edit description"})}),e.jsx("div",{className:"grid grid-cols-1 gap-3 py-2",children:e.jsxs("div",{children:[e.jsx(Gt,{children:"Description"}),e.jsx(Js,{value:O,onChange:W=>ne(W.target.value),placeholder:"Folder description",rows:4})]})}),e.jsxs(Ns,{children:[e.jsx(be,{variant:"outline",onClick:()=>Q(!1),children:"Cancel"}),e.jsx(be,{onClick:Re,children:"Save"})]})]})}),e.jsx(yh,{open:k,onOpenChange:W=>{D(W),W||$("")},kbs:s,initialKbId:L||Ie,lockKbSelection:!1,disableOutsideClose:!0,onCompleted:async()=>{await ve()}}),e.jsx(ue,{}),H&&P&&e.jsxs("div",{className:"fixed inset-0 z-40 flex items-end justify-center",children:[e.jsx("div",{className:"absolute inset-0 bg-black/40",onClick:()=>A(!1)}),e.jsxs("div",{className:"bg-white w-full rounded-t-2xl relative z-50 p-6 pb-8 flex flex-col gap-2 animate-in slide-in-from-bottom duration-200",children:[e.jsx("div",{className:"w-12 h-1 bg-gray-200 rounded-full mx-auto mb-3"}),e.jsx("h3",{className:"text-center text-base font-medium text-gray-800 mb-2",children:"Add"}),e.jsxs("button",{onClick:()=>{A(!1),R(!0)},className:"w-full flex items-center gap-3 px-4 py-3 rounded-xl bg-slate-50 hover:bg-slate-100 text-slate-800",children:[e.jsx(Jo,{className:"h-5 w-5 text-slate-600"}),e.jsx("span",{className:"text-sm font-medium",children:"New folder"})]}),e.jsxs("button",{onClick:()=>{A(!1),$(Ie||""),D(!0)},className:"w-full flex items-center gap-3 px-4 py-3 rounded-xl bg-slate-50 hover:bg-slate-100 text-slate-800",children:[e.jsx(Gn,{className:"h-5 w-5 text-slate-600"}),e.jsx("span",{className:"text-sm font-medium",children:"File upload"})]}),e.jsxs("button",{onClick:()=>{A(!1),$(Ie||""),D(!0)},className:"w-full flex items-center gap-3 px-4 py-3 rounded-xl bg-slate-50 hover:bg-slate-100 text-slate-800",children:[e.jsx(Xo,{className:"h-5 w-5 text-slate-600"}),e.jsx("span",{className:"text-sm font-medium",children:"Folder upload"})]}),e.jsx("button",{onClick:()=>A(!1),className:"mt-2 py-3 text-slate-500 font-medium text-sm w-full hover:bg-slate-50 rounded-xl",children:"Cancel"})]})]}),Te==="list"&&e.jsx("button",{onClick:Z.startManual,className:"fixed bottom-16 right-5 z-50 h-8 w-8 rounded-full bg-white border border-slate-200 shadow-md hover:shadow-lg hover:bg-slate-50 transition-all hover:scale-105 hidden sm:flex items-center justify-center",title:"View navigation guide","aria-label":"View navigation guide",children:e.jsx(Hs,{className:"h-4 w-4 text-slate-600"})})]})}const iN=["contains","equals","not equals","starts with","ends with"];function lN({fields:t,filters:s,onFiltersChange:a,onClose:n}){const[o,i]=v.useState(s);v.useEffect(()=>{i(s)},[s]);const l=(f,b,y)=>{const x=[...o];x[f]={...x[f],[b]:y},i(x)},c=()=>{const f=t[0].value;i([...o,{field:f,operator:"contains",value:""}])},d=f=>{i(o.filter((b,y)=>y!==f))},m=()=>{i([])},h=()=>{a(o),n?.()},p=()=>{i(s),n?.()};return e.jsxs("div",{className:"absolute z-[200] mt-2 w-[560px] rounded-[10px] border border-slate-200 bg-white p-3 shadow-[0_8px_24px_rgba(0,0,0,0.15)]","data-filter-popover":"true",onClick:f=>f.stopPropagation(),children:[e.jsx("div",{className:"text-xs mb-3 text-slate-600",children:"Where"}),e.jsxs("div",{className:"max-h-[260px] overflow-y-auto mb-2",children:[o.map((f,b)=>e.jsxs("div",{className:"grid grid-cols-[1fr_1fr_2fr_auto] gap-2 items-center mb-2",children:[e.jsx("select",{className:"h-8 rounded border border-slate-200 bg-white px-2 text-xs text-slate-700",value:f.field,onChange:y=>l(b,"field",y.target.value),children:t.map(y=>e.jsx("option",{value:y.value,children:y.label},y.value))}),e.jsx("select",{className:"h-8 rounded border border-slate-200 bg-white px-2 text-xs text-slate-700",value:f.operator,onChange:y=>l(b,"operator",y.target.value),children:iN.map(y=>e.jsx("option",{value:y,children:y},y))}),e.jsx("input",{className:"h-8 rounded border border-slate-200 bg-white px-2 text-xs text-slate-700",placeholder:"Enter value",value:f.value,onChange:y=>l(b,"value",y.target.value)}),e.jsx("button",{className:"h-8 w-8 flex items-center justify-center text-xs text-slate-600 hover:bg-slate-100 rounded",onClick:()=>d(b),title:"Remove filter",children:e.jsx("svg",{className:"h-4 w-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]},b)),o.length===0&&e.jsx("div",{className:"text-xs text-slate-500 text-center py-2",children:"No filters applied"})]}),e.jsxs("div",{className:"flex justify-between border-t border-slate-200",children:[e.jsxs("div",{className:"flex items-center gap-2 mt-2",children:[e.jsx("button",{className:"cursor-pointer h-8 rounded border border-slate-200 bg-white px-3 text-xs text-slate-700 hover:bg-slate-50",onClick:c,children:"+ Add filter"}),e.jsxs("button",{className:"cursor-pointer h-8 bg-transparent border-none text-xs text-red-600 hover:text-red-700 flex items-center gap-1",onClick:m,children:[e.jsx("span",{className:"text-red-600",children:"✕"}),e.jsx("span",{children:"Clear filters"})]})]}),e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[e.jsx("button",{className:"cursor-pointer h-8 rounded border border-slate-200 bg-white px-4 text-xs text-slate-700 hover:bg-slate-50",onClick:p,children:"Cancel"}),e.jsx("button",{className:"cursor-pointer h-8 rounded bg-slate-900 text-white px-4 text-xs hover:bg-slate-800",onClick:h,children:"Apply"})]})]})]})}function cN(){const[t,s]=r.useState(()=>typeof window<"u"&&window.innerWidth<768);return r.useEffect(()=>{const a=()=>s(window.innerWidth<768);return window.addEventListener("resize",a),()=>window.removeEventListener("resize",a)},[]),t}function Bn(t){const s=t.match(/(\d{4})-W?(\d{2})/i);if(!s)return t;const a=parseInt(s[1]),n=parseInt(s[2]),o=new Date(a,0,4),i=o.getDay()||7,l=1+(n-1)*7-i,c=new Date(o.getTime()+l*24*60*60*1e3),d=new Date(c.getTime()+8640*60*1e3),m=h=>{const p=(h.getMonth()+1).toString().padStart(2,"0"),f=h.getDate().toString().padStart(2,"0");return`${p}.${f}`};return`${t.toUpperCase().replace("-W","-w")}(${m(c)}~${m(d)})`}function dN(t,s){const a=new Date,n=new Date(Date.UTC(a.getUTCFullYear(),a.getUTCMonth(),a.getUTCDate()));let o=27;t==="last_7_days"&&(o=6),t==="last_3_months"&&(o=89);const i=new Date(n);i.setUTCDate(n.getUTCDate()-o);const l=c=>c.toISOString().slice(0,10);return{start:l(i),end:l(n)}}function Jl(){const t=new Date,s=new Date(Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate())),a=l=>l.toISOString().slice(0,10),n=new Date(s);n.setUTCDate(s.getUTCDate()-6);const o=new Date(s);o.setUTCDate(s.getUTCDate()-27);const i=new Date(s);return i.setUTCDate(s.getUTCDate()-89),[{label:"Last 7 days",value:{from:a(n),to:a(s)}},{label:"Last 28 days",value:{from:a(o),to:a(s)}},{label:"Last 3 months",value:{from:a(i),to:a(s)}}]}function jm(t){if(!t.from||!t.to)return null;
217const s=Jl();for(const a of s)if(a.value.from===t.from&&a.value.to===t.to){if(a.label==="Last 7 days")return"last_7_days";if(a.label==="Last 28 days")return"last_28_days";if(a.label==="Last 3 months")return"last_3_months"}return null}const yl=[{key:"query",label:"QUERIES"},{key:"page",label:"PAGES"},{key:"country",label:"COUNTRIES"},{key:"device",label:"DEVICES"},{key:"searchAppearance",label:"SEARCH APPEARANCE"}],vm=[{value:"date",label:"DAY"},{value:"week",label:"WEEK"},{value:"month",label:"MONTH"}],wh="flowwriter.dashboard.filters";function mN(){try{const t=localStorage.getItem(wh);if(t)return JSON.parse(t)}catch(t){console.error("Failed to load dashboard filters from storage:",t)}return{}}function uN(t){try{localStorage.setItem(wh,JSON.stringify(t))}catch(s){console.error("Failed to save dashboard filters to storage:",s)}}const Nm=t=>{try{let s=t.replace(/^sc-domain:/,"").replace(/^https?:\/\//,"").replace(/^www\./,"").replace(/\/$/,"").toLowerCase();const a=s.indexOf("/");return a>0&&(s=s.substring(0,a)),s}catch{return t.toLowerCase()}},xN=(t,s)=>{if(!t||t.length===0)return null;if(!s)return t[0].site_url;const a=Nm(s),n=t.map(o=>{const i=Nm(o.site_url);let l=0;if(i===a)l=100;else if(i.includes(a)||a.includes(i))l=80;else{const c=i.split(".").slice(-2).join("."),d=a.split(".").slice(-2).join(".");c===d&&(l=60)}return{site:o,score:l}});return n.sort((o,i)=>i.score-o.score),n[0].score===0?t[0].site_url:n[0].site.site_url};function hN(){const t=mN(),s=cN(),[a,n]=r.useState([]),[o,i]=r.useState(t.site||""),[l,c]=r.useState(t.preset||"last_3_months"),[d,m]=r.useState(t.customDateRange||{}),[h,p]=r.useState(t.searchType||"web"),[f,b]=r.useState({clicks:0,impressions:0,ctr:0,position:0}),[y,x]=r.useState(t.dimension||"page"),[u,g]=r.useState(t.timeGrouping||"date"),[w,_]=r.useState([]),[E,N]=r.useState(1),[S,k]=r.useState(t.pageSize||25),[D,F]=r.useState(!1),[R,L]=r.useState(!1),[$,H]=r.useState(!1),[K,X]=r.useState([]),[V,P]=r.useState(!1),A=r.useRef(null),[C,I]=r.useState(!1),[j,q]=r.useState(30),T=30;r.useEffect(()=>{const O=ne=>{I(ne.detail??!C)};return window.addEventListener("mobile-filter-toggle",O),()=>window.removeEventListener("mobile-filter-toggle",O)},[C]);const M=[{value:"page",label:"Page"},{value:"query",label:"Query"},{value:"country",label:"Country"},{value:"device",label:"Device"}],Z=(O,ne)=>{const ge=String(ne.field==="page"||ne.field==="query"||ne.field==="country"||ne.field==="device"?O.key:"").toLowerCase(),ze=ne.value.toLowerCase();if({page:"page",query:"query",country:"country",device:"device"}[ne.field]!==y)return!0;switch(ne.operator){case"contains":return ge.includes(ze);case"equals":return ge===ze;case"not equals":return ge!==ze;case"starts with":return ge.startsWith(ze);case"ends with":return ge.endsWith(ze);default:return!0}},B=r.useMemo(()=>{let O=[...w];return K.forEach(ne=>{ne.value.trim()&&(O=O.filter(ge=>Z(ge,ne)))}),O},[w,K,y]),ae=O=>{const ne=O.target,{scrollTop:ge,scrollHeight:ze,clientHeight:Ke}=ne;ze-ge-Ke<100&&q(ie=>Math.min(ie+T,B.length))},de=r.useMemo(()=>B.slice(0,j),[B,j]),fe=r.useMemo(()=>{const O=(E-1)*S,ne=O+S;return B.slice(O,ne)},[B,E,S]);r.useEffect(()=>{if(!V)return;const O=ne=>{const ge=ne.target;A.current&&!A.current.contains(ge)&&!ge.closest('[data-filter-popover="true"]')&&P(!1)};return document.addEventListener("mousedown",O),()=>document.removeEventListener("mousedown",O)},[V]),r.useEffect(()=>{(async()=>{try{const[O,ne]=await Promise.all([Ro(),Or().catch(()=>null)]),ge=O.items||[];if(n(ge),ge.length===0||o&&ge.some(Ke=>Ke.site_url===o))return;const ze=t.site;if(ze&&ge.some(Ke=>Ke.site_url===ze))i(ze);else{const Ke=ne?.domain,ie=xN(ge,Ke);ie?i(ie):ge[0]?.site_url&&i(ge[0].site_url)}}catch{n([])}})()},[]),r.useEffect(()=>{if(l==="custom"&&(!d.from||!d.to)){const O=new Date,ne=new Date(Date.UTC(O.getUTCFullYear(),O.getUTCMonth(),O.getUTCDate())),ge=new Date(ne);ge.setUTCDate(ne.getUTCDate()-27);const ze=Ke=>Ke.toISOString().slice(0,10);m({from:ze(ge),to:ze(ne)})}},[l,d]);const se=r.useMemo(()=>l==="custom"&&d.from&&d.to?{start:d.from,end:d.to}:dN(l),[l,d]);r.useEffect(()=>{if(!o||l==="custom"&&(!d.from||!d.to))return;const{start:O,end:ne}=se;F(!0),N(1),Promise.all([Rx({site_url:o,start_date:O,end_date:ne,search_type:h}),Pa({site_url:o,dimension:y,start_date:O,end_date:ne,search_type:h,time_grouping:u})]).then(([ge,ze])=>{b(ge),_(ze.items||[])}).catch(()=>{b({clicks:0,impressions:0,ctr:0,position:0}),_([])}).finally(()=>F(!1))}
217,[o,l,d,h,y,u,se]);const{start:z,end:U}=se;r.useEffect(()=>{uN({site:o,preset:l,customDateRange:d,searchType:h,dimension:y,timeGrouping:u,pageSize:S})},[o,l,d,h,y,u,S]);const Q=()=>{if(w.length===0)return;if(!w[0].key?.includes("|")){const Oe=[[y,"Clicks","Impressions","CTR","Position"].join(",")];w.forEach(re=>{const Se=[`"${re.key}"`,re.clicks||0,re.impressions||0,((re.ctr||0)*100).toFixed(2)+"%",(re.position||0).toFixed(2)];Oe.push(Se.join(","))});const J=Oe.join(`
218`);ar({filename:`gsc-dashboard-${y||"all"}-${z}-${U}.csv`,content:J,mimeType:"text/csv;charset=utf-8;"});return}const ne=new Map,ge=new Set;w.forEach(Ie=>{const[Oe,J]=Ie.key?.split("|")||[],re=J||Oe,Se=Oe;ge.add(Se),ne.has(re)||ne.set(re,{metrics:new Map});const je=ne.get(re);je.metrics.set(Se,{clicks:Ie.clicks||0,impressions:Ie.impressions||0,ctr:Ie.ctr||0,position:Ie.position||0}),y==="page"&&Ie.keyword_group&&(je.keyword_group=Ie.keyword_group)});const ze=Array.from(ge).sort((Ie,Oe)=>{if(u==="date")return Oe.localeCompare(Ie);if(u==="month")return Oe.localeCompare(Ie);{const J=Ie.match(/w\d+/),re=Oe.match(/w\d+/);if(J&&re){const Se=parseInt(J[0].replace("w",""));return parseInt(re[0].replace("w",""))-Se}return Oe.localeCompare(Ie)}}),Ke=[y],ie=[...Ke];ze.forEach(Ie=>{const Oe=u==="week"?Bn(Ie):Ie;ie.push(Oe),ie.push("","","","")});const ve=Ke.map(()=>"");ze.forEach(()=>{ve.push("Clicks","Impressions","CTR","Position")});const we=ie.length,Pe=Array(we-1).fill("").join(","),Ae=[ie.join(","),ve.join(",")];Array.from(ne.keys()).sort().forEach(Ie=>{const Oe=ne.get(Ie),J=[`"${Ie}"`];ze.forEach(re=>{const Se=Oe.metrics.get(re)||{clicks:0,impressions:0,ctr:0,position:0};J.push(String(Se.clicks),String(Se.impressions),((Se.ctr||0)*100).toFixed(2)+"%",String((Se.position||0).toFixed(2)))}),Ae.push(J.join(","))}),Ae.push(Pe);const Te=Ae.join(`
219`);ar({filename:`gsc-dashboard-${y||"all"}-${z}-${U}.csv`,content:Te,mimeType:"text/csv;charset=utf-8;"})},me=async()=>{if(o){if(l==="custom"&&(!d.from||!d.to)){alert("Please select a custom date range first");return}H(!0);try{const{start:O,end:ne}=se,ge=as.book_new(),ze=await Promise.all([Pa({site_url:o,dimension:"page",start_date:O,end_date:ne,search_type:h,time_grouping:u}),Pa({site_url:o,dimension:"query",start_date:O,end_date:ne,search_type:h,time_grouping:u}),Pa({site_url:o,dimension:"country",start_date:O,end_date:ne,search_type:h,time_grouping:u}),Pa({site_url:o,dimension:"device",start_date:O,end_date:ne,search_type:h,time_grouping:u}),Pa({site_url:o,dimension:"searchAppearance",start_date:O,end_date:ne,search_type:h,time_grouping:u})]),Ke=await Promise.all([Pa({site_url:o,dimension:"page",start_date:O,end_date:ne,search_type:h}),Pa({site_url:o,dimension:"query",start_date:O,end_date:ne,search_type:h}),Pa({site_url:o,dimension:"country",start_date:O,end_date:ne,search_type:h}),Pa({site_url:o,dimension:"device",start_date:O,end_date:ne,search_type:h}),Pa({site_url:o,dimension:"searchAppearance",start_date:O,end_date:ne,search_type:h})]),ie=new Map,ve=new Set;ze.forEach(Se=>{Se.items.forEach(je=>{if(je.key?.includes("|")){const[he]=je.key.split("|");ve.add(he)}})}),ze.forEach(Se=>{Se.items.forEach(je=>{if(je.key?.includes("|")){const[he]=je.key.split("|");ie.has(he)||ie.set(he,{clicks:0,impressions:0,totalWeightedPosition:0,totalClicks:0});const Re=ie.get(he);Re.clicks+=je.clicks||0,Re.impressions+=je.impressions||0,je.clicks&&je.position&&(Re.totalWeightedPosition+=je.position*je.clicks,Re.totalClicks+=je.clicks)}})});const we=Array.from(ve).sort((Se,je)=>{if(u==="date")return je.localeCompare(Se);if(u==="month")return je.localeCompare(Se);{const he=Se.match(/w\d+/),Re=je.match(/w\d+/);if(he&&Re){const Me=parseInt(he[0].replace("w",""));return parseInt(Re[0].replace("w",""))-Me}return je.localeCompare(Se)}}),Pe=["Time Group","Clicks","Impressions","CTR","Position"],Ae=[];we.forEach(Se=>{const je=ie.get(Se)||{clicks:0,impressions:0,totalWeightedPosition:0,totalClicks:0},he=je.impressions>0?je.clicks/je.impressions:0,Re=je.totalClicks>0?je.totalWeightedPosition/je.totalClicks:0,Me=u==="week"?Bn(Se):Se;Ae.push([Me,je.clicks,je.impressions,((he||0)*100).toFixed(2),(Re||0).toFixed(2)])});const ye=[Pe,...Ae],Te=as.aoa_to_sheet(ye);as.book_append_sheet(ge,Te,"Performance Overview");const Ie=[["Filter","Value"],["Site",o],["Date Preset",l==="custom"?"Custom"
219:l.replace(/_/g," ").replace(/\b\w/g,Se=>Se.toUpperCase())]];l==="custom"&&d.from&&d.to&&Ie.push(["Custom Date Range",`${d.from} to ${d.to}`]),Ie.push(["Search Type",h],["Dimension",y],["Time Grouping",u],["Date Range",`${O} to ${ne}`]);const Oe=as.aoa_to_sheet(Ie);as.book_append_sheet(ge,Oe,"Export Metadata & Filters");const J=(Se,je,he=!1)=>{if(Se.length===0)return as.aoa_to_sheet([["No data available"]]);if(!Se[0].key?.includes("|"))return as.aoa_to_sheet([["No time grouping data"]]);const Me=new Map,Ze=new Set;Se.forEach(te=>{const[G,pe]=te.key?.split("|")||[],ce=pe||G,Y=G;Ze.add(Y),Me.has(ce)||Me.set(ce,{metrics:new Map});const xe=Me.get(ce);xe.metrics.set(Y,{clicks:te.clicks||0,impressions:te.impressions||0,ctr:te.ctr||0,position:te.position||0}),he&&te.keyword_group&&(xe.keyword_group=te.keyword_group)});const Be=Array.from(Ze).sort((te,G)=>{if(u==="date")return G.localeCompare(te);if(u==="month")return G.localeCompare(te);{const pe=te.match(/w\d+/),ce=G.match(/w\d+/);if(pe&&ce){const Y=parseInt(pe[0].replace("w",""));return parseInt(ce[0].replace("w",""))-Y}return G.localeCompare(te)}}),et=[je==="page"?"Content URL":je];je==="page"&&et.push("Call to Action link");const $e=[...et],ue=[];let W=et.length;et.length>0&&ue.push({s:{r:0,c:0},e:{r:1,c:0}}),et.length>1&&ue.push({s:{r:0,c:1},e:{r:1,c:1}}),$e.push("Clicks");for(let te=1;te<Be.length;te++)$e.push(null);ue.push({s:{r:0,c:W},e:{r:0,c:W+Be.length-1}}),W+=Be.length,$e.push("Impressions");for(let te=1;te<Be.length;te++)$e.push(null);ue.push({s:{r:0,c:W},e:{r:0,c:W+Be.length-1}}),W+=Be.length,$e.push("CTR");for(let te=1;te<Be.length;te++)$e.push(null);ue.push({s:{r:0,c:W},e:{r:0,c:W+Be.length-1}}),W+=Be.length,$e.push("Position");for(let te=1;te<Be.length;te++)$e.push(null);ue.push({s:{r:0,c:W},e:{r:0,c:W+Be.length-1}});const ke=et.map(()=>null);Be.forEach(te=>{const G=u==="week"?Bn(te):te;ke.push(G)}),Be.forEach(te=>{const G=u==="week"?Bn(te):te;ke.push(G)}),Be.forEach(te=>{const G=u==="week"?Bn(te):te;ke.push(G)}),Be.forEach(te=>{const G=u==="week"?Bn(te):te;ke.push(G)});const qe=[$e,ke],Qe=Array.from(Me.keys()).sort(),ct=new Map;Qe.forEach(te=>{Me.get(te).metrics.forEach((pe,ce)=>{ct.has(ce)||ct.set(ce,{clicks:0,impressions:0,ctr:0,position:0});const Y=ct.get(ce);Y.clicks+=pe.clicks,Y.impressions+=pe.impressions})}),ct.forEach((te,G)=>{te.impressions>0&&(te.ctr=te.clicks/te.impressions);let pe=0,ce=0;Qe.forEach(Y=>{const Ee=Me.get(Y).metrics.get(G);Ee&&Ee.clicks>0&&(pe+=Ee.position*Ee.clicks,ce+=Ee.clicks)}),ce>0&&(te.position=pe/ce)});const pt=["All Contents"];je==="page"&&pt.push(""),Be.forEach(te=>{const G=ct.get(te)||{clicks:0,impressions:0,ctr:0,position:0};pt.push(G.clicks)}),Be.forEach(te=>{const G=ct.get(te)||{clicks:0,impressions:0,ctr:0,position:0};pt.push(G.impressions)}),Be.forEach(te=>{const G=ct.get(te)||{clicks:0,impressions:0,ctr:0,position:0};pt.push(((G.ctr||0)*100).toFixed(2))}),Be.forEach(te=>{const G=ct.get(te)||{clicks:0,impressions:0,ctr:0,position:0};pt.push((G.position||0).toFixed(2))}),qe.push(pt),Qe.forEach(te=>{const G=Me.get(te),pe=[te];je==="page"&&pe.push(""),Be.forEach(ce=>{const Y=G.metrics.get(ce)||{clicks:0,impressions:0,ctr:0,position:0};pe.push(Y.clicks)}),Be.forEach(ce=>{const Y=G.metrics.get(ce)||{clicks:0,impressions:0,ctr:0,position:0};pe.push(Y.impressions)}),Be.forEach(ce=>{const Y=G.metrics.get(ce)||{clicks:0,impressions:0,ctr:0,position:0};pe.push(((Y.ctr||0)*100).toFixed(2))}),Be.forEach(ce=>{const Y=G.metrics.get(ce)||{clicks:0,impressions:0,ctr:0,position:0};pe.push((Y.position||0).toFixed(2))}),qe.push(pe)});const At=as.aoa_to_sheet(qe);return ue.length>0&&(At["!merges"]=ue),At},re=(Se,je)=>{const Re=[[je,"Clicks","Impressions","CTR","Position"]],Me=new Map;return Se.forEach(Be=>{const et=Be.key?.includes("|")?Be.key.split("|")[1]||Be.key.split("|")[0]:Be.key||"";Me.has(et)||Me.set(et,{clicks:0,impressions:0,totalWeightedPosition:0,totalClicks:0});const $e=Me.get(et);$e.clicks+=Be.clicks||0,$e.impressions+=Be.impressions||0,Be.clicks&&Be.position&&($e.totalWeightedPosition+=Be.position*Be.clicks,$e.totalClicks+=Be.clicks),je==="page"&&Be.keyword_group&&!$e.keyword_group&&($e.keyword_group=Be.keyword_group)}
219),Array.from(Me.keys()).sort().forEach(Be=>{const et=Me.get(Be),$e=et.impressions>0?et.clicks/et.impressions:0,ue=et.totalClicks>0?et.totalWeightedPosition/et.totalClicks:0,W=[Be,et.clicks,et.impressions,($e*100).toFixed(2)+"%",ue.toFixed(2)];Re.push(W)}),as.aoa_to_sheet(Re)};as.book_append_sheet(ge,J(ze[0].items,"page",!0),"Content Pages - Time Series"),as.book_append_sheet(ge,re(Ke[0].items,"page"),"Content Pages - Summary"),as.book_append_sheet(ge,J(ze[1].items,"query"),"Search Queries - Time Series"),as.book_append_sheet(ge,re(Ke[1].items,"query"),"Search Queries - Summary"),as.book_append_sheet(ge,J(ze[2].items,"country"),"Geography - Time Series"),as.book_append_sheet(ge,re(Ke[2].items,"country"),"Geography - Summary"),as.book_append_sheet(ge,J(ze[3].items,"device"),"Devices - Time Series"),as.book_append_sheet(ge,re(Ke[3].items,"device"),"Devices - Summary"),as.book_append_sheet(ge,J(ze[4].items,"searchAppearance"),"Appearance - Time Series"),as.book_append_sheet(ge,re(Ke[4].items,"searchAppearance"),"Search Appearance - Summary"),mi(ge,`gsc-dashboard-all-${O}-${ne}.xlsx`)}catch(O){console.error("Export all failed:",O),alert(`Export failed: ${O?.message||O}`)}finally{H(!1)}}},le=()=>{if(w.length===0)return;const O=w[0].key?.includes("|"),ne=[],ge=[];if(O){const ve=new Map,we=new Set;w.forEach(J=>{const[re,Se]=J.key?.split("|")||[],je=Se||re,he=re;we.add(he),ve.has(je)||ve.set(je,{metrics:new Map});const Re=ve.get(je);Re.metrics.set(he,{clicks:J.clicks||0,impressions:J.impressions||0,ctr:J.ctr||0,position:J.position||0}),y==="page"&&J.keyword_group&&(Re.keyword_group=J.keyword_group)});const Pe=Array.from(we).sort((J,re)=>{if(u==="date")return re.localeCompare(J);if(u==="month")return re.localeCompare(J);{const Se=J.match(/w\d+/),je=re.match(/w\d+/);if(Se&&je){const he=parseInt(Se[0].replace("w",""));return parseInt(je[0].replace("w",""))-he}return re.localeCompare(J)}}),Ae=[y],ye=[...Ae];let Te=Ae.length;Pe.forEach(J=>{const re=u==="week"?Bn(J):J;ye.push(re),ye.push(null,null,null),ge.push({s:{r:0,c:Te},e:{r:0,c:Te+3}}),Te+=4});const Ie=Ae.map(()=>null);Pe.forEach(()=>{Ie.push("Clicks","Impressions","CTR","Position")}),ne.push(ye,Ie),Array.from(ve.keys()).sort().forEach(J=>{const re=ve.get(J),Se=[J];Pe.forEach(je=>{const he=re.metrics.get(je)||{clicks:0,impressions:0,ctr:0,position:0};Se.push(he.clicks,he.impressions,((he.ctr||0)*100).toFixed(2)+"%",(he.position||0).toFixed(2))}),ne.push(Se)})}else{const ve=[y,"Clicks","Impressions","CTR","Position"];ne.push(ve),w.forEach(we=>{const Pe=[we.key,we.clicks||0,we.impressions||0,((we.ctr||0)*100).toFixed(2)+"%",(we.position||0).toFixed(2)];ne.push(Pe)})}const ze=as.aoa_to_sheet(ne);ge.length>0&&(ze["!merges"]=ge);const Ke=[{wch:30},{wch:15},{wch:15},{wch:15},{wch:10},{wch:10}];ze["!cols"]=Ke;const ie=as.book_new();as.book_append_sheet(ie,ze,"Dashboard"),mi(ie,`gsc-dashboard-${y||"all"}-${z}-${U}.xlsx`)};return e.jsxs("div",{className:`max-w-7xl mx-auto space-y-4 ${s?"p-3":"p-6 space-y-6"}`,children:[e.jsx("div",{className:"hidden sm:block",children:e.jsx("h1",{className:"text-3xl font-bold tracking-tight",children:"Page Ranking"})}),s&&C&&e.jsx(xs,{className:"rounded-xl",children:e.jsxs(fs,{className:"pt-4 grid gap-3 grid-cols-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-slate-500 mb-1",children:"Site"}),e.jsx("select",{className:"w-full h-8 text-xs border border-slate-200 rounded-md px-2 bg-white",value:o,onChange:O=>{i(O.target.value),N(1),q(30)},children:a.map(O=>{const ne=O.site_url.replace(/^sc-domain:/,"");return e.jsx("option",{value:O.site_url,children:ne},O.site_url)})})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-slate-500 mb-1",children:"Date range"}),e.jsx(Sa,{value:l==="custom"?d:{from:se.start,to:se.end},onChange:O=>{N(1),q(30);const ne=jm(O);ne?c(ne):(c("custom"),m(O))},placeholder:"Date range",className:"w-full text-xs",showClear:!1,presets:Jl()})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-slate-500 mb-1",children:"Time grouping"}),e.jsx("select",{className:"w-full h-8 text-xs border border-slate-200 rounded-md px-2 bg-white",value:u,onChange:O=>{g(O.target.value),N(1),q(30)},children:vm.map(O=>e.jsx("option",{value:O.value,children:O.label},O.value))})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-slate-500 mb-1",children:"Search type"}),e.jsxs("select",{className:"w-full h-8 text-xs border border-slate-200 rounded-md px-2 bg-white",value:h,onChange:O=>{p(O.target.value),N(1),q(30)},children:[e.jsx("option",{value:"web",children:"Web"}),e.jsx("option",{value:"image",children:"Image"}),e.jsx("option",{value:"video",children:"Video"}),e.jsx("option",{value:"news",children:"News"})]})]}),e.jsxs("div",{className:"col-span-2",children:[e.jsx("div",{className:"text-xs text-slate-500 mb-1",children:"Dimension"}),e.jsx("select",{className:"w-full h-8 text-xs border border-slate-200 rounded-md px-2 bg-white",value:y||"",onChange:O=>{x(O.target.value),N(1),q(30)},children:yl.map(O=>e.jsx("option",{value:O.key||"",children:O.label},O.key||"all"))})]})]})}),e.jsx(xs,{className:"rounded-2xl hidden sm:block",children:e.jsxs(fs,{className:"pt-6 gap-4 grid md:grid-cols-5",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-slate-500 mb-1",children:"Site"}),e.jsx("select",{className:"w-full h-9 border border-slate-200 rounded-md px-2 bg-white",value:o,onChange:O=>{i(O.target.value),N(1)},children:a.map(O=>{const ne=O.site_url.replace(/^sc-domain:/,"");return e.jsx("option",{value:O.site_url,children:ne},O.site_url)})})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-slate-500 mb-1",children:"Date range"}),e.jsx(Sa,{value:l==="custom"?d:{from:se.start,to:se.end},onChange:O=>{N(1);const ne=jm(O);ne?c(ne):(c("custom"),m(O))},placeholder:"Select date range",className:"w-full",showClear:!1,presets:Jl()})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-slate-500 mb-1",children:"Time grouping"}),e.jsx("select",{className:"w-full h-9 border border-slate-200 rounded-md px-2 bg-white",value:u,onChange:O=>{g(O.target.value),N(1)},children:vm.map(O=>e.jsx("option",{value:O.value,children:O.label},O.value))})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-slate-500 mb-1",children:"Search type"}),e.jsxs("select",{className:"w-full h-9 border border-slate-200 rounded-md px-2 bg-white",value:h,onChange:O=>{p(O.target.value),N(1)},children:[e.jsx("option",{value:"web",children:"Web"}),e.jsx("option",{value:"image",children:"Image"}),e.jsx("option",{value:"video",children:"Video"}),e.jsx("option",{value:"news",children:"News"})]})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-slate-500 mb-1",children:"Dimension"}),e.jsx("select",{className:"w-full h-9 border border-slate-200 rounded-md px-2 bg-white",value:y||"",onChange:O=>{x(O.target.value),N(1)},children:yl.map(O=>e.jsx("option",{value:O.key||"",children:O.label},O.key||"all"))})]})]})}),e.jsxs(xs,{className:s?"rounded-xl":"rounded-2xl",children:[e.jsxs(Bs,{className:`${s?"p-3":"flex flex-row items-center justify-between"}`,children:[e.jsx(Xs,{className:s?"text-sm":"",children:y?yl.find(O=>O.key===y)?.label||"LIST":"ALL"}),e.jsxs("div",{className:"hidden sm:flex items-center gap-2",children:[e.jsx("button",{className:"px-4 py-2 text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 border border-blue-700 rounded-md transition-colors flex items-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed",onClick:me,disabled:$||!o,children:$?e.jsxs(e.Fragment,{children:[e.jsx(He,{className:"h-4 w-4 animate-spin"}),"Exporting all..."]}):e.jsx(e.Fragment,{children:"📥 Export all"})}),e.jsxs("div",{className:"relative",children:[e.jsxs("button",{className:"px-4 py-2 text-sm font-medium text-slate-700 bg-slate-100 hover:bg-slate-200 border border-slate-300 rounded-md transition-colors flex items-center gap-2",onClick:()=>L(!R),children:["📥 Export",e.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]}),R&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>L(!1)}),e.jsxs("div",{className:"absolute right-0 mt-2 w-24 bg-white border border-slate-200 rounded-md shadow-lg z-20 py-1",children:[e.jsx("button",{className:"w-full text-left px-4 py-2 text-sm text-slate-700 hover:bg-slate-50 flex items-center gap-2",onClick:()=>{Q(),L(!1)},children:".csv"}),e.jsx("button",{className:"w-full text-left px-4 py-2 text-sm text-slate-700 hover:bg-slate-50 flex items-center gap-2",onClick:()=>{le(),L(!1)},children:".xlsx"})]})]})]})]})]}),e.jsxs(fs,{className:s?"p-3":"",children:[e.jsxs("div",{className:"hidden sm:flex items-center gap-3 mb-4 pb-4 border-b border-slate-200",children:[e.jsxs("div",{className:"relative",children:[e.jsxs("button",{ref:A,onClick:()=>P(!V),className:`h-9 px-3 rounded-md border border-slate-200 bg-white text-sm flex items-center gap-2 hover:bg-slate-50 ${K.length>0?"border-slate-900 bg-slate-50":""}`,children:[e.jsx(eo,{className:"h-4 w-4"}),"Filter",K.length>0&&e.jsx("span",{className:"bg-slate-900 text-white text-xs px-1.5 py-0.5 rounded",children:K.length})]}),V&&e.jsx(lN,{fields:M,filters:K,onFiltersChange:O=>{X(O),N(1)},onClose:()=>P(!1)})]}),K.length>0&&e.jsx("div",{className:"flex flex-wrap items-center gap-2 flex-1",children:K.map((O,ne)=>e.jsxs(ls,{variant:"secondary",className:"text-xs flex items-center gap-1",children:[M.find(ge=>ge.value===O.field)?.label," ",O.operator,' "',O.value,'"',e.jsx("button",{onClick:()=>{const ge=K.filter((ze,Ke)=>Ke!==ne);X(ge),N(1)},className:"ml-1 hover:text-slate-900",children:"×"})]},ne))})]}),s&&e.jsxs("div",{className:"mb-2 text-xs text-slate-500",children:["Showing ",de.length," of ",B.length," total"]}),e.jsxs("div",{className:"hidden sm:flex items-center justify-between mb-4 pb-4 border-b border-slate-200 text-sm text-slate-600",children:[e.jsxs("div",{children:["Showing ",B.length>0?(E-1)*S+1:0," ","- ",Math.min(E*S,B.length)," of"," ",B.length," total"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{children:"Rows per page"}),e.jsx("select",{className:"h-8 px-2 rounded-md border border-slate-200 bg-white",value:S,onChange:O=>{k(Number(O.target.value)),N(1)},children:[25,50,100].map(O=>e.jsx("option",{value:O,children:O},O))}),e.jsx("button",{className:`rounded-md border border-slate-200 hover:bg-slate-50 ${s?"px-2 py-0.5 text-xs":"px-3 py-1"}`,onClick:()=>N(O=>
219Math.max(1,O-1)),disabled:E<=1,children:"Prev"}),e.jsx("button",{className:`rounded-md border border-slate-200 hover:bg-slate-50 disabled:opacity-50 disabled:cursor-not-allowed ${s?"px-2 py-0.5 text-xs":"px-3 py-1"}`,onClick:()=>N(O=>O+1),disabled:E*S>=B.length,children:"Next"})]})]}),e.jsx("div",{className:"overflow-x-auto",style:s?{maxHeight:"calc(100vh - 200px)"}:void 0,onScroll:s?ae:void 0,children:e.jsxs("table",{className:`min-w-full text-sm ${s?"text-xs":""}`,children:[e.jsx("thead",{className:`text-left text-slate-500 ${s?"sticky top-0 bg-white z-10":""}`,children:e.jsxs("tr",{children:[e.jsx("th",{className:`py-2 pr-4 text-center ${s?"py-1.5 pr-2":""}`,children:"Time"}),e.jsx("th",{className:`py-2 pr-4 ${s?"py-1.5 pr-2":""}`,children:y}),e.jsx("th",{className:`py-2 pr-4 text-center ${s?"py-1.5 pr-2":""}`,children:"Clicks"}),e.jsx("th",{className:`py-2 pr-4 text-center ${s?"py-1.5 pr-2":""}`,children:"Impressions"}),e.jsx("th",{className:`py-2 pr-4 text-center ${s?"py-1.5 pr-2":""}`,children:"CTR"}),e.jsx("th",{className:`py-2 pr-4 text-center ${s?"py-1.5 pr-2":""}`,children:"Position"})]})}),e.jsx("tbody",{className:"border-b border-gray-200",children:D?e.jsx("tr",{children:e.jsx("td",{colSpan:6,className:"py-8 text-center text-slate-500",children:"Loading data..."})}):(s?de:fe).length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:6,className:"py-8 text-center text-slate-500",children:"No data available"})}):(s?de:fe).map((O,ne)=>{const[ge,ze]=O.key?.split("|")||[],Ke=ze||ge||"—";return e.jsxs("tr",{className:"hover:bg-slate-50",children:[e.jsx("td",{className:`py-3 pr-4 text-center text-xs text-slate-500 ${s?"py-2 pr-2":""}`,children:ge}),e.jsx("td",{className:`py-3 pr-4 break-all ${s?"py-2 pr-2 max-w-[120px] truncate":""}`,children:Ke}),e.jsx("td",{className:`py-3 pr-4 text-right ${s?"py-2 pr-2":""}`,children:(O.clicks||0).toLocaleString()}),e.jsx("td",{className:`py-3 pr-4 text-right ${s?"py-2 pr-2":""}`,children:(O.impressions||0).toLocaleString()}),e.jsxs("td",{className:`py-3 pr-4 text-right ${s?"py-2 pr-2":""}`,children:[((O.ctr||0)*100).toFixed(2),"%"]}),e.jsx("td",{className:`py-3 pr-4 text-right ${s?"py-2 pr-2":""}`,children:(O.position||0).toFixed(2)})]},`${ne}-${O.key}`)})})]})}),e.jsxs("div",{className:"hidden sm:flex items-center justify-between mt-4 text-sm text-slate-600",children:[e.jsxs("div",{children:["Showing ",B.length>0?(E-1)*S+1:0," ","- ",Math.min(E*S,B.length)," of"," ",B.length," total"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{children:"Rows per page"}),e.jsx("select",{className:"h-8 px-2 rounded-md border border-slate-200 bg-white",value:S,onChange:O=>{k(Number(O.target.value)),N(1)},children:[25,50,100].map(O=>e.jsx("option",{value:O,children:O},O))}),e.jsx("button",{className:"px-3 py-1 rounded-md border border-slate-200 hover:bg-slate-50",onClick:()=>N(O=>Math.max(1,O-1)),disabled:E<=1,children:"Prev"}),e.jsx("button",{className:"px-3 py-1 rounded-md border border-slate-200 hover:bg-slate-50 disabled:opacity-50 disabled:cursor-not-allowed",onClick:()=>N(O=>O+1),disabled:E*S>=B.length,children:"Next"})]})]})]})]})]})}const Kn={async createReport(t){return await Je("/report/create",t)},async listReports(t){return await ot("/report/list",t)},async getReport(t){return await ot(`/report/${t}`)},async getTaskStatus(t){return await ot(`/report/task/${t}/status`)},async deleteReport(t){return await Ca(`/report/${t}`)}},km=t=>t.replace(/^sc-domain:/,""),pN=({value:t,onChange:s,placeholder:a="Select a site",disabled:n,className:o=""})=>{const[i,l]=v.useState([]),[c,d]=v.useState(!1),m=v.useRef(!1),h=v.useCallback(async()=>{if(!(m.current&&i.length>0))try{d(!0);const p=await Ro();l(p.items||[]),m.current=!0}catch(p){console.error("Failed to load GSC sites:",p),l([])}finally{d(!1)}},[i.length]);return e.jsxs(Pn,{value:t,onValueChange:p=>s?.(p),onOpenChange:p=>{p&&h()},children:[e.jsx(In,{disabled:n,className:o,children:e.jsx(Tc,{placeholder:c?"Loading sites...":a,children:t?km(t):void 0})}),e.jsx(Mn,{children:c?e.jsx("div",{className:"px-2 py-1.5 text-sm text-slate-500",children:"Loading..."}):i.length===0?e.jsx("div",{className:"px-2 py-1.5 text-sm text-slate-500",children:"No sites available"}):i.map(p=>e.jsx(js,{value:p.site_url,children:km(p.site_url)},p.site_url))})]})};async function gN(t,s=1e4){const a=Date.now();let n=null;for(;Date.now()-a<s;){const o=document.querySelector(t);if(o){const i=o.getBoundingClientRect(),l=i.width>0&&i.height>0,c=o.offsetParent!==null||o.style.display!=="none"||window.getComputedStyle(o).display!=="none";if(l&&c)return console.log(`✅ Element found and visible: ${t}`,{width:i.width,height:i.height,offsetWidth:o.offsetWidth,offsetHeight:o.offsetHeight,scrollWidth:o.scrollWidth,scrollHeight:o.scrollHeight}),o;n=o,console.log(`⏳ Element exists but not ready: ${t}`,{rect:{width:i.width,height:i.height},offsetParent:o.offsetParent!==null,display:window.getComputedStyle(o).display})}else console.log(`⏳ Element not found yet: ${t}`);await new Promise(i=>setTimeout(i,100))}return n&&console.warn(`⚠️ Timeout waiting for element visibility: ${t}`,{element:n,computedStyle:window.getComputedStyle(n)}),n}async function _m(t){const s=t.querySelectorAll("canvas");if(console.log(`📊 Found ${s.length} canvas element(s)`),s.length>0){await new Promise(n=>setTimeout(n,1e3));let a=0;for(;a<10;){if(Array.from(s).some(o=>{const i=o.getContext("2d");if(!i)return!1;try{const l=i.getImageData(0,0,Math.min(10,o.width),Math.min(10,o.height)),c=Array.from(l.data).some((d,m)=>m%4===3&&l.data[m]>0);return o.width>0&&o.height>0&&c}catch{return o.width>0&&o.height>0}}
219)){console.log("✅ Charts rendered successfully");break}console.log(`⏳ Waiting for charts to render... (retry ${a+1}/10)`),await new Promise(o=>setTimeout(o,300)),a++}}}function Cm(t){const s=t.textContent?.trim()||"",a=t.querySelectorAll("img"),n=t.querySelectorAll("canvas"),o=t.querySelectorAll("svg"),i=t.children;let l=!1;n.forEach(m=>{try{const h=m.getContext("2d");if(h&&m.width>0&&m.height>0){const p=h.getImageData(0,0,Math.min(100,m.width),Math.min(100,m.height));Array.from(p.data).some((b,y)=>y%4===3&&p.data[y]>0)&&(l=!0)}}catch{m.width>0&&m.height>0&&(l=!0)}});const c={hasText:s.length>0,hasImages:a.length>0,hasCharts:n.length>0&&l,hasChildren:i.length>0,textContent:s.substring(0,100)+(s.length>100?"...":""),imageCount:a.length,canvasCount:n.length,svgCount:o.length};return{hasContent:c.hasText||c.hasImages||c.hasCharts||c.hasChildren||t.offsetHeight>100,details:c}}async function fN(t,s={}){const{filename:a="report.pdf",waitForRender:n=2e3,onProgress:o,reportMetadata:i}=s,l=10,c=340,d=c+l*2,m=297,h=new qh({orientation:"landscape",unit:"mm",format:[d,m]}),p=.264583,f=t.length;if(o&&o({currentStep:0,totalSteps:f,currentStepName:"Initializing PDF exp
219ort..."}),i){let b=60;if(i.title){h.setFontSize(24),h.setFont("helvetica","bold");const x=h.splitTextToSize(i.title,c);h.text(x,l,b,{maxWidth:c,align:"left"}),b+=x.length*10+10}if(i.siteUrl){h.setFontSize(12),h.setFont("helvetica","normal");const x=i.siteUrl.replace(/^https?:\/\//,"").replace("sc-domain:","");h.text(`Site: ${x}`,l,b),b+=12}i.periodStartDate&&i.periodEndDate&&(h.setFontSize(12),h.setFont("helvetica","normal"),h.text(`Period: ${i.periodStartDate} - ${i.periodEndDate}`,l,b),b+=12);const y=new Date().toLocaleDateString("en-US",{year:"numeric",month:"long",day:"numeric"});h.setFontSize(10),h.setFont("helvetica","italic"),h.setTextColor(128,128,128),h.text(`Generated: ${y}`,l,b),h.setTextColor(0,0,0)}for(let b=0;b<t.length;b++){const y=t[b];console.log(`
220📄 ===== Exporting tab ${b+1}/${t.length}: ${y.title} =====`),o&&o({currentStep:b,totalSteps:f,currentStepName:`Preparing ${y.title}...`}),s.onTabSwitch&&y.tabValue&&(console.log(`🔄 Switching to tab: ${y.tabValue}`),o&&o({currentStep:b,totalSteps:f,currentStepName:`Switching to ${y.title}...`}),await s.onTabSwitch(y.tabValue),await new Promise(g=>setTimeout(g,800))),o&&o({currentStep:b,totalSteps:f,currentStepName:`Loading ${y.title} content...`});const x=await gN(y.contentSelector,1e4);if(!x){console.error(`❌ Element not found for selector: ${y.contentSelector}`),console.log("Available elements with data-export-id:",Array.from(document.querySelectorAll("[data-export-id]")).map(g=>({id:g.getAttribute("data-export-id"),visible:g.offsetHeight>0})));continue}const u=Cm(x);if(console.log(`📋 Content check for ${y.title}:`,u.details),!u.hasContent){console.error("❌ Element has no content! Details:",u.details),console.log("⏳ Waiting longer for content to render..."),await new Promise(w=>setTimeout(w,2e3));const g=Cm(x);if(console.log("📋 Content check after waiting:",g.details),!g.hasContent){console.error(`❌ Still no content after waiting. Skipping ${y.title}`);continue}}await _m(x),await new Promise(g=>setTimeout(g,n));try{const g=window.getComputedStyle(x),w={position:x.style.position,visibility:x.style.visibility,display:x.style.display,overflow:x.style.overflow,transform:x.style.transform,maxHeight:x.style.maxHeight,height:x.style.height,opacity:x.style.opacity};console.log("📐 Original element styles:",{computed:{display:g.display,visibility:g.visibility,position:g.position,overflow:g.overflow},inline:w}),x.style.position="relative",x.style.visibility="visible",x.style.display="block",x.style.overflow="visible",x.style.transform="none",x.style.maxHeight="none",x.style.height="auto",x.style.opacity="1",x.offsetHeight,x.scrollIntoView({behavior:"instant",block:"start"}),await new Promise(I=>setTimeout(I,500)),await _m(x),await new Promise(I=>setTimeout(I,500));const _=x.scrollWidth||x.offsetWidth,E=x.scrollHeight||x.offsetHeight;if(console.log("📸 Capturing element at natural size:",{title:y.title,dimensions:`${_}x${E}px`}),o&&o({currentStep:b,totalSteps:f,currentStepName:`Capturing ${y.title}...`}),_===0||E===0){console.error("❌ Element has zero dimensions!"),Object.assign(x.style,w);continue}const N=await Yh(x,{backgroundColor:"#ffffff",pixelRatio:1,cacheBust:!0,skipFonts:!0,filter:I=>{if(I.tagName==="LINK"){const j=I.href;if(j&&!j.startsWith(window.location.origin))return!1}return!0}}),S=new Image;await new Promise((I,j)=>{S.onload=()=>I(),S.onerror=j,S.src=N});const k=document.createElement("canvas");k.width=S.width,k.height=S.height;const D=k.getContext("2d");if(D&&D.drawImage(S,0,0),console.log(`✅ Image captured: ${k.width}x${k.height}`),Object.assign(x.style,w),!k||k.width===0||k.height===0){console.error(`❌ Empty canvas for ${y.title}`,{canvasWidth:k?.width,canvasHeight:k?.height});continue}console.log(`✅ Canvas created successfully: ${k.width}x${k.height}`),o&&o({currentStep:b,totalSteps:f,currentStepName:`Adding ${y.title} to PDF...`});const F=k.toDataURL("image/png",.95),R=k.width,L=k.height,$=R*p,H=L*p,K=c/$,X=c,V=H*K;console.log("📐 Image scaling:",{imgSizePx:`${R}x${L}`,imgSizeMm:`${$.toFixed(2)}x${H.toFixed(2)}`,targetWidthMm:c.toFixed(2),scaledSizeMm:`${X.toFixed(2)}x${V.toFixed(2)}`,widthRatio:K.toFixed(4)});let P=l,A=0;(i||b>0)&&(h.addPage(),P=l),h.setFontSize(16),h.setFont("helvetica","bold"),h.text(y.title,l,P),P+=10;let C=0;for(;A<L;){C++,P>l+5&&A>0&&(h.addPage(),P=l,h.setFontSize(16),h.setFont("helvetica","bold"),h.text(y.title,l,P),P+=10);const I=L-A,j=m-P-l,q=V/L,M=Math.min(I,j/q),Z=Math.floor(M);if(Z<=0){console.warn("⚠️ No space left on page");break}const B=document.createElement("canvas");B.width=R,B.height=Z;const ae=B.getContext("2d");if(ae){const de=new Image;de.src=F,await new Promise(z=>{de.onload=()=>{try{ae.drawImage(de,0,A,R,Z,0,0,R,Z),z(void 0)}catch(U){console.error("❌ Error drawing image:",U),z(void 0)}},de.onerror=U=>{console.error("❌ Error loading image:",U),z(void 0)}});const fe=B.toDataURL("image/png",.95),se=Z*q;h.addImage(fe,"PNG",l,P,X,se),console.log(`📄 Added page section ${C}:`,{sourceY:A,sourceHeightToUse:Z,currentY:P,sectionHeightMm:se.toFixed(2),mmPerPixel:q.toFixed(6)}),P+=se,A+=Z}else{console.error("❌ Failed to get canvas context");break}}console.log(`✅ Tab "${y.title}" exported successfully (${C} page(s))`),o&&o({currentStep:b+1,totalSteps:f,currentStepName:`Completed ${y.title}`})}catch(g){console.error(`❌ Error exporting tab "${y.title}":`,g),console.error(g),o&&o({currentStep:b+1,totalSteps:f,currentStepName:`Error exporting ${y.title}`})}}o&&o({currentStep:f,totalSteps:f,currentStepName:"Finalizing PDF..."}),console.log(`
221💾 Saving PDF: ${a}`),h.save(a),console.log("✅ PDF export completed!")}function yN({visible:t,currentStep:s,totalSteps:a,currentStepName:n,zIndex:o=999}){return t?e.jsx("div",{className:"fixed inset-0 flex items-center justify-center bg-slate-900/60 backdrop-blur-sm transition-opacity duration-200",style:{zIndex:o,pointerEvents:"auto"},onClick:i=>{i.preventDefault(),i.stopPropagation()},onMouseDown:i=>{i.preventDefault(),i.stopPropagation()},onTouchStart:i=>{i.preventDefault(),i.stopPropagation()},onKeyDown:i=>{i.preventDefault(),i.stopPropagation()},children:e.jsxs("div",{className:"flex flex-col items-center gap-6 bg-white rounded-xl shadow-2xl px-10 py-8 border border-slate-200 max-w-md w-full mx-4",children:[e.jsxs("div",{className:"relative h-16 w-16",children:[e.jsx("div",{className:"h-16 w-16 border-4 border-slate-200 border-t-slate-900 rounded-full animate-spin"}),e.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:e.jsx(is,{className:"h-6 w-6 text-slate-900"})})]}),e.jsxs("div",{className:"text-center",children:[e.jsx("h3",{className:"text-lg font-semibold text-slate-900 mb-1",children:"Exporting PDF"}),n&&e.jsx("p",{className:"text-sm text-slate-600 mt-2",children:n})]}),e.jsx("div",{className:"w-full",children:e.jsx(ji,{value:s,max:a,showPercentage:!0,showValue:!0,valueLabel:`Step ${s} of ${a}`})}),e.jsx("div",{className:"text-xs text-slate-500 text-center",children:"Please wait while we generate your PDF..."})]})}):null}function jh(){const[t,s]=r.useState(()=>typeof window<"u"&&window.innerWidth<768);return r.useEffect(()=>{const a=()=>s(window.innerWidth<768);return window.addEventListener("resize",a),()=>window.removeEventListener("resize",a)},[]),t}function bN({onShowToast:t}){const s=jh(),[a,n]=r.useState(null),[o,i]=r.useState([]),[l,c]=r.useState(!1),[d,m]=r.useState(0),[h,p]=r.useState(1),[f]=r.useState(20),[b,y]=r.useState(!1),[x,u]=r.useState(20),g=20;r.useEffect(()=>{const ye=Ie=>{y(Ie.detail??!b)},Te=()=>{k(!0)};return window.addEventListener("mobile-filter-toggle",ye),window.addEventListener("mobile-add-click",Te),()=>{window.removeEventListener("mobile-filter-toggle",ye),window.removeEventListener("mobile-add-click",Te)}},[b]);const[w,_]=r.useState(""),[E,N]=r.useState("all"),[S,k]=r.useState(!1),[D,F]=r.useState(!1),[R,L]=r.useState([]),[$,H]=r.useState(!1),[K,X]=r.useState({site_url:"",name:"",search_type:"web"}),[V,P]=r.useState({}),[A,C]=r.useState([]),I=r.useRef(new Set),[j,q]=r.useState(new Set),[T,M]=r.useState(!1),{confirm:Z}=ia(),B=r.useCallback(ye=>
221{t?.({title:ye.title,description:ye.description||""})},[t]),ae=ta({enabled:S,scenario:"data_report_create",params:{}});r.useRef(null);const de=r.useCallback(async()=>{try{c(!0);const ye=await Kn.listReports({site_url:E==="all"?void 0:E,page:h,page_size:f});let Te=ye.items;if(w.trim()){const Ie=w.toLowerCase().trim();Te=ye.items.filter(Oe=>Oe.name?.toLowerCase().includes(Ie)||Oe.site_url?.toLowerCase().includes(Ie))}i(Te),m(w.trim()?Te.length:ye.total),q(new Set)}catch(ye){t?.({title:"Error",description:ye.message||"Failed to load reports"})}finally{c(!1)}},[E,w,h,f,t]);r.useEffect(()=>{p(1)},[E,w]),r.useEffect(()=>{de()},[de]),r.useEffect(()=>{fe()},[]);const fe=async()=>{try{H(!0);const ye=await Ro();L(ye.items||[])}catch(ye){t?.({title:"Error",description:ye.message||"Failed to load GSC sites"})}finally{H(!1)}},se=(ye,Te)=>{if(!ye||!Te)return{period_type:"custom"};const Ie=new Date(ye),Oe=new Date(Te),J=Math.abs(Oe.getTime()-Ie.getTime()),re=Math.ceil(J/(1e3*60*60*24))+1;if(re===1)return{period_type:"day",period_value:ye};if(re===7){const Se=Ie.getDay(),je=Oe.getDay();if((Se===0?7:Se)===1&&(je===0?7:je)===7){const Me=z(Ie);return{period_type:"week",period_value:`${Ie.getFullYear()}-W${Me.toString().padStart(2,"0")}`}}}if(Ie.getDate()===1&&Oe.getDate()===new Date(Oe.getFullYear(),Oe.getMonth()+1,0).getDate()&&Ie.getMonth()===Oe.getMonth()&&Ie.getFullYear()===Oe.getFullYear()){const Se=Ie.getFullYear(),je=(Ie.getMonth()+1).toString().padStart(2,"0");return{period_type:"month",period_value:`${Se}-${je}`}}return{period_type:"custom"}},z=ye=>{const Te=new Date(Date.UTC(ye.getFullYear(),ye.getMonth(),ye.getDate())),Ie=Te.getUTCDay()||7;Te.setUTCDate(Te.getUTCDate()+4-Ie);const Oe=new Date(Date.UTC(Te.getUTCFullYear(),0,1));return Math.ceil(((Te.getTime()-Oe.getTime())/864e5+1)/7)},U=()=>{const{from:ye,to:Te}=V;if(!ye||!Te)return"";const Ie=se(ye,Te),{period_type:Oe,period_value:J}=Ie;if(Oe==="day"&&J)return`Daily Report - ${J}`;if(Oe==="week"&&J)return`Weekly Report - ${J}`;if(Oe==="month"&&J){const[re,Se]=J.split("-");return`Monthly Report - ${["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"][parseInt(Se)-1]} ${re}`}else if(Oe==="custom"&&ye&&Te)return`Custom Report - ${ye} to ${Te}`;return""},Q=async()=>{try{const{site_url:ye,name:Te,search_type:Ie}=K,{from:Oe,to:J}=V;
221if(!ye){t?.({title:"Error",description:"Site URL is required"});return}if(!Oe||!J){t?.({title:"Error",description:"Date range is required"});return}if(ae.estimating||!ae.estimatedRange){B({title:"Estimating credits",description:"Please wait a moment and try again."});return}const{validateCreditBalance:re}=await Bt(async()=>{const{validateCreditBalance:Be}=await Promise.resolve().then(()=>ua);return{validateCreditBalance:Be}},void 0);if(!await re({estimatedRange:ae.estimatedRange,requiredMinimumBalance:ae.requiredMinimumBalance,toast:B}))return;F(!0);const je=se(Oe,J),{period_type:he,period_value:Re}=je,Me={site_url:ye,period_type:he,search_type:Ie};he==="custom"?(Me.start_date=Oe,Me.end_date=J):Me.period_value=Re,Te?Me.name=Te:Me.name=U();const Ze=await Kn.createReport(Me);C(Be=>[...Be,{taskId:Ze.task_id,reportId:Ze.report_id,reportName:Me.name}]),t?.({title:"Success",description:"Report creation started successfully"}),X({site_url:"",name:"",search_type:"web"}),P({}),k(!1)}catch(ye){t?.({title:"Error",description:ye.message||"Failed to create report"})}finally{F(!1)}},me=()=>{_(""),N("all")},le=r.useCallback((ye,Te)=>{I.current.has(ye)||(I.current.add(ye),setTimeout(()=>{C(Ie=>Ie.filter(Oe=>Oe.taskId!==ye)),I.current.delete(ye)},3e3),de())},[de]),O=ye=>{C(Te=>Te.filter(Ie=>Ie.taskId!==ye))},ne=ye=>{q(Te=>{const Ie=new Set(Te);return Ie.has(ye)?Ie.delete(ye):Ie.add(ye),Ie})},ge=()=>{j.size===o.length?q(new Set):q(new Set(o.map(ye=>ye.id)))},ze=async()=>{if(!(j.size===0||!await Z({title:"Delete Reports",message:`Are you sure you want to delete ${j.size} report(s)? This action cannot be undone.`,confirmText:"Delete",cancelText:"Cancel",variant:"danger"})))try{M(!0),await Promise.all(Array.from(j).map(Te=>Kn.deleteReport(Te))),t?.({title:"Success",description:`Successfully deleted ${j.size} report(s)`}),q(new Set),de()}catch(Te){t?.({title:"Error",description:Te.message||"Failed to delete reports"})}finally{M(!1)}},Ke=async ye=>{try{const{from:Te,to:Ie}={from:ye.period_start_date,to:ye.period_end_date},Oe=se(Te,Ie),{period_type:J,period_value:re}=Oe,Se={site_url:ye.site_url,period_type:J,search_type:"web"};J==="custom"?(Se.start_date=Te,Se.end_date=Ie):Se.period_value=re,ye.name&&(Se.name=ye.name),await Kn.deleteReport(ye.id),i(he=>he.filter(Re=>Re.id!==ye.id));const je=await Kn.createReport(Se);C(he=>[...he,{taskId:je.task_id,reportId:je.report_id,reportName:Se.name||"Report"}]),t?.({title:"Success",description:"Report regeneration started successfully"})}catch(Te){de(),t?.({title:"Error",description:Te.message||"Failed to retry report"})}},ie=ye=>ye.replace(/^sc-domain:/,""),ve=ye=>ye?new Date(ye).toLocaleDateString():"N/A",we=ye=>{const Ie={completed:{label:"Completed",className:"bg-green-50 text-green-700 border-green-200"},processing:{label:"Processing",className:"bg-blue-50 text-blue-700 border-blue-200"},failed:{label:"Failed",className:"bg-red-50 text-red-700 border-red-200"}}[ye]||{label:ye,className:"bg-gray-50 text-gray-700 border-gray-200"};return e.jsx("span",{className:`px-2 py-0.5 rounded text-[10px] font-medium border ${Ie.className}`,children:Ie.label})},Pe=r.useMemo(()=>o.slice(0,x),[o,x]),Ae=r.useCallback(ye=>{const Te=ye.target,{scrollTop:Ie,scrollHeight:Oe,clientHeight:J}=Te;Oe-Ie-J<100&&u(re=>Math.min(re+g,o.length))},[o.length]);return a?e.jsx(wN,{reportId:a,onBack:()=>n(null),onShowToast:t}):e.jsxs("div",{className:"flex-1 overflow-y-auto bg-gray-50/50",onScroll:s?Ae:void 0,style:s?{maxHeight:"calc(100vh - 120px)"}:void 0,children:[e.jsxs("div",{className:`max-w-6xl mx-auto ${s?"px-3 py-3":"px-6 py-4"}`,children:[e.jsxs("div",{className:"hidden sm:flex mb-4 items-start justify-between",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-semibold text-gray-900",children:"SEO Reports"}),e.jsx("p",{className:"text-[12px] text-gray-500 mt-1",children:"Manage and view your SEO performance reports"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[j.size>0&&e.jsx("button",{onClick:ze,disabled:T,className:"px-3 py-1.5 rounded-lg border border-red-200 bg-red-50 text-[11px] font-medium text-red-600 hover:bg-red-100 transition-colors flex items-center gap-1.5 disabled:opacity-50 disabled:cursor-not-allowed",children:T?e.jsxs(e.Fragment,{children:[e.jsx(He,{size:12,className:"animate-spin"}),"Deleting..."]}):e.jsxs(e.Fragment,{children:[e.jsx(es,{size:12}),"Delete (",j.size,")"]})}),e.jsxs("button",{onClick:()=>k(!0),className:"px-3 py-1.5 rounded-lg border border-gray-200 text-[11px] font-medium text-gray-600 hover:bg-gray-50 transition-colors flex items-center gap-1.5",children:[e.jsx($t,{size:12}),"Create Report"]})]})]}),s&&e.jsxs("div",{className:"mb-3 flex items-center justify-between",children:[e.jsxs("span",{className:"text-xs text-gray-500",children:[d," reports"]}),j.size>0&&e.jsx("button",{onClick:ze,disabled:T,className:"px-2 py-1 rounded border border-red-200 bg-red-50 text-[10px] font-medium text-red-600 flex items-center gap-1",children:T?e.jsx(He,{size:10,
221className:"animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(es,{size:10}),"Delete (",j.size,")"]})})]}),s&&b&&e.jsx("div",{className:"bg-white border border-gray-100 rounded-xl p-3 mb-3",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-[10px] font-medium text-gray-600 block mb-1",children:"Search"}),e.jsx("input",{type:"text",placeholder:"Search reports...",value:w,onChange:ye=>_(ye.target.value),className:"w-full px-3 py-1.5 text-[11px] border border-gray-200 rounded-lg bg-white focus:outline-none focus:border-gray-300 text-gray-700 placeholder-gray-400"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-[10px] font-medium text-gray-600 block mb-1",children:"Site URL"}),e.jsxs("select",{value:E,onChange:ye=>N(ye.target.value),className:"w-full px-3 py-1.5 text-[11px] border border-gray-200 rounded-lg bg-white focus:outline-none focus:border-gray-300 text-gray-700",children:[e.jsx("option",{value:"all",children:"All sites"}),R.map(ye=>e.jsx("option",{value:ye.site_url,children:ie(ye.site_url)},ye.site_url))]})]}),e.jsx("button",{onClick:me,className:"w-full px-3 py-1.5 rounded-lg border border-gray-200 text-[10px] font-medium text-gray-600 hover:bg-gray-50 transition-colors",children:"Clear Filters"})]})}),e.jsxs("div",{className:"hidden sm:block bg-white border border-gray-100 rounded-xl p-4 mb-4",children:[e.jsx("h3",{className:"text-[12px] font-semibold text-gray-800 mb-3",children:"Filters"}),e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-[10px] font-medium text-gray-600 block mb-1.5",children:"Search"}),e.jsx("input",{type:"text",placeholder:"Search by report name or site URL",value:w,onChange:ye=>_(ye.target.value),className:"w-full px-3 py-1.5 text-[11px] border border-gray-200 rounded-lg bg-white focus:outline-none focus:border-gray-300 text-gray-700 placeholder-gray-400"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-[10px] font-medium text-gray-600 block mb-1.5",children:"Site URL"}),e.jsxs("select",{value:E,onChange:ye=>N(ye.target.value),className:"w-full px-3 py-1.5 text-[11px] border border-gray-200 rounded-lg bg-white focus:outline-none focus:border-gray-300 text-gray-700",children:[e.jsx("option",{value:"all",children:"All sites"}),R.map(ye=>e.jsx("option",{value:ye.site_url,children:ie(ye.site_url)},ye.site_url))]})]}),e.jsx("div",{className:"flex items-end",children:e.jsx("button",{onClick:me,className:"px-3 py-1.5 rounded-lg border border-gray-200 text-[11px] font-medium text-gray-600 hover:bg-gray-50 transition-colors",children:"Clear Filters"})})]})]}),e.jsxs("div",{className:`bg-white border border-gray-100 overflow-hidden ${s?"rounded-lg":"rounded-xl"}`,children:[e.jsx("div",{className:"hidden sm:block px-4 py-3 border-b border-gray-50",children:e.jsxs("h3",{className:"text-[12px] font-semibold text-gray-800",children:["Reports (",d,")"]})}),e.jsx("div",{className:"divide-y divide-gray-50",children:l?e.jsxs("div",{className:"px-4 py-8 text-center text-[11px] text-gray-400 flex items-center justify-center gap-2",children:[e.jsx(He,{className:"h-4 w-4 animate-spin"}),"Loading reports..."]}):(s?Pe:o).length===0?e.jsx("div",{className:"px-4 py-8 text-center text-[11px] text-gray-400",children:"No reports found"}):s?e.jsx(e.Fragment,{children:Pe.map(ye=>e.jsx("div",{className:"p-3 hover:bg-gray-50/50 transition-colors",onClick:()=>{ye.status==="completed"&&n(ye.id)},children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("input",{type:"checkbox",checked:j.has(ye.id),onChange:Te=>{Te.stopPropagation(),ne(ye.id)},onClick:Te=>Te.stopPropagation(),className:"h-3.5 w-3.5 rounded border-gray-300 text-gray-600 mt-0.5"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"text-[11px] font-medium text-gray-700 truncate",children:ye.name||"Unnamed Report"}),we(ye.status)]}),e.jsx("div",{className:"text-[10px] text-gray-500 mt-0.5",children:ie(ye.site_url)}),e.jsxs("div",{className:"text-[10px] text-gray-400 mt-0.5",children:[ve(ye.period_start_date)," - ",ve(ye.period_end_date)]})]}),e.jsx(Qn,{size:14,className:"text-gray-400 shrink-0"})]})},ye.id))}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"px-4 py-2.5 bg-gray-50/50 grid grid-cols-12 gap-4 text-[10px] font-medium text-gray-500 uppercase tracking-wide items-center",children:[e.jsx("div",{className:"col-span-1 flex items-center",children:e.jsx("input",{type:"checkbox",checked:o.length>0&&j.size===o.length,onChange:ge,className:"h-3.5 w-3.5 rounded border-gray-300 text-gray-600 focus:ring-gray-500 focus:ring-offset-0 cursor-pointer"})}),e.jsx("div",{className:"col-span-3",children:"Name"}),e.jsx("div",{className:"col-span-2",children:"Site URL"}),e.jsx("div",{className:"col-span-2",children:"Date Range"}),e.jsx("div",{className:"col-span-1",children:"Created At"}),e.jsx("div",{className:"col-span-1",children:"Status"}),e.jsx("div",{className:"col-span-2",children:"Actions"})]}),o.map(ye=>e.jsxs("div",{className:"px-4 py-3 hover:bg-gray-50/50 transition-colors grid grid-cols-12 gap-4 items-center",children:[e.jsx("div",{className:"col-span-1 flex items-center",children:e.jsx("input",{type:"checkbox",checked:j.has(ye.id),onChange:()=>ne(ye.id),className:"h-3.5 w-3.5 rounded border-gray-300 text-gray-600 focus:ring-gray-500 focus:ring-offset-0 cursor-pointer"})}),e.jsx("div",{className:"col-span-3",children:e.jsx("span",{className:"text-[11px] font-medium text-gray-700",children:ye.name||"Unnamed Report"})}),e.jsx("div",{className:"col-span-2",children:e.jsx("span",{className:"text-[11px] text-gray-600",children:ie(ye.site_url)})}),e.jsx("div",{className:"col-span-2",children:e.jsxs("span",{className:"text-[11px] text-gray-600",children:[ve(ye.period_start_date)," -"," ",ve(ye.period_end_date)]})}),e.jsx("div",{className:"col-span-1",children:e.jsx("span",{className:"text-[11px] text-gray-600",children:ve(ye.created_at)})}),e.jsx("div",{className:"col-span-1",children:we(ye.status)}),e.jsx("div",{className:"col-span-2",children:ye.status==="failed"?e.jsxs("button",{onClick:()=>Ke(ye),className:"text-[11px] font-medium text-blue-600 hover:text-blue-800 transition-colors flex items-center gap-1",children:[e.jsx(kt,{size:12}),"Retry"]}):e.jsxs("button",{onClick:()=>n(ye.id),disabled:ye.status!=="completed",className:`text-[11px] font-medium transition-colors flex items-center gap-1 ${ye.status==="completed"?"text-gray-600 hover:text-gray-800":"text-gray-300 cursor-not-allowed"}`,children:["View",e.jsx(Qn,{size:12})]})})]},ye.id))]})}),!s&&d>f&&e.jsxs("div",{className:"px-4 py-3 border-t border-gray-50 flex items-center justify-between",children:[e.jsxs("div",{className:"text-[11px] text-gray-500",children:["Showing ",(h-1)*f+1," to"," ",Math.min(h*f,d)," of ",d," reports"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("button",{onClick:()=>p(h-1),disabled:h===1,className:"px-3 py-1.5 text-[11px] font-medium border border-gray-200 rounded-lg disabled:opacity-50 disabled:cursor-not-allowed hover:bg-gray-50 transition-colors",children:"Previous"}),e.jsx("button",{onClick:()=>p(h+1),disabled:h*f>=d,className:"px-3 py-1.5 text-[11px] font-medium border border-gray-200 rounded-lg disabled:opacity-50 disabled:cursor-not-allowed hover:bg-gray-50 transition-colors",children:"Next"})]})]})]}),S&&e.jsx("div",{className:"fixed inset-0 bg-black/20 flex items-center justify-center z-50",onClick:()=>k(!1),children:e.jsxs("div",{className:"bg-white border border-gray-100 rounded-xl p-5 max-w-md w-full mx-4",onClick:ye=>ye.stopPropagation(),children:[e.jsx("h3",{className:"text-[13px] font-semibold text-gray-800 mb
221-4",children:"Create New Report"}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsxs("label",{className:"text-[10px] font-medium text-gray-600 block mb-1.5",children:["Site URL ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(pN,{value:K.site_url,onChange:ye=>X(Te=>({...Te,site_url:ye}))})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"text-[10px] font-medium text-gray-600 block mb-1.5",children:["Date Range ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(Sa,{value:V,onChange:P,placeholder:"Select date range",showClear:!1})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"text-[10px] font-medium text-gray-600 block mb-1.5",children:["Report Name"," ",e.jsx("span",{className:"text-gray-400",children:"(optional)"})]}),e.jsx("input",{type:"text",placeholder:"Auto-generated if empty",value:K.name,onChange:ye=>X(Te=>({...Te,name:ye.target.value})),className:"w-full px-3 py-2 text-[11px] border border-gray-200 rounded-lg bg-white focus:outline-none focus:border-gray-300 text-gray-700 placeholder-gray-400"})]}),e.jsxs("div",{className:"flex items-start gap-2 p-3 bg-amber-50 border border-amber-200 rounded-lg",children:[e.jsx(vs,{className:"h-4 w-4 text-amber-600 mt-0.5 shrink-0"}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[11px] font-medium text-amber-900",children:"This action will consume credits"}),e.jsx("div",{className:"text-[11px] text-amber-800",children:ae.estimating?"Estimating...":ae.estimatedRange?ae.estimatedRange.min===ae.estimatedRange.max?`Estimated cost: ${ae.estimatedRange.max} credits`:`Estimated cost: ${ae.estimatedRange.min}-${ae.estimatedRange.max} credits`:"Estimate unavailable"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-2",children:[e.jsx("button",{onClick:()=>{k(!1),X({site_url:"",name:"",search_type:"web"}),P({})},className:"flex-1 px-3 py-2 rounded-lg border border-gray-200 text-[11px] font-medium text-gray-600 hover:bg-gray-50 transition-colors",children:"Cancel"}),e.jsxs("button",{onClick:Q,disabled:D||ae.estimating,className:"flex-1 px-3 py-2 rounded-lg border border-gray-200 text-[11px] font-medium text-gray-600 hover:bg-gray-50 transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-1.5",children:[D&&e.jsx(He,{className:"h-3 w-3 animate-spin"}),D?"Creating...":ae.estimating?"Estimating...":"Create Report"]})]})]})]})})]}),A.length>0&&e.jsx("div",{className:"fixed right-4 top-20 z-50 flex flex-col gap-3 max-h-[calc(100vh-6rem)] overflow-y-auto",children:A.map(ye=>e.jsx(jN,{task:ye,onComplete:le,onDismiss:O},ye.taskId))})]})}function wN({reportId:t,onBack:s,onShowToast:a}){const n=jh(),[o,i]=r.useState(null),[l,c]=r.useState(!0),[d,m]=r.useState("summary"),[h,p]=r.useState(!1),[f,b]=r.useState(null);r.useEffect(()=>{y()},[t]);const y=async()=>{try{c(!0);const P=await Kn.getReport(t);i(P)}catch(P){a?.({title:"Error",description:P.message||"Failed to load report"}),s()}finally{c(!1)}},x=async()=>{if(o)try{p(!0),b({currentStep:0,totalSteps:5,currentStepName:"Initializing..."});const P=`${o.name||"SEO_Report"}
221_${o.period_start_date}_${o.period_end_date}.pdf`.replace(/[^a-z0-9_\-.]/gi,"_"),A=[{title:"Executive Summary",contentSelector:'[data-export-id="executive_summary"]',tabValue:"summary"},{title:"Top Queries",contentSelector:'[data-export-id="top_queries"]',tabValue:"queries"},{title:"Top Pages",contentSelector:'[data-export-id="top_pages"]',tabValue:"pages"},{title:"Geographic & Device",contentSelector:'[data-export-id="geographic_device"]',tabValue:"geographic"},{title:"Coverage & Sitemap",contentSelector:'[data-export-id="coverage_sitemap"]',tabValue:"coverage"}],C=d;await fN(A,{filename:P,waitForRender:2e3,reportMetadata:{title:o.name||"SEO Report",siteUrl:o.site_url,periodStartDate:o.period_start_date,periodEndDate:o.period_end_date},onProgress:I=>{b(I)},onTabSwitch:async I=>new Promise(j=>{m(I),requestAnimationFrame(()=>{requestAnimationFrame(async()=>{await new Promise(M=>setTimeout(M,300));let q=0;const T=20;for(;q<T;){const M=document.querySelector(`[data-export-id="${I}"]`);if(M){const Z=M.getBoundingClientRect();if(Z.width>0&&Z.height>0){await new Promise(ae=>setTimeout(ae,500)),j();return}}await new Promise(Z=>setTimeout(Z,100)),q++}j()})})})}),m(C),setTimeout(()=>{b(null)}
221,500),a?.({title:"Success",description:"PDF exported successfully"})}catch(P){console.error("Export PDF error:",P),b(null),a?.({title:"Error",description:P.message||"Failed to export PDF"})}finally{p(!1)}};if(l)return e.jsx("div",{className:"flex-1 overflow-y-auto bg-gray-50/50 flex items-center justify-center",children:e.jsx(He,{className:"h-8 w-8 animate-spin text-gray-400"})});if(!o)return e.jsx("div",{className:"flex-1 overflow-y-auto bg-gray-50/50 flex items-center justify-center",children:e.jsx("div",{className:"text-center text-gray-500",children:"Report not found"})});const u=({label:P,value:A,change:C,icon:I})=>e.jsxs("div",{className:"bg-white border border-gray-100 rounded-xl p-3",children:[e.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[e.jsx("span",{className:"text-[10px] text-gray-400 uppercase tracking-wide",children:P}),I&&e.jsx(I,{size:14,className:"text-gray-300"})]}),e.jsx("div",{className:"text-[20px] font-semibold text-gray-800",children:A}),C&&e.jsx("div",{className:"text-[10px] text-gray-400 mt-0.5",children:C})]}),g=o.pages.executive_summary?.data,w=o.pages.executive_summary?.insights,_=g?.time_series||[],E=o.pages.top_queries?.data?.queries||[],N=o.pages.top_queries?.insights,S=o.pages.top_pages?.data?.pages||[],k=o.pages.top_pages?.insights,D=o.pages.geographic?.data?.countries||[],F=o.pages.geographic?.insights,R=o.pages.device?.data?.devices||{},L=o.pages.device?.insights,$=o.pages.index_coverage?.data,H=o.pages.index_coverage?.insights,K=o.pages.sitemap?.data,X=o.pages.sitemap?.insights,V=P=>P>=1e6?`${(P/1e6).toFixed(1)}M`:P>=1e3?`${(P/1e3).toFixed(1)}K`:P.toFixed(0);return e.jsxs("div",{className:"flex-1 overflow-y-auto bg-gray-50/50 relative",children:[e.jsx(yN,{visible:h&&f!==null,currentStep:f?.currentStep||0,totalSteps:f?.totalSteps||5,currentStepName:f?.currentStepName||"Exporting..."}),e.jsxs("div",{className:`max-w-7xl mx-auto ${n?"px-3 py-3":"px-6 py-4"}`,children:[e.jsxs("div",{className:`mb-4 ${n?"":"flex items-center justify-between"}`,children:[e.jsxs("div",{className:n?"":"flex items-center gap-3",children:[e.jsxs("button",{onClick:s,className:`text-gray-500 hover:text-gray-700 transition-colors flex items-center gap-1 ${n?"text-[10px] mb-2":"text-[11px]"}`,children:[e.jsx(un,{size:n?12:14}),"Back"]}),e.jsxs("div",{children:[e.jsx("h2",{className:`font-semibold text-gray-900 ${n?"text-sm":"text-lg"}`,children:o.name||"SEO Report"}),e.jsxs("div",{className:`flex items-center gap-2 mt-1 ${n?"flex-wrap":""}`,children:[e.jsx("span",{className:`text-gray-500 ${n?"text-[10px]":"text-[11px]"}`,children:o.site_url.split(":")[1]||o.site_url}),e.jsx("span",{className:"text-[10px] text-gray-400",children:"•"}),e.jsxs("span",{className:`text-gray-500 ${n?"text-[10px]":"text-[11px]"}`,children:[o.period_start_date," - ",o.period_end_date]})]})]})]}),e.jsx("button",{onClick:x,disabled:h,className:`rounded-lg border border-gray-200 font-medium text-gray-600 hover:bg-gray-50 transition-colors flex items-center gap-1.5 disabled:opacity-50 disabled:cursor-not-allowed ${n?"mt-2 px-2 py-1 text-[10px]":"px-3 py-1.5 text-[11px]"}`,children:h?e.jsxs(e.Fragment,{children:[e.jsx(He,{size:12,className:"animate-spin"}),"Exporting..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Vs,{size:12}),"Export PDF"]})})]}),e.jsx("div",{className:`flex items-center gap-1 mb-4 border-b border-gray-100 ${n?"overflow-x-auto -mx-3 px-3":""}`,children:[{id:"summary",label:n?"Summary":"Executive Summary"},{id:"queries",label:"Queries"},{id:"pages",label:"Pages"},{id:"geographic",label:n?"Geo/Device":"Geographic & Device"},{id:"coverage",label:n?"Coverage":"Coverage & Sitemap"}].map(P=>e.jsxs("button",{onClick:()=>m(P.id),className:`font-medium transition-colors relative whitespace-nowrap ${d===P.id?"text-gray-800":"text-gray-400 hover:text-gray-600"} ${n?"px-2 py-1.5 text-[10px]":"px-4 py-2 text-[12px]"}`,children:[P.label,d===P.id&&e.jsx("div",{className:"absolute bottom-0 left-0 right-0 h-0.5 bg-gray-800"})]},P.id))}),d==="summary"&&e.jsxs("div",{className:"space-y-4","data-export-id":"executive_summary",children:[e.jsxs("div",{className:`grid gap-3 ${n?"grid-cols-2":"grid-cols-4"}`,children:[e.jsx(u,{label:"Total Clicks",value:g?.clicks||0,change:g?.clicks_change?`${g.clicks_change>0?"↑":"↓"} ${Math.abs(g.clicks_change).toFixed(1)}% vs prev`:void 0,icon:Di}),e.jsx(u,{label:"Total Impressions",value:g?.impressions||0,change:g?.impressions_change?`${g.impressions_change>0?"↑":"↓"} ${Math.abs(g.impressions_change).toFixed(1)}% vs prev`:void 0,icon:Qt}),e.jsx(u,{label:"CTR",value:g?.ctr?`${(g.ctr*100).toFixed(2)}%`:"0%",change:g?.ctr_change?`${g.ctr_change>0?"↑":"↓"} ${Math.abs(g.ctr_change).toFixed(1)}% vs prev`:void 0,icon:us}),e.jsx(u,{label:"Average Position",value:g?.position?g.position.toFixed(1):"N/A",change:g?.position_change?`${g.position_change>0?"↓":"↑"} ${Math.abs(g.position_change).toFixed(1)}% vs prev`:void 0,icon:Ma})]}),_.length>0&&e.jsxs("div",{className:"bg-white border border-gray-100 rounded-xl p-4",children:[e.jsx("div",{className:"text-[11px] font-medium text-gray-600 mb-3",children:"Performance Trend (clicks)"}),e.jsxs("div",{className:"relative h-48 mt-4",children:[e.jsx("div",{className:"absolute inset-0 flex items-end gap-0.5 pb-6",children:_.map((P,A)=>{const C=Math.max(..._.map(T=>T.clicks||0)),I=C>0?(P.clicks||0)/C*100:0,j=P.date||"",q=j.includes("-")?j.split("-").slice(1).join("-"):j;return e.jsxs("div",{className:"flex-1 min-w-0 flex flex-col items-center justify-end group relative",style:{height:"100%"},children:[e.jsx("div",{className:"absolute bottom-full mb-2 hidden group-hover:block z-10 pointer-events-none",children:e.jsxs("div",{className:"bg-gray-800 text-white text-[10px] px-2 py-1 rounded whitespace-nowrap",children:[q,": ",V(P.clicks||0)]})}),e.jsx("div",{className:"w-full bg-gray-300 hover:bg-gray-400 transition-colors rounded-t",style:{height:`${I}%`,minHeight:I>0?"2px":"0"}})]},A)})}),e.jsx("div",{className:"absolute bottom-0 left-0 right-0 flex gap-0.5 text-[9px] text-gray-400",children:_.map((P,A)=>{const C=P.date||"",I=C.includes("-")?C.split("-").slice(1).join("-"):C,j=_.length<=10||A%Math.ceil(_.length/10)===0||A===_.length-1;return e.jsx("div",{className:"flex-1 min-w-0 text-center truncate",style:{visibility:j?"visible":"hidden"},children:I},A)})})]})]}),e.jsxs("div",{className:"bg-white border border-gray-100 rounded-xl p-4",children:[e.jsx("h3",{className:"text-[12px] font-semibold text-gray-800 mb
221-3",children:"Key Insights"}),w?.key_insights&&Array.isArray(w.key_insights)&&w.key_insights.length>0?e.jsx("ul",{className:"space-y-2 text-[11px] text-gray-600",children:w.key_insights.map((P,A)=>e.jsxs("li",{children:["• ",P]},A))}):e.jsx("div",{className:"text-[11px] text-gray-500",children:"No insights available for this report period."}),w?.recommendations&&Array.isArray(w.recommendations)&&w.recommendations.length>0&&e.jsxs("div",{className:"mt-4 pt-4 border-t border-gray-100",children:[e.jsx("h4",{className:"text-[11px] font-semibold text-gray-800 mb-2",children:"Recommendations"}),e.jsx("ul",{className:"space-y-2 text-[11px] text-gray-600",children:w.recommendations.map((P,A)=>e.jsxs("li",{children:["• ",P]},A))})]})]})]}),d==="queries"&&e.jsxs("div",{className:"space-y-4","data-export-id":"top_queries",children:[e.jsxs("div",{className:"bg-white border border-gray-100 rounded-xl overflow-hidden",children:[e.jsx("div",{className:"px-4 py-3 border-b border-gray-50",children:e.jsxs("h3",{className:"text-[12px] font-semibold text-gray-800",children:["Top Performing Queries (",E.length,")"]})}),E.length===0?e.jsx("div",{className:"px-4 py-8 text-center text-[11px] text-gray-400",children:"No query data available"}):e.jsxs("div",{className:`divide-y divide-gray-50 ${n?"overflow-x-auto":""}`,children:[e.jsxs("div",{className:`px-4 py-2.5 bg-gray-50/50 grid grid-cols-5 gap-4 text-[10px] font-medium text-gray-500 uppercase tracking-wide ${n?"min-w-[500px]":""}`,children:[e.jsx("div",{children:"Query"}),e.jsx("div",{className:"text-right",children:"Clicks"}),e.jsx("div",{className:"text-right",children:"Impressions"}),e.jsx("div",{className:"text-right",children:"CTR"}),e.jsx("div",{className:"text-right",children:"Position"})]}),E.slice(0,20).map((P,A)=>e.jsxs("div",{className:`px-4 py-3 hover:bg-gray-50/50 transition-colors grid grid-cols-5 gap-4 items-center ${n?"min-w-[500px]":""}`,children:[e.jsx("div",{className:"text-[11px] font-medium text-gray-700",children:P.query}),e.jsx("div",{className:"text-[11px] text-gray-600 text-right",children:V(P.clicks||0)}),e.jsx("div",{className:"text-[11px] text-gray-600 text-right",children:V(P.impressions||0)}),e.jsxs("div",{className:"text-[11px] text-gray-600 text-right",children:[((P.ctr||0)*100).toFixed(2),"%"]}),e.jsx("div",{className:"text-[11px] text-gray-600 text-right",children:(P.position||0).toFixed(1)})]},A))]})]}),N&&(N.key_insights||N.recommendations)&&e.jsxs("div",{className:"bg-white border border-gray-100 rounded-xl p-4",children:[e.jsx("h3",{className:"text-[12px] font-semibold text-gray-800 mb-3",children:"Insights"}),N.key_insights&&Array.isArray(N.key_insights)&&N.key_insights.length>0&&e.jsxs("div",{className:"mb-4",children:[e.jsx("h4",{className:"text-[11px] font-semibold text-gray-700 mb-2",children:"Key Insights"}),e.jsx("ul",{className:"space-y-2 text-[11px] text-gray-600",children:N.key_insights.map((P,A)=>e.jsxs("li",{children:["• ",P]},A))})]}),N.recommendations&&Array.isArray(N.recommendations)&&N.recommendations.length>0&&e.jsxs("div",{children:[e.jsx("h4",{className:"text-[11px] font-semibold text-gray-700 mb-2",children:"Recommendations"}),e.jsx("ul",{className:"space-y-2 text-[11px] text-gray-600",children:N.recommendations.map((P,A)=>e.jsxs("li",{children:["• ",P]},A))})]})]})]}),d==="pages"&&e.jsxs("div",{className:"space-y-4","data-export-id":"top_pages",children:[e.jsxs("div",{className:"bg-white border border-gray-100 rounded-xl overflow-hidden",children:[e.jsx("div",{className:"px-4 py-3 border-b border-gray-50",children:e.jsxs("h3",{className:"text-[12px] font-semibold text-gray-800",children:["Top Performing Pages (",S.length,")"]})}),S.length===0?e.jsx("div",{className:"px-4 py-8 text-center text-[11px] text-gray-400",children:"No page data available"}):e.jsxs("div",{className:`divide-y divide-gray-50 ${n?"overflow-x-auto":""}`,children:[e.jsxs("div",{className:`px-4 py-2.5 bg-gray-50/50 grid grid-cols-5 gap-4 text-[10px] font-medium text-gray-500 uppercase tracking-wide ${n?"min-w-[500px]":""}`,children:[e.jsx("div",{className:"col-span-2",children:"Page URL"}),e.jsx("div",{className:"text-right",children:"Clicks"}),e.jsx("div",{className:"text-right",children:"CTR"}),e.jsx("div",{className:"text-right",children:"Position"})]}),S.slice(0,20).map((P,A)=>e.jsxs("div",{className:`px-4 py-3 hover:bg-gray-50/50 transition-colors grid grid-cols-5 ga
221p-4 items-center ${n?"min-w-[500px]":""}`,children:[e.jsx("div",{className:"col-span-2 text-[11px] font-medium text-gray-700 truncate",title:P.page_url,children:P.page_url}),e.jsx("div",{className:"text-[11px] text-gray-600 text-right",children:V(P.clicks||0)}),e.jsxs("div",{className:"text-[11px] text-gray-600 text-right",children:[((P.ctr||0)*100).toFixed(2),"%"]}),e.jsx("div",{className:"text-[11px] text-gray-600 text-right",children:(P.position||0).toFixed(1)})]},A))]})]}),S.length>0&&e.jsxs("div",{className:"bg-white border border-gray-100 rounded-xl p-4",children:[e.jsx("div",{className:"text-[11px] font-medium text-gray-600 mb-3",children:"Top Pages by Clicks"}),e.jsx("div",{className:"space-y-2",children:S.slice(0,10).map((P,A)=>{const C=Math.max(...S.slice(0,10).map(q=>q.clicks||0)),I=C>0?(P.clicks||0)/C*100:0,j=P.page_url.length>40?P.page_url.substring(0,40)+"...":P.page_url;return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-32 text-[10px] text-gray-600 truncate flex-shrink-0",title:P.page_url,children:j}),e.jsx("div",{className:"flex-1 relative",children:e.jsx("div",{className:"h-6 bg-gray-100 rounded overflow-hidden",children:e.jsx("div",{className:"h-full bg-gray-400 hover:bg-gray-500 transition-colors flex items-center justify-end px-2",style:{width:`${I}%`},children:e.jsx("span",{className:"text-[10px] text-white font-medium",children:V(P.clicks||0)})})})})]},A)})})]}),k&&(k.key_insights||k.recommendations)&&e.jsxs("div",{className:"bg-white border border-gray-100 rounded-xl p-4",children:[e.jsx("h3",{className:"text-[12px] font-semibold text-gray-800 mb-3",children:"Insights"}),k.key_insights&&Array.isArray(k.key_insights)&&k.key_insights.length>0&&e.jsxs("div",{className:"mb-4",children:[e.jsx("h4",{className:"text-[11px] font-semibold text-gray-700 mb-2",children:"Key Insights"}),e.jsx("ul",{className:"space-y-2 text-[11px] text-gray-600",children:k.key_insights.map((P,A)=>e.jsxs("li",{children:["• ",P]},A))})]}),k.recommendations&&Array.isArray(k.recommendations)&&k.recommendations.length>0&&e.jsxs("div",{children:[e.jsx("h4",{className:"text-[11px] font-semibold text-gray-700 mb-2",children:"Recommendations"}),e.jsx("ul",{className:"space-y-2 text-[11px] text-gray-600",children:k.recommendations.map((P,A)=>e.jsxs("li",{children:["• ",P]},A))})]})]})]}),d==="geographic"&&e.jsxs("div",{className:"space-y-4","data-export-id":"geographic_device",children:[e.jsxs("div",{className:"bg-white border border-gray-100 rounded-xl overflow-hidden",children:[e.jsx("div",{className:"px-4 py-3 border-b border-gray-50",children:e.jsxs("h3",{className:"text-[12px] font-semibold text-gray-800",children:["Geographic Performance (",D.length,")"]})}),D.length===0?e.jsx("div",{className:"px-4 py-8 text-center text-[11px] text-gray-400",children:"No geographic data available"}):e.jsxs("div",{className:`divide-y divide-gray-50 ${n?"overflow-x-auto":""}`,children:[e.jsxs("div",{className:`px-4 py-2.5 bg-gray-50/50 grid grid-cols-5 gap-4 text-[10px] font-medium text-gray-500 uppercase tracking-wide ${n?"min-w-[500px]":""}`,children:[e.jsx("div",{children:"Country"}),e.jsx("div",{className:"text-right",children:"Clicks"}),e.jsx("div",{className:"text-right",children:"Impressions"}),e.jsx("div",{className:"text-right",children:"CTR"}),e.jsx("div",{className:"text-right",children:"Position"})]}),D.slice(0,20).map((P,A)=>e.jsxs("div",{className:`px-4 py-3 hover:bg-gray-50/50 transition-colors grid grid-cols-5 gap-4 items-center ${n?"min-w-[500px]":""}`,children:[e.jsx("div",{className:"text-[11px] font-medium text-gray-700 uppercase",children:P.country}),e.jsx("div",{className:"text-[11px] text-gray-600 text-right",children:V(P.clicks||0)}),e.jsx("div",{className:"text-[11px] text-gray-600 text-right",children:V(P.impressions||0)}),e.jsxs("div",{className:"text-[11px] text-gray-600 text-right",children:[((P.ctr||0)*100).toFixed(2),"%"]}),e.jsx("div",{className:"text-[11px] text-gray-600 text-right",children:(P.position||0).toFixed(1)})]},A))]})]}),D.length>0&&e.jsxs("div",{className:"bg-white border border-gray-100 rounded-xl p-4",children:[e.jsx("div",{className:"text-[11px] font-medium text-gray-600 mb-3",children:"Top Countries by Clicks"}),e.jsxs("div",{className:"relative h-48 mt-4",children:[e.jsx("div",{className:"absolute inset-0 flex items-end gap-2 pb-6",children:D.slice(0,10).map((P,A)=>{const C=Math.max(...D.slice(0,10).map(j=>j.clicks||0)),I=C>0?(P.clicks||0)/C*100:0;return e.jsxs("div",{className:"flex-1 min-w-0 flex flex-col items-center justify-end group relative",style:{height:"100%"},children:[e.jsx("div",{className:"absolute bottom-full mb-2 hidden group-hover:block z-10 pointer-events-none",children:e.jsxs("div",{className:"bg-gray-800 text-white text-[10px] px-2 py-1 rounded whitespace-nowrap",children:[P.country.toUpperCase(),":"," ",V(P.clicks||0)]})}),e.jsx("div",{className:"w-full bg-gray-300 hover:bg-gray-400 transition-colors rounded-t",style:{height:`${I}%`,minHeight:I>0?"2px":"0"}})]},A)})}),e.jsx("div",{className:"absolute bottom-0 left-0 right-0 flex gap-2 text-[9px] text-gray-400",children:D.slice(0,10).map((P,A)=>e.jsx("div",{className:"flex-1 min-w-0 text-center uppercase truncate",children:P.country},A))})]})]}),e.jsxs("div",{className:"bg-white border border-gray-100 rounded-xl p-4",children:[e.jsx("h3",{className:"text-[12px] font-semibold text-gray-800 mb
221-3",children:"Device Performance"}),Object.keys(R).length===0?e.jsx("div",{className:"text-center py-8 text-[11px] text-gray-400",children:"No device data available"}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-3",children:Object.entries(R).map(([P,A])=>e.jsxs("div",{className:"bg-gray-50 border border-gray-100 rounded-lg p-3",children:[e.jsx("h4",{className:"text-[11px] font-semibold text-gray-700 capitalize mb-2",children:P}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-[10px] text-gray-500",children:"Clicks:"}),e.jsx("span",{className:"text-[10px] font-medium text-gray-700",children:V(A.clicks||0)})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-[10px] text-gray-500",children:"Impressions:"}),e.jsx("span",{className:"text-[10px] font-medium text-gray-700",children:V(A.impressions||0)})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-[10px] text-gray-500",children:"CTR:"}),e.jsxs("span",{className:"text-[10px] font-medium text-gray-700",children:[((A.ctr||0)*100).toFixed(2),"%"]})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-[10px] text-gray-500",children:"Position:"}),e.jsx("span",{className:"text-[10px] font-medium text-gray-700",children:(A.position||0).toFixed(1)})]})]})]},P))})]}),Object.keys(R).length>0&&e.jsxs("div",{className:"bg-white border border-gray-100 rounded-xl p-4",children:[e.jsx("div",{className:"text-[11px] font-medium text-gray-600 mb-3",children:"Device Clicks Comparison"}),e.jsx("div",{className:"space-y-2",children:Object.entries(R).map(([P,A],C)=>{const I=Math.max(...Object.values(R).map(q=>q.clicks||0)),j=I>0?(A.clicks||0)/I*100:0;return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-20 text-[10px] text-gray-600 capitalize flex-shrink-0",children:P}),e.jsx("div",{className:"flex-1 relative",children:e.jsx("div",{className:"h-6 bg-gray-100 rounded overflow-hidden",children:e.jsx("div",{className:"h-full bg-gray-400 hover:bg-gray-500 transition-colors flex items-center justify-end px-2",style:{width:`${j}%`},children:e.jsx("span",{className:"text-[10px] text-white font-medium",children:V(A.clicks||0)})})})})]},C)})})]}),(F||L)&&e.jsxs("div",{className:"bg-white border border-gray-100 rounded-xl p-4",children:[e.jsx("h3",{className:"text-[12px] font-semibold text-gray-800 mb-3",children:"Insights"}),F?.key_insights&&Array.isArray(F.key_insights)&&F.key_insights.length>0&&e.jsxs("div",{className:"mb-4",children:[e.jsx("h4",{className:"text-[11px] font-semibold text-gray-700 mb-2",children:"Geographic Key Insights"}),e.jsx("ul",{className:"space-y-2 text-[11px] text-gray-600",children:F.key_insights.map((P,A)=>e.jsxs("li",{children:["• ",P]},A))})]}),L?.key_insights&&Array.isArray(L.key_insights)&&L.key_insights.length>0&&e.jsxs("div",{className:"mb-4",children:[e.jsx("h4",{className:"text-[11px] font-semibold text-gray-700 mb-2",children:"Device Key Insights"}),e.jsx("ul",{className:"space-y-2 text-[11px] text-gray-600",children:L.key_insights.map((P,A)=>e.jsxs("li",{children:["• ",P]},A))})]}),(F?.recommendations||L?.recommendations)&&e.jsxs("div",{children:[e.jsx("h4",{className:"text-[11px] font-semibold text-gray-700 mb-2",children:"Recommendations"}),e.jsxs("ul",{className:"space-y-2 text-[11px] text-gray-600",children:[F?.recommendations?.map((P,A)=>e.jsxs("li",{children:["• ",P]},`geo-${A}`)),L?.recommendations?.map((P,A)=>e.jsxs("li",{children:["• ",P]},`device-${A}`))]})]})]})]}),d==="coverage"&&e.jsxs("div",{className:"space-y-4","data-export-id":"coverage_sitemap",children:[e.jsxs("div",{className:"bg-white border border-gray-100 rounded-xl p-4",children:[e.jsx("h3",{className:"text-[12px] font-semibold text-gray-800 mb-4",children:"Index Coverage Status"}),$?e.jsx("div",{className:"space-y-3",children:[{label:"Valid Pages",value:$.valid_pages||0,color:"bg-gray-700"},{label:"Valid with Warnings",value:$.warnings||0,color:"bg-gray-400"},{label:"Error",value:$.errors||0,color:"bg-gray-300"},{label:"Excluded",value:$.excluded_pages||0,color:"bg-gray-200"}].map(P=>{const A=($.valid_pages||0)+($.warnings||0)+($.errors||0)+($.excluded_pages||0),
221C=A>0?Math.round(P.value/A*100):0;return e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx("span",{className:"text-[10px] text-gray-600",children:P.label}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"text-[10px] font-medium text-gray-700",children:[C,"%"]}),e.jsxs("span",{className:"text-[10px] text-gray-500",children:[V(P.value)," pages"]})]})]}),e.jsx("div",{className:"h-2 bg-gray-100 rounded-full overflow-hidden",children:e.jsx("div",{className:`h-full ${P.color} transition-all`,style:{width:`${C}%`}})})]},P.label)})}):e.jsx("div",{className:"text-center py-8 text-[11px] text-gray-400",children:"No coverage data available"})]}),e.jsxs("div",{className:"bg-white border border-gray-100 rounded-xl overflow-hidden",children:[e.jsx("div",{className:"px-4 py-3 border-b border-gray-50",children:e.jsx("h3",{className:"text-[12px] font-semibold text-gray-800",children:"Sitemap Status"})}),!K?.sitemaps||K.sitemaps.length===0?e.jsx("div",{className:"px-4 py-8 text-center text-[11px] text-gray-400",children:"No sitemap data available"}):e.jsxs("div",{className:`divide-y divide-gray-50 ${n?"overflow-x-auto":""}`,children:[e.jsxs("div",{className:`px-4 py-2.5 bg-gray-50/50 grid grid-cols-4 gap-4 text-[10px] font-medium text-gray-500 uppercase tracking-wide ${n?"min-w-[400px]":""}`,children:[e.jsx("div",{children:"Sitemap URL"}),e.jsx("div",{className:"text-right",children:"Submitted"}),e.jsx("div",{className:"text-right",children:"Indexed"}),e.jsx("div",{children:"Status"})]}),K.sitemaps.map((P,A)=>e.jsxs("div",{className:`px-4 py-3 hover:bg-gray-50/50 transition-colors grid grid-cols-4 gap-4 items-center ${n?"min-w-[400px]":""}`,children:[e.jsx("div",{className:"text-[11px] font-medium text-gray-700 truncate",title:P.sitemap_url,children:P.sitemap_url}),e.jsx("div",{className:"text-[11px] text-gray-600 text-right",children:V(P.submitted_urls||0)}),e.jsx("div",{className:"text-[11px] text-gray-600 text-right",children:V(P.indexed_urls||0)}),e.jsx("div",{children:e.jsx("span",{className:`text-[10px] px-2 py-0.5 rounded font-medium ${P.status==="ok"||P.status==="success"?"bg-green-50 text-green-700 border border-green-200":"bg-gray-50 text-gray-600 border border-gray-200"}`,children:P.status||"unknown"})})]},A))]})]}),(H||X)&&e.jsxs("div",{className:"bg-white border border-gray-100 rounded-xl p-4",children:[e.jsx("h3",{className:"text-[12px] font-semibold text-gray-800 mb-3",children:"Insights & Recommendations"}),H?.key_insights&&Array.isArray(H.key_insights)&&H.key_insights.length>0&&e.jsxs("div",{className:"mb-4",children:[e.jsx("h4",{className:"text-[11px] font-semibold text-gray-700 mb-2",children:"Index Coverage Insights"}),e.jsx("ul",{className:"space-y-2 text-[11px] text-gray-600",children:H.key_insights.map((P,A)=>e.jsxs("li",{children:["• ",P]},A))})]}),X?.key_insights&&Array.isArray(X.key_insights)&&X.key_insights.length>0&&e.jsxs("div",{className:"mb-4",children:[e.jsx("h4",{className:"text-[11px] font-semibold text-gray-700 mb-2",children:"Sitemap Insights"}),e.jsx("ul",{className:"space-y-2 text-[11px] text-gray-600",children:X.key_insights.map((P,A)=>e.jsxs("li",{children:["• ",P]},A))})]}),(H?.recommendations||X?.recommendations)&&e.jsxs("div",{children:[e.jsx("h4",{className:"text-[11px] font-semibold text-gray-700 mb-2",children:"Recommendations"}),e.jsxs("ul",{className:"space-y-2 text-[11px] text-gray-600",children:[H?.recommendations?.map((P,A)=>e.jsxs("li",{children:["• ",P]},`coverage-${A}`)),X?.recommendations?.map((P,A)=>e.jsxs("li",{children:["• ",P]},`sitemap-${A}`))]})]})]})]})]})]})}function jN({task:t,onComplete:s,onDismiss:a}){const[n,o]=r.useState(null),[i,l]=r.useState(!0),[c,d]=r.useState(null),m=r.useRef(!1);r.useEffect(()=>{let u=!0,g=null,w=!0;const _=async()=>{if(!(!u||!w))try{const E=await Kn.getTaskStatus(t.taskId);if(!u||!w)return;if(o(E),l(!1),d(null),E.status==="done"||E.status==="error"){w=!1,g&&(clearInterval(g),g=null),E.status==="done"&&s&&!m.current&&(m.current=!0,s(t.taskId,E.report_id));return}}
221catch(E){if(!u||!w)return;d(E.message||"Failed to fetch task status"),l(!1)}};return _(),w&&(g=setInterval(()=>{w&&_()},2e3)),()=>{u=!1,w=!1,g&&(clearInterval(g),g=null)}},[t.taskId,s]);const h=()=>{a&&a(t.taskId)},p=()=>i?e.jsx(He,{className:"h-3.5 w-3.5 animate-spin text-gray-500"}):n?.status==="done"?e.jsx(Rs,{className:"h-3.5 w-3.5 text-green-600"}):n?.status==="error"?e.jsx(Ss,{className:"h-3.5 w-3.5 text-red-600"}):e.jsx(He,{className:"h-3.5 w-3.5 animate-spin text-gray-500"}),f=()=>i?"Loading...":n?.status==="done"?"Completed":n?.status==="error"?"Failed":n?.status==="processing"?"Processing...":"Unknown",b=n?n.status==="done"?n.total:n.progress:0,y=n?n.total:0,x=y>0?Math.round(b/y*100):0;return e.jsx("div",{className:"w-80 bg-white border border-gray-200 rounded-xl shadow-lg overflow-hidden",children:e.jsxs("div",{className:"p-4",children:[e.jsxs("div",{className:"flex items-start justify-between mb-3",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[p(),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-[11px] font-semibold text-gray-800 truncate",children:t.reportName||"Report Generation"}),e.jsx("div",{className:"text-[10px] text-gray-500",children:f()})]})]}),e.jsx("button",{onClick:h,className:"flex-shrink-0 h-6 w-6 flex items-center justify-center hover:bg-gray-100 rounded transition-colors",children:e.jsx(mt,{className:"h-3.5 w-3.5 text-gray-400"})})]}),c?e.jsx("div",{className:"text-[10px] text-red-600 mb-2",children:c}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"mb-2",children:[e.jsx("div",{className:"h-1.5 bg-gray-100 rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full bg-gray-400 transition-all duration-300",style:{width:`${x}%`}})}),e.jsxs("div",{className:"flex items-center justify-between mt-1",children:[e.jsxs("div",{className:"text-[9px] text-gray-500",children:[b," / ",y]}),e.jsxs("div",{className:"text-[9px] font-medium text-gray-600",children:[x,"%"]})]})]}),n?.error&&e.jsx("div",{className:"text-[10px] text-red-600 mt-2",children:n.error})]})]})})}const vN=[{target:'[data-onboarding="reports-intro"]',content:"Data & Report provides access to your Google Search Console data and SEO performance reports. Switch between raw GSC data and formatted report views.",placement:"bottom",disableBeacon:!0},{target:'[data-onboarding="tab-gsc-data"]',content:"GSC Data tab displays raw search performance metrics from Google Search Console including queries, pages, clicks, and impressions.",placement:"bottom",disableBeacon:!0},{target:'[data-onboarding="tab-report"]',content:"Report View tab presents your SEO data in a formatted report layout suitable for sharing with stakeholders or clients.",placement:"bottom",disableBeacon:!0}];function NN(){const[t,s]=r.useState(()=>typeof window<"u"&&window.innerWidth<768);return r.useEffect(()=>{const a=()=>s(window.innerWidth<768);return window.addEventListener("resize",a),()=>window.removeEventListener("resize",a)},[]),t}function Sm(){try{return new URLSearchParams(window.location.search).get("tab")==="report"?"report":"gsc_data"}catch{return"gsc_data"}}function kN(t){try{const s=new URL(window.location.href);s.searchParams.set("tab",t),window.history.replaceState({},"",s.toString())}catch{}}function _N({gscAuthCompleted:t}){const[s,a]=r.useState(Sm),n=Zs(Us.data_report),{toast:o}=_t(),i=NN();r.useEffect(()=>{const d=()=>{a(Sm())};return window.addEventListener("popstate",d),()=>window.removeEventListener("popstate",d)},[]);const l=d=>{a(d),kN(d)},c=d=>{o(d)};return e.jsxs("div",{className:`h-full flex flex-col overflow-hidden ${i?"bg-white":"bg-slate-50"}`,"data-onboarding":"reports-intro",children:[e.jsx("div",{className:"shrink-0 bg-white border-b border-slate-200 hidden sm:block",children:e.jsx("div",{className:"max-w-7xl mx-auto px-6 py-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 bg-slate-100 rounded-xl flex items-center justify-center",children:e.jsx(cu,{className:"w-5 h-5 text-slate-600"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-lg font-semibold text-slate-900",children:"Data & Report"}),e.jsx("p",{className:"text-xs text-slate-500",children:"GSC data and SEO performance reports"})]})]}),e.jsxs("div",{className:"flex items-center gap-1 bg-slate-100 p-1 rounded-lg",children:[e.jsxs("button",{onClick:()=>l("gsc_data"),className:`flex items-center gap-2 px-4 py-2 rounded-md text-sm font-medium transition-colors ${s==="gsc_data"?"bg-white text-slate-900 shadow-sm":"text-slate-600 hover:text-slate-900"}`,"data-onboarding":"tab-gsc-data",children:[e.jsx(Al,{size:16}),"GSC Data"]}),e.jsxs("button",{onClick:()=>l("report"),className:`flex items-center gap-2 px-4 py-2 rounded-md text-sm font-medium transition-colors ${s==="report"?"bg-white text-slate-900 shadow-sm":"text-slate-600 hover:text-slate-900"}`,"data-onboarding":"tab-report",children:[e.jsx(Xc,{size:16}),"Report View"]})]}),e.jsx("div",{className:"w-[200px]"})]})})}),i&&e.jsx("div",{className:"shrink-0 bg-white border-b border-slate-200 px-4 py-2",children:e.jsxs("div",{className:"flex items-center gap-1 bg-slate-100 p-1 rounded-lg",children:[e.jsxs("button",{onClick:()=>l("gsc_data"),className:`flex-1 flex items-center justify-center gap-1.5 px-3 py-2 rounded-md text-xs font-medium transition-colors ${s==="gsc_data"?"bg-white text-slate-900 shadow-sm":"text-slate-600"}`,children:[e.jsx(Al,{size:14}),"GSC Data"]}),e.jsxs("button",{onClick:()=>l("report"),className:`flex-1 flex items-center justify-center gap-1.5 px-3 py-2 rounded-md text-xs font-medium transition-colors ${s==="report"?"bg-white text-slate-900 shadow-sm":"text-slate-600"}`,children:[e.jsx(Xc,{size:14}),"Report View"]})]})}),e.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:e.jsxs("div",{className:i?"px-3":"max-w-7xl mx-auto",children:[s==="gsc_data"&&e.jsx(CN,{}),s==="report"&&e.jsx(SN,{onShowToast:c})]})}),e.jsx("button",{onClick:n.startManual,className:"fixed bottom-5 right-5 z-50 h-8 w-8 rounded-full bg-white border border-slate-200 shadow-md hover:shadow-lg hover:bg-slate-50 transition-all hover:scale-105 hidden sm:flex items-center justify-center",title:"View navigation guide","aria-label":"View navigation guide",children:e.jsx(Hs,{className:"h-4 w-4 text-slate-600"})}),!i&&e.jsx(oa,{steps:vN,run:n.run,onComplete:n.stopAndMarkCompleted,onSkip:n.stopAndMarkCompleted})]})}function CN(){return e.jsxs("div",{className:"gsc-data-wrapper",children:[e.jsx("style",{children:`
222        /* Hide the original title from DashboardV2View */
223        .gsc-data-wrapper .p-6.max-w-7xl > div:first-child {
224          display: none;
225        }
226        /* Adjust padding */
227        .gsc-data-wrapper .p-6.max-w-7xl {
228          padding-top: 1rem;
229        }
230      `}),e.jsx(hN,{})]})}function SN({onShowToast:t}){return e.jsxs("div",{className:"report-wrapper",children:[e.jsx("style",{children:`
231        /* Hide the original header from ReportNewPageContent */
232        .report-wrapper .max-w-6xl > .mb-4 >
232 div:first-child > h2 {
233          display: none;
234        }
235        .report-wrapper .max-w-6xl > .mb-4 > div:first-child > p {
236          display: none;
237        }
238        /* Adjust container width to match */
239        .report-wrapper .max-w-6xl {
240          max-width: 80rem;
241        }
242      `}),e.jsx(bN,{onShowToast:t})]})}function EN({onStatusChange:t}){const{toast:s}=_t(),[a,n]=r.useState("idle"),[o,i]=r.useState(""),[l,c]=r.useState(null),[d,m]=r.useState(!1);r.useEffect(()=>{(async()=>{try{const f=await bs.getGoogleAuthExistsCached();f.exists&&(n("connected"),c({email:f.email,expiresAt:f.expires_at}))}catch{}})()},[]),r.useEffect(()=>{t?.(a)},[a,t]);async function h(){n("connecting"),i(""),m(!0);try{const f=await gc(),b=await kx(f,{name:"google_oauth",width:500,height:650});if(b.error){n("error"),i(b.error),s({title:"GSC error",description:b.error});return}!b.success&&b.code&&await pc(b.code);try{bs.invalidate();const y=await bs.getGoogleAuthExistsCached({force:!0});if(!y.exists)throw new Error("Authorization not found after callback");n("connected"),c({email:y.email,expiresAt:y.expires_at}),i("Authorized"),s({title:"GSC authorized",description:"Google Search Console connected"})}catch(y){n("error"),i(y?.message||"Authorization failed"),s({title:"GSC error",description:y?.message||"Authorization failed"})}}catch(f){n("error"),i(f?.message||"Authorization error"),s({title:"GSC error",description:f?.message||"Authorization error"})}finally{m(!1)}}async function p(){try{await _u(),bs.invalidate(),n("idle"),i(""),c(null),s({title:"GSC disconnected",description:"Google Search Console disconnected successfully"})}catch(f){s({title:"GSC error",description:f?.message||"Failed to disconnect"})}}return e.jsxs(xs,{className:"rounded-2xl flex flex-col h-full shadow-sm hover:shadow-md transition-shadow duration-200",children:[e.jsx(Bs,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Xs,{children:"Google Search Console"}),e.jsx(Br,{children:"Connect your GSC account to unlock SEO reports"})]}),e.jsx("div",{className:"text-xs",children:e.jsxs(ls,{variant:a==="connected"?"default":"secondary",children:[a==="idle"&&"UnConnected",a==="connecting"&&"Connecting",a==="connected"&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Rs,{className:"h-3 w-3"}),"Connected"]}),a==="error"&&"Error"]})})]})}),e.jsxs(fs,{className:"flex flex-col flex-1 space-y-4",children:[a==="connected"&&l?e.jsxs("div",{className:"rounded-lg border border-slate-200 p-3 bg-slate-50 flex-1",children:[e.jsx("div",{className:"text-sm font-medium text-slate-900 mb-2",children:"Connected Account"}),l.email&&e.jsxs("div",{className:"text-sm text-slate-700 mb-1",children:[e.jsx("span",{className:"font-medium",children:"Email:"})," ",l.email]})]}):e.jsx("div",{className:"flex-1",children:e.jsxs("div",{className:"rounded-lg border border-dashed border-slate-200 p-4 bg-slate-50/50",children:[e.jsx("p",{className:"text-sm font-medium text-slate-800 mb-3",children:"🚀 Unlock powerful insights after connecting GSC:"}),e.jsxs("ul",{className:"list-disc list-inside space-y-2 text-sm text-slate-700",children:[e.jsx("li",{children:"Track real-time keyword rankings & search performance"}),e.jsx("li",{children:"Monitor clicks, impressions & CTR for all your pages"}),e.jsx("li",{children:"Discover new keyword opportunities from search queries"}),e.jsx("li",{children:"Get actionable SEO recommendations based on your data"})]})]})}),o&&e.jsx("div",{className:"text-xs text-slate-500",children:o}),e.jsx("div",{className:"mt-auto pt-2",children:a==="connected"?e.jsx(be,{className:"w-full rounded-xl",onClick:p,variant:"outline",children:"Disconnect"}):e.jsx(be,{className:"w-full rounded-xl",onClick:h,disabled:a==="connecting"||d,variant:"default",children:a==="connecting"?e.jsxs(e.Fragment,{children:[e.jsx(He,{className:"mr-2 h-4 w-4 animate-spin"}),"Connecting..."]}):"Integrate GSC"})})]})]})}function vh({onStatusChange:t,fetchButtonText:s="Next"}){const{toast:a}=_t(),[n,o]=r.useState(""),[i,l]=r.useState(""),[c,d]=r.useState("idle"),[m,h]=r.useState(""),[p,f]=r.useState(null),[b,y]=r.useState([]),[x,u]=r.useState(""),[g,w]=r.useState(!1);r.useEffect(()=>{(async()=>{try{const{getWebflowCredentialExists:S}=await Bt(async()=>{const{getWebflowCredentialExists:D}=await Promise.resolve().then(()=>no);return{getWebflowCredentialExists:D}},void 0),k=await S();if(k.exists){d("connected");const D={siteUrl:k.site_url,siteName:k.site_name,siteId:k.site_id};f(D),k.site_url&&l(k.site_url)}}catch{}})()},[]),r.useEffect(()=>{c==="connected"&&!p&&(async()=>{try{const{getWebflowCredentialExists:S}=await Bt(async()=>{const{getWebflowCredentialExists:D}=await Promise.resolve().then(()=>no);return{getWebflowCredentialExists:D}},void 0),k=await S();k.exists&&(f({siteUrl:k.site_url,siteName:k.site_name,siteId:k.site_id}),k.site_url&&l(k.site_url))}catch{}})()},[c,p]),r.useEffect(()=>{t?.(c)},[c,t]);async function _(){if(!n.trim()){a({title:"API key required",description:"Please enter your Webflow API key first"});return}w(!0),y([]),u(""),h("");try{const{listSitesByKey:S}=await Bt(async()=>{const{listSitesByKey:F}=await Promise.resolve().then(()=>no);return{listSitesByKey:F}},void 0),D=(await S(n)).sites||[];if(D.length===0){h("No sites found for this API key"),a({title:"No sites found",description:"This API key doesn't have access to any sites"});return}if(y(D),D.length>0){const F=D[0];
242u(F.id),l(`https://${F.shortName}.webflow.io`)}}catch(S){h(S?.message||"Failed to fetch sites"),a({title:"Fetch error",description:S?.message||"Failed to fetch sites"})}finally{w(!1)}}async function E(){if(!n.trim()){a({title:"API key required",description:"Please enter your Webflow API key"});return}if(!x){a({title:"Site selection required",description:"Please fetch and select a site"});return}d("connecting"),h("");try{const S=await Au(n);if(!S.ok){d("error"),h(S.detail||"Connection test failed"),a({title:"Webflow error",description:S.detail||"Connection test failed"});return}const k=b.find(F=>F.id===x);if(!k)throw new Error("Selected site not found");const D=i.trim()||`https://${k.shortName}.webflow.io`;await Su(n,k.id,D,k.displayName),d("connected"),f({siteUrl:D,siteName:k.displayName,siteId:k.id}),h("Connected successfully"),a({title:"Webflow connected",description:"Webflow CMS integration successful"})}catch(S){d("error"),h(S?.message||"Failed to connect"),a({title:"Webflow error",description:S?.message||"Failed to connect"})}}async function N(){try{await Eu(),d("idle"),h(""),f(null),o(""),l(""),y([]),u(""),a({title:"Webflow disconnected",description:"Webflow CMS disconnected successfully"})}catch(S){a({title:"Webflow error",description:S?.message||"Failed to disconnect"})}}return e.jsxs(xs,{className:"rounded-2xl flex flex-col h-full shadow-sm hover:shadow-md transition-shadow duration-200",children:[e.jsx(Bs,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Xs,{children:"Webflow CMS"}),e.jsx(Br,{children:"Connect your Webflow site for content management"})]}),e.jsx("div",{className:"text-xs",children:e.jsxs(ls,{variant:c==="connected"?"default":"secondary",children:[c==="idle"&&"UnConnected",c==="connecting"&&"Connecting",c==="connected"&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Rs,{className:"h-3 w-3"}),"Connected"]}),c==="error"&&"Error"]})})]})}),e.jsx(fs,{className:"flex flex-col flex-1 space-y-4",children:c==="connected"?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"rounded-lg border border-slate-200 p-3 bg-slate-50 flex-1",children:[e.jsx("div",{className:"text-sm font-medium text-slate-900 mb-2",children:"Connected Site"}),p?e.jsxs(e.Fragment,{children:[p.siteName&&e.jsxs("div",{className:"text-sm text-slate-700 mb-1",children:[e.jsx("span",{className:"font-medium",children:"Site:"})," ",p.siteName]}),p.siteUrl&&e.jsxs("div",{className:"text-sm text-slate-700 mb-1",children:[e.jsx("span",{className:"font-medium",children:"URL:"})," ",e.jsx("a",{href:p.siteUrl,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:underline break-all",children:p.siteUrl})]}),p.siteId&&e.jsxs("div",{className:"text-xs text-slate-500",children:[e.jsx("span",{className:"font-medium",children:"Site ID:"})," ",p.siteId]}),!p.siteName&&!p.siteUrl&&!p.siteId&&e.jsx("div",{className:"text-sm text-slate-600",children:"Webflow CMS is connected"})]}):e.jsx("div",{className:"text-sm text-slate-600",children:"Webflow CMS is connected"})]}),m&&e.jsx("div",{className:"text-xs text-slate-500",children:m}),e.jsx("div",{className:"mt-auto pt-2",children:e.jsx(be,{className:"w-full rounded-xl",variant:"outline",onClick:N,children:"Disconnect"})})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex-1 flex flex-col",children:[e.jsx("div",{className:"rounded-lg border border-dashed border-slate-200 p-4 bg-slate-50/50 mb-3",children:e.jsx("p",{className:"text-sm text-slate-700",children:"Connect your Webflow CMS to publish and manage content directly from Rankgale."})}),e.jsx("div",{className:"space-y-3 flex-1",children:b.length===0?e.jsxs(e.Fragment,{children:[e.jsx(bt,{type:"password",placeholder:"wf_pat_xxx (Webflow API Key)",value:n,onChange:S=>o(S.target.value),disabled:c==="connecting"||g}),m&&e.jsx("div",{className:"text-xs text-slate-500",children:m})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{children:e.jsxs(Pn,{value:x,onValueChange:S=>{u(S);const k=b.find(D=>D.id===S);k&&l(`https://${k.shortName}.webflow.io`)},children:[e.jsx(In,{disabled:c==="connecting",children:e.jsx(Tc,{placeholder:"Select a site",children:b.find(S=>
242S.id===x)?.displayName})}),e.jsx(Mn,{children:b.map(S=>e.jsx(js,{value:S.id,children:S.displayName},S.id))})]})}),e.jsx(bt,{type:"text",placeholder:"https://your-site.webflow.io or sc-domain:example.com (optional)",value:i,onChange:S=>l(S.target.value),disabled:c==="connecting"}),m&&e.jsx("div",{className:"text-xs text-slate-500",children:m})]})})]}),m&&e.jsx("div",{className:"text-xs text-slate-500",children:m}),e.jsx("div",{className:"mt-auto pt-2",children:b.length===0?e.jsx(be,{onClick:_,disabled:!n.trim()||g||c==="connecting",className:"w-full rounded-xl",variant:"default",children:g?e.jsxs(e.Fragment,{children:[e.jsx(He,{className:"mr-2 h-4 w-4 animate-spin"}),"Fetching Sites..."]}):s}):e.jsx(be,{className:"w-full rounded-xl",onClick:E,disabled:c==="connecting"||!n.trim()||!x,variant:"default",children:c==="connecting"?e.jsxs(e.Fragment,{children:[e.jsx(He,{className:"mr-2 h-4 w-4 animate-spin"}),"Connecting..."]}):"Integrate Webflow"})})]})})]})}const Pi="shopify_oauth_return_url";function Nh({onStatusChange:t}){const{toast:s}=_t(),[a,n]=r.useState([]),[o,i]=r.useState(!1),[l,c]=r.useState(""),[d,m]=r.useState(null),[h,p]=r.useState(!1);r.useEffect(()=>{(async()=>await f())()},[]),r.useEffect(()=>{if(a.some(g=>g.status==="connected"))t?.("connected");else if(o)t?.("connecting");else if(a.length===0)t?.("idle");else{const g=a.some(w=>w.status==="invalid"||w.status==="error");t?.(g?"error":"idle")}},[a,o,t]);async function f(){try{i(!0);const g=((await bo()).shops||[]).map(w=>({...w,localStatus:w.status}));n(g),await Promise.all(g.map(async w=>{n(_=>_.map(E=>E.id===w.id?{...E,localStatus:"checking"}:E));try{const _=await gi(w.id);n(E=>E.map(N=>N.id===w.id?{...N,..._,localStatus:_.status}:N))}catch{n(E=>E.map(N=>N.id===w.id?{...N,localStatus:"error",status:"error"}:N))}}))}catch(u){s({title:"Shopify error",description:u?.message||"Failed to load Shopify shops"})}finally{i(!1)}}async function b(){if(!l.trim()){s({title:"Shop name required",description:"Please enter your Shopify shop name"});return}try{p(!0);try{sessionStorage.setItem(Pi,window.location.href)}catch{}const u=await md(l.trim());u.auth_url&&(window.location.href=u.auth_url)}catch(u){p(!1),s({title:"Shopify error",description:u?.message||"Failed to start Shopify authorization"})}}async function y(u){try{m(u.id);try{sessionStorage.setItem(Pi,window.location.href)}catch{}const g=await md(u.shop_name);g.auth_url&&(window.location.href=g.auth_url)}catch(g){m(null),s({title:"Shopify error",description:g?.message||"Failed to start Shopify re-authorization"})}}async function x(u){try{await p0(u.id),n(g=>g.filter(w=>w.id!==u.id)),s({title:"Shop removed",description:`Shop ${u.display_name||u.shop_name} removed`})}catch(g){s({title:"Shopify error",description:g?.message||"Failed to remove shop"})}}return e.jsxs(xs,{className:"rounded-2xl flex flex-col h-full shadow-sm hover:shadow-md transition-shadow duration-200",children:[e.jsx(Bs,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Xs,{children:"Shopify"}),e.jsx(Br,{children:"Connect your Shopify stores for content publishing"})]}),e.jsx(ls,{variant:a.some(u=>u.status==="connected")?"default":"secondary",children:a.some(u=>u.status==="connected")?"Connected":"UnConnected"})]})}),e.jsx(fs,{className:"flex flex-col flex-1 space-y-6",children:e.jsxs("div",{className:"flex-1 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm font-medium text-slate-900",children:"Connected stores"}),e.jsx(be,{variant:"outline",size:"sm",className:"h-7 px-2 text-slate-600 hover:text-slate-900 hover:bg-slate-50",onClick:f,disabled:o,children:e.jsx(kt,{className:`h-3.5 w-3.5 ${o?"animate-spin":""} text-slate-500`})})]}),e.jsxs("div",{className:"space-y-3 max-h-[240px] overflow-y-auto pr-1",children:[a.map(u=>{const g=u.localStatus,w=g==="invalid"||g==="error",_=g==="checking"||g==="pending",E=g==="connected";return e.jsxs("div",{className:`
243                    rounded-lg border p-3 transition-all duration-200
244                    ${w?"border-red-200 bg-red-50":"border-slate-200 bg-white"}
245                  `,children:[e.jsxs("div",{className:"flex items-center justify-between mb-2 last:mb-0",children:[e.jsxs("div",{className:"flex flex-col flex-1 min-w-0 mr-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:`text-sm font-medium truncate ${w?"text-red-900":"text-slate-900"}`,children:u.display_name||u.shop_name}),_&&e.jsxs("span",{className:"relative flex h-2 w-2 shrink-0",children:[e.jsx("span",{className:"animate-ping absolute inline-flex h-full w-full rounded-full opacity-75",style:{backgroundColor:"#facc15"}}),e.jsx("span",{className:"relative inline-flex rounded-full h-2 w-2",style:{backgroundColor:"#facc15"}})]}),E&&e.jsx("span",{className:"h-2 w-2 shrink-0 rounded-full shadow-sm",style:{backgroundColor:"#22c55e"}}),w&&e.jsx("span",{className:"h-2 w-2 shrink-0 rounded-full shadow-sm",style:{backgroundColor:"#ef4444"}}),!_&&!E&&!w&&e.jsx("span",{className:"h-2 w-2 shrink-0 rounded-full",style:{backgroundColor:"#d4d4d8"}})]}),e.jsxs("span",{className:"text-[10px] text-slate-500 truncate",children:[u.shop_name,".myshopify.com"]})]}),!w&&e.jsx(be,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 text-slate-400 hover:text-red-500 hover:bg-red-50 shrink-0",onClick:()=>x(u),children:e.jsx(es,{className:"h-3.5 w-3.5"})})]}),w&&e.jsxs("div",{className:"mt-3 flex items-center gap-2 animate-in fade-in slide-in-from-top-1",children:[e.jsx(be,{size:"sm",variant:"default",className:"flex-1 bg-red-600 hover:bg-red-700 text-white shadow-sm disabled:opacity-70",onClick:()=>y(u),disabled:d===u.id,children:d===u.id?e.jsxs(e.Fragment,{children:[e.jsx(He,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}),"Connecting..."]}):"Reconnect"}),e.jsx(be,{size:"sm",variant:"outline",className:"flex-1 border-red-200 text-red-700 hover:bg-red-100 hover:text-red-800 hover:border-red-300",onClick:()=>x(u),disabled:d===u.id,children:"Remove"})]})]},u.id)}),a.length===0&&!o&&e.jsx("div",{className:"text-center py-6 border border-dashed border-slate-200 rounded-lg bg-slate-50/50",children:e.jsx("span",{className:"text-xs text-slate-500",children:"No stores connected"})})]}),e.jsx("div",{className:"pt-4 border-t border-slate-100",children:e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(bt,{placeholder:"SHOP_NAME",value:l,onCh
245ange:u=>c(u.target.value),className:"pr-20"}),e.jsx("span",{className:"absolute right-3 top-1/2 -translate-y-1/2 text-[10px] text-slate-400 pointer-events-none",children:".myshopify.com"})]}),e.jsx(be,{onClick:b,disabled:!l||h,children:h?e.jsxs(e.Fragment,{children:[e.jsx(He,{className:"h-4 w-4 mr-1 animate-spin"}),"Connecting..."]}):e.jsxs(e.Fragment,{children:[e.jsx($t,{className:"h-4 w-4 mr-1"}),"Connect"]})})]})})]})})]})}function AN({onStatusChange:t,fetchButtonText:s="Next"}){const{toast:a}=_t(),[n,o]=r.useState(""),[i,l]=r.useState(""),[c,d]=r.useState(!1),[m,h]=r.useState(!1),[p,f]=r.useState("idle"),[b,y]=r.useState(""),[x,u]=r.useState(null),[g,w]=r.useState("unknown"),_=v.useMemo(()=>{const R=x?.apiOrigin||wa.getUrl("VITE_ATTRIBUTION_BASE_ORIGIN")||"https://attribution.getu.ai";return`${String(R).replace(/\/$/,"")}/app/api-keys`},[x?.apiOrigin]);r.useEffect(()=>{(async()=>{try{const F=await Pl();F.exists&&(f("connected"),u({keyId:F.key_id,clientName:F.client_name,apiOrigin:F.api_origin}))}catch{}})()},[]),r.useEffect(()=>{if(p!=="connected")return;let F=!0;return(async()=>{try{w("unknown");const R=await C0();if(!F)return;w(R.ok?"valid":"invalid")}catch{if(!F)return;w("invalid")}})(),()=>{F=!1}},[p]),r.useEffect(()=>{t?.(p)},[p,t]);async function E(){if(!n.trim()){a({title:"API key required",description:"Please enter your Attribution API key"});return}const F=i.trim()||void 0;f("connecting"),y("");try{const R=await Pu(n.trim(),F);if(!R.ok){f("error"),y(R.detail||"Connection test failed"),a({title:"Attribution error",description:R.detail||"Connection test failed"});return}const L=await Tu(n.trim(),F);f("connected"),h(!1),o(""),u({keyId:L.key_id,clientName:L.client_name,apiOrigin:L.api_origin}),y("Connected successfully"),a({title:"Attribution connected",description:"Attribution integration successful"})}catch(R){f("error"),y(R?.message||"Failed to connect"),a({title:"Attribution error",description:R?.message||"Failed to connect"})}}function N(){o(""),l(x?.apiOrigin??""),d(!!x?.apiOrigin),y(""),h(!0)}function S(){o(""),l(""),d(!1),y(""),h(!1)}async function k(){try{await _0(),f("idle"),h(!1),y(""),u(null),o(""),l(""),a({title:"Attribution disconnected",description:"Attribution disconnected successfully"})}catch(F){a({title:"Attribution error",description:F?.message||"Failed to disconnect"})}}function D(){try{window.open(_,"_blank","noopener,noreferrer")}catch(F){a({title:"Failed to open Attribution",description:F?.message||"Please try again"})}}return e.jsxs(xs,{className:"rounded-2xl flex flex-col h-full shadow-sm hover:shadow-md transition-shadow duration-200",children:[e.jsx(Bs,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Xs,{children:"Attribution"}),e.jsx(Br,{children:"Connect your Attribution workspace to unlock analytics insights"})]}),e.jsx("div",{className:"text-xs",children:e.jsxs(ls,{variant:p==="connected"?"default":"secondary",children:[p==="idle"&&"UnConnected",p==="connecting"&&"Connecting",p==="connected"&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Rs,{className:"h-3 w-3"}),"Connected"]}),p==="error"&&"Error"]})})]})}),e.jsx(fs,{className:"flex flex-col flex-1 space-y-4",children:p==="connected"&&!m?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"rounded-lg border border-slate-200 p-3 bg-slate-50 flex-1",children:[e.jsx("div",{className:"text-sm font-medium text-slate-900 mb-2",children:"Connected Client"}),x?.clientName&&e.jsxs("div",{className:"text-sm text-slate-700 mb-1",children:[e.jsx("span",{className:"font-medium",children:"Client:"})," ",x.clientName]}),e.jsxs("div",{className:"text-xs text-slate-500 mb-1",children:[e.jsx("span",{className:"font-medium",children:"Key status:"})," ",g==="unknown"?"Checking...":g==="valid"?"Valid":"Invalid"]}),x?.apiOrigin&&e.jsxs("div",{className:"text-xs text-slate-500",children:[e.jsx("span",{className:"font-medium",children:"Origin:"})," ",e.jsx("span",{className:"font-mono",children:x.apiOrigin})]}),!x?.clientName&&!x?.keyId&&e.jsx("div",{className:"text-sm text-slate-600",children:"Attribution is connected"})]}),b&&e.jsx("div",{className:"text-xs text-slate-500",children:b}),e.jsxs("div",{className:"mt-auto pt-2 flex gap-2",children:[e.jsx(be,{className:"flex-1 rounded-xl",variant:"outline",onClick:N,children:"Update Credentials"}),e.jsx(be,{className:"flex-1 rounded-xl",variant:"outline",onClick:k,children:"Disconnect"})]})]}):e.jsx(e.Fragment,{children:e.jsxs("div",{className:"flex-1 flex flex-col",children:[!m&&e.jsx("div",{className:"rounded-lg border border-dashed border-slate-200 p-4 bg-slate-50/50 mb-3",children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsx("p",{className:"text-sm text-slate-700",children:"Connect your Attribution API key to view user journeys and traffic sources directly from Rankgale."}),e.jsx("button",{type:"button",className:"shrink-0 text-xs text-slate-600 underline underline-offset-4 hover:text-slate-900",onClick:D,title:"Open Attribution API keys page",children:"Get API key"})]})}),m&&e.jsx("div",{className:"rounded-lg border border-amber-200 p-3 bg-amber-50 mb
245-3 text-xs text-amber-700",children:"Enter a new API key to update your credentials. Leave API Origin empty to keep the current value."}),e.jsxs("div",{className:"mt-auto pt-2 space-y-2",children:[e.jsxs("div",{className:"flex gap-2 items-start",children:[e.jsx("div",{className:"flex-1",children:e.jsx(bt,{type:"password",placeholder:"getu_xxx (Attribution API Key)",value:n,onChange:F=>o(F.target.value),disabled:p==="connecting"})}),e.jsx(be,{onClick:E,disabled:!n.trim()||p==="connecting",className:"shrink-0",variant:"default",children:p==="connecting"?e.jsxs(e.Fragment,{children:[e.jsx(He,{className:"mr-2 h-4 w-4 animate-spin"}),"Connecting..."]}):m?"Update":s})]}),e.jsxs("div",{children:[e.jsx("button",{type:"button",className:"text-xs text-slate-400 hover:text-slate-600",onClick:()=>d(F=>!F),children:c?"Hide advanced":"Advanced"}),c&&e.jsxs("div",{className:"mt-2 space-y-1",children:[e.jsxs("div",{className:"text-xs font-medium text-slate-600",children:["API Origin"," ",e.jsx("span",{className:"font-normal text-slate-400",children:"(optional)"})]}),e.jsx(bt,{type:"url",placeholder:"https://attribution.getu.ai",value:i,onChange:F=>l(F.target.value),disabled:p==="connecting"}),e.jsx("p",{className:"text-xs text-slate-400",children:"Leave empty to use the default. Set only if you self-host Attribution."})]})]}),m&&e.jsx(be,{variant:"ghost",className:"w-full text-slate-500",onClick:S,disabled:p==="connecting",children:"Cancel"}),b&&e.jsx("div",{className:"text-xs text-slate-500",children:b})]})]})})})]})}const TN=[{target:'[data-onboarding="integration-intro"]',content:"Integration connects external services to Rankgale. Each integration unlocks specific features for SEO analysis, content publishing, or data synchronization.",placement:"bottom",disableBeacon:!0},{target:'[data-onboarding="gsc-integration-card"]',content:"Google Search Console integration enables real-time keyword ranking data, search performance metrics (clicks, impressions, CTR), and query-based keyword discovery. Authorization uses OAuth with read-only access.",placement:"right",disableBeacon:!0},{target:'[data-onboarding="webflow-integration-card"]',content:"Webflow CMS integration allows direct content publishing to your Webflow site. Requires a Webflow API key with appropriate permissions. Select the target site after authentication.",placement:"left",disableBeacon:!0},{target:'[data-onboarding="shopify-integration-card"]',content:"Shopify integration enables blog content publishing to your Shopify stores. Multiple stores can be connected simultaneously. OAuth authorization is required for each store.",placement:"right",disableBeacon:!0}];function PN({onClick:t}){return e.jsx("button",{onClick:t,className:"fixed bottom-5 right-5 z-50 h-8 w-8 rounded-full bg-white border border-slate-200 shadow-md hover:shadow-lg hover:bg-slate-50 transition-all hover:scale-105 hidden sm:flex items-center justify-center",title:"View navigation guide","aria-label":"View navigation guide",children:e.jsx(Hs,{className:"h-4 w-4 text-slate-600"})})}function IN(){const t=Zs(Us.integration),[s,a]=v.useState(!1);return v.useEffect(()=>{if(typeof window>"u")return;const n=window.matchMedia("(max-width: 767px)"),o=()=>a(n.matches);return o(),n.addEventListener("change",o),()=>n.removeEventListener("change",o)},[]),e.jsxs("div",{className:"p-4 md:p-6 max-w-5xl mx-auto space-y-6 overflow-auto md:overflow-visible max-h-[calc(100vh-56px)] md:max-h-none","data-onboarding":"integration-intro",children:[e.jsxs("div",{className:"hidden md:block",children:[e.jsx("h1",{className:"text-3xl font-bold tracking-tight",children:"Integration"}),e.jsx("p",{className:"text-slate-600 mt-2",children:"Connect your external services to unlock powerful features"})]}),e.jsxs("div",{className:"grid gap-6 md:grid-cols-2 items-stretch",children:[e.jsx("div",{"data-onboarding":"gsc-integration-card",className:"flex w-full self-stretch items-stretch [&>*]:w-full [&>*]:flex-1",children:e.jsx(EN,{})}),e.jsx("div",{"data-onboarding":"webflow-integration-card",className:"flex w-full self-stretch items-stretch [&>*]:w-full [&>*]:flex-1",children:e.jsx(vh,{})}),e.jsx("div",{"data-onboarding":"shopify-integration-card",className:"flex w-full self
245-stretch items-stretch [&>*]:w-full [&>*]:flex-1",children:e.jsx(Nh,{})}),e.jsx("div",{"data-onboarding":"attribution-integration-card",className:"flex w-full self-stretch items-stretch [&>*]:w-full [&>*]:flex-1",children:e.jsx(AN,{})})]}),e.jsx(PN,{onClick:t.startManual}),!s&&e.jsx(oa,{steps:TN,run:t.run,onComplete:t.stopAndMarkCompleted,onSkip:t.stopAndMarkCompleted})]})}function Xl(t){if(!t)return"-";let s=t.trim();return s.startsWith('"')&&s.endsWith('"')&&(s=s.slice(1,-1)),s}function MN(t){const s=t.map((n,o)=>Xl(n)||`node_${o}`),a=new Map;return s.map((n,o)=>{const i=(a.get(n)||0)+1;return a.set(n,i),i>1?`${n}_${o}`:n})}function RN({data:t,loading:s}){const[a,n]=v.useState(!1);v.useEffect(()=>{if(!a)return;const i=l=>{l.key==="Escape"&&n(!1)};return window.addEventListener("keydown",i),()=>window.removeEventListener("keydown",i)},[a]);const o=v.useMemo(()=>{const i=t?.nodes||[],l=t?.links||[];if(!i.length||!l.length)return{series:[]};const c=MN(i),d=l.filter(m=>typeof m.source=="number"&&typeof m.target=="number"&&m.source>=0&&m.target>=0&&m.source<c.length&&m.target<c.length&&m.value>0);return{tooltip:{trigger:"item",triggerOn:"mousemove",backgroundColor:"rgba(255, 255, 255, 0.95)",borderColor:"#e5e7eb",borderWidth:1,textStyle:{color:"#111827"},formatter:m=>{if(m?.dataType==="node"){const h=i[m.dataIndex];return`<div style="padding:8px;max-width:360px">
246              <div style="font-weight:600;margin-bottom:6px">URL</div>
247              <div style="font-size:12px;color:#374151;word-break:break-all;font-family:monospace">${Xl(h)}</div>
248            </div>`}return m?.dataType==="edge"?`<div style="padding:8px">
249              <div style="font-weight:600;margin-bottom:6px">Flow</div>
250              <div style="font-size:12px;color:#374151">${m.value.toLocaleString()} events</div>
251            </div>`:""}},series:[{type:"sankey",layout:"none",top:18,bottom:10,left:10,right:10,nodeWidth:18,nodeGap:10,draggable:!0,emphasis:{focus:"adjacency"},data:i.map((m,h)=>({name:c[h],value:Xl(m),itemStyle:{color:"#f59e0b",borderColor:"#ffffff",borderWidth:1},label:{show:a,fontSize:10,color:"#111827",backgroundColor:"rgba(255,255,255,0.95)",padding:[2,4,2,4],borderRadius:4,borderColor:"#e5e7eb",borderWidth:1,width:220,overflow:"break"}})),links:d.map(m=>({source:c[m.source],target:c[m.target],value:m.value,lineStyle:{opacity:.25,curveness:.5,color:"source"}}))}]}},[t,a]);return e.jsxs("div",{className:`rounded-2xl border border-slate-100 bg-white shadow-sm ${a?"fixed inset-0 z-[9999] rounded-none":"h-full flex flex-col"}`,children:[e.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b border-slate-100",children:[e.jsx("div",{className:"flex items-center gap-2 text-sm font-semibold text-slate-900",children:e.jsx("span",{children:"Journey Flow"})}),e.jsx("button",{className:"h-8 w-8 inline-flex items-center justify-center rounded-lg border border-slate-200 hover:bg-slate-50",onClick:()=>n(i=>!i),title:a?"Exit fullscreen (ESC)":"View fullscreen",children:a?e.jsx(mt,{size:16}):e.jsx(er,{size:16})})]}),e.jsx("div",{className:a?"h-[calc(100vh-52px)]":"h-[300px]",children:s?e.jsx("div",{className:"h-full flex items-center justify-center text-xs text-slate-500",children:"Loading journey flow..."}):t?.nodes?.length&&t?.links?.length?e.jsx(Cr,{option:o,style:{height:"100%",width:"100%"},opts:{renderer:"canvas"}}):e.jsx("div",{className:"h-full flex items-center justify-center text-xs text-slate-500",children:"No journey flow data available"})})]})}function Em({visible:t,onIntegrated:s,onCancel:a,apiKeysUrl:n,mode:o="connect",savedApiOrigin:i}){const{toast:l}=_t(),[c,d]=v.useState(""),[m,h]=v.useState(i??""),[p,f]=v.useState(o==="edit"&&!!i),[b,y]=v.useState(!1);v.useEffect(()=>{t&&(d(""),h(i??""),f(o==="edit"&&!!i))},[t,i,o]);const x=o==="edit",u=v.useCallback(async()=>{const w=c.trim();if(!w){l({title:"API key required",description:"Please enter your Attribution API key"});return}const _=m.trim()||void 0;y(!0);try{const E=await Pu(w,_);if(!E.ok){l({title:"Attribution error",description:E.detail||"Connection test failed"});return}await Tu(w,_),l({title:x?"Credentials updated":"Attribution connected",description:x?"Credentials updated successfully":"API key saved successfully"}),s(),x||window.location.reload()}catch(E){l({title:"Attribution error",description:E?.message||"Failed to connect"})}finally{y(!1)}},[c,m,x,s,l]),g=v.useCallback(()=>
251{if(!n){l({title:"Missing API keys URL",description:"Please contact support or check your configuration."});return}try{window.open(n,"_blank","noopener,noreferrer")}catch(w){l({title:"Failed to open Attribution",description:w?.message||"Please try again"})}},[n,l]);return t?e.jsx("div",{className:"absolute inset-0 z-[50] bg-slate-50/80 backdrop-blur-sm flex items-center justify-center p-6",children:e.jsxs(xs,{className:"w-full max-w-lg rounded-2xl shadow-lg border-slate-200",children:[e.jsx(Bs,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(Xs,{className:"flex items-center gap-2",children:[e.jsx(lu,{className:"h-5 w-5 text-slate-700"}),x?"Update Credentials":"Attribution Integration Required"]}),!x&&e.jsx(ls,{variant:"secondary",children:"Blocked"})]})}),e.jsxs(fs,{className:"space-y-4",children:[x?e.jsx("div",{className:"text-sm text-slate-700",children:"Enter a new API key to update your Attribution credentials."}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-sm text-slate-700",children:"To view this dashboard, please connect your Attribution API key."}),e.jsxs("div",{className:"rounded-lg border border-dashed border-slate-200 bg-slate-50 p-4 text-sm text-slate-700",children:[e.jsx("div",{className:"font-medium mb-1",children:"What you'll unlock"}),e.jsxs("ul",{className:"list-disc list-inside space-y-1 text-slate-600",children:[e.jsx("li",{children:"Daily events trend and revenue overview"}),e.jsx("li",{children:"Top UTM sources and campaigns"}),e.jsx("li",{children:"User journey Sankey visualization"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-xs font-medium text-slate-700",children:"API Key"}),e.jsx(bt,{type:"password",placeholder:"getu_xxx (Attribution API Key)",value:c,onChange:w=>d(w.target.value),disabled:b}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("button",{type:"button",className:"text-xs text-slate-600 underline underline-offset-4 hover:text-slate-900",onClick:g,disabled:!n,"aria-disabled":!n,title:"Open Attribution API keys page",children:"Get API key"}),e.jsx("button",{type:"button",className:"text-xs text-slate-400 hover:text-slate-600",onClick:()=>f(w=>!w),children:p?"Hide advanced":"Advanced"})]}),p&&e.jsxs("div",{className:"space-y-1 pt-1",children:[e.jsxs("div",{className:"text-xs font-medium text-slate-600",children:["API Origin"," ",e.jsx("span",{className:"font-normal text-slate-400",children:"(optional)"})]}),e.jsx(bt,{type:"url",placeholder:"https://attribution.getu.ai",value:m,onChange:w=>h(w.target.value),disabled:b}),e.jsx("p",{className:"text-xs text-slate-400",children:"Leave empty to use the default origin. Set this only if you self-host Attribution."})]})]}),e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[x&&a&&e.jsx(be,{variant:"ghost",onClick:a,disabled:b,children:"Cancel"}),e.jsx(be,{className:"bg-slate-900 hover:bg-slate-800",onClick:u,disabled:!c.trim()||b,children:b?e.jsxs(e.Fragment,{children:[e.jsx(He,{className:"mr-2 h-4 w-4 animate-spin"}),x?"Updating...":"Connecting..."]}):x?"Update":"Connect"})]})]})]})}):null}function DN(){const t=new Date().toISOString().slice(0,10);return{from:new Date(Date.now()-29*864e5).toISOString().slice(0,10),to:t}}function Ts(t){const s=Number(t);return Number.isFinite(s)?s:0}function Go(t){const s=String(t||"").trim();return!s||s.toLowerCase()==="unknown"?"organic":s}function Am(t){const s=String(t||"").trim();return s?s.toLowerCase()==="unknown"?"organic":s:"none"}const Tm=[{value:"all",label:"All Events"},{value:"page_view",label:"page view"},{value:"video_play",label:"video play"},{value:"form_submit",label:"form submit"},{value:"email_verification",label:"email verification"},{value:"login",label:"login"},{value:"signup",label:"signup"},{value:"product_view",label:"product view"},{value:"add_to_cart",label:"add to cart"},{value:"purchase",label:"purchase"},{value:"audit_approved",label:"audit approved"}];function Pm(t,s,a){if(!s.length)return;const n=i=>`"${String(i??"").replace(/"/g,'""')}"`,o=[s.join(","),...a.map(i=>i.map(n).join(","))].join(`
252`);ar({filename:t,content:o,mimeType:"text/csv;charset=utf-8;"})}function LN(){const{toast:t}=_t(),s=v.useRef(null),[a,n]=v.useState(void 0),o=v.useMemo(()=>{const M=a||wa.getUrl("VITE_ATTRIBUTION_BASE_ORIGIN")||"https://attribution.getu.ai";return String(M).replace(/\/$/,"")},[a]),i=v.useMemo(()=>`${o}/app/api-keys`,[o]),[l,c]=v.useState(()=>DN()),[d,m]=v.useState(!0),[h,p]=v.useState(!1),[f,b]=v.useState(!1),[y,x]=v.useState(!1),[u,g]=v.useState(!1),[w,_]=v.useState(!1),[E,N]=v.useState(!1),[S,k]=v.useState(!1),[D,F]=v.useState(null),[R,L]=v.useState([]),[$,H]=v.useState("all"),[K,X]=v.useState([]),[V,P]=v.useState([]),[A,C]=v.useState(null);v.useEffect(()=>{(async()=>{try{const M=await Pl();p(!!M.exists),M.api_origin&&n(M.api_origin)}catch{p(!1)}finally{m(!1)}})()},[]);const I=!!l.from&&!!l.to&&h,j=v.useCallback(async()=>{!l.from||!l.to||h&&(x(!0),S0({start_date:l.from,end_date:l.to}).then(M=>{F({totalEvents:Ts(M?.totalEvents),totalUsers:Ts(M?.totalUsers),totalRevenue:Ts(M?.totalRevenue),purchasesCount:Ts(M?.purchasesCount),avgOrderValue:Ts(M?.avgOrderValue)})}).catch(M=>{t({title:"Failed to load metrics",description:M?.message||"Please try again"})}).finally(()=>x(!1)),g(!0),E0({start_date:l.from,end_date:l.to,event_type:$==="all"?void 0:$}).then(M=>{L(Array.isArray(M)?M.map(Z=>({date:String(Z.date),value:Ts(Z.value)})):[])}).catch(M=>{t({title:"Failed to load events trend",description:M?.message||"Please try again"})}).finally(()=>g(!1)),N(!0),A0({start_date:l.from,end_date:l.to,limit:50}).then(M=>{X(Array.isArray(M)?M:[])}).catch(M=>{t({title:"Failed to load UTM sources",description:M?.message||"Please try again"})}).finally(()=>N(!1)),k(!0),T0({start_date:l.from,end_date:l.to,limit:50}).then(M=>{P(Array.isArray(M)?M:[])}).catch(M=>{t({title:"Failed to load UTM campaigns",description:M?.message||"Please try again"})}).finally(()=>k(!1)),_(!0),P0({start_date:l.from,end_date:l.to,max_urls:20}).then(M=>{C(M||null)}
252).catch(M=>{t({title:"Failed to load journey flow",description:M?.message||"Please try again"})}).finally(()=>_(!1)))},[l.from,l.to,h,$,t]);v.useEffect(()=>{I&&j()},[I,j]),v.useEffect(()=>{const M=()=>{try{s.current?.getEchartsInstance?.()?.resize?.()}catch{}},Z=window.setTimeout(M,0);return window.addEventListener("resize",M),()=>{window.clearTimeout(Z),window.removeEventListener("resize",M)}},[R.length]);const q=v.useMemo(()=>{const M=R.map(B=>B.date),Z=R.map(B=>B.value);return{tooltip:{trigger:"axis",backgroundColor:"rgba(255, 255, 255, 0.95)",borderColor:"#e5e7eb",borderWidth:1,textStyle:{color:"#111827"}},grid:{left:24,right:24,top:18,bottom:36,containLabel:!0},xAxis:{type:"category",data:M,boundaryGap:!1,axisLine:{show:!1},axisTick:{show:!1},axisLabel:{color:"#94a3b8",margin:12,hideOverlap:!0,formatter:B=>{const ae=String(B??""),de=ae.split("-");return de.length>=3&&de[1]&&de[2]?`${de[1]}/${de[2]}`:ae}}},yAxis:{type:"value",axisLine:{show:!1},axisTick:{show:!1},axisLabel:{color:"#94a3b8"},splitLine:{lineStyle:{color:"#f1f5f9"}}},series:[{name:"Events",type:"line",smooth:!0,symbol:"none",lineStyle:{color:"#2563eb",width:2},areaStyle:{color:{type:"linear",x:0,y:0,x2:0,y2:1,colorStops:[{offset:0,color:"rgba(37, 99, 235, 0.22)"},{offset:1,color:"rgba(37, 99, 235, 0)"}]}},data:Z}]}},[R]),T=D?Math.round(D.totalEvents/3):0;return d?e.jsx("div",{className:"h-full flex items-center justify-center text-sm text-slate-500",children:"Loading..."}):e.jsxs("div",{className:"relative p-6 max-w-6xl mx-auto space-y-6 pb-12",children:[e.jsx(Em,{visible:!h,apiKeysUrl:i,onIntegrated:()=>{p(!0)}}),e.jsx(Em,{visible:f,mode:"edit",savedApiOrigin:a,apiKeysUrl:i,onIntegrated:()=>{b(!1),Pl().then(M=>{M.api_origin&&n(M.api_origin),j()})},onCancel:()=>b(!1)}),e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-3xl font-bold tracking-tight",children:"Attribution"}),e.jsx("p",{className:"text-slate-600 mt-2",children:"Explore attribution metrics, traffic sources, and user journeys"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"min-w-[260px]",children:e.jsx(Sa,{value:l,onChange:c})}),h&&e.jsx(be,{variant:"outline",onClick:()=>b(!0),title:"Update API credentials",children:e.jsx(Jh,{className:"h-4 w-4"})}),e.jsx(be,{onClick:()=>{const M=`${o}/app/dashboard?tab=overview`;window.open(M,"_blank","noopener,noreferrer")},children:"Go to Attribution"})]})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-4",children:[e.jsxs("div",{className:"rounded-2xl border border-slate-100 bg-white p-5 shadow-sm",children:[e.jsx("div",{className:"text-xs font-semibold text-slate-500",children:"Total Page Views"}),e.jsx("div",{className:"mt-2 text-3xl font-bold text-slate-900",children:y?"—":(D?.totalEvents||0).toLocaleString()}),e.jsx("div",{className:"mt-1 text-xs text-slate-500",children:"page_view events in range"})]}),e.jsxs("div",{className:"rounded-2xl border border-slate-100 bg-white p-5 shadow-sm",children:[e.jsx("div",{className:"text-xs font-semibold text-slate-500",children:"Unique Users"}),e.jsx("div",{className:"mt-2 text-3xl font-bold text-slate-900",children:y?"—":(D?.totalUsers||0).toLocaleString()}),e.jsx("div",{className:"mt-1 text-xs text-slate-500",children:"By tracking_user_id"})]}),e.jsxs("div",{className:"rounded-2xl border border-slate-100 bg-white p-5 shadow-sm",children:[e.jsx("div",{className:"text-xs font-semibold text-slate-500",children:"Total Sessions"}),e.jsx("div",{className:"mt-2 text-3xl font-bold text-slate-900",children:y?"—":T.toLocaleString()}),e.jsx("div",{className:"mt-1 text-xs text-slate-500",children:"Estimated sessions"})]}),e.jsxs("div",{className:"rounded-2xl border border-slate-100 bg-white p-5 shadow-sm",children:[e.jsx("div",{className:"text-xs font-semibold text-slate-500",children:"Total Revenue"}),e.jsx("div",{className:"mt-2 text-3xl font-bold text-slate-900",children:y?"—":`$${(D?.totalRevenue||0).toLocaleString()}`}),e.jsx("div",{className:"mt-1 text-xs text-slate-500",children:"From purchase events"})]})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs("div",{className:"rounded-2xl border border-slate-100 bg-white shadow-sm",children:[e.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b border-slate-100",children:[e.jsx("div",{className:"text-sm font-semibold text-slate-900",children:"📈 Events Trend by Day"}),e.jsxs(nr,{value:$,onValueChange:H,className:"w-[140px]",size:"sm",children:[e.jsx(rr,{className:"w-[140px]",children:Tm.find(M=>M.value===$)?.label||"All Events"}),e.jsx(or,{align:"right",children:Tm.map(M=>e.jsx(_s,{value:M.value,children:M.label},M.value))})]})]}),e.jsx("div",{className:"h-[300px]",children:u?e.jsx("div",{className:"h-full flex items-center justify-center text-xs text-slate-500",children:"Loading events trend..."}):e.jsx(Cr,{ref:s,option:q,style:{height:"100%",width:"100%"},opts:{renderer:"canvas"}})})]}),e.jsx(RN,{data:A,loading:w})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs("div",{className:"rounded-2xl border border-slate-100 bg-white shadow-sm overflow-hidden",children:[e.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b border-slate-100",children:[e.jsx("div",{className:"text-sm font-semibold text-slate-900",children:"📊 Top UTM Sources"}),e.jsxs("button",{className:"inline-flex items-center gap-1 rounded-lg border border-slate-200 bg-white px-2.5 py-1.5 text-xs font-medium text-slate-700 hover:bg-slate-50 disabled:opacity-50",onClick:()=>{const M=l.from||"start",Z=l.to||"end";Pm(`utm_sources_${M}_to_${Z}.csv`,["utm_source","events","users","revenue","share"],K.map(B=>[Go(B.source),Ts(B.events),Ts(B.users),Ts(B.revenue),`${Ts(B.share)}%`]))},disabled:K.length===0,title:"Export CSV",children:[e.jsx(Vs,{className:"h-4 w-4"}),"CSV"]})]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-slate-50 text-xs text-slate-500",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left px-4 py-3",children:"utm_source"}),e.jsx("th",{className:"text-right px-4 py-3",children:"Events"}),e.jsx("th",{className:"text-right px-4 py-3",children:"Users"}),e.jsx("th",{className:"text-right px-4 py-3",children:"Revenue"}),e.jsx("th",{className:"text-right px-4 py-3",children:"Share"})]})}),e.jsxs("tbody",{children:[K.map((M,Z)=>e.jsxs("tr",{className:"border-t border-slate-100",children:[e.jsx("td",{className:"px-4 py-3",children:e.jsx("span",{className:"inline-flex items-center rounded-md bg-slate-100 px-2 py-1 text-xs font-medium text-slate-700",children:Go(M.source)})}),e.jsx("td",{className:"px-4 py-3 text-right",children:Ts(M.events).toLocaleStr
252ing()}),e.jsx("td",{className:"px-4 py-3 text-right",children:Ts(M.users).toLocaleString()}),e.jsxs("td",{className:"px-4 py-3 text-right",children:["$",Ts(M.revenue).toLocaleString()]}),e.jsxs("td",{className:"px-4 py-3 text-right",children:[Ts(M.share),"%"]})]},Z)),!K.length&&e.jsx("tr",{children:e.jsx("td",{className:"px-4 py-6 text-center text-slate-500",colSpan:5,children:E?"Loading...":"No data available"})})]})]})})]}),e.jsxs("div",{className:"rounded-2xl border border-slate-100 bg-white shadow-sm overflow-hidden",children:[e.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b border-slate-100",children:[e.jsx("div",{className:"text-sm font-semibold text-slate-900",children:"📊 Top UTM Campaigns"}),e.jsxs("button",{className:"inline-flex items-center gap-1 rounded-lg border border-slate-200 bg-white px-2.5 py-1.5 text-xs font-medium text-slate-700 hover:bg-slate-50 disabled:opacity-50",onClick:()=>{const M=l.from||"start",Z=l.to||"end";Pm(`utm_campaigns_${M}_to_${Z}.csv`,["utm_campaign","utm_source","events","revenue"],V.map(B=>[Am(B.campaign),Go(B.utm_source),Ts(B.events),Ts(B.revenue)]))},disabled:V.length===0,title:"Export CSV",children:[e.jsx(Vs,{className:"h-4 w-4"}),"CSV"]})]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-slate-50 text-xs text-slate-500",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left px-4 py-3",children:"utm_campaign"}),e.jsx("th",{className:"text-left px-4 py-3",children:"utm_source"}),e.jsx("th",{className:"text-right px-4 py-3",children:"Events"}),e.jsx("th",{className:"text-right px-4 py-3",children:"Revenue"})]})}),e.jsxs("tbody",{children:[V.map((M,Z)=>e.jsxs("tr",{className:"border-t border-slate-100",children:[e.jsx("td",{className:"px-4 py-3 font-mono text-xs text-slate-800",children:Am(M.campaign)}),e.jsx("td",{className:"px-4 py-3",children:e.jsx("span",{className:"inline-flex items-center rounded-md bg-slate-100 px-2 py-1 text-xs font-medium text-slate-700",children:Go(M.utm_source)})}),e.jsx("td",{className:"px-4 py-3 text-right",children:Ts(M.events).toLocaleString()}),e.jsxs("td",{className:"px-4 py-3 text-right",children:["$",Ts(M.revenue).toLocaleString()]})]},Z)),!V.length&&e.jsx("tr",{children:e.jsx("td",{className:"px-4 py-6 text-center text-slate-500",colSpan:4,children:S?"Loading...":"No data available"})})]})]})})]})]})]})}const zN=[{target:'[data-onboarding="keywords-tracking-intro"]',content:"Keywords Tracking monitors your keyword rankings across search engines. Track position changes over time to evaluate SEO performance and identify ranking trends.",placement:"bottom",disableBeacon:!0},{target:'[data-onboarding="add-keywords-button"]',content:"Add keywords to track. Import from your target keywords list, select from keyword groups, or enter keywords manually.",placement:"bottom",disableBeacon:!0},{target:'[data-onboarding="date-range-picker"]',content:"Select a date range to view ranking history. Data is organized by week for trend analysis.",placement:"bottom",disableBeacon:!0},{target:'[data-onboarding="keywords-rankings-table"]',content:"The rankings table shows position data for each period. Green indicates improvement, red indicates decline. Click a keyword row to view detailed insights.",placement:"top",disableBeacon:!0,spotlightClicks:!1,styles:{spotlight:{pointerEvents:"none"}}},{target:'[data-onboarding="refresh-rankings-button"]',content:"Refresh rankings to fetch the latest position data from search engines. This consumes credits based on the number of keywords tracked.",placement:"bottom",disableBeacon:!0}];function Ql({layoutMode:t,selectedKeywords:s,selectedCount:a,estimatedCredits:n,estimatedCreditsRange:o,isExisting:i,getItemTitle:l,onClearAll:c,onRemoveKeyword:d,onCancel:m,onConfirm:h,confirmDisabled:p,confirmLabel:f="Add",cancelLabel:b="Cancel",emptyText:y="Select keywords from the table to see them here."}){const x=t==="split",u=o??(typeof n=="number"?{min:n,max:n}:null),g=u===null?null:u.min===u.max?`${u.max}`:`${u.min}-${u.max}`,w=x?"h-full min-h-0 flex flex-col bg-white gap-3":"flex-shrink-0 bg-white pt-3 z-50",_=x?"border border-slate-200 rounded-xl bg-slate-50 p-3 flex-1 min-h-0 overflow-hidden flex flex-col":"border border-slate-200 rounded-xl bg-slate-50 p-3 mb-3 max-h-[120px] overflow-y-auto",E=x?"flex-1 min-h-0 overflow-y-auto":"",N=x?"mb-2":"mb-2 sticky top-0 bg-white",S=x?"pt-3 border-t border-slate-200 bg-white":"",k=(s||[]).map(D=>
252String(D||"").trim()).filter(Boolean);return e.jsxs("div",{className:w,children:[e.jsxs("div",{className:_,children:[e.jsx("div",{className:N,children:x?e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"text-sm font-medium text-slate-800",children:["Selected Keywords (",a,")"]}),g!==null&&a>0&&e.jsxs("div",{className:"mt-0.5 text-xs text-slate-600",children:["Estimated cost:"," ",e.jsxs("span",{className:"font-bold text-blue-700",children:[g," credits"]})]})]}),e.jsx("button",{type:"button",className:"flex-shrink-0 text-xs text-slate-600 hover:text-slate-900 disabled:text-slate-300",disabled:k.length===0,onClick:c,children:"Clear all"})]}):e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("span",{className:"text-sm font-medium text-slate-800",children:["Selected Keywords (",a,")"]}),g!==null&&a>0&&e.jsxs("span",{className:"text text-slate-600",children:["Estimated cost:"," ",e.jsxs("span",{className:"font-bold text-blue-700",children:[g," credits"]})]})]}),e.jsx("button",{type:"button",className:"text-xs text-slate-600 hover:text-slate-900 disabled:text-slate-300",disabled:k.length===0,onClick:c,children:"Clear all"})]})}),e.jsx("div",{className:E,children:k.length===0?e.jsx("div",{className:"text-xs text-slate-500",children:y}):e.jsx("div",{className:"flex flex-wrap gap-2",children:k.map(D=>{const F=i?i(D):!1;return e.jsxs("div",{className:F?"flex items-center gap-2 px-2 py-1 rounded-lg bg-slate-100 border border-slate-200 opacity-70":"flex items-center gap-2 px-2 py-1 rounded-lg bg-white border border-slate-200",title:l?l(D):void 0,children:[e.jsx("span",{className:F?"text-xs font-medium text-slate-500 max-w-[220px] truncate line-through":"text-xs font-medium text-slate-800 max-w-[220px] truncate",children:D}),!F&&d?e.jsx("button",{type:"button",className:"text-xs text-slate-400 hover:text-slate-700",onClick:()=>d(D),children:"×"}):null,F?e.jsx("span",{className:"text-[10px] text-slate-400",children:"exists"}):null]},`selected-${D.toLowerCase()}`)})})})]}),e.jsx("div",{className:S,children:e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsx("div",{className:"text-sm text-slate-600 min-w-[160px]",children:a>0&&e.jsxs("span",{children:[a," keyword(s) selected"]})}),e.jsxs("div",{className:"flex flex-wrap gap-2 justify-end",children:[e.jsx("button",{onClick:m,className:"px-4 py-2 text-sm font-medium text-slate-700 hover:bg-slate-100 rounded-md transition-colors",children:b}),e.jsxs("button",{onClick:h,disabled:p,className:"px-4 py-2 text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 disabled:bg-slate-300 disabled:cursor-not-allowed rounded-md transition-colors",children:[f," ",a>0?`(${a})`:""]})]})]})})]})}const Wo=t=>(t||"").trim().toLowerCase();function $N({onKeywordsSelected:t,onCancel:s,existingKeywords:a=new Set,userDomain:n,getEstimatedCreditsForSelection:o,creditEstimate:i,layoutMode:l="stacked",skipConfirmation:c=!1}){const{toast:d}=_t(),{confirm:m}=ia(),[h,p]=r.useState([]),[f,b]=r.useState(!1),[y,x]=r.useState([]),[u,g]=r.useState({});r.useEffect(()=>{(async()=>{b(!0);try{const V=await Tn();p(V.details||[])}catch(V){console.error("Failed to load competitors:",V),d({title:"Failed to load competitors",description:V.message})}finally{b(!1)}})()},[]),r.useEffect(()=>{(async()=>{try{const P=(await Or()).top_keywords||[],A={};P.forEach(C=>{A[C.keyword]=C.landing_page||null}),g(A)}catch(V){console.error("Failed to load top keywords:",V)}})()},[]);const w=X=>{x(X)},_=r.useMemo(()=>y.filter(X=>!a.has(Wo(X))),[y,a]),E=r.useMemo(()=>{if(i||!o)return null;try{return o(_.length)}catch(X){return console.warn("⚠️ Failed to estimate credits:",X),null}},[i,o,_.length]),N=i?.keywordCountParamKey||"keyword_count",S=r.useMemo(()=>i?{...i.params||{},[N]:_.length}:{},[i,N,_.length]),{estimatedRange:k}=ta({enabled:!!i&&_.length>0,scenario:i?.scenario||"keywords_tracking_refresh_keywords",params:S,debounceMs:i?.debounceMs}),D=()=>{x([])},F=()=>y.filter(X=>!a.has(Wo(X))).map(X=>
252({keyword:X,landing_page:u[X]||null})),R=async()=>{if(y.length===0){d({title:"Please select keywords from the table"});return}const X=F();if(X.length===0){d({title:"No new keywords",description:"All selected keywords are already tracked"});return}if(c){t(X);return}const V=X.length,P=k===null&&E===null?"":k!==null?e.jsxs(e.Fragment,{children:[" ","Estimated cost:"," ",e.jsx("span",{className:"font-bold text-blue-700",children:k.min===k.max?`${k.max} credits`:`${k.min}-${k.max} credits`}),"."]}):e.jsxs(e.Fragment,{children:[" ","Estimated cost:"," ",e.jsxs("span",{className:"font-bold text-blue-700",children:[E," credits"]}),"."]}),A=e.jsxs(e.Fragment,{children:["You are about to add ",V," keyword(s). This will trigger a refresh and may deduct credits.",P," Actual cost may be lower due to cache."]});await m({title:"Confirm adding keywords?",message:A,confirmText:"Confirm & Add",cancelText:"Cancel",variant:"info"})&&t(X)},L=()=>_.length,$=X=>{x(V=>V.filter(P=>P!==X))},H=l==="split";if(f)return e.jsx("div",{className:"flex-1 min-h-[240px] flex items-center justify-center",children:e.jsxs("div",{className:"flex items-center gap-2 text-slate-600",children:[e.jsx(He,{className:"w-4 h-4 animate-spin"}),e.jsx("span",{children:"Loading competitors..."})]})});const K=L();return e.jsxs("div",{className:H?"flex flex-col md:flex-row h-full min-h-0":"flex flex-col h-full min-h-0",children:[e.jsx("div",{className:H?"flex-[3] basis-0 min-w-0 min-h-0 overflow-hidden pt-3 pr-3":"flex-1 min-h-0 overflow-hidden",children:e.jsx(Gi,{competitors:h,userDomain:n,selectedKeywords:y,onSelectedKeywordsChange:w})}),H?e.jsx("div",{className:"flex-[1] basis-0 min-w-0 min-h-0 overflow-hidden bg-white border-t md:border-t-0 md:border-l border-slate-200 p-3",children:e.jsx(Ql,{layoutMode:"split",selectedKeywords:y,selectedCount:K,estimatedCredits:E,estimatedCreditsRange:i?k:null,isExisting:X=>a.has(Wo(X)),getItemTitle:X=>u[X]||void 0,onClearAll:D,onRemoveKeyword:$,onCancel:s,onConfirm:()=>{R()},confirmDisabled:K===0,emptyText:"Select keywords from the table to see them here."})}):e.jsx(Ql,{layoutMode:"stacked",selectedKeywords:y,selectedCount:K,estimatedCredits:E,estimatedCreditsRange:i?k:null,isExisting:X=>a.has(Wo(X)),getItemTitle:X=>u[X]||void 0,onClearAll:D,onRemoveKeyword:$,onCancel:s,onConfirm:()=>{R()},confirmDisabled:K===0,emptyText:"Select keywords from the table to see them here."})]})}function Kc({isOpen:t,title:s,description:a,existingKeywords:n=new Set,isProcessing:o=!1,processingText:i="Processing...",closeOnOutside:l,onClose:c,onConfirm:d,getEstimatedCreditsForSelection:m,creditEstimate:h,skipConfirmation:p=!1}){return e.jsx(Ht,{open:t,onOpenChange:b=>!b&&c(),children:e.jsxs(qt,{className:"w-[96vw] max-w-[96vw] h-[90vh] max-h-[90vh] flex flex-col gap-0 overflow-hidden p-0",closeOnOutside:l,children:[e.jsxs(Zt,{variant:"full",density:"sm",divider:!0,children:[e.jsx(Yt,{className:"text-sm font-medium text-slate-800",children:s}),a?e.jsx(Ds,{className:"text-xs text-slate-500",children:a}):null]}),e.jsx("div",{className:"flex-1 min-h-0 overflow-hidden",children:e.jsx($N,{onKeywordsSelected:d,onCancel:c,existingKeywords:n,getEstimatedCreditsForSelection:m,creditEstimate:h,layoutMode:"split",skipConfirmation:p})}),o&&e.jsx("div",{className:"flex items-center justify-end px-5 py-3 border-t border-slate-200 bg-white flex-shrink-0",children:e.jsx("div",{className:"flex items-center gap-2 text-sm text-slate-600",children:e.jsx("span",{children:i})})})]})})}const kh=({checked:t=!1,onCheckedChange:s,className:a="",disabled:n,...o})=>{const[i,l]=v.useState(t);return v.useEffect(()=>{l(t)},[t]),e.jsx("button",{role:"switch","aria-checked":i,disabled:n,className:`relative inline-flex h-5 w-9 items-center rounded-full border border-slate-300 transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-slate-400 focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 
253        ${i?"bg-slate-900 border-slate-900":"bg-gray-200"} 
254        ${a}`,onClick:c=>{if(n)return;const d=!i;l(d),s?.(d),o.onClick?.(c)},...o,children:e.jsx("span",{className:`pointer-events-none block h-3.5 w-3.5 rounded-full bg-white shadow-lg ring-0 transition-transform ${i?"translate-x-4":"translate-x-0.5"} ${i?"":"bg-slate-500"}`})})};function Im(t){return t?t.min===t.max?`${t.max}`:`${t.min}-${t.max}`:"—"}function Mm(t){const[s,a]=v.useState(!1),n=async()=>{a(!1),await t.onSync()};return e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(kh,{checked:t.enabled,onCheckedChange:t.onToggle,disabled:t.disabled,id:"auto-refresh-switch",className:"scale-90"}),e.jsx("label",{htmlFor:"auto-refresh-switch",className:"text-xs font-medium text-slate-600 cursor-pointer select-none whitespace-nowrap",children:"Auto refresh"})]}),e.jsxs("div",{className:"hidden sm:flex items-center gap-1 text-xs text-slate-500 
254whitespace-nowrap",children:[e.jsx(vs,{className:"w-3 h-3 text-amber-500"}),e.jsx("span",{children:t.estimatingCredits?"Estimating...":`${Im(t.estimatedCreditsRange)} credits`})]}),e.jsxs(be,{variant:"outline",size:"sm",className:"gap-1.5 whitespace-nowrap h-8",onClick:()=>a(!0),disabled:t.disabled||t.isSyncing,children:[e.jsx(kt,{className:`w-3.5 h-3.5 ${t.isSyncing?"animate-spin":""}`}),"Refresh"]}),e.jsx(Ht,{open:s,onOpenChange:a,children:e.jsxs(qt,{className:"sm:max-w-md",children:[e.jsxs(Zt,{children:[e.jsxs(Yt,{className:"flex items-center gap-2",children:[e.jsx(kt,{className:"w-4 h-4 text-slate-500"}),"Refresh keywords rankings"]}),e.jsx(Ds,{children:"Refreshing will fetch the latest ranking data for all your keywords."})]}),e.jsx("div",{className:"space-y-4",children:e.jsxs("div",{className:"flex items-start gap-3 p-4 bg-amber-50 border border-amber-200 rounded-lg",children:[e.jsx(vs,{className:"w-5 h-5 text-amber-600 flex-shrink-0 mt-0.5"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-amber-800",children:"This action will consume credits"}),e.jsxs("p",{className:"text-sm text-amber-700 mt-1",children:["Estimated cost:"," ",e.jsx("strong",{children:t.estimatingCredits?"Estimating...":`${Im(t.estimatedCreditsRange)} credits`})," ","for ",e.jsx("strong",{children:t.keywordCount})," keywords",t.marketsCount&&t.marketsCount>1?e.jsxs(e.Fragment,{children:[" ","across ",e.jsx("strong",{children:t.marketsCount})," markets"]}):null]})]})]})}),e.jsxs(Ns,{children:[e.jsx(be,{variant:"outline",onClick:()=>a(!1),disabled:t.isSyncing,children:"Cancel"}),e.jsx(be,{onClick:n,disabled:t.isSyncing,className:"gap-2",children:t.isSyncing?e.jsxs(e.Fragment,{children:[e.jsx(kt,{className:"w-4 h-4 animate-spin"}),"Refreshing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(vs,{className:"w-4 h-4"}),"Refresh Now"]})})]})]})})]})}const bl=t=>String(Math.max(0,Math.floor(t))).padStart(2,"0"),FN=t=>{const s=Math.max(0,Math.floor(t)),a=Math.floor(s/3600),n=Math.floor(s%3600/60),o=s%60;return a>0?`${a}:${bl(n)}:${bl(o)}`:`${n}:${bl(o)}`};function ON(t){const[s,a]=v.useState(()=>Date.now());if(v.useEffect(()=>{if(t.state.phase!=="running")return;const p=window.setInterval(()=>a(Date.now()),1e3);return()=>window.clearInterval(p)},[t.state.phase]),t.state.phase==="idle")return null;const n=t.state.startedAtMs||s,o=(s-n)/1e3,i=FN(o),l=t.state.etaText||"10-30s",c=t.state.progress,d=c?.percentage??0,m=t.state.phase==="running"?e.jsx(kt,{className:"w-4 h-4 text-slate-500 animate-spin"}):t.state.phase==="completed"?e.jsx(Rs,{className:"w-4 h-4 text-emerald-600"}):e.jsx(Ja,{className:"w-4 h-4 text-amber-600"}),h=t.state.phase==="running"?"Syncing in background":t.state.phase==="completed"?"Sync completed":t.state.phase==="timeout"?"Sync timeout":"Sync finished";return e.jsx("div",{className:"w-full bg-white border border-slate-200 rounded-lg px-3 py-2 shadow-sm",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-[170px]",children:[m,e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[11px] font-semibold text-slate-800 truncate",children:h}),e.jsx("div",{className:"text-[10px] text-slate-500 truncate",children:t.state.message||" "})]})]}),e.jsx("div",{className:"flex-1 min-w-[160px]",children:e.jsx("div",{className:"w-full bg-slate-200 rounded-full h-2 overflow-hidden",children:e.jsx("div",{className:"h-full bg-blue-600 transition-all duration-300 ease-out rounded-full",style:{width:`${d}%`}})})}),e.jsxs("div",{className:"flex items-center gap-3 text-[10px] text-slate-500 flex-shrink-0",children:[e.jsxs("span",{className:"whitespace-nowrap",children:["Est. ",e.jsx("span",{className:"font-medium text-slate-700",children:l})]}),e.jsx("span",{className:"whitespace-nowrap",children:c&&c.total>0?`${c.completed}/${c.total} (${d}%)`:`${d}%`}),e.jsxs("span",{className:"flex items-center gap-1 whitespace-nowrap",children:[e.jsx(Ra,{className:"w-3.5 h-3.5 text-slate-400"}),i]})]})]})})}const BN=1e3,UN=(t,s)=>{const a=Array.isArray(t)?t:[],n=Math.max(1,Math.floor(s)),o=[];for(let i=0;i<a.length;i+=n)o.push(a.slice(i,i+n));return o};function KN(t){const s=v.useRef(null),[a,n]=v.useState({phase:"idle",startedAtMs:null,etaText:null,progress:null,message:""}),o=v.useCallback(()=>{s.current&&(window.clearTimeout(s.current),s.current=null)},[]),i=v.useCallback(d=>{n(d),s.current&&window.clearTimeout(s.current),s.current=window.setTimeout(()=>{n({phase:"idle",startedAtMs:null,etaText:null,progress:null,message:""})},4e3)},[]),l=v.useCallback(async d=>{const m=Array.isArray(d.keywordList)?d.keywordList:[],h=Array.from(new Set(m.map(f=>
254String(f||"").trim()).filter(Boolean)));if(h.length===0){t.toast({title:"No keywords to sync",description:"Please add keywords first"});return}if(a.phase==="running"){t.toast({title:"Sync already running",description:"Please wait for the current sync to finish"});return}const p=Date.now();n({phase:"running",startedAtMs:p,etaText:d.etaText||null,progress:{completed:0,total:h.length,percentage:0},message:"Refreshing keywords..."});try{const f=UN(h,BN),b=h.length;let y=0;for(let x=0;x<f.length;x++){const u=f[x];n(g=>({...g,phase:"running",startedAtMs:p,etaText:d.etaText||g.etaText||null,progress:{completed:y,total:b,percentage:b>0?Math.round(y/b*100):0},message:`Refreshing... ${y}/${b} (${x+1}/${f.length} batches)`})),await $w({keywords:u}),y+=u.length}n(x=>({...x,phase:"running",startedAtMs:p,progress:{completed:y,total:b,percentage:b>0?100:0},message:"Refreshing completed, updating table..."}));try{await t.onCompleted()}catch(x){console.warn("⚠️ Failed to refresh after ranked_keywords:",x)}t.toast({title:"Refresh completed successfully"}),i({phase:"completed",startedAtMs:p,etaText:d.etaText||null,progress:{completed:y,total:b,percentage:b>0?100:0},message:"Refresh completed"})}catch(f){console.error("❌ Failed to start sync:",f),i({phase:"error",startedAtMs:p,etaText:d.etaText||null,progress:null,message:"Failed to refresh keywords",errorMessage:f?.message||"Failed to refresh keywords"}),t.toast({title:"Failed to refresh keywords",description:f?.message||"Unknown error"})}},[i,a.phase,t]),c=v.useCallback(async d=>{},[]);return v.useEffect(()=>()=>{o()},[o]),{panel:a,isRunning:a.phase==="running",startSync:l,resumeOrDetect:c}}const Rm=t=>t==null||!Number.isFinite(t)?"-":new Intl.NumberFormat("en-US").format(t),wl=t=>t==null||!Number.isFinite(t)?"-":String(t),Dm=t=>{if(!t)return"-";try{return new Date(t).toLocaleDateString("en-US")}catch{return String(t)}},GN=t=>{if(!t||t.length===0)return null;try{return[...t].sort((a,n)=>new Date(n.snapshot_date).getTime()-new Date(a.snapshot_date).getTime())[0]||null}catch{return t[t.length-1]||null}};function WN(t){const{toast:s}=_t(),a=r.useMemo(()=>GN(t.history),[t.history]),n=r.useMemo(()=>[...Array.isArray(t.history)?t.history:[]].sort((D,F)=>new Date(F.snapshot_date).getTime()-new Date(D.snapshot_date).getTime()).slice(0,20),[t.history]),o=a?.rank??null,[i,l]=v.useState(null),[c,d]=v.useState(!1),[m,h]=v.useState(null);v.useEffect(()=>{if(!t.open||!t.keyword)return;let S=!1;return(async()=>{d(!0),h(null);try{const D=await Fw({keyword:t.keyword});if(S)return;l(D)}catch(D){if(S)return;
254console.error("❌ Failed to load keyword detail:",D);const F=D?.message||"Failed to load keyword detail";h(F),s({title:"Failed to load keyword detail",description:F})}finally{S||d(!1)}})(),()=>{S=!0}},[t.open,t.keyword,s]);const p=i?.item?.keyword_data?.keyword_info||null,f=i?.item?.ranked_serp_element?.serp_item||null,b=f?.rank_absolute??o,y=i?.snapshot_date??a?.snapshot_date,x=p?.search_volume??null,u=(p?.cpc??null)?.toFixed(2)??null,g=p?.competition_level??null,w=f?.url??null,_=f?.title??null,E=f?.rank_absolute??null,N=r.useMemo(()=>{const S=p?.monthly_searches||[];return[...Array.isArray(S)?S:[]].sort((F,R)=>{const L=Number(F?.year||0),$=Number(R?.year||0),H=Number(F?.month||0),K=Number(R?.month||0);return L!==$?$-L:K-H}).slice(0,24)},[p?.monthly_searches]);return e.jsx(Ht,{open:t.open,onOpenChange:t.onOpenChange,children:e.jsxs(qt,{className:"sm:max-w-3xl",children:[e.jsxs(Zt,{children:[e.jsxs(Yt,{className:"flex items-center gap-2",children:[e.jsx(Ma,{className:"w-4 h-4 text-slate-500"}),"Keyword insights"]}),e.jsxs(Ds,{children:["Keyword: ",e.jsx("span",{className:"font-medium",children:t.keyword})," • Latest rank: ",wl(b)," • Latest snapshot:"," ",Dm(y)]})]}),m?e.jsxs("div",{className:"flex items-start gap-3 p-4 bg-red-50 border border-red-200 rounded-lg",children:[e.jsx(qr,{className:"w-5 h-5 text-red-600 flex-shrink-0 mt-0.5"}),e.jsxs("div",{className:"text-sm text-red-800",children:[e.jsx("div",{className:"font-medium",children:"Failed to load detail"}),e.jsx("div",{className:"mt-1 text-red-700",children:m})]})]}):c?e.jsxs("div",{className:"flex items-start gap-3 p-4 bg-slate-50 border border-slate-200 rounded-lg",children:[e.jsx(qr,{className:"w-5 h-5 text-slate-500 flex-shrink-0 mt-0.5"}),e.jsxs("div",{className:"text-sm text-slate-700",children:[e.jsx("div",{className:"font-medium",children:"Loading keyword detail..."}),e.jsx("div",{className:"mt-1 text-slate-600",children:"Fetching full metrics from saved DataForSEO payload."})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"border border-slate-200 rounded-xl p-3 bg-white",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Sn,{className:"w-4 h-4 text-slate-400"}),e.jsx("div",{className:"text-[10px] text-slate-400 uppercase tracking-wider",children:"Search volume"})]}),e.jsx("div",{className:"mt-1 text-lg font-semibold text-slate-900 tabular-nums",children:Rm(x)})]}),e.jsxs("div",{className:"border border-slate-200 rounded-xl p-3 bg-white",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(vs,{className:"w-4 h-4 text-slate-400"}),e.jsx("div",{className:"text-[10px] text-slate-400 uppercase tracking-wider",children:"CPC"})]}),e.jsxs("div",{className:"mt-1 text-lg font-semibold text-slate-900 tabular-nums",children:[u==null?"-":`$${u}`,e.jsx("span",{className:"ml-1 text-[11px] text-slate-500",children:g?`Competition: ${g}`:" "})]})]}),e.jsxs("div",{className:"border border-slate-200 rounded-xl p-3 bg-white",children:[e.jsx("div",{className:"text-[10px] text-slate-400 uppercase tracking-wider",children:"Rank"}),e.jsx("div",{className:"mt-1 text-lg font-semibold text-slate-900 tabular-nums",children:E!=null?wl(E):"-"})]})]}),e.jsx("div",{className:"mt-3",children:e.jsxs("div",{className:"border border-slate-200 rounded-xl p-3 bg-white",children:[e.jsx("div",{className:"text-[10px] text-slate-400 uppercase tracking-wider",children:"Landing page"}),e.jsx("div",{className:"mt-2",children:w?e.jsxs("a",{href:w,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1 text-sm text-blue-600 hover:text-blue-800 hover:underline max-w-full truncate",title:w,children:[e.jsx(ns,{className:"w-4 h-4"}),e.jsx("span",{className:"truncate",children:_||w})]}):e.jsx("span",{className:"text-sm text-slate-400",children:"-"})}),e.jsx("div",{className:"mt-1 text-[11px] text-slate-500 truncate",children:_?w:" "})]})}),e.jsxs("div",{className:"mt-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("div",{className:"text-sm font-semibold text-slate-800",children:"Monthly search volume"}),e.jsxs(ls,{variant:"secondary",className:"bg-slate-100 text-slate-700",children:["Last ",N.length]})]}),N.length===0?e.jsxs("div",{className:"flex items-start gap-3 p-4 bg-slate-50 border border-slate-200 rounded-lg",children:[e.jsx(qr,{className:"w-5 h-5 text-slate-500 flex-shrink-0 mt-0.5"}),e.jsxs("div",{className:"text-sm text-slate-700",children:[e.jsx("div",{className:"font-medium",children:"No monthly volume data"}),e.jsx("div",{className:"mt-1 text-slate-600",children:"The saved payload does not include monthly_searches for this keyword."})]})]}):e.jsx("div",{className:"border border-slate-200 rounded-xl overflow-hidden",children:e.jsx("div",{className:"max-h-[240px] overflow-auto",children:e.jsxs("table",{className:"min-w-full text-sm",children:[e.jsx("thead",{className:"text-left text-slate-600 bg-slate-50 border-b border-slate-200 sticky top-0 z-10",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-4 py-2.5 font-semibold",children:"Year"}),e.jsx("th",{className:"px-4 py-2.5 font-semibold",children:"Month"}),e.jsx("th",{className:"px-4 py-2.5 font-semibold",children:"Volume"})]})}),e.jsx("tbody",{className:"divide-y divide-slate-100",children:N.map((S,k)=>e.jsxs("tr",{children:[e.jsx("td",{className:"px-4 py-2.5 text-slate-700 tabular-nums",children:S?.year??"-"}),e.jsx("td",{className:"px-4 py-2.5 text-slate-700 tabular-nums",children:S?.month??"-"}),e.jsx("td",{className:"px-4 py-2.5 text-slate-900 tabular-nums font-medium",children:Rm(S?.search_volume)})]},`${S?.year}-${S?.month}-${k}`))})]})})})]})]}),e.jsxs("div",{className:"mt-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("div",{className:"text-sm font-semibold text-slate-800",children:"Ranking history"}),e.jsxs(ls,{variant:"secondary",className:"bg-slate-100 text-slate-700",children:["Last ",n.length]})]}),n.length===0?e.jsxs("div",{className:"flex items-start gap-3 p-4 bg-slate-50 border border-slate-200 rounded-lg",children:[e.jsx(qr,{className:"w-5 h-5 text-slate-500 flex-shrink-0 mt-0.5"}),e.jsxs("div",{className:"text-sm text-slate-700",children:[e.jsx("div",{className:"font-medium",children:"No history yet"}),e.jsx("div",{className:"mt-1 text-slate-600",children:"Run a refresh to fetch and persist the latest ranked keywords."})]})]}):e.jsx("div",{className:"border border-slate-200 rounded-xl overflow-hidden",children:e.jsx("div",{className:"max-h-[420px] overflow-auto",children:e.jsxs("table",{className:"min-w-full text-sm",children:[e.jsx("thead",{className:"text-left text-slate-600 bg-slate-50 border-b border-slate-200 sticky top-0 z-10",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-4 py-2.5 font-semibold",children:"Snapshot"}),e.jsx("th",{className:"px-4 py-2.5 font-semibold",children:"Rank"}),e.jsx("th",{className:"px-4 py-2.5 font-semibold",children:"URL"})]})}),e.jsx("tbody",{className:"divide-y divide-slate-100",children:n.map(S=>e.jsxs("tr",{children:[e.jsx("td",{className:"px-4 py-2.5 text-slate-700",children:Dm(S.snapshot_date)}),e.jsx("td",{className:"px-4 py-2.5 tabular-nums font-medium text-slate-900",children:wl(S.rank)}),e.jsx("td",{className:"px-4 py-2.5",children:S.url?e.jsx("a",{href:S.url,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:text-blue-800 hover:underline truncate block max-w-[720px]",title:S.url,children:S.url}):e.jsx("span",{className:"text-slate-400",children:"-"})})]},`${S.snapshot_date}-${S.rank??"null"}`))})]})})})]}),e.jsx(Ns,{children:e.jsx(be,{variant:"outline",onClick:()=>t.onOpenChange(!1),children:"Close"})})]})})}function VN({isOpen:t,onClose:s,onAddKeywords:a,getEstimatedCreditsForSelection:n,marketsCount:o}){const{toast:i}=_t(),[l,c]=r.useState([]),[d,m]=r.useState(""),[h,p]=r.useState(!1),f=r.useRef(null),b=r.useMemo(()=>
254{if(typeof o=="number"||!n||l.length===0)return null;try{return n(l.length)}catch(E){return console.warn("⚠️ Failed to estimate credits:",E),null}},[n,o,l.length]),{estimatedRange:y}=ta({enabled:typeof o=="number"&&l.length>0,scenario:"keywords_tracking_refresh_keywords",params:{keyword_count:l.length,markets_count:Math.max(1,Math.floor(Number(o||1)))}}),x=typeof o=="number"&&y!==null?y.min===y.max?`${y.max}`:`${y.min}-${y.max}`:b!==null?`${b}`:null;r.useEffect(()=>{const E=f.current;if(!E)return;E.style.height="auto";const N=Math.min(E.scrollHeight,200);E.style.height=`${N}px`},[d]),r.useEffect(()=>{t||(c([]),m(""))},[t]);const u=()=>{if(!d.trim())return;const E=d.split(/\n/).map(k=>k.trim()).filter(k=>k.length>0);if(E.length===0)return;const N=E.filter(k=>!l.includes(k));if(N.length===0){i({title:"No new keywords",description:"All keywords are already in the list."}),m("");return}const S=[...l,...N];c(S),m("")},g=E=>{c(N=>N.filter(S=>S!==E))},w=()=>{c([])},_=async()=>{if(l.length!==0){p(!0);try{await a(l),c([]),m(""),s()}catch{}finally{p(!1)}}};return e.jsx(Ht,{open:t,onOpenChange:s,children:e.jsxs(qt,{className:"max-w-3xl max-h-[80vh] flex flex-col p-0 gap-0 overflow-hidden",children:[e.jsxs("div",{className:"p-4 border-b border-slate-100 flex-shrink-0 flex flex-row items-center justify-between",children:[e.jsx("div",{className:"min-w-0",children:e.jsxs(Yt,{className:"text-lg font-semibold text-slate-900",children:["Add Manual Keywords (",l.length,")"]})}),e.jsxs("div",{className:"flex items-center gap-2",children:[l.length>0&&e.jsx(be,{variant:"ghost",size:"sm",onClick:w,className:"text-red-500 hover:text-red-700 hover:bg-red-50 h-8 px-2 text-xs",children:"Clear All"}),e.jsx(be,{variant:"ghost",size:"xs",className:"h-8 w-8",onClick:s,children:e.jsx(mt,{size:18,className:"text-slate-400"})})]})]}),e.jsxs("div",{className:"p-4 border-b border-slate-100 flex flex-col gap-2",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Js,{ref:f,value:d,onChange:E=>m(E.target.value),placeholder:`Keyword 1
255Keyword 2`,className:"min-h-[40px] max-h-[200px] text-sm resize-none overflow-y-auto",onKeyDown:E=>{E.key==="Enter"&&(E.ctrlKey||E.metaKey)&&(E.preventDefault(),u())}}),e.jsxs(be,{onClick:u,size:"sm",className:"bg-slate-900 text-white hover:bg-slate-800 shrink-0 self-start",children:[e.jsx($t,{size:16,className:"mr-1"}),"Add"]})]}),e.jsx("p",{className:"text-xs text-slate-500",children:"Enter one keyword per line. Press Ctrl+Enter (or Cmd+Enter) to add all keywords."})]}),e.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto bg-slate-50/50",children:e.jsx("div",{className:"p-3",children:l.length===0?e.jsxs("div",{className:"py-12 text-center text-slate-400 text-sm flex flex-col items-center",children:[e.jsx("p",{children:"No keywords yet"}),e.jsx("p",{className:"text-xs mt-1 text-slate-300",children:"Add keywords manually above."})]}):e.jsx("div",{className:"flex flex-wrap gap-2",children:l.map(E=>e.jsxs("div",{className:"inline-flex items-center gap-1.5 group px-3 py-1.5 rounded-md bg-white border border-slate-200 shadow-sm hover:border-slate-300 transition-all text-sm",children:[e.jsx("span",{className:"font-medium text-slate-700 select-all max-w-[200px] truncate",title:E,children:E}),e.jsx(be,{variant:"ghost",size:"xs",onClick:()=>g(E),className:"h-5 opacity-0 group-hover:opacity-100 transition-opacity text-slate-400 hover:text-red-600 hover:bg-red-50 flex-shrink-0 p-0",children:e.jsx(mt,{size:12})})]},E))})})}),e.jsxs("div",{className:"p-4 border-t border-slate-100 flex justify-between items-center shrink-0 bg-white rounded-b-2xl",children:[l.length>0&&e.jsx(be,{variant:"outline",onClick:w,className:"text-red-500 border-red-200 hover:bg-red-50 hover:text-red-700 hover:border-red-300",children:"Clear All"}),x!==null&&l.length>0&&e.jsxs("div",{className:"text-xs text-slate-600 ml-2",children:["Estimated cost:"," ",e.jsxs("span",{className:"font-bold text-blue-700",children:[x," credits"]})]}),e.jsxs("div",{className:"flex gap-2 ml-auto",children:[e.jsx(be,{variant:"outline",onClick:s,disabled:h,children:"Cancel"}),e.jsx(be,{onClick:_,disabled:l.length===0||h,className:"bg-slate-900 text-white hover:bg-slate-800",children:h?"Adding...":`Confirm ${l.length>0?`(${l.length})`:""}`})]})]})]})})}function HN({disabled:t,label:s,compactLabel:a,size:n="sm",align:o="left",onSelectKeywords:i,onImportFromTargetKeywords:l,onAddManualKeywords:c}){return e.jsxs(Pn,{selectionMode:"none",children:[e.jsx(In,{asChild:!0,noChevron:!0,disabled:t,children:e.jsxs(be,{size:n,className:"gap-1.5 whitespace-nowrap",disabled:t,children:[e.jsx("span",{className:"hidden lg:inline",children:s}),e.jsx("span",{className:"lg:hidden",children:a??s}),e.jsx(Gs,{className:"w-4 h-4 ml-1"})]})}),e.jsxs(Mn,{align:o,className:"w-60 rounded-lg border border-slate-200 bg-white shadow-lg p-1",children:[e.jsx(js,{value:"select_keywords",className:"flex items-center gap-2 px-3 py-2 text-sm rounded-md",onClick:()=>i(),children:e.jsx("span",{children:"Import from Keywords Gap"})}),l?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"my-1 border-b border-slate-100"}),e.jsx(js,{value:"import_target_keywords",className:"flex items-center gap-2 px-3 py-2 text-sm rounded-md",onClick:()=>l(),children:e.jsx("span",{children:"Import from Keywords Group"})})]}):null,e.jsx("div",{className:"my-1 border-b border-slate-100"}),e.jsx(js,{value:"add_manual_keywords",className:"flex items-center gap-2 px-3 py-2 text-sm rounded-md",onClick:()=>c(),children:e.jsx("span",{children:"Add Keywords Manually"})})]})]})}class qN{constructor(s){this.inFlight=new Map,this.lastUsedAt=new Map,this.maxEntries=Math.max(10,Math.floor(s?.maxEntries??50))}run(s,a){const n=String(s||"");if(!n)return a();const o=this.inFlight.get(n);if(o)return this.touch(n),o;const i=a().then(l=>(this.touch(n),l)).finally(()=>{this.inFlight.delete(n),this.evictIfNeeded()});return this.inFlight.set(n,i),this.touch(n),this.evictIfNeeded(),i}touch(s){this.lastUsedAt.set(s,Date.now())}evictIfNeeded(){if(this.inFlight.size-this.maxEntries<=0)return;const a=Array.from(this.lastUsedAt.entries()).sort((n,o)=>n[1]-o[1]).map(([n])=>n);for(const n of a){if(this.inFlight.size<=this.maxEntries)break;this.inFlight.has(n)||this.lastUsedAt.delete(n)}}}function bn(t){return String(t||"").trim().toLowerCase()}function YN(t){try{return new Date(t).toLocaleDateString()}catch{return t}}function JN(t){const s=[],a=new Set;for(const n of t||[]){const o=String(n||"").trim();if(!o)continue;const i=o.toLowerCase();a.has(i)||(a.add(i),s.push(o))}return s}function XN({isOpen:t,existingKeywords:s,getEstimatedCreditsForSelection:a,marketsCount:n,onClose:o,onConfirm:i}){const l=v.useMemo(()=>{const B=s||new Set;return new Set(Array.from(B).map(ae=>bn(ae)))},[s]),[c,d]=v.useState(""),[m,h]=v.useState(""),[p,f]=v.useState(!1),[b,y]=v.useState(!0),[x,u]=v.useState([]),[g,w]=v.useState(0),[_,E]=v.useState(1),[N,S]=v.useState(50),[k,D]=v.useState(new Set),F=v.useRef(new Map);v.useEffect(()=>{if(!t)return;const B=window.setTimeout(()=>h(c.trim()),250);return()=>window.clearTimeout(B)},[t,c]),v.useEffect(()=>{t&&E(1)},[t,m]);const R=v.useCallback(async()=>
255{if(t){f(!0);try{let de=1,fe=[],se=0;for(;fe.length<5e3;){const z=await ds.listKeywords({keyword:m||void 0,page:de,page_size:1e3}),U=z.items||[];se=z.total||0;const Q=U.map(le=>({keyword:le.keyword,created_at:le.created_at}));if(fe=fe.concat(Q),fe.length>=se||U.length===0||U.length<1e3)break;de+=1}u(fe),w(se)}catch(B){console.error("❌ Failed to load target keywords:",B),u([]),w(0)}finally{f(!1)}}},[m,t]);v.useEffect(()=>{R()},[R]);const L=v.useCallback(B=>{const ae=bn(B);ae&&(l.has(ae)||(F.current.set(ae,String(B||"").trim()),D(de=>{const fe=new Set(de);return fe.has(ae)?fe.delete(ae):fe.add(ae),fe})))},[l]),$=v.useMemo(()=>{const B=x||[];return b?B.filter(ae=>{const de=bn(ae.keyword);return de&&!l.has(de)}):B},[x,l,b]),H=$.length,K=v.useMemo(()=>{const B=(_-1)*N;return $.slice(B,B+N)},[$,_,N]),X=v.useMemo(()=>K.map(B=>bn(B.keyword)).filter(B=>B&&!l.has(B)),[l,K]),V=X.length>0&&X.every(B=>k.has(B)),P=X.length===0?!1:V?!0:X.some(B=>k.has(B))?"indeterminate":!1,A=v.useCallback(()=>{D(B=>{const ae=new Set(B);if(V)X.forEach(de=>ae.delete(de));else{for(const de of K){const fe=bn(de.keyword);fe&&(l.has(fe)||F.current.set(fe,String(de.keyword||"").trim()))}X.forEach(de=>ae.add(de))}return ae})},[V,l,X,K]),C=v.useMemo(()=>[{header:e.jsx("div",{className:"flex items-center justify-center",children:e.jsx(Kt,{checked:P,onCheckedChange:A,"aria-label":"Select all",disabled:X.length===0})}),width:"40px",align:"center",isSelection:!0,render:B=>{const ae=bn(B.keyword),de=!ae||l.has(ae),fe=ae?k.has(ae):!1;return e.jsx("div",{className:"flex items-center justify-center",children:e.jsx(Kt,{checked:fe,disabled:de,onCheckedChange:()=>L(B.keyword),"aria-label":"Select row"})})}},{header:"Keyword",accessorKey:"keyword",className:"font-medium text-slate-800"},{header:"Added",accessorKey:"created_at",className:"text-slate-600",render:B=>YN(B.created_at)}],[l,A,P,X.length,k,L]);k.size;const I=v.useMemo(()=>{const B=[];for(const ae of Array.from(k)){const de=F.current.get(ae);de&&de.trim()&&B.push(de.trim())}return JN(B).sort((ae,de)=>ae.localeCompare(de))},[k]),j=v.useMemo(()=>{if(typeof n=="number"||!a)return null;try{return a(I.length)}catch(B){return console.warn("⚠️ Failed to estimate credits:",B),null}},[a,n,I.length]),{estimatedRange:q}=ta({enabled:typeof n=="number"&&I.length>0,scenario:"keywords_tracking_refresh_keywords",params:{keyword_count:I.length,markets_count:Math.max(1,Math.floor(Number(n||1)))}}),T=B=>{const ae=bn(B);ae&&D(de=>{const fe=new Set(de);return fe.delete(ae),fe})},M=()=>{D(new Set)},Z=()=>{k.size!==0&&i(I)};return e.jsx(Ht,{open:t,onOpenChange:B=>!B&&o(),children:e.jsxs(qt,{className:"w-[96vw] max-w-[1100px] h-[85vh] max-h-[85vh] flex flex-col gap-0 overflow-hidden p-0",children:[e.jsxs(Zt,{variant:"full",density:"sm",divider:!0,children:[e.jsx(Yt,{className:"text-sm font-medium text-slate-800",children:"Import from Keywords Group"}),e.jsx(Ds,{className:"text-xs text-slate-500",children:"Select keywords from your saved Target Keywords list."})]}),e.jsx("div",{className:"flex-1 min-h-0 overflow-hidden bg-white",children:e.jsxs("div",{className:"h-full grid grid-cols-1 lg:grid-cols-[1fr_360px]",children:[e.jsxs("div",{className:"h-full flex flex-col gap-3 pr-3 min-h-0 ",children:[e.jsxs("div",{className:"p-4 border-b border-slate-200 bg-white",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Pt,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400"}),e.jsx(bt,{value:c,onChange:B=>d(B.target.value),placeholder:"Search target keywords...",className:"pl-9 pr-9"}),c?e.jsxs("button",{onClick:()=>d(""),className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 hover:bg-slate-100 rounded",type:"button",children:[e.jsx(mt,{className:"w-3 h-3 text-slate-400"}),e.jsx("span",{className:"sr-only",children:"Clear search"})]}):null]}),e.jsxs(be,{variant:"outline",size:"sm",onClick:()=>{R()},disabled:p,className:"gap-2",children:[e.jsx(kt,{className:p?"w-4 h-4 animate-spin":"w-4 h-4"}),"Refresh"]})]}),e.jsxs("div",{className:"mt-3 flex items-center justify-between gap-3",children:[e.jsxs("label",{className:"flex items-center gap-2 text-xs text-slate-600 select-none",children:[e.jsx(Kt,{checked:b,onCheckedChange:B=>y(!!B)}),"Hide already-tracked keywords"]}),e.jsxs("div",{className:"text-[11px] text-slate-400",children:["Total: ",H,g>0&&g!==H?e.jsxs("span",{className:"ml-2",children:["(raw ",g,")"]}):null]})]})]}),e.jsx("div",{className:"flex-1 min-h-0 overflow-hidden bg-white",children:e.jsx(Lc,{data:K,columns:C,emptyMessage:e.jsx("div",{className:"py-10 text-center text-slate-500",children:p?"Loading target keywords...":"No target keywords foun
255d"}),rowClassName:B=>{const ae=bn(B.keyword);return ae?!b&&l.has(ae)?"opacity-60":k.has(ae)?"bg-blue-50":"":""},pagination:{currentPage:_,pageSize:N,total:H,onPageChange:E,onPageSizeChange:B=>{S(B),E(1)}}})})]}),e.jsx("div",{className:"h-full min-h-0 overflow-hidden bg-white border-t lg:border-t-0 lg:border-l border-slate-200 p-3",children:e.jsx(Ql,{layoutMode:"split",selectedKeywords:I,selectedCount:I.length,estimatedCredits:j,estimatedCreditsRange:typeof n=="number"?q:null,onClearAll:M,onRemoveKeyword:T,onCancel:o,onConfirm:Z,confirmDisabled:I.length===0,emptyText:"Select keywords from the table to see them here."})})]})})]})})}const QN=100,Vo="~2-5 min",jl=new qN({maxEntries:30});function ZN({marketReloadNonce:t,actionLabel:s,actionIcon:a,onAction:n,emptyStateLabel:o,onEmptyStateAction:i,useAbsoluteActionBar:l=!1}={}){const{toast:c}=_t(),d=t??0,m=r.useRef(async()=>{}),h=r.useRef(0),p=r.useMemo(()=>new Kx,[]),f=KN({toast:c,onCompleted:async()=>{await m.current()}}),[b,y]=r.useState("weekly"),[x,u]=r.useState(()=>br("weekly")),g=r.useMemo(()=>Lx(x,b),[x,b]),w=r.useMemo(()=>g.length>0?g[g.length-1]?.period:null,[g]),[_,E]=r.useState({key:"",direction:null});r.useEffect(()=>{w&&!_.key&&E({key:`period:${w}`,direction:"asc"})},[w,_.key]);const[N,S]=r.useState(1),[k,D]=r.useState(100),[F,R]=r.useState({autoRefreshEnabled:!0}),L=Zs(Us.keywords_tracking),[$,H]=v.useState(!1),[K,X]=v.useState(!1),[V,P]=v.useState(!1),[A,C]=v.useState(!1),[I,j]=v.useState(!0);v.useEffect(()=>{if(typeof window>"u")return;const Ue=window.matchMedia("(max-width: 767px)"),tt=()=>H(Ue.matches);return tt(),Ue.addEventListener("change",tt),()=>Ue.removeEventListener("change",tt)},[]);const q=QN,[T,M]=r.useState(""),[Z,B]=r.useState(!1),[ae,de]=r.useState(!1),[fe,se]=r.useState(!1),[z,U]=r.useState(!1),[Q,me]=r.useState(!1),[le,O]=r.useState(null),{confirm:ne}=ia(),[ge,ze]=r.useState(!1),[Ke,ie]=r.useState(""),[ve,we]=r.useState(!1),[Pe,Ae]=r.useState({}),[ye,Te]=r.useState(null),[Ie,Oe]=r.useState({}),[J,re]=r.useState({}),[Se,je]=r.useState({}),he=r.useRef({}),Re=r.useRef("");r.useEffect(()=>{he.current=Se},[Se]);const[Me,Ze]=r.useState(!1),[Be,et]=r.useState("");v.useEffect(()=>{(async()=>{try{we(!1),ie("");try{if(ma().length>0){const st=await Or();st?.domain&&ie(st.domain)}}catch(tt){console.warn("⚠️ Failed to load domain overview:",tt)}try{const tt=await jl.run("serp:settings",()=>Dw());R(st=>({...st,autoRefreshEnabled:tt.serp_auto_sync_period!=="disabled"}))}catch(tt){console.error("❌ Failed to load SERP settings:",tt)}}catch(tt){console.error("❌ Failed to load initial SERP data:",tt)}finally{we(!0)}})()},[d]);const[$e,ue]=r.useState([]),[W,ke]=r.useState(null);r.useEffect(()=>{let Ue=!1;return(async()=>{try{const ft=(await Xa())?.plan?.plan_type||"free",ht=Nt.getLimit("tracked_keywords",ft);if(Ue)return;ke(typeof ht=="number"&&Number.isFinite(ht)?ht:null)}catch{Ue||ke(null)}})(),()=>{Ue=!0}},[]);const qe=r.useMemo(()=>{const Ue=new Set;for(const tt of $e||[]){if(!tt?.isActive)continue;const st=Nn(String(tt.keyword||""));st&&Ue.add(st)}return Ue},[$e]),Qe=r.useCallback(Ue=>{const tt=W;if(tt===null)return{allowed:!0,remaining:null};const st=qe.size,ft=Math.max(0,tt-st),ht=new Set;for(const Ot of Ue||[]){const Tt=Nn(String(Ot||""));Tt&&(qe.has(Tt)||ht.add(Tt))}return ht.size>ft?{allowed:!1,remaining:ft}:{allowed:!0,remaining:ft}},[qe,W]),[ct,pt]=r.useState(null),At=r.useMemo(()=>{if($e.length===0||!$e.some(ft=>ft.rankings.length>0))return g;const tt=new Set;for(const ft of $e)for(const ht of ft.rankings||[])ht.rank!==null&&ht.rank!==void 0&&tt.add(ht.period);const st=g.filter(ft=>tt.has(ft.period));return st.length===0&&g.length>0?[g[g.length-1]]:st},[g,$e]),[te,G]=r.useState(new Set),pe=r.useCallback((Ue,tt)=>(Ue||[]).filter(st=>st.is_active).map(st=>({id:st.id,keyword:st.keyword,domain:Ke||"",landingPage:tt[st.keyword]||null,rankings:[],isActive:st.is_active,createdAt:st.created_at.split("T")[0]})),[Ke]);v.useEffect(()=>{ve&&g.length>0&&x.from&&x.to&&ce()},[ve,g.length,x.from,x.to,b,d]);const ce=async Ue=>{if(!x.from||!x.to||g.length===0)return;const tt=++h.current;ze(!0),Ze(!0),et("Loading rankings...");try{const st=x.from,ft=x.to,ht=ma(),Ot=ht.length>0?$a(ht):null,Tt=(ht||[]).map(Jt=>Si({location_code:Number(Jt.location_code),language_code:String(Jt.language_code||"")})),vt=Ot?Ot.location_ids?.join(",")||(Ot.markets||[]).map(Jt=>`${Jt.location_code}/${Jt.language_code}`).join(","):"none",Ft=`${b}:${st}:${ft}`;Re.current!==Ft&&(Re.current=Ft,he.current={},je({})),Ue?.force&&(Re.current=Ft,he.current={},je({}));const ks=Tt,Le=(g||[]).map(Jt=>Jt.period),We=(ht||[]).filter(Jt=>{const qs=Si({location_code:Number(Jt.location_code),language_code:String(Jt.language_code||"")});return!he.current[qs]}),at=We.length>0?$a(We):null,it=at?.location_ids?.join(",")||(at?.markets||[]).map(Jt=>`${Jt.location_code}/${Jt.language_code}
255`).join(",")||"none",[dt,Et]=await Promise.all([at?jl.run(`serp:rankings_batch_grouped:${Ft}:missing:${it}`,()=>Bx({selector:at,period:b,date_from:st,date_to:ft})):Promise.resolve(null),jl.run(`serp:tracked_keywords:${vt}`,async()=>{let Jt=[],qs={},Ta=null;if(Ot){const Fa=await Ux({selector:Ot});Jt=Fa.keywords||[],Ta=Fa.last_synced_at||null;const yn=Jt.filter(Fn=>Fn.is_active).map(Fn=>Fn.keyword);qs=Fa.keyword_landing_pages||Ox({keywords:yn,by_market:Fa.by_market||{},preferred_market_keys:Tt})}else Jt=[],qs={},Ta=null;return{trackedList:Jt,landingPageMap:qs,lastSyncedAt:Ta}})]);if(tt!==h.current)return;const Dt={...he.current||{},...dt?.by_market||{}};he.current=Dt,je(Dt);const os=p.aggregate({byMarket:Dt,selectedMarketKeys:ks,periodKeys:Le}),ts={},Es={},sa={};for(const Jt of os.items||[])ts[Jt.keyword]=Jt.latest_volume??null,Es[Jt.keyword]=Jt.latest_rank??null,sa[Jt.keyword]=(g||[]).map(qs=>({snapshot_date:qs.periodStart,rank:Jt.ranks?.[qs.period]??null,url:Jt.urls?.[qs.period]??null}));Oe(ts),re(Es),Ae(sa);const fa=(Et.trackedList||[]).filter(Jt=>Jt.is_active),hs=Et.landingPageMap||{},xr=pe(fa,hs);pt(Et.lastSyncedAt||null);const Ur=xr.map(Jt=>{const qs=(os.items||[]).find(yn=>Nn(yn.keyword)===Nn(Jt.keyword))||null,Ta=zx(g,qs?.ranks,qs?.urls),Fa=Es?.[Jt.keyword]??Es?.[Nn(Jt.keyword)];if(Ta.length>0&&Fa!==void 0){const yn=Ta.length-1,Fn={...Ta[yn],rank:Fa,status:Fa===null?"not_ranked":"ranked"},oe=[...Ta];return oe[yn]=Fn,{...Jt,rankings:oe}}return{...Jt,rankings:Ta}});ue(Ur)}catch(st){console.error("❌ Failed to load rankings:",st),c({title:"Failed to load rankings",description:st.message})}finally{ze(!1),Ze(!1),et("")}};m.current=async()=>{await ce({force:!0})};const Y=r.useMemo(()=>T.trim()?$e.filter(Ue=>Ue.keyword.toLowerCase().includes(T.toLowerCase())):$e,[$e,T]),xe=Ue=>{E(tt=>tt.key!==Ue?{key:Ue,direction:"asc"}:tt.direction==="asc"?{key:Ue,direction:"desc"}:tt.direction==="desc"?{key:"",direction:null}:{key:Ue,direction:"asc"})},Ee=Ue=>_.key!==Ue?e.jsx(dn,{size:14,className:"text-slate-400 opacity-70"}):_.direction==="asc"?e.jsx(Is,{size:14,className:"text-slate-500"}):_.direction==="desc"?e.jsx(Ws,{size:14,className:"text-slate-500"}):e.jsx(dn,{size:14,className:"text-slate-400 opacity-70"}),Ne=r.useMemo(()=>{if(!_.key||!_.direction)return Y;const Ue=_.direction,tt=_.key,st=(Tt,vt)=>{const Ft=Tt==null,ks=vt==null;if(Ft&&ks)return 0;if(Ft)return 1;if(ks)return-1;if(typeof Tt=="number"&&typeof vt=="number"){const it=Tt-vt;return Ue==="asc"?it:-it}const Le=String(Tt),We=String(vt),at=Le.localeCompare(We);return Ue==="asc"?at:-at},ft=(Tt,vt)=>{const Ft=Tt.rankings.find(ks=>ks.period===vt);return!Ft||Ft.status==="no_data"||Ft.rank===null?null:Ft.rank},ht=Tt=>{const vt=Tt.rankings[Tt.rankings.length-2],Ft=Tt.rankings[Tt.rankings.length-1];return!Ft||Ft.status==="no_data"?null:!vt||vt.status==="no_data"?999999:vt.rank===null&&Ft.rank===null?null:vt.rank===null&&Ft.rank!==null?999999:vt.rank!==null&&Ft.rank===null?-999999:vt.rank-Ft.rank},Ot=[...Y];return Ot.sort((Tt,vt)=>{if(tt==="keyword")return st(Tt.keyword,vt.keyword);if(tt==="landing_page")return st(Tt.landingPage,vt.landingPage);if(tt==="change")return st(ht(Tt),ht(vt));if(tt.startsWith("period:")){const Ft=tt.replace("period:","");return st(ft(Tt,Ft),ft(vt,Ft))}return 0}),Ot},[Y,_]),Ce=r.useMemo(()=>{const Ue=(N-1)*k;return Ne.slice(Ue,Ue+k)},[Ne,N,k]);v.useEffect(()=>{S(1)},[T,x,b,_]),v.useEffect(()=>{const Ue=new Set($e.map(tt=>tt.id));G(tt=>{const st=new Set(Array.from(tt).filter(ft=>Ue.has(ft)));return st.size===tt.size?tt:st})},[$e]);const De=r.useCallback(Ue=>{G(tt=>{const st=new Set(tt);return st.has(Ue)?st.delete(Ue):st.add(Ue),st})},[]);r.useCallback(()=>{const Ue=Ce.map(st=>st.id),tt=Ue.every(st=>te.has(st));G(st=>{const ft=new Set(st);return tt?Ue.forEach(ht=>ft.delete(ht)):Ue.forEach(ht=>ft.add(ht)),ft})},[Ce,te]),r.useMemo(()=>Ce.length===0?!1:Ce.every(Ue=>te.has(Ue.id)),[Ce,te]),r.useMemo(()=>{if(Ce.length===0)return!1;const Ue=Ce.filter(tt=>te.has(tt.id)).length;return Ue>0&&Ue<Ce.length},[Ce,te]),r.useMemo(()=>Ce.map(Ue=>({id:Ue.id,keyword:Ue.keyword,landingPage:Ue.landingPage,rankings:Ue.rankings})),[Ce]);const Ge=r.useMemo(()=>{const Ue={};for(const[tt,st]of Object.entries(Ie||{}))Ue[tt]=st!=null?`Vol ${st}`:null;return Ue},[Ie]);r.useCallback(async()=>
255{if(te.size===0){c({title:"No keywords selected",description:"Please select keywords to delete"});return}const tt=$e.filter(ht=>te.has(ht.id)).map(ht=>ht.keyword);if(!(!await ne({title:"Delete Keywords?",message:`Are you sure you want to delete ${te.size} keyword(s)? This action will remove all ranking history for these keywords.`,confirmText:"Delete",cancelText:"Cancel",variant:"danger"})||(await new Promise(ht=>setTimeout(ht,100)),!await ne({title:"Confirm Deletion",message:`This action cannot be undone. Are you absolutely sure you want to permanently delete ${te.size} keyword(s)?`,confirmText:"Yes, Delete Permanently",cancelText:"Cancel",variant:"danger"})))){Ze(!0),et(`Deleting ${te.size} keyword(s)...`);try{const ht=tt.map(Ft=>Zd(Ft).catch(ks=>(console.error(`Failed to delete keyword "${Ft}":`,ks),{keyword:Ft,error:ks}))),Ot=await Promise.allSettled(ht),Tt=Ot.filter(Ft=>Ft.status==="fulfilled").length,vt=Ot.length-Tt;await ce(),G(new Set),Tt>0&&c({title:"Keywords deleted successfully",description:`${Tt} keyword(s) deleted`}),vt>0&&c({title:"Some keywords failed to delete",description:`${vt} keyword(s) could not be deleted`})}catch(ht){console.error("Failed to delete keywords:",ht),c({title:"Failed to delete keywords",description:ht.message})}finally{Ze(!1),et("")}}},[te,$e,ne,c,ce]);const ee=r.useMemo(()=>{const Ue=$e.filter(ht=>ht.isActive),tt=Ue.filter(ht=>ht.rankings[ht.rankings.length-1]?.rank!==null),st=tt.filter(ht=>(ht.rankings[ht.rankings.length-1]?.rank??q+1)<=10),ft=Ue.filter(ht=>{const Ot=ht.rankings[ht.rankings.length-2],Tt=ht.rankings[ht.rankings.length-1];return!Ot||!Tt||Ot.status==="no_data"||Tt.status==="no_data"||Ot.rank===null||Tt.rank===null?!1:Tt.rank<Ot.rank});return{total:Ue.length,ranked:tt.length,top10:st.length,improved:ft.length}},[$e]),Fe=r.useCallback(async Ue=>{if(Ue.length===0)return;const tt=Qe(Ue.map(st=>st.keyword));if(!tt.allowed){c({title:"Plan limit exceeded",description:`Tracked keywords limit reached. Remaining slots: ${tt.remaining??0}.`});return}Ze(!0),et(`Adding ${Ue.length} keyword(s)...`);try{const st=await Qd({keywords:Ue.map(vt=>({keyword:vt.keyword}))}),ft=st.keywords.map(vt=>vt.keyword),ht=st.keywords.length,Ot=st.added_count,Tt=st.reactivated_count;if(et("Loading latest data..."),await ce(),de(!1),ht>0){const vt=[];Ot>0&&vt.push(`${Ot} added`),Tt>0&&vt.push(`${Tt} reactivated`),c({title:"Keywords added successfully",description:`${ht} keyword(s) processed (${vt.join(", ")})`})}ft.length>0&&f.startSync({keywordList:ft,etaText:Vo})}catch(st){console.error("❌ Failed to add keywords:",st),c({title:"Failed to add keywords",description:st.message})}finally{Ze(!1),et("")}},[c,f,ce]),Xe=r.useCallback(async Ue=>{if(Ue.length===0)return;const tt=Qe(Ue);if(!tt.allowed){c({title:"Plan limit exceeded",description:`Tracked keywords limit reached. Remaining slots: ${tt.remaining??0}.`});return}const st=1e3;Ze(!0),et(`Adding ${Ue.length} keyword(s)...`);try{const ft=[];let ht=0,Ot=0;for(let vt=0;vt<Ue.length;vt+=st){const Ft=Ue.slice(vt,vt+st),ks=Math.floor(vt/st)+1,Le=Math.ceil(Ue.length/st);Le>1&&et(`Adding batch ${ks}/${Le} (${Ft.length} keywords)...`);try{const We=await Qd({keywords:Ft.map(it=>({keyword:it.trim()}))}),at=We.keywords.map(it=>it.keyword);ft.push(...at),ht+=We.added_count,Ot+=We.reactivated_count}catch(We){console.error(`❌ Failed to add batch ${ks}:`,We)}}const Tt=ft.length;if(et("Loading latest data..."),await ce(),Tt>0){const vt=[];ht>0&&vt.push(`${ht} added`),Ot>0&&vt.push(`${Ot} reactivated`),c({title:"Keywords added successfully",description:`${Tt} keyword(s) processed (${vt.join(", ")})`})}ft.length>0&&f.startSync({keywordList:ft,etaText:Vo})}catch(ft){throw console.error("❌ Failed to add keywords:",ft),c({title:"Failed to add keywords",description:ft.message}),ft}finally{Ze(!1),et("")}},[c,f,ce,Qe]),yt=r.useCallback(async Ue=>{Ue.length!==0&&await Xe(Ue)},[Xe]),ut=r.useCallback(async(Ue,tt)=>{if(!(!await ne({title:"Delete Keyword?",message:`Are you sure you want to delete the keyword "${tt}"? This action will remove all ranking history for this keyword.`,confirmText:"Delete",cancelText:"Cancel",variant:"danger"})||(await new Promise(ht=>
255setTimeout(ht,100)),!await ne({title:"Confirm Deletion",message:`This action cannot be undone. Are you absolutely sure you want to permanently delete the keyword "${tt}"?`,confirmText:"Yes, Delete Permanently",cancelText:"Cancel",variant:"danger"})))){Ze(!0),et("Deleting keyword...");try{await Zd(tt),await ce(),c({title:"Keyword deleted successfully"})}catch(ht){console.error("Failed to delete keyword:",ht),c({title:"Failed to delete keyword",description:ht.message})}finally{Ze(!1),et("")}}},[ne,c,ce]),It=async()=>{if($e.length===0){c({title:"No keywords to sync",description:"Please add keywords first"});return}const{validateCreditBalance:Ue}=await Bt(async()=>{const{validateCreditBalance:ft}=await Promise.resolve().then(()=>ua);return{validateCreditBalance:ft}},void 0);if(!await Ue({estimatedRange:Ls,requiredMinimumBalance:null,toast:c}))return;const st=$e.map(ft=>ft.keyword);await f.startSync({keywordList:st,etaText:Vo})},Ct=r.useRef(It);v.useEffect(()=>{Ct.current=It},[It]),v.useEffect(()=>{const Ue=ft=>{try{const ht=!!ft.detail;X(ht)}catch{}},tt=()=>{$&&C(!0)},st=()=>{$&&P(!0)};return window.addEventListener("mobile-filter-toggle",Ue),window.addEventListener("mobile-refresh-click",tt),window.addEventListener("mobile-add-click",st),()=>{window.removeEventListener("mobile-filter-toggle",Ue),window.removeEventListener("mobile-refresh-click",tt),window.removeEventListener("mobile-add-click",st)}},[$]);const cs=r.useRef(!1);v.useEffect(()=>{cs.current||$e.length!==0&&(cs.current=!0,f.resumeOrDetect({currentKeywordList:$e.map(Ue=>Ue.keyword),etaText:Vo}))},[$e.length,f,$e]);const xa=async Ue=>{Ze(!0),et("Saving auto refresh setting...");try{await Lw({serp_auto_sync_period:Ue?"weekly":"disabled"}),R(tt=>({...tt,autoRefreshEnabled:Ue})),c({title:"Auto refresh updated",description:Ue?"Auto refresh is enabled (weekly)":"Auto refresh is disabled"})}catch(tt){console.error("❌ Failed to update auto refresh:",tt),c({title:"Failed to update auto refresh",description:tt.message})}finally{Ze(!1),et("")}},zs=r.useMemo(()=>{const Ue=ma().length;return Math.max(1,Ue)},[d]),{estimating:hn,estimatedRange:Ls}=ta({enabled:!0,scenario:"keywords_tracking_refresh_keywords",params:{keyword_count:$e.length,markets_count:zs}}),la=r.useMemo(()=>ct?new Date(ct).toLocaleDateString("en-CA"):null,[ct]),pn=()=>{const Ue=b==="weekly"?"weekly":"monthly",tt=x.from||"start",st=x.to||"end";return`seo_keywords_ranking_${Ke||"domain"}_${Ue}_${tt}_to_${st}.xlsx`.replace(/[^a-zA-Z0-9_\-.]/g,"_")},gn=()=>{const tt=[["Keyword",...At.map(st=>st.periodLabel||st.period),"Latest Rank",...At.length>=2?["Change vs prev."]:[],"Landing Page"]];return Y.forEach(st=>{const ft=st.rankings[st.rankings.length-1],ht=st.rankings[st.rankings.length-2],Ot=ft?.rank??null,Tt=Aw(ht,ft,b),vt=At.map(ks=>{const Le=st.rankings.find(We=>We.period===ks.period);return!Le||Le.status==="no_data"?"-":Le.rank===null?`${q}+`:Le.rank}),Ft=!ft||ft.status==="no_data"?"-":Ot===null?`${q}+`:Ot;tt.push([st.keyword,...vt,Ft,...At.length>=2?[Tt.text]:[],st.landingPage||""])}),tt},$s=r.useCallback(()=>{if(At.length===0){c({title:"Cannot export",description:"Please select a date range first"});return}if(Y.length===0){c({title:"Nothing to export",description:"No keywords available for the current filters"});return}try{const Ue=gn(),tt=as.book_new(),st=as.aoa_to_sheet(Ue);as.book_append_sheet(tt,st,"SEO Keywords Tracking");const ft=pn();mi(tt,ft),c({title:"Export completed",description:`Exported ${Y.length} keyword(s) to Excel`})}catch(Ue){console.error("Failed to export SERP rankings:",Ue),c({title:"Export failed",description:Ue?.message||"Unable to export SERP rankings"})}},[At,Y,c]);if(i&&$e.length===0&&!ge)return e.jsxs("div",{className:`h-full flex flex-col items-center justify-center ${l?"relative":""}`,children:[e.jsx("div",{className:"w-16 h-16 bg-slate-100 rounded-full flex items-center justify-center mx-auto mb-4",children:e.jsx(us,{className:"w-8 h-8 text-slate-400"})}),e.jsx("h3",{className:"text-lg font-medium text-slate-900 mb-1",children:"No keywords to track"}),e.jsx("p",{className:"text-sm text-slate-500 mb-4",children:"Add keywords to start tracking their rankings over time"}),e.jsx(be,{size:"md",className:"gap-2",onClick:i,children:o||"Add Keywords"})]});const Ea=r.useCallback(Ue=>{const tt=Mr.find(Ot=>Ot.id===Ue)?.name||"Content generation",st=new Date,ft=st.toLocaleStr
255ing("en-US",{month:"short"}),ht=st.getDate();return`${tt} - ${ft} ${ht}`},[]),Aa=r.useCallback(()=>$e.filter(Ue=>te.has(Ue.id)).map(Ue=>Ue.keyword).filter(Ue=>typeof Ue=="string"&&Ue.trim().length>0),[$e,te]),ha=r.useCallback(async(Ue,tt,st)=>{const ft=Aa();if(ft.length===0){c({title:"No keywords selected",description:"Please select keywords to generate content"});return}U(!1),Ze(!0),et("Creating worksheet...");try{const ht=Ea(Ue),Ot=ft.map((vt,Ft)=>({id:`kw-${Ft+1}`,name:vt,keywords:[{keyword:vt}]})),Tt=await cr.createWorksheetAndGenerateFromGroups({source:{kind:"content_generation_template",templateType:Ue},campaignSource:"keywords_research",campaignName:ht,groups:Ot,options:{generateTitleAndContent:st,titlePollingTimeoutMs:12e4,titlePollingIntervalMs:2e3,context:tt,onProgress:(vt,Ft)=>{et((Ft?.trim()||Yl(vt)).trim())}}});try{localStorage.setItem("flowwriter.currentCampaign",JSON.stringify({id:Tt.campaignId,name:ht}))}catch{}c({title:"✅ Worksheet created",description:st?"Keywords filled. Title & content generation started.":"Keywords filled. You can run generation from the table."}),G(new Set),jt("table-new",{campaign:Tt.campaignId,view:Tt.viewId})}catch(ht){console.error("❌ Failed to create worksheet and generate:",ht),c({title:"Create & generate failed",description:ht?.message||"Please try again."})}finally{Ze(!1),et("")}},[Ea,Aa,jt,c]),Ln=r.useCallback(async(Ue,tt,st,ft)=>{if(Ue!=="ai")return;if(Aa().length===0){c({title:"No keywords selected",description:"Please select keywords to group"});return}U(!1),Ze(!0),et("Starting AI grouping...");try{const{creditEstimateService:Ot}=await Bt(async()=>{const{creditEstimateService:at}=await Promise.resolve().then(()=>Ya);return{creditEstimateService:at}},void 0),{validateCreditBalance:Tt}=await Bt(async()=>{const{validateCreditBalance:at}=await Promise.resolve().then(()=>ua);return{validateCreditBalance:at}},void 0),vt=Aa(),Ft=await Ot.estimateCredits({scenario:"keyword_group_ai_group_keywords",params:{keyword_count:vt.length,total_keyword_chars:vt.reduce((at,it)=>at+it.length,0)}});if(!await Tt({estimatedRange:Ft?{min:Ft.estimated_min_credits,max:Ft.estimated_max_credits}:null,requiredMinimumBalance:Ft?.required_minimum_balance??null,toast:c})){Ze(!1),et("");return}const Le=await ds.aiGroupKeywords({keywords:vt.map(at=>({keyword:at,source:"keywords_tracking"}))}),We=Le?.task_id?String(Le.task_id):"";if(!We)throw new Error("Failed to start AI grouping task.");console.log("🧠 Started AI grouping task:",We),O(We)}catch(Ot){console.error("❌ Failed to start AI grouping:",Ot),c({title:"Failed to start AI grouping",description:Ot?.message||"Please try again later"})}finally{Ze(!1),et("")}},[Aa,c]),zn=r.useCallback(async(Ue,tt)=>
255{if(tt.status==="done"){const ft=(tt.all_groups||tt.groups_created||[]||[]).map(ht=>ht.id).filter(Boolean);if(c({title:"✅ AI Groups Processed",description:tt.message||"Grouping completed"}),ft.length>0)try{sessionStorage.setItem("ai_group_selected_ids",JSON.stringify(ft))}catch(ht){console.warn("⚠️ Failed to store group IDs in sessionStorage:",ht)}O(null),G(new Set),jt("keyword_research",{view:"groups"});return}tt.status==="error"&&(c({title:"Failed to create AI groups",description:tt.error||"Please try again later"}),O(null))},[jt,c]),$n=r.useCallback(()=>{O(null)},[]),pa=te.size>0;v.useEffect(()=>{$&&te.size>0&&j(!1)},[$,te.size]);const ys=r.useMemo(()=>$?Ne:Ce,[$,Ce,Ne]),fn=r.useMemo(()=>ys.map(Ue=>Ue.id),[ys]),ga=r.useMemo(()=>ys.length===0?!1:ys.every(Ue=>te.has(Ue.id)),[ys,te]),ur=r.useMemo(()=>{if(ys.length===0)return!1;const Ue=ys.filter(tt=>te.has(tt.id)).length;return Ue>0&&Ue<ys.length},[ys,te]);return e.jsxs("div",{className:`h-full flex flex-col overflow-hidden bg-white sm:bg-transparent p-0 ${$&&pa?"pb-24":""} md:pb-0 md:p-4 ${l?"relative":""}`,"data-onboarding":"keywords-tracking-intro",children:[e.jsx(Do,{visible:Me,message:Be,fixed:!0,zIndex:9999}),e.jsx("div",{className:"hidden md:block mb-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 bg-slate-100 rounded-xl flex items-center justify-center",children:e.jsx(Ma,{className:"w-5 h-5 text-slate-600"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-slate-900",children:"SEO Keywords Tracking"}),e.jsxs("p",{className:"text-sm text-slate-500",children:[At.length," ",b==="weekly"?"weeks":"months"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[la&&e.jsxs("div",{className:"flex items-center gap-2 text-xs text-slate-400",children:[e.jsx(ka,{size:12}),e.jsxs("span",{children:["last refresh: ",la]})]}),F.autoRefreshEnabled&&e.jsx("span",{className:"text-xs text-slate-500 bg-slate-100 px-2.5 py-1 rounded-full",children:"Auto refresh: enabled"})]})]})}),e.jsxs("div",{className:"hidden md:grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-3 md:gap-4 mb-4",children:[e.jsx("div",{className:"bg-white border border-slate-200 rounded-xl p-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-9 h-9 rounded-lg bg-slate-50 flex items-center justify-center",children:e.jsx(us,{size:16,className:"text-slate-500"})}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] text-slate-400 uppercase tracking-wider",children:"Total Keywords"}),e.jsx("div",{className:"text-lg font-semibold text-slate-800",children:ee.total})]})]})}),e.jsx("div",{className:"bg-white border border-slate-200 rounded-xl p-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-9 h-9 rounded-lg bg-slate-50 flex items-center justify-center",children:e.jsx(Qt,{size:16,className:"text-slate-500"})}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] text-slate-400 uppercase tracking-wider",children:"Ranked"}),e.jsx("div",{className:"text-lg font-semibold text-slate-800",children:ee.ranked})]})]})}),e.jsx("div",{className:"bg-white border border-slate-200 rounded-xl p-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-9 h-9 rounded-lg bg-slate-50 flex items-center justify-center",children:e.jsx(Ks,{size:16,className:"text-slate-500"})}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] text-slate-400 uppercase tracking-wider",children:"Top 10 Rankings"}),e.jsx("div",{className:"text-lg font-semibold text-slate-800",children:ee.top10})]})]})}),e.jsx("div",{className:"bg-white border border-slate-200 rounded-xl p-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-9 h-9 rounded-lg bg-slate-50 flex items-center justify-center",children:e.jsx(Ma,{size:16,className:"text-slate-500"})}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] text-slate-400 uppercase tracking-wider",children:"Improved"}),e.jsx("div",{className:"text-lg font-semibold text-slate-800",children:ee.improved})]})]})})]}),e.jsxs("div",{className:"hidden md:block bg-white rounded-xl border border-slate-200 p-3 md:p-4 mb-4",children:[f.panel&&f.panel.phase!=="idle"&&e.jsx("div",{className:"mb-3 pb-3 border-b border-slate-100",children:e.jsx(ON,{state:{...f.panel,etaText:f.panel.etaText||"10-30s"}})}),e.jsxs("div",{className:"flex flex-col lg:flex-row sm:flex-wrap lg:items-center lg:justify-between gap-3",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center gap-3",children:[e.jsxs("div",{className:"relative w-full sm:w-auto",children:[e.jsx(Pt,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400"}),e.jsx(bt,{placeholder:"Search keywords...",value:T,onChange:Ue=>M(Ue.target.value),onFocus:()=>B(!0),onBlur:()=>B(!1),className:`pl-9 pr-8 w-full sm:w-56 transition-all ${Z?"ring-2 ring-blue-100":""}`}),T&&e.jsx("button",{onClick:()=>M(""),className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 hover:bg-slate-100 rounded",children:e.jsx(mt,{className:"w-3 h-3 text-slate-400"})})]}),e.jsx("div",{className:"hidden sm:block h-8 w-px bg-slate-200"}),e.jsxs("div",{className:"flex items-center bg-slate-100 rounded-lg p-0.5 w-full sm:w-auto",children:[e.jsx("button",{onClick:()=>{y("weekly"),u(br("weekly"))},className:`flex-1 sm:flex-none px-3 py-1.5 text-sm font-medium rounded-md transition-all ${b==="weekly"?"bg-white text-slate-900 shadow-sm":"text-slate-600 hover:text-slate-900"}`,children:"Weekly"}),e.jsx("button",{onClick:()=>{y("monthly"),u(br("monthly"))},className:`flex-1 sm:flex-none px-3 py-1.5 text-sm font-medium rounded-md transition-all ${b==="monthly"?"bg-white text-slate-900 shadow-sm":"text-slate-600 hover:text-slate-900"}`,children:"Monthly"})]}),e.jsx("div",{"data-onboarding":"date-range-picker",children:e.jsx(Sa,{value:x,onChange:u,presets:Xd,placeholder:"Select date range",className:"w-full sm:w-64"})})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center gap-2 sm:gap-3 sm:justify-start",children:[e.jsx("div",{"data-onboarding":"refresh-rankings-button",children:e.jsx(Mm,{enabled:F.autoRefreshEnabled,onToggle:xa,keywordCount:$e.length,estimatedCreditsRange:Ls,estimatingCredits:hn,marketsCount:zs,disabled:Me,onSync:It,isSyncing:f.isRunning,syncPanelState:null})}),e.jsx("div",{className:"hidden sm:block h-6 w-px bg-slate-200"}),e.jsx("div",{className:"w-full sm:w-auto","data-onboarding":"add-keywords-button",children:e.jsx(HN,{disabled:Me,label:"Add Keywords",compactLabel:"Add",align:"right",onSelectKeywords:()=>de(!0),onImportFromTargetKeywords:()=>me(!0),onAddManualKeywords:()=>se(!0)})}),e.jsxs(be,{variant:"outline",size:"sm",className:"gap-1.5 whitespace-nowrap w-full sm:w-auto",onClick:$s,children:[e.jsx(Vs,{className:"w-4 h-4"}),"Export"]})]})]})]}),$&&K&&e.jsxs("div",{className:"md:hidden border-b border-slate-100 bg-white px-4 py-3 space-y-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Pt,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400"}),e.jsx(bt,{placeholder:"Search keywords...",value:T,onChange:Ue=>M(Ue.target.value),onFocus:()=>B(!0),onBlur:()=>B(!1),className:`pl-9 pr-8 w-full transition-all ${Z?"ring-2 ring-blue-100":""}`}),T&&e.jsx("button",{onClick:()=>M(""),className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 hover:bg-slate-100 rounded","aria-label":"Clear search",children:e.jsx(mt,{className:"w-3 h-3 text-slate-400"})})]}),e.jsxs("div",{className:"flex items-center bg-slate-100 rounded-lg p-0.5 w-full",children:[e.jsx("button",{onClick:()=>{y("weekly"),u(br("weekly"))},className:`flex-1 px-3 py-1.5 text-sm font-medium rounded-md transition-all ${b==="weekly"?"bg-white text-slate-900 shadow-sm":"text-slate-600 hover:text-slate-900"}`,children:"Weekly"}),e.jsx("button",{onClick:()=>{y("monthly"),u(br("monthly"))},className:`flex-1 px-3 py-1.5 text-sm font-medium rounded-md transition-all ${b==="monthly"?"bg-white text-slate-900 shadow-sm":"text-slate-600 hover:text-slate-900"}`,children:"Monthly"})]}),e.jsx(Sa,{value:x,onChange:u,presets:Xd,placeholder:"Select date range",className:"w-full"}),e.jsx("div",{className:"pt-1",children:e.jsx(Mm,{enabled:F.autoRefreshEnabled,onToggle:xa,keywordCount:$e.length,estimatedCreditsRange:Ls,estimatingCredits:hn,marketsCount:zs,disabled:Me,onSync:It,isSyncing:f.isRunning,syncPanelState:null})})]}),le&&e.jsx("div",{className:"mb-4",children:e.jsx(ph,{taskId:le,onComplete:zn,onDismiss:$n})}),e.jsx("div",{className:"md:hidden px-4 py-3 bg-white border-b border-slate-100",children:e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx("div",{className:"bg-white border border-slate-200 rounded-xl p-3",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-8 h-8 rounded-lg bg-slate-50 flex items-center justify-center",children:e.jsx(us,{size:16,className:"text-slate-500"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[10px] text-slate-400 uppercase tracking-wider",children:"Total Keywords"}),e.jsx("div",{className:"text-lg font-semibold text-slate-800 tabular-nums",children:ee.total})]})]})}),e.jsx("div",{className:"bg-white border border-slate-200 rounded-xl p-3",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-8 h-8 rounded-lg bg-slate-50 flex items-center justify-center",children:e.jsx(Qt,{size:16,className:"text-slate-500"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[10px] text-slate-400 uppercase tracking-wider",children:"Ranked"}),e.jsx("div",{className:"text-lg font-semibold text-slate-800 tabular-nums",children:ee.ranked})]})]})}),e.jsx("div",{className:"bg-white border border-slate-200 rounded-xl p-3",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-8 h-8 rounded-lg bg-slate-50 flex items-center justify-center",children:e.jsx(Ks,{size:16,className:"text-slate-500"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[10px] text-slate-400 uppercase tracking-wider",children:"Top 10 Rankings"}),e.jsx("div",{className:"text-lg font-semibold text-slate-800 tabular-nums",children:ee.top10})]})]})}),e.jsx("div",{className:"bg-white border border-slate-200 rounded-xl p-3",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-8 h-8 rounded-lg bg-slate-50 flex items-center justify-center",children:e.jsx(Ma,{size:16,className:"text-slate-500"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[10px] text-slate-400 uppercase tracking-wider",children:"Improved"}),e.jsx("div",{className:"text-lg font-semibold text-slate-800 tabular-nums",children:ee.improved})]})]})})]})}),e.jsxs("div",{className:"flex-1 min-h-0 bg-white md:rounded-xl md:border md:border-slate-200 flex flex-col","data-onboarding":"keywords-rankings-table",children:[e.jsxs("div",{className:"flex-1 overflow-hidden",children:[e.jsx(Wx,{rows:ys.map(Ue=>({id:Ue.id,keyword:Ue.keyword,landingPage:Ue.landingPage,rankings:Ue.rankings})),isMobile:$,mobileBottomInset:pa,periods:At,viewMode:b,depth:q,onSort:xe,renderSortIcon:Ee,showSelection:!0,selectedRowIds:te,headerSelectionState:ga?!0:ur?"indeterminate":!1,onToggleAllSelection:()=>{const Ue=fn.every(tt=>te.has(tt));G(tt=>{const st=new Set(tt);
255return Ue?fn.forEach(ft=>st.delete(ft)):fn.forEach(ft=>st.add(ft)),st})},onToggleRowSelection:De,metaTextByKeyword:Ge,showActions:!0,onViewInsights:Ue=>Te(Ue),onDeleteKeyword:(Ue,tt)=>ut(Ue,tt)}),ge&&Y.length===0&&e.jsxs("div",{className:"py-16 text-center",children:[e.jsx("div",{className:"w-16 h-16 bg-slate-100 rounded-full flex items-center justify-center mx-auto mb-4",children:e.jsx(kt,{className:"w-8 h-8 text-slate-400 animate-spin"})}),e.jsx("h3",{className:"text-lg font-medium text-slate-900 mb-1",children:"Loading rankings..."})]}),!ge&&Y.length===0&&e.jsxs("div",{className:"py-16 text-center",children:[e.jsx("div",{className:"w-16 h-16 bg-slate-100 rounded-full flex items-center justify-center mx-auto mb-4",children:e.jsx(us,{className:"w-8 h-8 text-slate-400"})}),e.jsx("h3",{className:"text-lg font-medium text-slate-900 mb-1",children:T?"No keywords found":$e.length===0?"No keywords to track":"No keywords match your search"}),e.jsx("p",{className:"text-sm text-slate-500 mb-4",children:T?"Try adjusting your search query":At.length===0?"Select a date range to view rankings":$e.length===0?"Add keywords to start tracking their rankings over time":"Start by adding keywords to track"}),!T&&$e.length===0&&e.jsx("div",{className:"flex flex-col sm:flex-row items-stretch sm:items-center justify-center gap-2",children:i?e.jsx(be,{size:"md",className:"gap-2",disabled:Me,onClick:i,children:o||"Add Keywords"}):e.jsxs(e.Fragment,{children:[e.jsx(be,{size:"md",className:"gap-2",disabled:Me,onClick:()=>de(!0),children:"Import from Keywords Gap"}),e.jsx(be,{size:"md",variant:"outline",className:"gap-2",disabled:Me,onClick:()=>se(!0),children:"Add manually"})]})})]})]}),e.jsx("div",{className:"hidden md:block flex-none md:border-t md:border-slate-200 bg-white md:rounded-b-xl z-20 space-y-4",children:e.jsx(xn,{maxPageSize:500,page:N,pageSize:k,total:Y.length,onPageChange:S,onPageSizeChange:D})})]}),e.jsx(WN,{open:!!ye,onOpenChange:Ue=>{Ue||Te(null)},keyword:ye||"",history:ye?Pe[ye]:void 0}),e.jsx(Kc,{isOpen:ae,title:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx($t,{className:"w-4 h-4 text-slate-500"}),"Add Keywords"]}),description:"Import keywords from Keywords Gap (competitors vs you).",closeOnOutside:!1,existingKeywords:new Set($e.map(Ue=>Ue.keyword.toLowerCase())),creditEstimate:{scenario:"keywords_tracking_refresh_keywords",params:{markets_count:zs}},onClose:()=>de(!1),onConfirm:Fe}),e.jsx(XN,{isOpen:Q,onClose:()=>me(!1),existingKeywords:new Set($e.map(Ue=>Ue.keyword.toLowerCase())),marketsCount:zs,onConfirm:async Ue=>{try{await yt(Ue),me(!1)}catch{}}}),e.jsx(VN,{isOpen:fe,onClose:()=>se(!1),onAddKeywords:Xe,marketsCount:zs}),e.jsx(hh,{isOpen:z,onClose:()=>U(!1),selectedCount:te.size,selectedKeywords:$e.filter(Ue=>te.has(Ue.id)).map(Ue=>Ue.keyword),onGenerateForEach:ha,onGroupAndGenerate:Ln,onManualGroup:async(Ue,tt)=>{U(!1),G(new Set),jt("keyword_research",{view:"groups"})}}),e.jsx(Ht,{open:A,onOpenChange:C,children:e.jsxs(qt,{className:"sm:max-w-md",children:[e.jsxs(Zt,{children:[e.jsxs(Yt,{className:"flex items-center gap-2",children:[e.jsx(kt,{className:"w-4 h-4 text-slate-500"}),"Refresh keywords rankings"]}),e.jsx(Ds,{children:"Refreshing will fetch the latest ranking data for all your keywords."})]}),e.jsx("div",{className:"space-y-4",children:e.jsxs("div",{className:"flex items-start gap-3 p-4 bg-amber-50 border border-amber-200 rounded-lg",children:[e.jsx(Ks,{className:"w-5 h-5 text-amber-600 flex-shrink-0 mt-0.5"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-amber-800",children:"This action will consume credits"}),e.jsxs("p",{className:"text-sm text-amber-700 mt-1",children:["Estimated cost:"," ",e.jsx("strong",{children:hn?"Estimating...":Ls?.min===Ls?.max?`${Ls?.max} credits`:`${Ls?.min}-${Ls?.max} credits`})," ","for ",e.jsx("strong",{children:$e.length})," keywords",zs>1?e.jsxs(e.Fragment,{children:[" ","across ",e.jsx("strong",{children:zs})," markets"]}):null]})]})]})}),e.jsxs(Ns,{children:[e.jsx(be,{variant:"outline",onClick:()=>C(!1),disabled:f.isRunning,children:"Cancel"}),e.jsx(be,{onClick:async()=>{C(!1),await Ct.current()},disabled:f.isRunning,className:"gap-2",children:f.isRunning?e.jsxs(e.Fragment,{children:[e.jsx(kt,{className:"w-4 h-4 animate-spin"}),"Refreshing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(kt,{className:"w-4 h-4"}),"Refresh Now"]})})]})]})}),$&&V&&e.jsxs("div",{className:"fixed inset-0 z-40 flex items-end justify-center",children:[e.jsx("div",{className:"absolute inset-0 bg-black/40",onClick:()=>P(!1)}),e.jsxs("div",{className:"bg-white w-full rounded-t-2xl relative z-50 p-6 pb-8 flex flex-col gap-2 animate-in slide-in-from-bottom duration-200",children:[e.jsx("div",{className:"w-12 h-1 bg-gray-200 rounded-full mx-auto mb-3"}),e.jsx("h3",{className:"text-center text-base font-medium text-gray-800 mb
255-2",children:"Actions"}),e.jsxs("button",{onClick:()=>{P(!1),de(!0)},className:"w-full flex items-center gap-3 px-4 py-3 rounded-xl bg-slate-50 hover:bg-slate-100 text-slate-800",children:[e.jsx(us,{className:"h-5 w-5 text-slate-600"}),e.jsx("span",{className:"text-sm font-medium",children:"Import from Keywords Gap"})]}),e.jsxs("button",{onClick:()=>{P(!1),me(!0)},className:"w-full flex items-center gap-3 px-4 py-3 rounded-xl bg-slate-50 hover:bg-slate-100 text-slate-800",children:[e.jsx(us,{className:"h-5 w-5 text-slate-600"}),e.jsx("span",{className:"text-sm font-medium",children:"Import from Keywords Group"})]}),e.jsxs("button",{onClick:()=>{P(!1),se(!0)},className:"w-full flex items-center gap-3 px-4 py-3 rounded-xl bg-slate-50 hover:bg-slate-100 text-slate-800",children:[e.jsx($t,{className:"h-5 w-5 text-slate-600"}),e.jsx("span",{className:"text-sm font-medium",children:"Add manually"})]}),e.jsxs("button",{onClick:()=>{P(!1),$s()},className:"w-full flex items-center gap-3 px-4 py-3 rounded-xl bg-slate-50 hover:bg-slate-100 text-slate-800",children:[e.jsx(Vs,{className:"h-5 w-5 text-slate-600"}),e.jsx("span",{className:"text-sm font-medium",children:"Export"})]}),e.jsx("button",{onClick:()=>P(!1),className:"mt-2 py-3 text-slate-500 font-medium text-sm w-full hover:bg-slate-50 rounded-xl",children:"Cancel"})]})]}),e.jsx("button",{onClick:L.startManual,className:"fixed bottom-5 right-5 z-50 h-8 w-8 rounded-full bg-white border border-slate-200 shadow-md hover:shadow-lg hover:bg-slate-50 transition-all hover:scale-105 hidden sm:flex items-center justify-center",title:"View navigation guide","aria-label":"View navigation guide",children:e.jsx(Hs,{className:"h-4 w-4 text-slate-600"})}),!$&&e.jsx(oa,{steps:zN,run:L.run,onComplete:L.stopAndMarkCompleted,onSkip:L.stopAndMarkCompleted})]})}async function _h(t){return await ot("/usage_history/credit_records",t)}async function ek(t){return await ot("/usage_history/daily_credits",t)}async function tk(t){return await ot("/usage_history/usage_breakdown",t)}const sk=[{target:'[data-onboarding="usage-intro"]',content:"Usage History tracks your credit consumption over time. Monitor spending patterns to optimize your usage and plan renewals.",placement:"bottom",disableBeacon:!0},{target:'[data-onboarding="date-filter"]',content:"Filter usage records by date range. View consumption for specific periods to analyze spending trends.",placement:"bottom",disableBeacon:!0},{target:'[data-onboarding="usage-chart"]',content:"The daily credits chart visualizes consumption over time. Identify usage spikes and patterns to better manage your credit budget.",placement:"bottom",disableBeacon:!0},{target:'[data-onboarding="usage-breakdown"]',content:"Usage breakdown shows credit consumption by category. Understand which features consume the most credits.",placement:"left",disableBeacon:!0},{target:'[data-onboarding="usage-records"]',content:"Detailed records list each credit transaction with timestamp, category, and amount. Export data for external analysis if needed.",placement:"top",disableBeacon:!0}],Lm={worksheets:"Worksheets",prompt_tracking:"Prompt tracking",data_report:"Data report",unknown:"Unknown operation"},zm={domain_sync_overview:"Sync domain overview",domain_sync_ranked_keywords:"Sync ranked keywords",competitors_intelligence_add_competitor:"Add competitor",competitors_intelligence_refresh_competitor:"Refresh competitor",keywords_research_refresh_competitor:"Refresh competitors (keyword research)",keywords_tracking_refresh_keywords:"Refresh tracked keywords",company_full_analysis:"Company full analysis",unknown:"Unknown operation"};function $m(t){return t.trim().toLowerCase()}function ak(t){return t.split("_").filter(Boolean).map(s=>s.charAt(0).toUpperCase()+s.slice(1).toLowerCase()).join(" ")}function Ch({bizType:t,source:s}){const a=typeof t=="string"?t.trim():"",n=typeof s=="string"?s.trim():"";if(a.length===0)return"Data fetch";const o=$m(a),i=$m(n);return o==="unknown"?i==="tokenusage"||i==="token_usage"?"LLM cost":"Data fetch":!a.includes("_")&&a!==a.toLowerCase()?a:o in Lm?Lm[o]||a:o in zm?zm[o]||a:ak(a)}function nk(t){if(!t)return"—";try{const s=new Date(t),a=s.getUTCFullYear(),n=String(s.getUTCMonth()+1).padStart(2,"0"),o=String(s.getUTCDate()).padStart(2,"0"),i=String(s.getUTCHours()).padStart(2,"0"),l=String(s.getUTCMinutes()).padStart(2,"0"),c=String(s.getUTCSeconds()).padStart(2,"0");return`${a}-${n}-${o} ${i}:${l}:${c}`}catch{return t}}function Fm(t){const s=t.getUTCFullYear(),a=String(t.getUTCMonth()+1).padStart(2,"0"),n=String(t.getUTCDate()).padStart(2,"0");return`${s}-${a}
255-${n}`}function rk(){const t=new Date,s=Fm(t),a=new Date(Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate()));return a.setUTCDate(a.getUTCDate()-29),{start_date:Fm(a),end_date:s}}function ok(t){return{start_date:t.start_date||void 0,end_date:t.end_date||void 0,include_increase:t.include_increase}}function wn(t){return Number.isFinite(t)?Math.round(t).toLocaleString():"0"}function vl(t,s){return Ch({bizType:t,source:s})}function ik(){const{toast:t}=_t(),s=Zs(Us.usage_history),a=v.useMemo(()=>rk(),[]),[n,o]=v.useState(()=>({start_date:a.start_date,end_date:a.end_date,include_increase:!1})),[i,l]=v.useState(1),[c,d]=v.useState(20),[m,h]=v.useState(!1),[p,f]=v.useState([]),[b,y]=v.useState(0),[x,u]=v.useState([]),[g,w]=v.useState([]),_=Math.max(1,Math.ceil(b/c)),E=v.useCallback(async()=>{h(!0);try{const R=ok(n),[L,$,H]=await Promise.all([_h({...R,page:i,page_size:c}),ek(R),tk(R)]);f(L.items||[]),y(L.total||0),u($.items||[]),w(H.items||[])}catch(R){const L=ya(R);t({title:L.type==="warning"?"Warning":"Error",description:L.content||"Failed to load usage history."})}finally{h(!1)}},[n.start_date,n.end_date,n.include_increase,i,c,t]);v.useEffect(()=>{E()},[E]);const N=v.useMemo(()=>(x||[]).reduce((R,L)=>R+(L.credit_cost||0),0),[x]),S=v.useMemo(()=>x.length===0?0:N/x.length,[N,x]),k=v.useCallback(()=>{o({start_date:a.start_date,end_date:a.end_date,include_increase:!1}),l(1)},[a]),D=v.useMemo(()=>{const R=x.map($=>$.date),L=x.map($=>$.credit_cost);return{tooltip:{trigger:"axis",backgroundColor:"rgba(255, 255, 255, 0.95)",borderColor:"#e2e8f0",borderWidth:1,textStyle:{color:"#1e293b",fontSize:12},padding:[8,12],extraCssText:"box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1); border-radius: 8px;",formatter:$=>{const H=Array.isArray($)?$[0]:$;return`
256            <div style="font-weight:600; margin-bottom:4px;">${H.name}</div>
257            <div style="display:flex; align-items:center; gap:8px;">
258              <span style="display:inline-block;width:8px;height:8px;border-radius:50%;background-color:${typeof H.color=="object"&&H.color.colorStops?H.color.colorStops[0].color:H.color}"></span>
259              <span style="color:#64748b">Usage:</span>
260              <span style="font-weight:600; color:#0f172a">${wn(H.value)}</span>
261            </div>
262          `}},grid:{left:"10",right:"10",top:"20",bottom:"10",containLabel:!0},xAxis:{type:"category",data:R,axisLine:{show:!1},axisTick:{show:!1},axisLabel:{color:"#94a3b8",margin:12,fontSize:10,formatter:$=>$.slice(5)}},yAxis:{type:"value",splitLine:{lineStyle:{color:"#f1f5f9",type:"dashed"}},axisLabel:{color:"#94a3b8",fontSize:10,formatter:$=>$>=1e3?`${($/1e3).toFixed(1)}k`:$}},series:[{name:"Usage",data:L,type:"bar",barMaxWidth:30,itemStyle:{color:new Xh(0,0,0,1,[{offset:0,color:"#6366f1"},{offset:1,color:"#818cf8"}]),borderRadius:[4,4,0,0]},animationDuration:1e3},{name:"Trend",data:L,type:"line",smooth:!0,showSymbol:!1,lineStyle:{color:"#fbbf24",width:3,shadowColor:"rgba(251, 191, 36, 0.3)",shadowBlur:10},z:10}]}},[x]),F=v.useMemo(()=>{const R=g.map(L=>({name:vl(L.biz_type,L.source),value:L.credit_cost})).filter(L=>L.name);return{tooltip:{trigger:"item",backgroundColor:"rgba(255, 255, 255, 0.95)",borderColor:"#e2e8f0",borderWidth:1,textStyle:{color:"#1e293b",fontSize:12},formatter:L=>`
263                  <div style="font-weight:600; margin-bottom:4px;">${L.name}</div>
264                  <div style="display:flex; align-items:center; gap:8px;">
265                     <span style="font-weight:600; color:#0f172a">${wn(L.value)}</span>
266                     <span style="color:#64748b">(${L.percent}%)</span>
267                  </div>
268                `},legend:{type:"scroll",orient:"horizontal",bottom:10,left:"center",textStyle:{color:"#64748b",fontSize:10},itemWidth:12,itemHeight:8,itemGap:8,formatter:L=>L.length>20?L.substring(0,20)+"...":L,pageIconColor:"#64748b",pageTextStyle:{color:"#64748b",fontSize:10}},series:[{name:"Usage Breakdown",type:"pie",radius:["35%","65%"],center:["50%","45%"],avoidLabelOverlap:!1,itemStyle:{borderRadius:5,borderColor:"#fff",borderWidth:2},label:{show:!1,position:"center"},emphasis:{label:{show:!0,fontSize:14,fontWeight:"bold",color:"#0f172a"}},labelLine:{show:!1},data:R}]}},[g]);return e.jsxs("div",{className:"h-full overflow-y-auto p-6 max-w-7xl mx-auto 
268space-y-6 animate-in fade-in duration-500","data-onboarding":"usage-intro",children:[e.jsx("div",{className:"flex flex-col md:flex-row md:items-end justify-between gap-6",children:e.jsxs("div",{children:[e.jsx("h1",{className:"text-3xl font-bold tracking-tight text-slate-900",children:"Usage History"}),e.jsx("p",{className:"text-slate-500 mt-2 text-sm max-w-2xl leading-relaxed",children:"Track your credit consumption across different services. All dates and times are displayed in UTC."})]})}),e.jsxs("div",{className:"bg-white rounded-xl border border-slate-200 shadow-sm p-1.5 flex flex-wrap items-center gap-2 sticky top-4 z-10 backdrop-blur-xl bg-white/90 supports-[backdrop-filter]:bg-white/80","data-onboarding":"date-filter",children:[e.jsx(Sa,{value:{from:n.start_date,to:n.end_date},onChange:R=>{o(L=>({...L,start_date:R.from||"",end_date:R.to||""}))},placeholder:"Select date range",className:"w-64",showClear:!0}),e.jsxs("div",{className:"flex items-center gap-2 ml-auto",children:[m&&e.jsxs("div",{className:"flex items-center text-xs text-indigo-600 mr-2 bg-indigo-50 px-2 py-1 rounded-full animate-pulse",children:[e.jsx(He,{className:"h-3 w-3 mr-1.5 animate-spin"}),"Updating..."]}),e.jsxs(be,{variant:"ghost",size:"sm",onClick:k,disabled:m,className:"text-slate-500 hover:text-slate-700 hover:bg-slate-100",children:[e.jsx(kt,{className:"h-4 w-4 mr-2"}),"Reset"]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs(xs,{className:"border-slate-200 shadow-sm overflow-hidden","data-onboarding":"usage-chart",children:[e.jsx(Bs,{className:"border-b border-slate-100 bg-slate-50/50 py-3 px-4",children:e.jsxs(Xs,{className:"text-sm font-semibold text-slate-700 flex items-center gap-2",children:[e.jsx(Ma,{className:"h-4 w-4 text-slate-500"}),"Daily Trend"]})}),e.jsx(fs,{className:"p-4",children:m&&x.length===0?e.jsxs("div",{className:"h-[220px] flex items-center justify-center text-slate-400",children:[e.jsx(He,{className:"h-6 w-6 animate-spin mr-2"}),"Loading chart data..."]}):x.length===0?e.jsxs("div",{className:"h-[220px] flex items-center justify-center text-slate-400 flex-col gap-2",children:[e.jsx("div",{className:"p-3 bg-slate-50 rounded-full",children:e.jsx(Zi,{className:"h-6 w-6 text-slate-300"})}),e.jsx("p",{className:"text-sm",children:"No usage data available."})]}):e.jsx(Cr,{option:D,style:{height:"220px",width:"100%"},opts:{renderer:"canvas"}})})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-4",children:[e.jsx(xs,{className:"border-none shadow-sm bg-gradient-to-br from-indigo-50 to-white ring-1 ring-slate-200/60",children:e.jsxs(fs,{children:[e.jsxs("div",{className:"flex items-center gap-3 mb-2 mt-4",children:[e.jsx("div",{className:"p-1.5 bg-indigo-100/50 rounded-lg",children:e.jsx(Wa,{className:"h-4 w-4 text-indigo-600"})}),e.jsx("span",{className:"text-xs font-medium text-slate-500 uppercase tracking-wide",children:"Total"})]}),e.jsx("div",{className:"text-xl font-bold text-slate-900",children:wn(N)})]})}),e.jsx(xs,{className:"border-none shadow-sm bg-gradient-to-br from-emerald-50 to-white ring-1 ring-slate-200/60",children:e.jsxs(fs,{children:[e.jsxs("div",{className:"flex items-center gap-3 mb-2 mt-4",children:[e.jsx("div",{className:"p-1.5 bg-emerald-100/50 rounded-lg",children:e.jsx(Zi,{className:"h-4 w-4 text-emerald-600"})}),e.jsx("span",{className:"text-xs font-medium text-slate-500 uppercase tracking-wide",children:"Daily Avg"})]}),e.jsx("div",{className:"text-xl font-bold text-slate-900",children:wn(S)})]})}),e.jsx(xs,{className:"border-none shadow-sm bg-gradient-to-br from-blue-50 to-white ring-1 ring-slate-200/60",children:e.jsxs(fs,{children:[e.jsxs("div",{className:"flex items-center gap-3 mb-2 mt-4",children:[e.jsx("div",{className:"p-1.5 bg-blue-100/50 rounded-lg",children:e.jsx(Ms,{className:"h-4 w-4 text-blue-600"})}),e.jsx("span",{className:"text-xs font-medium text-slate-500 uppercase tracking-wide",children:"Records"})]}),e.jsx("div",{className:"text-xl font-bold text-slate-900",children:b.toLocaleStr
268ing()})]})})]})]}),e.jsx("div",{className:"space-y-6","data-onboarding":"usage-breakdown",children:e.jsxs(xs,{className:"border-slate-200 shadow-sm overflow-hidden h-full",children:[e.jsx(Bs,{className:"border-b border-slate-100 bg-slate-50/50 py-3 px-4",children:e.jsxs(Xs,{className:"text-sm font-semibold text-slate-700 flex items-center gap-2",children:[e.jsx(Qh,{className:"h-4 w-4 text-slate-500"}),"Usage Breakdown"]})}),e.jsx(fs,{className:"p-0 relative min-h-[300px]",children:m&&g.length===0?e.jsx("div",{className:"absolute inset-0 flex items-center justify-center text-slate-400 bg-white/50 z-10",children:e.jsx(He,{className:"h-6 w-6 animate-spin mr-2"})}):g.length===0?e.jsx("div",{className:"absolute inset-0 flex items-center justify-center text-slate-400 flex-col gap-2",children:e.jsx("p",{className:"text-sm",children:"No data for breakdown."})}):e.jsx(Cr,{option:F,style:{height:"340px",width:"100%"},opts:{renderer:"canvas"}})})]})})]}),e.jsxs(xs,{className:"border-slate-200 shadow-sm overflow-hidden","data-onboarding":"usage-records",children:[e.jsxs(Bs,{className:"border-b border-slate-100 bg-slate-50/50 py-3 px-6 flex flex-row items-center justify-between",children:[e.jsx(Xs,{className:"text-base font-semibold text-slate-800 flex items-center gap-2",children:"Logs"}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("span",{className:"text-xs text-slate-500 font-medium bg-white px-2 py-1 rounded border border-slate-200",children:[b," records"]}),e.jsxs("select",{className:"h-8 rounded-md border border-slate-200 bg-white px-2 text-xs font-medium text-slate-600 outline-none focus:ring-2 focus:ring-indigo-500/20 focus:border-indigo-500 cursor-pointer hover:bg-slate-50",value:String(c),onChange:R=>{const L=Number(R.target.value)||20;d(L),l(1)},disabled:m,children:[e.jsx("option",{value:"10",children:"10 / page"}),e.jsx("option",{value:"20",children:"20 / page"}),e.jsx("option",{value:"50",children:"50 / page"}),e.jsx("option",{value:"100",children:"100 / page"})]})]})]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm text-left",children:[e.jsx("thead",{className:"bg-slate-50/80 border-b border-slate-200",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-6 py-3 font-semibold text-slate-500 text-xs uppercase tracking-wider w-[180px]",children:"Timestamp (UTC)"}),e.jsx("th",{className:"px-6 py-3 font-semibold text-slate-500 text-xs uppercase tracking-wider",children:"Type"}),e.jsx("th",{className:"px-6 py-3 font-semibold text-slate-500 text-xs uppercase tracking-wider text-right w-[120px]",children:"Cost"}),e.jsx("th",{className:"px-6 py-3 font-semibold text-slate-500 text-xs uppercase tracking-wider text-right w-[180px]",children:"Balance Flow"})]})}),e.jsx("tbody",{className:"divide-y divide-slate-100 bg-white",children:m&&p.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:4,className:"px-6 py-16 text-center text-slate-500",children:e.jsxs("div",{className:"flex flex-col items-center justify-center gap-2",children:[e.jsx(He,{className:"h-6 w-6 animate-spin text-indigo-500"}),e.jsx("p",{className:"text-xs font-medium",children:"Loading records..."})]})})}):p.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:4,className:"px-6 py-16 text-center text-slate-500",children:e.jsxs("div",{className:"flex flex-col items-center justify-center gap-2",children:[e.jsx(Zi,{className:"h-8 w-8 text-slate-300"}),e.jsx("p",{children:"No transaction records found."})]})})}):p.map(R=>e.jsxs("tr",{className:"hover:bg-slate-50/80 transition-colors group",children:[e.jsx("td",{className:"px-6 py-3 text-slate-600 font-medium text-xs font-mono whitespace-nowrap",children:nk(R.created_at)}),e.jsx("td",{className:"px-6 py-3 text-slate-700",children:e.jsx("div",{className:"text-sm",title:vl(R.biz_type,R.source),children:vl(R.biz_type,R.source)})}),e.jsx("td",{className:"px-6 py-3 text-right font-semibold tabular-nums text-xs",children:R.is_increase?e.jsxs("span",{className:"text-green-600",children:["+",wn(R.credit_cost)]}):e.jsxs("span",{className:"text-slate-900",children:["-",wn(R.credit_cost)]})}),e.jsx("td",{className:"px-6 py-3 text-right tabular-nums text-xs",children:e.jsxs("div",{className:"flex items-center justify-end gap-1.5",children:[e.jsx("span",{className:"text-slate-400 line-through opacity-70",children:wn(R.before_balance)}),e.jsx(Ms,{className:"h-3 w-3 text-slate-300"}),e.jsx("span",{className:"font-bold text-slate-700",children:wn(R.after_balance)})]})})]},R.id))})]})}),e.jsxs("div",{className:"bg-slate-50/50 border-t border-slate-100 px-6 py-3 flex items-center justify-between",children:[e.jsxs("div",{className:"text-xs text-slate-500",children:["Page ",i," of ",_]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(be,{variant:"outline",size:"sm",onClick:()=>l(R=>Math.max(1,R-1)),disabled:m||i<=1,className:"h-7 px-3 text-xs",children:"Previous"}),e.jsx(be,{variant:"outline",size:"sm",onClick:()=>l(R=>Math.min(_,R+1)),disabled:m||i>=_,className:"h-7 px-3 text-xs",children:"Next"})]})]})]}),e.jsx("button",{onClick:s.startManual,className:"fixed bottom-5 right-5 z-50 h-8 w-8 rounded-full bg-white border border-slate-200 shadow-md hover:shadow-lg hover:bg-slate-50 transition-all hover:scale-105 hidden sm:flex items-center justify-center",title:"View navigation guide","aria-label":"View navigation guide",children:e.jsx(Hs,{className:"h-4 w-4 text-slate-600"})}),e.jsx(oa,{steps:sk,run:s.run,onComplete:s.stopAndMarkCompleted,onSkip:s.stopAndMarkCompleted})]})}function lk(){sg("content");const[t,s]=v.useState(!0);return v.useEffect(()=>{(async()=>{const n=da();if(!n){console.warn("No campaign ID found, redirecting to campaigns"),jt("campaigns");return}try{const o=await Wt.listViewConfigs({campaign_id:n,view_system_name:"content"});o.items.length>0?jt("table",{campaign:n,view:o.items[0].id}):(console.error("Content system view not found"),s(!1))}catch(o){console.error("Failed to load content view:",o),s(!1)}})()},[]),t?e.jsx("div",{className:"flex items-center justify-center h-screen",children:e.jsx("div",{className:"text-slate-600",children:"Loading content view..."})}):e.jsx("div",{className:"flex items-center justify-center h-screen",children:e.jsx("div",{className:"text-slate-600",children:"Content view not found. Please contact support."})})}const mn={text:_a,number:qn,select:_o,date:ka,checkbox:zi,url:Li,email:ui,enumerate:mc,image:rn,knowledge:iu,ai:Zh,ai_image:rn,keywords:Lr,seo_analysis:Pt,seo_action:us,webflow:rn,shopify:dc,system:cc,composite:qa,ai_seo_analysis:Di,ai_keywords:oc,status:wt},kr={text:"Text",number:"Number",select:"Select",date:"Date",checkbox:"Checkbox",url:"URL",email:"Email",enumerate:"Enumerate",image:"Image",knowledge:"Knowledge",ai:"AI",ai_image:"AI Image (nanobanana)",keywords:"Keywords",seo_analysis:"PAGE ANALYSIS FOR GEO&SEO",seo_action:"SEO Action",webflow:"Webflow",shopify:"Shopify",system:"System",composite:"Composite",ai_
268seo_analysis:"SEO Health",ai_keywords:"AI Keywords",status:"Status"},ko=["ai","ai_image","keywords","seo_analysis","ai_seo_analysis","ai_keywords"],Ii=[{id:"gemini-3-pro",name:"Gemini 3.1 Pro",provider:"Google"},{id:"gemini-3-flash",name:"Gemini 3 Flash",provider:"Google"}],Nl=[{id:"gemini-3-pro-preview",name:"Gemini 3.1 Pro",provider:"Google"},{id:"gemini-3-flash-preview",name:"Gemini 3 Flash",provider:"Google"}],Om={text:"text",number:"number",select:"select",status:"status",date:"date",checkbox:"checkbox",url:"url",email:"email",enumerate:"enumerate",image:"image",knowledge:"knowledge",ai:"ai",ai_text:"ai",ai_image:"ai_image",keywords:"keywords",seo_analysis:"seo_analysis",seo_action:"seo_action",webflow:"webflow",shopify:"shopify",system:"system",composite:"composite"},Ho=10,ck=[{name:"Basic",types:["text","number","select","date","checkbox","url","email","image","knowledge"]},{name:"AI & Advanced",types:["ai","ai_image","keywords","seo_analysis","seo_action"]},{name:"Integrations",types:["webflow","shopify"]},{name:"Layout",types:["composite"]}],Sh=r.createContext(null),dk=()=>{const t=r.useContext(Sh);if(!t)throw new Error("useSelection must be used within SelectionProvider");return t},na=(t,s)=>{const a=s?.pretty??!1,n=s?.fallback??"";if(t==null||t&&typeof t=="object"&&t.__pending===!0&&typeof t.__task_id=="string")return n;if(typeof t=="string")return t;if(typeof t=="number"||typeof t=="boolean")return String(t);if(typeof t=="object")try{return JSON.stringify(t,null,a?2:void 0)??n}catch(o){return console.error("[serializeCustomDataValue] Failed to stringify value:",o),String(t)}return String(t)};function Bm(t,s={}){const{preventFormulaInjection:a=!0}=s;let n=t==null?"":String(t);if(a&&n.length>0){const i=n[0];(i==="="||i==="+"||i==="-"||i==="@")&&(n="'"+n)}const o=n.includes('"')||n.includes(",")||n.includes(`
269`)||n.includes("\r");return n.includes('"')&&(n=n.replace(/"/g,'""')),o?`"${n}"`:n}function mk(t){const{headers:s,rows:a,lineEnding:n=`\r
270`,preventFormulaInjection:o=!0}=t,i=[];i.push(s.map(l=>Bm(l,{preventFormulaInjection:o})).join(","));for(const l of a)i.push(l.map(c=>Bm(c,{preventFormulaInjection:o})).join(","));return i.join(n)}function uk(t){const{filename:s,csvContent:a,bom:n=!0}=t,o=s.toLowerCase().endsWith(".csv")?s:`${s}.csv`,i=n?"\uFEFF"+a:a,l=new Blob([i],{type:"text/csv;charset=utf-8;"});Ar({filename:o,blob:l})}function Um(t){const{filename:s,data:a,pretty:n=!0}=t,o=s.toLowerCase().endsWith(".json")?s:`${s}.json`,i=JSON.stringify(a,null,n?2:void 0),l=new Blob([i],{type:"application/json;charset=utf-8;"});Ar({filename:o,blob:l})}const Un=(t,s)=>`${t}:${s}`,Km=t=>{const[s,a]=t.split(":");return{rowId:s,colId:a}},Eh=(t="")=>`${t}${Math.random().toString(36).substr(2,9)}`,xk=({open:t,columnName:s,onConfirm:a,onCancel:n})=>{const[o,i]=r.useState(!0);return t?e.jsxs("div",{className:"fixed inset-0 z-[10002] flex items-center justify-center",children:[e.jsx("div",{className:"absolute inset-0 bg-black/20 backdrop-blur-sm",onClick:n}),e.jsxs("div",{className:"relative bg-white rounded-xl shadow-lg max-w-md w-full mx-4 border border-gray-200",children:[e.jsxs("div",{className:"flex items-start justify-between p-4 border-b border-gray-100",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(qa,{className:"h-4 w-4 text-blue-600"}),e.jsx("h3",{className:"text-[13px] font-semibold text-gray-800",children:"Add Column to Composite"})]}),e.jsx("button",{onClick:n,className:"flex-shrink-0 h-6 w-6 flex items-center justify-center hover:bg-gray-100 rounded transition-colors",children:e.jsx(mt,{className:"h-3.5 w-3.5 text-gray-400"})})]}),e.jsxs("div",{className:"p-4 space-y-4",children:[e.jsxs("p",{className:"text-[11px] text-gray-600 leading-relaxed",children:["You are adding ",e.jsxs("span",{className:"font-semibold",children:['"',s,'"']})," ","to this composite column."]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-[11px] font-medium text-gray-700",children:"Do you want to hide its standalone display?"}),e.jsxs("label",{className:"flex items-center gap-2 p-2 rounded-lg hover:bg-gray-50 cursor-pointer",children:[e.jsx("input",{type:"radio",name:"hideStandalone",checked:!o,onChange:()=>i(!1),className:"text-blue-600"}),e.jsx("span",{className:"text-[11px] text-gray-600",children:"Keep standalone column visible"})]}),e.jsxs("label",{className:"flex items-center gap-2 p-2 rounded-lg hover:bg-gray-50 cursor-pointer",children:[e.jsx("input",{type:"radio",name:"hideStandalone",checked:o,onChange:()=>i(!0),className:"text-blue-600"}),e.jsxs("div",{children:[e.jsx("span",{className:"text-[11px] text-gray-600",children:"Hide standalone column"}),e.jsx("span",{className:"text-[10px] text-gray-400 ml-1",children:"(data will be preserved)"})]})]})]})]}),e.jsxs("div",{className:"flex items-center justify-end gap-2 p-4 border-t border-gray-100",children:[e.jsx("button",{onClick:n,className:"px-3 py-1.5 rounded-lg border border-gray-200 text-[11px] font-medium text-gray-600 hover:bg-gray-50 transition-colors",children:"Cancel"}),e.jsx("button",{onClick:()=>a(o),className:"px-3 py-1.5 rounded-lg text-[11px] font-medium transition-colors bg-blue-600 hover:bg-blue-700 text-white",children:"Confirm"})]})]})]}):null},hk=({open:t,availableColumns:s,onSelect:a,onClose:n,anchorRef:o})=>{const[i,l]=r.useState(""),[c,d]=r.useState(null);r.useEffect(()=>{if(t&&o.current){const h=o.current.getBoundingClientRect();d({top:h.bottom+window.scrollY+4,left:h.left+window.scrollX})}},[t,o]);const m=r.useMemo(()=>{const h=i.toLowerCase().trim();return h?s.filter(p=>p.title.toLowerCase().includes(h)||p.type.toLowerCase().includes(h)):s},[s,i]);return!t||!c?null:Ha.createPortal(e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[10001]",onClick:n}),e.jsxs("div",{className:"fixed w-72 bg-white border border-gray-200 rounded-lg shadow-lg z-[10002] overflow-hidden",style:{to
270p:c.top,left:c.left},children:[e.jsx("div",{className:"p-2 border-b border-gray-100",children:e.jsx("input",{type:"text",value:i,onChange:h=>l(h.target.value),placeholder:"Search columns...",className:"w-full px-2 py-1.5 text-[11px] border border-gray-200 rounded focus:outline-none focus:border-blue-400",autoFocus:!0})}),e.jsx("div",{className:"max-h-64 overflow-y-auto",children:m.length===0?e.jsx("div",{className:"p-4 text-center text-[11px] text-gray-400",children:"No available columns"}):m.map(h=>{const p=mn[h.type]||mn.text;return e.jsxs("button",{onClick:()=>{a(h),n(),l("")},className:"w-full flex items-center gap-2 px-3 py-2 hover:bg-gray-50 text-left transition-colors",children:[e.jsx(p,{size:12,className:"text-gray-400 flex-shrink-0"}),e.jsx("span",{className:"text-[11px] text-gray-700 truncate flex-1",children:h.title}),e.jsx("span",{className:"text-[10px] text-gray-400 flex-shrink-0",children:kr[h.type]||h.type})]},h.id)})})]})]}),document.body)},pk=({col:t,allColumns:s,onUpdateChildren:a,onUpdateChildColumn:n,onTrackRemovedChild:o,onTrackAddedChild:i})=>{const[l,c]=r.useState(!1),[d,m]=r.useState(null),[h,p]=r.useState(null),f=v.useRef(null),b=r.useMemo(()=>t.config?.composite?.children||[],[t.config?.composite?.children]),y=r.useMemo(()=>{const S=new Set(b.map(k=>k.column_id));return s.filter(k=>k.id!==t.id&&k.type!=="composite"&&!S.has(k.id))},[s,b,t.id]),x=r.useMemo(()=>b.sort((S,k)=>S.order-k.order).map(S=>{const k=s.find(D=>D.id===S.column_id);return{child:S,column:k}}).filter(S=>S.column!==void 0),[b,s]),u=r.useCallback(S=>{m(S)},[]),g=r.useCallback(S=>{if(!d)return;const k={column_id:d.id,order:b.length,hide_standalone:S};a([...b,k]),t.id&&i&&i(d.id,S),m(null)},[d,b,a,i,t.id]),w=r.useCallback(S=>{const k=b.filter(D=>D.column_id!==S).map((D,F)=>({...D,order:F}));a(k),o&&o(S)},[b,a,o]),_=S=>{p(S)},E=(S,k)=>{if(S.preventDefault(),h===null||h===k)return;const D=[...b].sort((L,$)=>L.order-$.order),[F]=D.splice(h,1);D.splice(k,0,F);const R=D.map((L,$)=>({...L,order:$}));a(R),p(k)},N=()=>{p(null)};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h4",{className:"text-[12px] font-semibold text-gray-700",children:"Child Columns"}),e.jsxs("span",{className:"text-[10px] text-gray-400",children:[x.length," column",x.length!==1?"s":""]})]}),e.jsx("div",{className:"border border-gray-200 rounded-lg overflow-hidden max-h-[200px] overflow-y-auto custom-scrollbar",children:x.length===0?e.jsxs("div",{className:"p-6 text-center",children:[e.jsx(qa,{size:24,className:"mx-auto text-gray-300 mb-2"}),e.jsx("p",{className:"text-[11px] text-gray-400",children:"No columns added yet"}),e.jsx("p",{className:"text-[10px] text-gray-300 mt-1",children:'Click "Add Column" to select existing columns'})]}):e.jsx("div",{className:"divide-y divide-gray-100",children:x.map(({child:S,column:k},D)=>{const F=mn[k.type]||mn.text;return e.jsxs("div",{draggable:!0,onDragStart:()=>_(D),onDragOver:R=>E(R,D),onDragEnd:N,className:`flex items-center gap-2 px-3 py-2 bg-white hover:bg-gray-50 transition-colors ${h===D?"opacity-50":""}`,children:[e.jsx(ru,{size:12,className:"text-gray-300 cursor-grab flex-shrink-0"}),e.jsx(F,{size:12,className:"text-gray-400 flex-shrink-0"}),e.jsx("span",{className:"text-[11px] text-gray-700 truncate flex-1",children:k.title}),e.jsx("span",{className:"text-[10px] text-gray-400 bg-gray-100 px-1.5 py-0.5 rounded flex-shrink-0",children:kr[k.type]||k.type}),e.jsx("button",{onClick:()=>w(S.column_id),className:"p-1 hover:bg-red-50 rounded transition-colors flex-shrink-0",title:"Remove from composite",children:e.jsx(es,{size:12,className:"text-gray-400 hover:text-red-500"})})]},S.column_id)})})}),e.jsxs("div",{className:"flex items-center gap-2 relative",children:[e.jsxs("button",{ref:f,onClick:()=>c(!0),disabled:y.length===0,className:"flex items-center gap-1.5 px-3 py-1.5 text-[11px] font-medium text-blue-600 border border-blue-200 rounded-lg hover:bg-blue-50 transition-colors disabled:opacity-50 disabled:cursor-not-allowed",children:[e.jsx($t,{size:12}),"Add Column"]}),e.jsx(hk,{open:l,availableColumns:y,onSelect:u,onClose:()=>c(!1),anchorRef:f})]}),e.jsx(xk,{open:d!==null,columnName:d?.title||"",onConfirm:g,onCancel:()=>m(null)})]})};class gk{async getCollectionTypes(){const s=await ot("/articles/get_collections");return Array.isArray(s)?{collections:s,customDomains:[]}:s}}const Mi=new gk;function Gm({value:t,onChange:s,columns:a,placeholder:n="Type / to insert column reference",className:o="",minHeight:i=120,maxHeight:l=300,fillHeight:c=!1}){const d=r.useRef(null),[m,h]=r.useState(!1),[p,f]=r.useState(""),[b,y]=r.useState({top:0,left:0}),[x,u]=r.useState(0),g=r.useRef(null),w=r.useRef(null),_=r.useRef(!1),E=r.useRef(!1),N=["CAMPAIGN INFO"],S={"CAMPAIGN INFO":"campaign info"},k=v.useMemo(()=>a.map(T=>typeof T=="string"?{id:T,name:T,system_name:void 0}:T),[a]),D=v.useMemo(()=>{const T=new Map,M=new Map;
270return k.forEach(Z=>{Z.system_name&&T.set(Z.system_name,Z),M.set(Z.name,Z)}),{bySystemName:T,byName:M}},[k]),F=r.useCallback(T=>{if(D.bySystemName.has(T))return D.bySystemName.get(T);if(D.byName.has(T))return D.byName.get(T)},[D]),R=r.useCallback(T=>T.system_name||T.name,[]),L=r.useCallback(T=>{const M=F(T);return M?M.name:T},[F]),$=v.useMemo(()=>{const T=p.toLowerCase(),M=N.filter(B=>B.toLowerCase().includes(T)),Z=k.filter(B=>B.name.toLowerCase().includes(T)).map(B=>B.name);return[...M,...Z]},[k,p]),H=r.useCallback(T=>T.replace(/\$\{([^}]+)\}/g,(M,Z)=>{const B=L(Z);return`<span class="column-pill" contenteditable="false" data-column="${Z}"><svg class="column-pill-icon" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path></svg><span class="column-pill-text">${B}</span><span class="column-pill-close"><svg fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path></svg></span></span>`}),[L]),K=r.useCallback(T=>{let M="";const Z=B=>{if(B.nodeType===Node.TEXT_NODE)M+=B.textContent||"";else if(B.nodeType===Node.ELEMENT_NODE){const ae=B;if(ae.classList?.contains("column-pill")){const de=ae.getAttribute("data-column")||"";M+=`\${${de}}`}else B.childNodes.forEach(Z)}};return T.childNodes.forEach(Z),M},[]),X=r.useCallback(()=>{if(!d.current)return;const T=K(d.current);_.current=!0,s(T)},[K,s]),V=r.useCallback(()=>{d.current&&d.current.querySelectorAll(".column-pill-close").forEach(T=>{T.onclick=M=>{M.stopPropagation(),M.preventDefault();const Z=M.target.closest(".column-pill");Z&&(Z.remove(),X())}})},[X]);r.useEffect(()=>{if(d.current){if(_.current){_.current=!1;return}if(!E.current||K(d.current)!==t){const T=H(t);d.current.innerHTML=T,E.current=!0,V()}}},[t,K,H,V]);const P=r.useCallback(T=>{X();const M=window.getSelection();if(!M||M.rangeCount===0)return;const Z=M.getRangeAt(0),B=Z.startContainer,ae=Z.startOffset;if(B.nodeType===Node.TEXT_NODE){const de=B.textContent||"";if(de.charAt(ae-1)==="/"){g.current={node:B,offset:ae-1},f(""),u(0);const se=Z.getBoundingClientRect();y({top:se.bottom+window.scrollY+4,left:se.left+window.scrollX}),h(!0)}else if(m&&g.current){const se=g.current.offset,z=de.substring(se+1,ae);f(z)}}},[m,X]),A=r.useCallback(T=>{T.stopPropagation(),m&&(T.key==="ArrowDown"?(T.preventDefault(),u(M=>Math.min(M+1,$.length-1))):T.key==="ArrowUp"?(T.preventDefault(),u(M=>Math.max(M-1,0))):T.key==="Enter"||T.key==="Tab"?(T.preventDefault(),$.length>0&&C($[x])):T.key==="Escape"&&(T.preventDefault(),h(!1)))},[m,$,x]),C=r.useCallback(T=>{if(!(!d.current||!g.current)){try{const M=window.getSelection();if(!M)return;const Z=document.createRange(),B=g.current.node,ae=g.current.offset;let de=ae+1;if(M.rangeCount>0){const fe=M.getRangeAt(0);fe.startContainer===B&&(de=fe.startOffset)}if(B.nodeType===Node.TEXT_NODE){const fe=B.textContent?.substring(0,ae)||"",se=B.textContent?.substring(de)||"";B.textContent=fe+se;let z=T,U=T;if(N.includes(T))z=S[T]||T,U=T;else{const O=F(T);O&&(z=R(O),U=O.name)}const Q=document.createElement("span");Q.className="column-pill",Q.contentEditable="false",Q.setAttribute("data-column",z),Q.innerHTML=`
271          <svg class="column-pill-icon" fill="none" stroke="currentColor" viewBox="0 0 24 24">
272            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path>
273          </svg>
274          <span class="column-pill-text">${U}</span>
275          <span class="column-pill-close">
276            <svg fill="none" stroke="currentColor" viewBox="0 0 24 24">
277              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
278            </svg>
279          </span>
280        `,Z.setStart(B,ae),Z.setEnd(B,ae),Z.insertNode(Q);const me=Q.querySelector(".column-pill-close");me&&(me.onclick=O=>{O.stopPropagation(),O.preventDefault(),Q.remove(),X()});const le=document.createTextNode(" ");Q.parentNode?.insertBefore(le,Q.nextSibling),Z.setStartAfter(le),Z.setEndAfter(le),Z.collapse(!0),M.removeAllRanges(),M.addRange(Z)}X()}catch(M){console.error("Error inserting column pill:",M)}h(!1),d.current?.focus()}},[X,F,R]);r.useEffect(()=>{const T=M=>{d.current&&!d.current.contains(M.target)&&w.current&&!w.current.contains(M.target)&&h(!1)};return document.addEventListener("mousedown",T),()=>document.removeEventListener("mousedown",T)},[]),r.useEffect(()=>{if(m&&w.current){const T=w.current.querySelector(".selected");T&&T.scrollIntoView({block:"nearest"})}},[x,m]);const I=l==="none"?"none":typeof l=="number"?`${l}px`:l,j={position:"relative",width:"100%",...c?{height:"100%",display:"flex",flexDirection:"column"}:{}},q={minHeight:`${i}px`,...c?{flex:1,height:"100%"}:{maxHeight:I},overflowY:"auto",whiteSpace:"pre-wrap",wordWrap:"break-word",lineHeight:1.6,padding:"12px",border:"2px s
280olid #cbd5e1",borderRadius:"6px",background:"white",color:"#0f172a",outline:"none",fontSize:"14px",cursor:"text"};return e.jsxs(e.Fragment,{children:[e.jsx("style",{children:`
281        .prompt-editor:focus {
282          border-color: #3b82f6 !important;
283          box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
284        }
285
286        .prompt-editor:empty:before {
287          content: attr(data-placeholder);
288          color: #94a3b8;
289          pointer-events: none;
290          position: absolute;
291        }
292
293        .column-pill {
294          display: inline-flex;
295          align-items: center;
296          gap: 3px;
297          padding: 2px 6px;
298          background-color: #f3f4f6;
299          border: 1px solid #d1d5db;
300          border-radius: 4px;
301          font-size: 13px;
302          line-height: 16px;
303          margin: 0 2px;
304          vertical-align: middle;
305          user-select: none;
306          transition: all 0.15s ease;
307          white-space: nowrap;
308        }
309
310        .column-pill:hover {
311          background-color: #e5e7eb;
312          border-color: #9ca3af;
313        }
314
315        .column-pill-icon {
316          width: 12px;
317          height: 12px;
318          color: #6b7280;
319          flex-shrink: 0;
320        }
321
322        .column-pill-text {
323          color: #1f2937;
324          font-weight: 500;
325        }
326
327        .column-pill-close {
328          width: 12px;
329          height: 12px;
330          color: #9ca3af;
331          cursor: pointer;
332          display: flex;
333          align-items: center;
334          justify-content: center;
335          margin-left: 1px;
336          flex-shrink: 0;
337          border-radius: 2px;
338        }
339
340        .column-pill-close:hover {
341          color: #1f2937;
342          background-color: #d1d5db;
343        }
344
345        .column-pill-close svg {
346          width: 10px;
347          height: 10px;
348        }
349
350        .column-dropdown {
351          position: fixed;
352          /* Ensure dropdown appears above ALL modals including expanded prompt editor (z-10101) */
353          z-index: 10200;
354          background: white;
355          border: 1px solid #e5e7eb;
356          border-radius: 8px;
357          box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
358          max-height: 300px;
359          overflow-y: auto;
360          min-width: 200px;
361          max-width: 400px;
362        }
363
364        .column-dropdown-item {
365          padding: 8px 12px;
366          cursor: pointer;
367          transition: background-color 0.15s ease;
368          border-bottom: 1px solid #f3f4f6;
369        }
370
371        .column-dropdown-item:last-child {
372          border-bottom: none;
373        }
374
375        .column-dropdown-item:hover,
376        .column-dropdown-item.selected {
377          background-color: #f3f4f6;
378        }
379
380        .column-dropdown-item.selected {
381          background-color: #dbeafe;
382        }
383
384        .column-dropdown-name {
385          font-size: 14px;
386          font-weight: 500;
387          color: #1f2937;
388        }
389      `}),e.jsxs("div",{className:`prompt-editor-container ${o}`,style:j,children:[e.jsx("div",{ref:d,className:"prompt-editor",style:q,contentEditable:!0,role:"textbox","aria-multiline":"true",tabIndex:0,"data-placeholder":n,onMouseDown:T=>{T.stopPropagation()},onClick:T=>{T.stopPropagation(),d.current?.focus()},onInput:P,onKeyDown:A,suppressContentEditableWarning:!0}),m&&gs.createPortal(e.jsx("div",{ref:w,className:"column-dropdown",style:{to
389p:`${b.top}px`,left:`${b.left}px`},children:$.length>0?$.map((T,M)=>e.jsx("div",{className:`column-dropdown-item ${M===x?"selected":""}`,onClick:()=>C(T),children:e.jsx("div",{className:"column-dropdown-name",children:T})},T)):e.jsx("div",{className:"column-dropdown-item",children:e.jsx("div",{className:"column-dropdown-name text-gray-500",children:"No columns found"})})}),document.body)]})]})}const fk=({info:t})=>t.exists?e.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded text-xs bg-gray-100 text-gray-700 border border-gray-200",children:[e.jsx(wt,{size:10,className:"text-green-500"}),e.jsx("span",{children:t.columnTitle})]}):e.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded text-xs bg-red-50 text-red-600 border border-red-200",children:[e.jsx(fu,{size:10}),e.jsx("span",{className:"line-through",children:t.columnName}),e.jsx("span",{className:"text-[10px] opacity-70",children:"(not found)"})]}),Wm=({prompt:t,columns:s,className:a=""})=>{const n=Rr(t);if(n.length===0)return e.jsx("div",{className:`text-xs text-gray-400 italic ${a}`,children:"No column dependencies detected"});const o=oh(s,n),i=o.some(l=>!l.exists);return e.jsxs("div",{className:a,children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsxs("span",{className:"text-xs font-medium text-gray-500",children:["Referenced Columns (",n.length,")"]}),i&&e.jsxs("span",{className:"text-[10px] text-red-500 flex items-center gap-1",children:[e.jsx(Ss,{size:10}),"Some columns not found"]})]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:o.map((l,c)=>e.jsx(fk,{info:l},c))})]})};function Xi({columns:t,onHighlightCell:s}){const a=r.useRef(null),n=r.useRef(null),o=r.useCallback(()=>{n.current&&(clearTimeout(n.current),n.current=null),a.current&&a.current.parentNode&&(a.current.style.animation="slideUp 0.2s ease-in forwards",setTimeout(()=>{a.current?.parentNode&&(document.body.removeChild(a.current),a.current=null)},200))},[]),i=r.useCallback((m,h,p,f=3e3)=>{o();const y={error:{bg:"#fef2f2",border:"#fecaca",text:"#b91c1c",icon:"❌"},warning:{bg:"#fffbeb",border:"#fde68a",text:"#b45309",icon:"⚠️"},info:{bg:"#eff6ff",border:"#bfdbfe",text:"#1d4ed8",icon:"⏳"},success:{bg:"#f0fdf4",border:"#bbf7d0",text:"#15803d",icon:"✅"}}[m],x=document.createElement("div");x.style.cssText=`
390      position: fixed;
391      top: 80px;
392      left: 50%;
393      transform: translateX(-50%);
394      background: ${y.bg};
395      border: 1px solid ${y.border};
396      color: ${y.text};
397      padding: 12px 16px;
398      border-radius: 8px;
399      font-size: 13px;
400      box-shadow: 0 4px 12px rgba(0,0,0,0.1);
401      z-index: 10000;
402      display: flex;
403      align-items: flex-start;
404      gap: 10px;
405      max-width: 400px;
406      animation: slideDown 0.2s ease-out;
407    `;let u=`<span style="font-size:14px;">${y.icon}</span><div>`;u+=`<div style="font-weight:500;">${h}</div>`,p&&p.length>0&&(u+='<div style="margin-top:4px;font-size:12px;opacity:0.85;">',u+=p.map(w=>`• ${w}`).join("<br>"),u+="</div>"),u+="</div>",x.innerHTML=u;const g=document.createElement("style");g.id="dep-toast-style",document.getElementById("dep-toast-style")||(g.textContent=`
408        @keyframes slideDown {
409          from { opacity: 0; transform: translateX(-50%) translateY(-10px); }
410          to { opacity: 1; transform: translateX(-50%) translateY(0); }
411        }
412        @keyframes slideUp {
413          to { opacity: 0; transform: translateX(-50%) translateY(-10px); }
414        }
415      `,document.head.appendChild(g)),document.body.appendChild(x),a.current=x,f>0&&(n.current=window.setTimeout(o,f))},[o]),l=r.useCallback((m,h)=>{const p=li(m,t,h);return p.valid||(p.invalidColumns.length>0?i("error","Invalid column references",p.invalidColumns.map(f=>`"${f}" does not exist`)):p.pendingColumns.length>0?i("warning","Please wait for generation to complete",p.pendingColumns.map(f=>`"${f}" is still generating...`)):p.missingColumns.length>0&&i("error","Missing required values",p.missingColumns.map(f=>`Please fill in "${f}" first`))),p},[t,i]),c=r.useCallback(m=>Rr(m),[]),d=r.useCallback(m=>oh(t,m),[t]);return r.useEffect(()=>()=>{o()},[o]),{checkAndShowError:l,parseDependencies:c,getDependencies:d,showToast:i,clearToast:o}}function yk(t){const s=t.outputFormat;if(s==="json_schema"){const a=(t.jsonSchemaText||"").trim();return a?`json_schema:
416${a}`:""}if(s==="fields"){const a=(t.fields||[]).map(n=>({name:String(n.name||"").trim(),type:String(n.type||"").trim()})).filter(n=>!!n.name&&!!n.type);return a.length<=0?"":`fields:
417${JSON.stringify(a,null,2)}`}return""}function bk(t){const s=Number.isFinite(t.maxTokens)?Math.max(0,Math.floor(t.maxTokens)):0,a=Number.isFinite(t.fieldCount)?Math.max(0,Math.floor(t.fieldCount)):0;if(t.outputFormat==="fields"){const o=Math.max(240,a*120);return Math.min(s||o,o)}if(t.outputFormat==="json_schema")return Math.min(s||600,600);const n=300;return Math.min(s||n,n)}function wk(t){const s=t.variant||"panel",a=r.useMemo(()=>yk({outputFormat:t.outputFormat,jsonSchemaText:t.jsonSchemaText,fields:t.fields}),[t.outputFormat,t.jsonSchemaText,t.fields]),n=r.useMemo(()=>t.outputFormat!=="fields"?0:(t.fields||[]).filter(m=>
417String(m.name||"").trim()).length,[t.outputFormat,t.fields]),o=r.useMemo(()=>bk({outputFormat:t.outputFormat,maxTokens:t.maxTokens,fieldCount:n}),[t.outputFormat,t.maxTokens,n]),i=r.useMemo(()=>{const m=[];t.outputFormat&&m.push(`output_format: ${t.outputFormat}`),t.outputLanguage&&m.push(`output_language: ${t.outputLanguage}`),t.useWebsearch&&m.push("use_websearch: true"),t.useKnowledgeBase&&m.push("use_knowledge_base: true"),a&&m.push(a);const h=m.length>0?m.join(`
418`):"";return{calls:1,model:String(t.model||"").trim()||"gemini-3-pro",system_prompt:String(t.systemPrompt||""),user_prompt:String(t.userPrompt||""),extra_input_text:h,use_websearch:!!t.useWebsearch,use_knowledge_base:!!t.useKnowledgeBase,typical_output_tokens:o,max_tokens:Number.isFinite(t.maxTokens)?Math.max(0,Math.floor(t.maxTokens)):0}},[t.model,t.systemPrompt,t.userPrompt,t.outputFormat,t.outputLanguage,t.useWebsearch,t.useKnowledgeBase,a,o,t.maxTokens]),l=r.useMemo(()=>!(!i.model||!Number.isFinite(i.calls)||i.calls<=0),[i.model,i.calls]),c=ta({enabled:l,scenario:"worksheet_ai_column_generate",params:i,debounceMs:250}),d=r.useMemo(()=>{if(!c.estimatedRange)return"—";const m=Math.max(0,Math.floor(c.estimatedRange.min)),h=Math.max(0,Math.floor(c.estimatedRange.max));return m===h?`${m}`:`${m}–${h}`},[c.estimatedRange]);return s==="footer"?e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsx("div",{className:"text-xs text-gray-600 whitespace-nowrap",children:"Estimated Credits (per cell)"}),e.jsx("div",{className:"flex items-center gap-2 min-w-0",children:c.estimating?e.jsxs(e.Fragment,{children:[e.jsx(He,{size:14,className:"animate-spin text-gray-400"}),e.jsx("span",{className:"text-xs text-gray-500",children:"Estimating..."})]}):e.jsxs("div",{className:"flex items-baseline gap-1 min-w-0",children:[e.jsx("span",{className:"text-sm font-semibold text-amber-600",children:d}),e.jsx("span",{className:"text-xs text-gray-600",children:"credits"})]})})]}):e.jsxs("div",{className:"p-3 bg-gray-50 border border-gray-200 rounded-md",children:[e.jsx("div",{className:"flex items-center justify-between gap-3",children:e.jsx("div",{className:"text-xs font-medium text-gray-700",children:"Estimated Credits (per cell)"})}),e.jsx("div",{className:"mt-2 flex items-center gap-2",children:c.estimating?e.jsxs(e.Fragment,{children:[e.jsx(He,{size:14,className:"animate-spin text-gray-400"}),e.jsx("span",{className:"text-sm text-gray-600",children:"Estimating..."})]}):e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-sm font-semibold text-amber-600",children:d}),e.jsx("span",{className:"text-sm text-gray-600",children:"credits"})]})}),e.jsx("div",{className:"mt-1 text-[10px] text-gray-400",children:"This is an estimate per cell. Actual usage may vary. Gemini websearch fees are included when enabled."})]})}const jk=({col:t,onReorder:s,onUpdate:a,onDelete:n,allColumns:o,onApplyColumnOrder:i,onBatchRun:l,availableRowCount:c=0,totalRowCount:d=0,getAvailableRowCountForRange:m,getRunnableRowCountForRange:h,dataOnboarding:p})=>{const[f,b]=r.useState(!1),[y,x]=r.useState(!1),[u,g]=r.useState(!1),[w,_]=r.useState(!1),[E,N]=r.useState(!1),[S,k]=r.useState(!1),[D,F]=r.useState(!1),[R,L]=r.useState(!1),[$,H]=r.useState("1"),[K,X]=r.useState(String(d||1)),[V,P]=r.useState(Math.min(10,c||10)),[A,C]=r.useState(String(Math.min(10,c||10))),[I,j]=r.useState(!1),[q,T]=r.useState(null),[M,Z]=r.useState(!1),B=r.useRef(!1),ae=r.useRef(0),de=r.useRef(0),fe=r.useRef(""),se=r.useRef(""),z=r.useRef(!1),[U,Q]=r.useState(!1);r.useRef(0),r.useRef(5);const me=r.useRef(null),le=r.useRef(null),O=(t.type==="keywords"||t.type==="ai_keywords")&&t.config?.keywords?.source==="competitors",ne=Math.max(1,parseInt($)||1),ge=Math.max(ne,Math.min(d||1,parseInt(K)||d||1)),ze=Math.max(0,ge-ne+1),Ke=m?m(ne,ge):c,ie=h?h(ne,ge):ze,ve=O&&q===!1?0:Ke,we=O&&q===!1?0:ie;r.useEffect(()=>{const he=ve||0;if(V>he){const Re=Math.max(1,he);P(Re),C(String(Re))}},[ve,V]),r.useEffect(()=>{w&&(H("1"),X(String(d||1)))},[w,d]),r.useEffect(()=>{if(w){const he=ve||0,Re=Math.min(V,he)||Math.min(10,he);P(Re>0?Re:he>0?1:0),C(String(Re>0?Re:he>0?1:0))}},[w,ve]),r.useEffect(()=>{(async()=>
418{if(!w||!O)return;const Re=t.config?.keywords?.competitor_domain;j(!0),T(null);try{const Me=await Cc(Re);T((Me?.keywords?.length||0)>0)}catch{T(!1)}finally{j(!1)}})()},[w,O,t.config?.keywords?.competitor_domain]);const Pe=ko.includes(t.type)||t.type==="webflow"||t.type==="shopify"||t.type==="seo_action",Ae=["ai","ai_image","text","number","select","status","enumerate","url","date","keywords","seo_analysis","seo_action","webflow","shopify","image","email","checkbox","composite"].includes(t.type),ye=r.useCallback(he=>{if(he.button!==0)return;he.preventDefault(),he.stopPropagation(),B.current=!0,x(!0),ae.current=he.clientX,de.current=t.width,fe.current=document.body.style.cursor,se.current=document.body.style.userSelect,document.body.style.cursor="col-resize",document.body.style.userSelect="none";const Re=Ze=>{const Be=Ze.clientX-ae.current,et=Math.max(80,Math.round(de.current+Be));a(t.id,{width:et})},Me=()=>{document.removeEventListener("mousemove",Re),document.removeEventListener("mouseup",Me),document.body.style.cursor=fe.current,document.body.style.userSelect=se.current,B.current=!1,x(!1)};document.addEventListener("mousemove",Re),document.addEventListener("mouseup",Me)},[t.id,t.width,a]),Te=r.useCallback(he=>{if(he.button!==0)return;const Re=he.target;if(Re.closest("button")||Re.closest("[data-no-drag]")||B.current)return;he.preventDefault();const Me=he.clientX,Ze=he.clientY;let Be=!1,et=!1;const $e=()=>{if(me.current)return;const ct=document.createElement("div");ct.className="fixed pointer-events-none z-[9999] bg-white border-2 border-blue-500 shadow-xl rounded-md px-3 py-2 text-xs font-bold text-gray-700 uppercase tracking-wider",ct.textContent=t.title,ct.style.transform="translate(-50%, -50%)",document.body.appendChild(ct),me.current=ct},ue=(ct,pt)=>{me.current&&(me.current.style.left=`${ct}px`,me.current.style.top=`${pt}px`)},W=()=>{me.current&&(me.current.remove(),me.current=null)},ke=ct=>{const pt=Array.from(document.querySelectorAll("th[data-col-id]"));for(let At=0;At<pt.length;At++){const te=pt[At],G=te.getBoundingClientRect();if(ct>=G.left&&ct<=G.right)return te.getAttribute("data-col-id")}return null},qe=ct=>{const pt=Math.abs(ct.clientX-Me),At=Math.abs(ct.clientY-Ze);if(!Be&&(pt>5||At>5)&&(Be=!0,et=!0,z.current=!0,Q(!0),document.body.style.cursor="grabbing",document.body.style.userSelect="none",$e()),et){ue(ct.clientX,ct.clientY);const te=ke(ct.clientX);document.querySelectorAll("th[data-col-id]").forEach(G=>{const pe=G;pe.getAttribute("data-col-id")===te&&te!==t.id?pe.style.boxShadow="inset 0 0 0 2px #3b82f6":pe.style.boxShadow=""})}},Qe=ct=>{if(document.removeEventListener("mousemove",qe),document.removeEventListener("mouseup",Qe),document.body.style.cursor="",document.body.style.userSelect="",W(),document.querySelectorAll("th[data-col-id]").forEach(pt=>{pt.style.boxShadow=""}),et){const pt=ke(ct.clientX);pt&&pt!==t.id&&s(t.id,pt)}else b(!0);z.current=!1,Q(!1)};document.addEventListener("mousemove",qe),document.addEventListener("mouseup",Qe)},[t.id,t.title,s]),Ie=he=>{const Me={...t.config?.ai||t.ai_config||{},...he};a(t.id,{ai_config:Me,config:{...t.config,ai:Me}})},Oe=()=>{l&&l(t.id,{count:Math.min(V,ve),startRow:ne,endRow:ge}),_(!1)},J=()=>{l&&l(t.id,{count:ze,startRow:ne,endRow:ge,overwrite:!0}),_(!1)},re=()=>{N(!0)},Se=async()=>{if(n){k(!0);try{await n(t.id),N(!1),b(!1)}catch(he){console.error("Failed to delete column:",he),alert("Failed to delete column: "+he?.message)}finally{k(!1)}}},je=mn[t.type]||qn;return e.jsxs("th",{ref:le,"data-col-id":t.id,onMouseDown:Te,className:`relative border-b border-r border-gray-200 bg-gray-50/50 hover:bg-gray-100 group select-none transition-colors h-10 min-h-[40px] ${U?"opacity-50 cursor-grabbing":"cursor-grab"}`,style:{width:t.width},...p?{"data-onboarding":p}:{},children:[e.jsxs("div",{className:"flex items-center justify-between h-full px-3 pr-4",children:[e.jsxs("div",{className:"flex items-center gap-2 overflow-hidden flex-1",children:[e.jsx(je,{size:12,className:"text-gray-400 flex-shrink-0"}),e.jsx("span",{className:"text-[11px] font-bold text-gray-500 uppercase tracking-wider truncate",children:t.title})]}),e.jsxs("div",{className:"flex items-center gap-0.5","data-no-drag":!0,children:[Pe&&e.jsx("button",{onClick:he=>{he.stopPropagation(),_(!0)},className:`p-1 rounded transition-all ${w?"bg-gray-200":"hover:bg-gray-200"}
418`,title:"Bulk Run AI",children:e.jsx(so,{size:10,className:"text-gray-600 fill-gray-600"})}),e.jsx("button",{className:`p-0.5 rounded transition-opacity ${f?"opacity-100":"opacity-0 group-hover:opacity-100"} hover:bg-gray-200`,onClick:he=>{he.stopPropagation(),b(!0)},children:e.jsx(Gs,{size:12,className:"text-gray-400 hover:text-gray-600"})})]})]}),w&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-30",onClick:()=>_(!1)}),e.jsxs("div",{className:"absolute top-full right-0 mt-1.5 w-52 bg-white border border-gray-200 shadow-lg rounded-lg z-40 overflow-hidden",children:[e.jsxs("div",{className:"bg-gray-50/80 border-b border-gray-100 px-2.5 py-2 flex items-center gap-2",children:[e.jsx("div",{className:"w-5 h-5 rounded bg-gray-100 border border-gray-200 flex items-center justify-center",children:e.jsx(fo,{size:10,className:"text-gray-500"})}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] font-semibold text-gray-700",children:"Bulk Run"}),e.jsx("div",{className:"text-[9px] text-gray-400",children:O&&I?"Checking keywords...":ve>0?`${ve} rows available`:"No rows available"})]})]}),ve>0||ne<=ge?e.jsxs("div",{className:"p-2.5 space-y-2.5",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[9px] font-medium text-gray-400 uppercase tracking-wide mb-1.5",children:"Row Range"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("input",{type:"number",value:$,onChange:he=>{const Re=he.target.value;(Re===""||/^\d+$/.test(Re))&&H(Re)},onBlur:()=>{const he=parseInt($)||1,Re=Math.max(1,Math.min(he,d||1));H(String(Re)),(parseInt(K)||d||1)<Re&&X(String(Re))},min:1,max:d||1,className:"w-16 text-[11px] border border-gray-200 rounded px-2 py-1 focus:border-gray-300 focus:outline-none focus:ring-1 focus:ring-gray-100 text-gray-600 font-mono bg-gray-50 text-center",placeholder:"Start"}),e.jsx("span",{className:"text-[10px] text-gray-400",children:"to"}),e.jsx("input",{type:"number",value:K,onChange:he=>{const Re=he.target.value;(Re===""||/^\d+$/.test(Re))&&X(Re)},onBlur:()=>{const he=parseInt(K)||d||1,Re=parseInt($)||1,Me=Math.max(Re,Math.min(he,d||1));X(String(Me))},min:ne,max:d||1,className:"w-16 text-[11px] border border-gray-200 rounded px-2 py-1 focus:border-gray-300 focus:outline-none focus:ring-1 focus:ring-gray-100 text-gray-600 font-mono bg-gray-50 text-center",placeholder:"End"}),e.jsxs("span",{className:"text-[10px] text-gray-400 whitespace-nowrap",children:["/ ",d]})]}),e.jsxs("div",{className:"mt-1 flex items-center justify-between gap-2",children:[e.jsx("div",{className:"text-[9px] text-gray-400 min-w-0 truncate",children:`Range: ${we} rows`}),e.jsxs("button",{onClick:J,disabled:we<=0,className:`flex-shrink-0 inline-flex items-center justify-center gap-1.5 px-2.5 py-1 text-[10px] font-medium rounded border transition-all active:scale-[0.98] ${we>0?"bg-gray-100 text-gray-700 border-gray-200 hover:bg-gray-200 hover:border-gray-300":"bg-gray-50 text-gray-300 border-gray-100 cursor-not-allowed"}`,title:we>0?`Run ${we} rows in range`:"No runnable rows (missing dependencies)",children:[e.jsx(so,{size:10,className:we>0?"text-gray-600":"text-gray-300"}),e.jsx("span",{className:"whitespace-nowrap",children:"Run range"})]})]})]}),ve>0&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[9px] font-medium text-gray-400 uppercase tracking-wide mb-1.5",children:"Quick Select"}),e.jsx("div",{className:"grid grid-cols-5 gap-1",children:[5,10,25,50,100].filter(he=>he<=ve||he===5).map(he=>e.jsx("button",{onClick:()=>{const Re=Math.min(he,ve);P(Re),C(String(Re))},disabled:he>ve,className:`py-1 text-[10px] font-medium rounded border transition-all ${V===Math.min(he,ve)?"bg-gray-100 text-gray-700 border-gray-300":he>ve?"bg-gray-50 text-gray-300 border-gray-100 cursor-not-allowed":"bg-white text-gray-500 border-gray-200 hover:bg-gray-50 hover:border-gray-300"}`,children:he>ve?ve:he},he))})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"text-[9px] font-medium text-gray-400 uppercase tracking-wide mb-1.5",children:["Custom (max ",ve,")"]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("input",{type:"number",value:A,onChange:he=>{const Re=he.target.value;if(Re===""){C("");return}const Me=parseInt(Re);isNaN(Me)||(Me>ve?(P(ve),C(String(ve))):Me>0?(P(Me),C(String(Me))):C(Re))},onBlur:()=>{const he=parseInt(A);if(isNaN(he)||he<1){const Re=Math.min(1,ve);P(Re),C(String(Re))}},min:1,max:ve,className:"flex-1 text-[11px] border border-gray-200 rounded px-2 py-1 focus:border-gray-300 focus:outline-none focus:ring-1 focus:ring-gray-100 text-gray-600 font-mono bg-gray-50"}),e.jsx("span",{className:"text-[10px] text-gray-400",children:"rows"})]})]})]}),e.jsx("div",{className:"h-px bg-gray-100"}),e.jsxs("button",{onClick:Oe,disabled:ve<=0,className:`w-full flex items-center justify-center gap-1.5 px-3 py-1.5 text-[11px] font-medium rounded border transition-all active:scale-[0.98] ${ve>0?"bg-gray-100 text-gray-700 border-gray-200 hover:bg-gray-200 hover:border-gray-300":"bg-gray-50 text-gray-400 border-gray-100 cursor-not-allowed"}
418`,children:[e.jsx(so,{size:10,className:ve>0?"text-gray-600":"text-gray-400"}),e.jsx("span",{children:ve>0?`Run ${Math.min(V,ve)} rows`:"No rows to run"})]}),O&&q===!1&&e.jsxs("div",{className:"mt-2 p-2 bg-amber-50 border border-amber-100 rounded text-center",children:[e.jsx("div",{className:"text-[10px] text-amber-700 mb-1.5",children:"No merged keywords available"}),e.jsxs("button",{onClick:()=>{_(!1),Z(!0)},className:"inline-flex items-center justify-center gap-1 px-2 py-1 bg-amber-100 text-amber-800 text-[10px] font-medium rounded border border-amber-200 hover:bg-amber-200 transition-all",children:[e.jsx(ns,{size:10}),"Configure Keywords"]})]}),e.jsx("div",{className:"text-[9px] text-gray-400 text-center mt-2",children:"ESC to cancel"})]}):e.jsxs("div",{className:"p-4 text-center",children:[e.jsx("div",{className:"text-[11px] text-gray-500 mb-1",children:"No rows in table"}),e.jsx("div",{className:"text-[9px] text-gray-400",children:"Add some rows first"})]})]})]}),f&&!u&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-30",onClick:he=>{he.stopPropagation(),b(!1)}}),e.jsxs("div",{className:"absolute top-full left-0 mt-1 w-56 bg-white border border-gray-200 shadow-lg rounded-md z-40 p-2 flex flex-col gap-2",children:[e.jsx("div",{className:"text-[10px] font-bold text-gray-400 uppercase px-1",children:"Column Settings"}),e.jsx("input",{className:"w-full text-xs border border-gray-200 rounded px-2 py-1.5 focus:border-gray-300 focus:outline-none text-gray-700 bg-gray-50",value:t.title,onChange:he=>a(t.id,{title:he.target.value}),onKeyDown:he=>he.stopPropagation(),placeholder:"Column Name"}),Ae&&e.jsxs("button",{onClick:()=>g(!0),className:"flex items-center gap-2 text-xs text-gray-700 hover:bg-gray-100 px-2 py-1.5 rounded text-left transition-colors",children:[e.jsx(cc,{size:12})," Column Setting"]}),t.type==="composite"?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"h-px bg-gray-100 my-1"}),e.jsxs("button",{onClick:()=>{b(!1),F(!0)},className:"flex items-center gap-2 text-xs text-red-500 hover:bg-red-50 px-2 py-1.5 rounded text-left transition-colors w-full",children:[e.jsx(Qc,{size:12})," Ungroup (Split)"]})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"h-px bg-gray-100 my-1"}),e.jsxs("button",{onClick:re,className:"flex items-center gap-2 text-xs text-red-500 hover:bg-red-50 px-2 py-1.5 rounded text-left transition-colors w-full",children:[e.jsx(es,{size:12})," Delete Column"]})]})]})]}),E&&typeof document<"u"&&gs.createPortal(e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 bg-black/30 z-[10000]",onClick:()=>!S&&N(!1)}),e.jsx("div",{className:"fixed inset-0 flex items-center justify-center z-[10001] p-4",children:e.jsxs("div",{className:"bg-white rounded-xl shadow-2xl w-full max-w-md overflow-hidden",children:[e.jsxs("div",{className:"px-6 py-5 text-center",children:[e.jsx("div",{className:"mx-auto w-12 h-12 rounded-full bg-red-100 flex items-center justify-center mb-4",children:e.jsx(es,{className:"h-6 w-6 text-red-600"})}),e.jsx("h3",{className:"text-lg font-semibold text-gray-900",children:"Delete Column"}),e.jsxs("p",{className:"text-sm text-gray-600 mt-2",children:["Are you sure you want to delete column"," ",e.jsxs("span",{className:"font-semibold text-gray-900",children:['"',t.title,'"']}),"?"]})]}),e.jsx("div",{className:"px-6 pb-5",children:e.jsxs("div",{className:"bg-gray-50 rounded-lg p-4 border border-gray-200",children:[e.jsx("p",{className:"text-sm text-gray-700 mb-2 font-medium",children:"This will delete:"}),e.jsxs("ul",{className:"text-sm text-gray-600 space-y-1 list-disc list-inside",children:[e.jsx("li",{children:"The column definition"}),e.jsx("li",{children:"All cell data for this column"})]}),e.jsx("p",{className:"text-sm text-red-600 font-medium mt-3",children:"This action cannot be undone."})]})}),e.jsxs("div",{className:"px-6 pb-6 flex gap-3",children:[e.jsx("button",{onClick:()=>N(!1),disabled:S,className:"flex-1 px-4 py-2.5 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors disabled:opacity-50",children:"Cancel"}),e.jsx("button",{onClick:Se,disabled:S,className:"flex-1 px-4 py-2.5 text-sm font-medium text-white bg-red-600 rounded-lg hover:bg-red-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2",children:S?e.jsxs(e.Fragment,{children:[e.jsx(He,{size:14,className:"animate-spin"}),"Deleting..."]}):"Delete Column"})]})]})})]}),document.body),D&&t.type==="composite"&&typeof document<"u"&&gs.createPortal(e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 bg-black/30 z-[10000]",onClick:()=>!R&&F(!1)}),e.jsx("div",{className:"fixed inset-0 flex items-center justify-center z-[10001] p-4",children:e.jsxs("div",{className:"bg-white rounded-xl shadow-2xl w-full max-w-md overflow-hidden",children:[e.jsxs("div",{className:"px-6 py-5 text-center",children:[e.jsx("div",{className:"mx-auto w-12 h-12 rounded-full bg-blue-100 flex items-center justify-center mb-4",children:e.jsx(Qc,{className:"h-6 w-6 text-blue-600"})}),e.jsx("h3",{className:"text-lg font-semibold text-gray-900",children:"Split Composite Column"}),e.jsxs("p",{className:"text-sm text-gray-600 mt-2",children:["This will split"," ",e.jsxs("span",{className:"font-semibold text-gray-900",children:['"',t.title,'"']})," ","into ",t.config?.composite?.children?.length||0," separate columns."]})]}),e.jsxs("div",{className:"px-6 pb-4",children:[e.jsxs("div",{className:"bg-gray-50 rounded-lg p-3 border border-gray-200",children:[e.jsx("p",{className:"text-xs font-medium text-gray-500 mb-2",children:"Columns to be restored:"}),e.jsx("ul",{className:"text-sm text-gray-600 space-y-1",children:t.config?.composite?.children?.map(he=>{const Re=o.find(Me=>Me.id===he.column_id);return e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-gray-400"}),e.jsx("span",{children:Re?.title||he.column_id})]},he.column_id)})})]}),e.jsx("p",{className:"text-xs text-gray-500 mt-3",children:"The composite column will be removed and child columns will be restored to independent display."})]}),e.jsxs("div",{className:"px-6 pb-6 flex gap-3",children:[e.jsx("button",{onClick:()=>F(!1),disabled:R,className:"flex-1 px-4 py-2.5 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors disabled:opacity-50",children:"Cancel"}),e.jsx("button",{onClick:async()=>
418{if(n){L(!0);try{const he=t.config?.composite?.children||[],Re=he.map(ke=>Promise.resolve(a(ke.column_id,{hidden_by_composite:null})));await Promise.all(Re);const Me=o.findIndex(ke=>ke.id===t.id),Be=[...he].sort((ke,qe)=>(ke.order??0)-(qe.order??0)).map(ke=>ke.column_id).filter(Boolean),$e=o.map(ke=>ke.id).filter(ke=>ke!==t.id).filter(ke=>!Be.includes(ke)),ue=Me>=0?Me:$e.length,W=[...$e.slice(0,ue),...Be,...$e.slice(ue)];await n(t.id),i&&await i(W),F(!1)}catch(he){console.error("Failed to ungroup:",he)}finally{L(!1)}}},disabled:R,className:"flex-1 px-4 py-2.5 text-sm font-medium text-white bg-blue-600 rounded-lg hover:bg-blue-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2",children:R?e.jsxs(e.Fragment,{children:[e.jsx(He,{size:14,className:"animate-spin"}),"Splitting..."]}):"Split Column"})]})]})})]}),document.body),M&&typeof document<"u"&&gs.createPortal(e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 bg-black/30 z-[10000]",onClick:()=>Z(!1)}),e.jsx("div",{className:"fixed inset-0 flex items-center justify-center z-[10001] p-4",children:e.jsxs("div",{className:"bg-white rounded-xl shadow-2xl w-full max-w-md overflow-hidden",children:[e.jsxs("div",{className:"px-6 py-5 text-center",children:[e.jsx("div",{className:"mx-auto w-12 h-12 rounded-full bg-amber-100 flex items-center justify-center mb-4",children:e.jsx(Ja,{className:"h-6 w-6 text-amber-600"})}),e.jsx("h3",{className:"text-lg font-semibold text-gray-900",children:"Configure Keywords"}),e.jsxs("p",{className:"text-sm text-gray-600 mt-2",children:["No merged keywords are available for this column. Please configure your Top Rank / Competitor settings in"," ",e.jsx("span",{className:"font-semibold text-gray-900",children:"geo/aeo Keywords Ranking"}),"."]})]}),e.jsxs("div",{className:"px-6 pb-6 flex gap-3",children:[e.jsx("button",{onClick:()=>Z(!1),className:"flex-1 px-4 py-2.5 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors",children:"Cancel"}),e.jsxs("button",{onClick:()=>{Z(!1),window.location.href="/app/serp_ranking"},className:"flex-1 px-4 py-2.5 text-sm font-medium text-white bg-blue-600 rounded-lg hover:bg-blue-700 transition-colors flex items-center justify-center gap-2",children:[e.jsx(ns,{size:14}),"Go to geo/aeo Keywords Ranking"]})]})]})})]}),document.body),f&&u&&typeof document<"u"&&gs.createPortal(e.jsx(Gc,{col:t,allColumns:o,onClose:()=>{g(!1),b(!1)},onUpdate:a,updateAIConfig:Ie}),document.body),e.jsxs("div",{onMouseDown:he=>{he.stopPropagation(),ye(he)},onClick:he=>he.stopPropagation(),style:{position:"absolute",right:-3,top:0,bottom:0,width:8,zIndex:20,cursor:"col-resize"},className:"group/resizer","aria-label":"Resize column",title:"Drag to resize column",children:[e.jsx("div",{style:{position:"absolute",right:3,top:0,bottom:0,width:2,transition:"background-color 0.15s, opacity 0.15s",backgroundColor:y?"#3b82f6":"transparent"},className:"group-hover/resizer:bg-gray-400"}),e.jsx("div",{style:{position:"absolute",right:"50%",top:"50%",transform:"translate(50%, -50%)",padding:"2px 4px",borderRadius:3,backgroundColor:"#374151",color:"white",fontSize:9,fontFamily:"monospace",whiteSpace:"nowrap",pointerEvents:"none",userSelect:"none",transition:"opacity 0.15s",opacity:y?1:0},className:"group-hover/resizer:opacity-100",children:"<->"})]})]})},Gc=({col:t,allColumns:s,onClose:a,onUpdate:n,updateAIConfig:o,mode:i="edit",onCreate:l})=>{const c=v.useRef(null),[d,m]=v.useState(!1),[h,p]=v.useState(i==="edit"),[f,b]=v.useState(null),[y,x]=v.useState(null),[u,g]=v.useState(t.config||{}),[w,_]=v.useState(t.options),[E,N]=v.useState(t.title||""),[S,k]=v.useState(i==="create"),[D,F]=v.useState(new Set),[R,L]=v.useState(new Map),$=v.useCallback(I=>{g(j=>({...j,ai:{...j.ai||{},...I}})),k(!0)},[]),H=v.useCallback(I=>{const j={...I||{}};if(!j.webflow)return j;const q=j.webflow||{},T=M=>{if(!M)return M;const Z=s.find(de=>de.id===M);if(Z?.system_name)return Z.system_name;const B=s.find(de=>de.system_name===M);if(B?.system_name)return B.system_name;const ae=s.find(de=>de.title===M);return ae?.system_name?ae.system_name:M};return j.webflow={...q,content_column:T(q.content_column),topic_column:T(q.topic_column),main_image_column:T(q.main_image_column)},j},[s]);v.useEffect(()=>{if(i==="create"){p(!1);return}let I=!0;return(async()=>{try{p(!0);const q=await Vt.getColumn(t.id);if(I&&q){const T=t.type==="webflow"?H(q.config||{}):q.config||{};g(T),N(q.name||t.title||""),q.config?.options&&_(q.config.options)}}catch(q){console.error("Failed to fetch latest column config:",q)}finally{I&&p(!1)}})(),()=>{I=!1}},[t.id,t.title,i,H]);const K=v.useCallback(I=>{g(j=>({...j,...I})),k(!0)},[]),X=v.useCallback(I=>{_(I),k(!0)},[]),V=v.useMemo(()=>({...t,config:u,options:w}
418),[t,u,w]),P=()=>{const I=t.type;if(I==="seo_analysis"&&!u.seo_analysis?.url_source_column_id)return"Please select a URL Source Column for geo/aeo Analysis.";if(I==="seo_action"){const j=u.seo_action;if(!j?.advice_source_column)return"Please select an Advice Source Column for geo/aeo Action.";if(!j?.page_url_column)return"Please select a Page URL Column for geo/aeo Action.";if(!j?.shop_id&&!j?.webflow_collection_slug)return"Please select an Action Page (Shopify Shop or Webflow Collection)."}if(I==="webflow"){const j=u.webflow;if(!j?.content_column)return"Please select a Content Column for Webflow publishing.";if(!j?.collection_type)return"Please select a Collection Type for Webflow publishing."}if(I==="shopify"){const j=u.shopify;if(!j?.shop_id)return"Please select a Shopify Shop.";if(!j?.content_type)return"Please select a Content Type (Article or Page).";if(j?.content_type==="article"){if(!j?.article?.blog_id)return"Please select a Blog for Shopify Article publishing.";if(!j?.article?.content_column)return"Please select a Content Column for Shopify Article publishing."}if(j?.content_type==="page"&&!j?.page?.content_column)return"Please select a Content Column for Shopify Page publishing."}if(I==="url"){const j=u.url;if(j?.mode==="integration"){if(j?.integration_type==="webflow"&&!j?.webflow_source_column_id)return"Please select a Webflow Source Column for Integration URL.";if(j?.integration_type==="shopify"&&!j?.shopify_source_column_id)return"Please select a Shopify Source Column for Integration URL."}}return null},A=async()=>{b(null);const I=P();if(I){b(I);return}m(!0);try{if(i==="create"&&l){let j={...u};if((t.type==="ai"||t.type==="ai_image")&&c.current){const M=c.current.getConfig();j={...j,ai:M}}(t.type==="select"||t.type==="status"||t.type==="enumerate")&&(j={options:w||[],multiple:j?.multiple===!0?!0:void 0});const q={...t,title:E||t.title,config:Object.keys(j).length>0?j:void 0,options:w};if(!await l(q)){b("Failed to create column. Please try again."),m(!1);return}return}if((t.type==="ai"||t.type==="ai_image")&&c.current&&await c.current.save(),S){const j={};E&&E!==t.title&&(j.title=E);let q={...u};(t.type==="select"||t.type==="status"||t.type==="enumerate")&&(q={options:w||[],multiple:u?.multiple===!0?!0:void 0}),Object.keys(q).length>0&&(j.config=q),w!==void 0&&JSON.stringify(w)!==JSON.stringify(t.options)&&(j.options=w),Object.keys(j).length>0&&n(t.id,j)}if(t.type==="composite"){for(const j of D)n(j,{hidden_by_composite:null});for(const[j,q]of R)q&&n(j,{hidden_by_composite:t.id})}}finally{m(!1)}a()},C=()=>{switch(t.type){case"ai":return"AI Column";case"ai_image":return"AI Image Column";case"text":return"Text Column";case"number":return"Number Column";case"select":case"status":case"enumerate":return"Select Column";case"knowledge":return"Knowledge Column";case"url":return"URL Column";case"date":return"Date Column";case"keywords":return"Keywords Column";case"seo_analysis":return"geo/aeo Analysis Column";case"seo_action":return"geo/aeo Action Column";case"webflow":return"Webflow Column";case"shopify":return"Shopify Column";case"image":return"Image Column";case"email":return"Email Column";case"checkbox":return"Checkbox Column";default:return"Column"}};return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 bg-black/30 z-[9998]",onClick:I=>{I.stopPropagation(),b(null),a()}}),e.jsxs("div",{className:"fixed top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 w-[720px] max-h-[85vh] overflow-y-auto bg-white border border-gray-200 shadow-2xl rounded-lg z-[9999]",onMouseDown:I=>I.stopPropagation(),onClick:I=>I.stopPropagation(),children:[e.jsxs("div",{className:"sticky top-0 bg-white border-b border-gray-200 px-4 py-3 flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(cc,{size:16,className:"text-gray-600"}),e.jsx("span",{className:"font-semibold text-gray-800",children:i==="create"?`Create ${C()}`:`${C()} Configuration`})]}),e.jsx("button",{onClick:I=>{I.stopPropagation(),b(null),a()},disabled:d,className:"p-1 hover:bg-gray-100 rounded transition-colors disabled:opacity-50",children:e.jsx(mt,{size:16,className:"text-gray-500"})})]}),e.jsxs("div",{className:"p-4 space-y-4",children:[f&&e.jsx("div",{className:"bg-red-50 border border-red-200 rounded-md px-3 py-2 text-sm text-red-700",children:f}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("label",{className:"text-xs font-medium text-gray-600 flex items-center gap-1.5",children:[e.jsx(_a,{size:12,className:"text-gray-500"}),"Column Name"]}),e.jsx("input",{type:"text",value:E,onChange:I=>{N(I.target.value),k(!0)},placeholder:"Enter column name",className:"w-full text-sm border border-gray-200 rounded-md px-3 py-2 focus:border-gray-400 focus:outline-none focus:ring-2 focus:ring-gray-100 bg-white text-gray-700"})]}),h?e.jsxs("div",{className:"flex items-center justify-center py-8",children:[e.jsx(He,{size:24,className:"animate-spin text-gray-400"}),e.jsx("span",{className:"ml-2 text-sm text-gray-500",children:"Loading configuration..."})]}):e.jsxs(e.Fragment,{children:[t.type==="text"&&e.jsx(vk,{col:V,updateConfig:K}),t.type==="number"&&e.jsx(Nk,{col:V,updateConfig:K}),(t.type==="select"||t.type==="status"||t.type==="enumerate")&&e.jsx(kk,{col:V,onUpdate:(I,j)=>
418{j.options&&X(j.options)},updateConfig:K}),t.type==="url"&&e.jsx(_k,{col:V,allColumns:s,updateConfig:K}),t.type==="date"&&e.jsx(Ck,{col:V,updateConfig:K}),t.type==="image"&&e.jsx(Sk,{col:V,updateConfig:K}),t.type==="email"&&e.jsx(Ek,{col:V,updateConfig:K}),t.type==="checkbox"&&e.jsx(Ak,{col:V,updateConfig:K}),t.type==="keywords"&&e.jsx(Tk,{col:V,allColumns:s,updateConfig:K}),t.type==="seo_analysis"&&e.jsx(Ik,{col:V,allColumns:s,updateConfig:K}),t.type==="seo_action"&&e.jsx(Mk,{col:V,allColumns:s,updateConfig:K}),t.type==="webflow"&&e.jsx(Rk,{col:V,allColumns:s,updateConfig:K}),t.type==="shopify"&&e.jsx(Dk,{col:V,allColumns:s,updateConfig:K}),(t.type==="ai"||t.type==="ai_image")&&e.jsx(zk,{ref:c,col:V,allColumns:s,updateAIConfig:i==="create"?$:o,footerLeftContainer:y}),t.type==="composite"&&e.jsx(pk,{col:V,allColumns:s,onUpdateChildren:I=>{K({composite:{children:I}})},onUpdateChildColumn:(I,j)=>{n(I,j)},onTrackRemovedChild:I=>{F(j=>new Set(j).add(I))},onTrackAddedChild:(I,j)=>{L(q=>new Map(q).set(I,j))}})]})]}),e.jsxs("div",{className:"sticky bottom-0 bg-gray-50 border-t border-gray-200 px-4 py-3 flex justify-end gap-2",children:[e.jsx("div",{className:"mr-auto flex items-center min-w-0",children:e.jsx("div",{ref:I=>x(I),className:"min-w-0"})}),i==="create"&&e.jsx("button",{onClick:a,disabled:d,className:"px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 hover:bg-gray-50 rounded-md transition-colors disabled:opacity-50",children:"Cancel"}),e.jsx("button",{onClick:A,disabled:d||h,className:"px-4 py-2 text-sm font-medium text-white bg-gray-600 hover:bg-gray-500 rounded-md transition-colors disabled:opacity-50 flex items-center gap-2",children:d?e.jsxs(e.Fragment,{children:[e.jsx(He,{size:14,className:"animate-spin"}),i==="create"?"Creating...":"Saving..."]}):h?e.jsxs(e.Fragment,{children:[e.jsx(He,{size:14,className:"animate-spin"}),"Loading..."]}):i==="create"?"Create":"Save"})]})]})]})},vk=({col:t,updateConfig:s})=>e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("label",{className:"text-xs font-medium text-gray-600 flex items-center gap-1.5",children:[e.jsx(_a,{size:12,className:"text-gray-500"}),"Max Length"]}),e.jsx("input",{type:"number",value:t.config?.maxLength??"",onChange:a=>s({maxLength:parseInt(a.target.value)||void 0}),placeholder:"No limit",className:"w-full text-sm border border-gray-200 rounded-md px-3 py-2 focus:border-gray-400 focus:outline-none focus:ring-2 focus:ring-gray-100 bg-white text-gray-700"}),e.jsx("p",{className:"text-[10px] text-gray-400",children:"Leave empty for no character limit"})]}),Nk=({col:t,updateConfig:s})=>e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("label",{className:"text-xs font-medium text-gray-600 flex items-center gap-1.5",children:[e.jsx(qn,{size:12,className:"text-gray-500"}),"Minimum"]}),e.jsx("input",{type:"number",value:t.config?.min??"",onChange:a=>s({min:a.target.value?parseFloat(a.target.value):void 0}),placeholder:"No min",className:"w-full text-sm border border-gray-200 rounded-md px-3 py-2 focus:border-gray-400 focus:outline-none focus:ring-2 focus:ring-gray-100 bg-white text-gray-700"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("label",{className:"text-xs font-medium text-gray-600 flex items-center gap-1.5",children:[e.jsx(qn,{size:12,className:"text-gray-500"}),"Maximum"]}),e.jsx("input",{type:"number",value:t.config?.max??"",onChange:a=>s({max:a.target.value?parseFloat(a.target.value):void 0}),placeholder:"No max",className:"w-full text-sm border border-gray-200 rounded-md px-3 py-2 focus:border-gray-400 focus:outline-none focus:ring-2 focus:ring-gray-100 bg-white text-gray-700"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("label",{className:"text-xs font-medium text-gray-600 flex items-center gap-1.5",children:[e.jsx(qn,{size:12,className:"text-gray-500"}),"Step"]}),e.jsx("input",{type:"number",value:t.config?.step??"",onChange:a=>s({step:a.target.value?parseFloat(a.target.value):void 0}),placeholder:"1",className:"w-full text-sm border border-gray-200 rounded-md px-3 py-2 focus:border-gray-400 focus:outline-none focus:ring-2 focus:ring-gray-100 bg-white text-gray-700"})]})]}),kk=({col:t,onUpdate:s,updateConfig:a})=>{const[n,o]=r.useState(""),[i,l]=r.useState(null),[c,d]=r.useState(""),m=t.options||t.config?.options||[],h=t.config?.multiple===!0,p=u=>{const g=Array.from(new Set(u.map(w=>
418w.trim()).filter(Boolean)));s(t.id,{options:g})},f=()=>{a&&a({multiple:!h})},b=()=>{const u=n.trim();u&&(p([...m,u]),o(""))},y=(u,g)=>{l(u),d(g)},x=()=>{if(i===null)return;const u=c.trim();if(u){const g=m.map((w,_)=>_===i?u:w);p(g)}else{const g=m.filter((w,_)=>_!==i);p(g)}l(null),d("")};return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"text-xs font-medium text-gray-600 flex items-center gap-1.5",children:[e.jsx(_o,{size:12,className:"text-gray-500"}),"Options"]}),e.jsxs("div",{className:"space-y-2",children:[m.length===0&&e.jsx("div",{className:"text-[11px] text-gray-400",children:"No options yet. Add one below."}),m.map((u,g)=>e.jsx("div",{className:"flex items-center gap-2 p-2 border border-gray-200 rounded-md bg-gray-50",children:i===g?e.jsxs(e.Fragment,{children:[e.jsx("input",{value:c,onChange:w=>d(w.target.value),onBlur:x,onKeyDown:w=>{w.key==="Enter"&&x(),w.key==="Escape"&&(l(null),d(""))},className:"flex-1 text-sm border border-gray-200 rounded px-2 py-1 focus:border-gray-400 focus:outline-none focus:ring-2 focus:ring-gray-100",autoFocus:!0}),e.jsx("button",{onClick:x,className:"px-2 py-1 text-xs text-white bg-gray-600 rounded hover:bg-gray-500",children:"Save"})]}):e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"flex-1 text-sm text-gray-700 cursor-pointer",onClick:()=>y(g,u),children:u}),e.jsx("button",{onClick:()=>y(g,u),className:"px-2 py-1 text-xs text-gray-600 border border-gray-300 rounded hover:bg-gray-100",children:"Edit"}),e.jsx("button",{onClick:()=>p(m.filter((w,_)=>_!==g)),className:"px-2 py-1 text-xs text-red-600 border border-red-200 rounded hover:bg-red-50",children:"Delete"})]})},`${u}-${g}`))]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{value:n,onChange:u=>o(u.target.value),placeholder:"New option",className:"flex-1 text-sm border border-gray-200 rounded-md px-3 py-2 focus:border-gray-400 focus:outline-none focus:ring-2 focus:ring-gray-100 bg-white text-gray-700"}),e.jsx("button",{onClick:b,className:"px-3 py-2 text-xs font-medium text-white bg-gray-600 hover:bg-gray-500 rounded-md",children:"Add option"})]}),e.jsx("p",{className:"text-[10px] text-gray-400",children:"Options are saved as an array like [A, B, C]."}),a&&e.jsxs("div",{className:"pt-3 border-t border-gray-100",children:[e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:h,onChange:f,className:"w-4 h-4 text-gray-600 border-gray-300 rounded focus:ring-gray-500 cursor-pointer"}),e.jsx("span",{className:"text-xs font-medium text-gray-600",children:"Allow Multiple Selections"})]}),e.jsx("p",{className:"text-[10px] text-gray-400 mt-1 ml-6",children:"When enabled, users can select multiple options in a cell."})]})]})},_k=({col:t,allColumns:s,updateConfig:a})=>{const n=s?.filter(m=>m.type==="webflow")||[],o=s?.filter(m=>m.type==="shopify")||[],i=n.length>0||o.length>0,l=t.config?.url||{},c=l.mode||"manual",d=l.integration_type||"webflow";return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("label",{className:"text-xs font-medium text-gray-600 flex items-center gap-1.5",children:[e.jsx(Li,{size:12,className:"text-gray-500"}),"URL Source"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("button",{onClick:()=>a({url:{...l,mode:"manual"}}),className:`flex-1 px-3 py-2 text-xs font-medium rounded-md border transition-all ${c==="manual"?"bg-gray-600 border-gray-600 text-white":"bg-white border-gray-200 text-gray-600 hover:bg-gray-50"}`,children:"Custom URL"}),e.jsx("button",{onClick:()=>a({url:{...l,mode:"integration"}}),disabled:!i,className:`flex-1 px-3 py-2 text-xs font-medium rounded-md border transition-all ${c==="integration"?"bg-gray-600 border-gray-600 text-white":i?"bg-white border-gray-200 text-gray-600 hover:bg-gray-50":"bg-gray-50 border-gray-100 text-gray-300 cursor-not-allowed"}`,children:"From Integration"})]}),!i&&e.jsx("p",{className:"text-[10px] text-amber-600",children:"No Webflow or Shopify columns available. Add a Webflow or Shopify column first to use this option."})]}),c==="integration"&&e.jsxs("div",{className:"space-y-3 pl-3 border-l-2 border-blue-100",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("label",{className:"text-xs font-medium text-gray-600",children:["Integration Type ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("button",{onClick:()=>a({url:{...l,mode:"integration",integration_type:"webflow"}}
418),disabled:n.length===0,className:`flex-1 px-3 py-2 text-xs font-medium rounded-md border transition-all ${d==="webflow"?"bg-gray-600 border-gray-600 text-white":n.length>0?"bg-white border-gray-200 text-gray-600 hover:bg-gray-50":"bg-gray-50 border-gray-100 text-gray-300 cursor-not-allowed"}`,children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(Qt,{size:12}),"Webflow"]})}),e.jsx("button",{onClick:()=>a({url:{...l,mode:"integration",integration_type:"shopify"}}),disabled:o.length===0,className:`flex-1 px-3 py-2 text-xs font-medium rounded-md border transition-all ${d==="shopify"?"bg-gray-600 border-gray-600 text-white":o.length>0?"bg-white border-gray-200 text-gray-600 hover:bg-gray-50":"bg-gray-50 border-gray-100 text-gray-300 cursor-not-allowed"}`,children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(dc,{size:12}),"Shopify"]})})]})]}),d==="webflow"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("label",{className:"text-xs font-medium text-gray-600",children:["Select Webflow Column ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsxs("select",{value:l.webflow_source_column_id||"",onChange:m=>a({url:{...l,mode:"integration",integration_type:"webflow",webflow_source_column_id:m.target.value||void 0}}),className:"w-full text-sm border border-gray-200 rounded-md px-3 py-2 focus:border-gray-400 focus:outline-none focus:ring-2 focus:ring-gray-100 bg-white text-gray-700",children:[e.jsx("option",{value:"",children:"Select a column..."}),n.map(m=>e.jsx("option",{value:m.id,children:m.title},m.id))]}),e.jsx("p",{className:"text-[10px] text-gray-400",children:"The URL value will be automatically updated when this Webflow column is published."})]}),e.jsxs("div",{className:"flex items-center justify-between py-2 px-3 bg-gray-50 rounded-md",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Qt,{size:14,className:"text-gray-500"}),e.jsxs("div",{children:[e.jsx("span",{className:"text-sm text-gray-700",children:"Use Webflow custom domain"}),e.jsx("p",{className:"text-[10px] text-gray-400",children:"For clickable preview links"})]})]}),e.jsx("button",{onClick:()=>a({url:{...l,mode:"integration",integration_type:"webflow",preview_from_webflow_domain:!l.preview_from_webflow_domain}}),className:`w-10 h-5 rounded-full transition-colors ${l.preview_from_webflow_domain?"bg-gray-600":"bg-gray-300"}`,children:e.jsx("div",{className:`w-4 h-4 bg-white rounded-full shadow transform transition-transform ${l.preview_from_webflow_domain?"translate-x-5":"translate-x-0.5"}`})})]})]}),d==="shopify"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("label",{className:"text-xs font-medium text-gray-600",children:["Select Shopify Column ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsxs("select",{value:l.shopify_source_column_id||"",onChange:m=>a({url:{...l,mode:"integration",integration_type:"shopify",shopify_source_column_id:m.target.value||void 0}}),className:"w-full text-sm border border-gray-200 rounded-md px-3 py-2 focus:border-gray-400 focus:outline-none focus:ring-2 focus:ring-gray-100 bg-white text-gray-700",children:[e.jsx("option",{value:"",children:"Select a column..."}),o.map(m=>e.jsx("option",{value:m.id,children:m.title},m.id))]}),e.jsx("p",{className:"text-[10px] text-gray-400",children:"The URL value will be automatically updated when this Shopify column is published."})]})]})]})},Ck=({col:t,updateConfig:s})=>e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("label",{className:"text-xs font-medium text-gray-600 flex items-center gap-1.5",children:[e.jsx(ka,{size:12,className:"text-gray-500"}),"Date Format"]}),e.jsxs("select",{value:t.config?.format||"YYYY-MM-DD",onChange:a=>s({format:a.target.value}),className:"w-full text-sm border border-gray-200 rounded-md px-3 py-2 focus:border-gray-400 focus:outline-none focus:ring-2 focus:ring-gray-100 bg-white text-gray-700",children:[e.jsx("option",{value:"YYYY-MM-DD",children:"YYYY-MM-DD (2024-01-15)"}),e.jsx("option",{value:"MM/DD/YYYY",children:"MM/DD/YYYY (01/15/2024)"}),e.jsx("option",{value:"DD/MM/YYYY",children:"DD/MM/YYYY (15/01/2024)"}),e.jsx("option",{value:"MMM DD, YYYY",children:"MMM DD, YYYY (Jan 15, 2024)"}),e.jsx("option",{value:"DD MMM YYYY",children:"DD MMM YYYY (15 Jan 2024)"})]})]}),Sk=({col:t,updateConfig:s})=>e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("label",{className:"text-xs font-medium text-gray-600 flex items-center gap-1.5",children:[e.jsx(rn,{size:12,className:"text-gray-500"}),"Image Display"]}),e.jsxs("div",{className:"py-2 px-3 bg-gray-50 rounded-md",children:[e.jsx("p",{className:"text-sm text-gray-700 mb-0.5",children:"Multiple image upload enabled"}),e.jsx("p",{className:"text-[10px] text-gray-400",children:"Users can upload up to 6 images per cell."})]})]}),Ek=({col:t,updateConfig:s})=>e.jsxs("div",{className:"flex items-center justify-between py-2 px-3 bg-gray-50 rounded-md",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ui,{size:14,className:"text-gray-500"}),e.jsx("span",{className:"text-sm text-gray-700",children:"Validate Email Format"})]}),e.jsx("button",{onClick:()=>s({validateFormat:!t.config?.validateFormat}),className:`w-10 h-5 rounded-full transition-colors ${t.config?.validateFormat!==!1?"bg-gray-600":"bg-gray-300"}`,children:e.jsx("div",{className:`w-4 h-4 bg-white rounded-full shadow transform transition-transform ${t.config?.validateFormat!==!1?"translate-x-5":"translate-x-0.5"}`})})]}),Ak=({col:t,updateConfig:s})=>e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between py-2 px-3 bg-gray-50 rounded-md",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(zi,{size:14,className:"text-gray-500"}),e.jsx("span",{className:"text-sm text-gray-700",children:"Default Value"})]}),e.jsx("button",{onClick:()=>s({defaultChecked:!t.config?.defaultChecked}),className:`w-10 h-5 rounded-full transition-colors ${t.config?.defaultChecked?"bg-gray-600":"bg-gray-300"}`,children:e.jsx("div",{className:`w-4 h-4 bg-white rounded-full shadow transform transition-transform ${t.config?.defaultChecked?"translate-x-5":"translate-x-0.5"}`})})]}),e.jsx("p",{className:"text-[10px] text-gray-400 px-1",children:"New rows will have this checkbox value b
418y default"})]}),Tk=({col:t,allColumns:s,updateConfig:a})=>{const n=t.config?.keywords?.source||"generation",o=d=>{a({keywords:{...t.config?.keywords,source:d,model:t.config?.keywords?.model||"gemini-3-pro",max_per_cell:t.config?.keywords?.max_per_cell||10}})},i=t.config?.keywords?.dependencies?.seeds?.[0]||"",l=s?.filter(d=>d.id!==t.id&&["text","ai","select","enumerate","number"].includes(d.type))||[],c=d=>{a({keywords:{...t.config?.keywords,source:"generation",model:t.config?.keywords?.model||"gemini-3-pro",max_per_cell:t.config?.keywords?.max_per_cell||10,dependencies:{seeds:d?[d]:[],context:[]}}})};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("label",{className:"text-xs font-medium text-gray-600 flex items-center gap-1.5",children:[e.jsx(us,{size:12,className:"text-gray-500"}),"Keywords Source"]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("button",{type:"button",onClick:()=>o("generation"),className:`flex items-center justify-center gap-1.5 px-3 py-2 rounded-md border text-sm transition-colors ${n==="generation"?"bg-blue-50 border-blue-300 text-blue-700":"bg-white border-gray-200 text-gray-600 hover:bg-gray-50"}`,children:[e.jsx(Ks,{size:14}),e.jsx("span",{children:"Generation"})]}),e.jsxs("button",{type:"button",onClick:()=>o("competitors"),className:`flex items-center justify-center gap-1.5 px-3 py-2 rounded-md border text-sm transition-colors ${n==="competitors"?"bg-blue-50 border-blue-300 text-blue-700":"bg-white border-gray-200 text-gray-600 hover:bg-gray-50"}`,children:[e.jsx(Qs,{size:14}),e.jsx("span",{children:"Keywords Opportunity"})]})]}),e.jsx("p",{className:"text-[10px] text-gray-400",children:n==="generation"?"Use AI to generate keywords based on seed data":"Select from Top Rank & Competitor intersection keywords"})]}),n==="generation"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("label",{className:"text-xs font-medium text-gray-600 flex items-center gap-1.5",children:[e.jsx(fo,{size:12,className:"text-gray-500"}),"Model"]}),e.jsx("select",{value:t.config?.keywords?.model||"gemini-3-pro",onChange:d=>a({keywords:{...t.config?.keywords,source:"generation",model:d.target.value,max_per_cell:t.config?.keywords?.max_per_cell||10}}),className:"w-full text-sm border border-gray-200 rounded-md px-3 py-2 focus:border-gray-400 focus:outline-none focus:ring-2 focus:ring-gray-100 bg-white text-gray-700",children:Ii.map(d=>e.jsxs("option",{value:d.id,children:[d.name," (",d.provider,")"]},d.id))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("label",{className:"text-xs font-medium text-gray-600 flex items-center gap-1.5",children:[e.jsx(Lr,{size:12,className:"text-gray-500"}),"Max Keywords Per Cell"]}),e.jsx("input",{type:"number",value:t.config?.keywords?.max_per_cell??10,onChange:d=>a({keywords:{...t.config?.keywords,source:"generation",model:t.config?.keywords?.model||"gemini-3-pro",max_per_cell:parseInt(d.target.value)||10}}),min:1,max:100,className:"w-full text-sm border border-gray-200 rounded-md px-3 py-2 focus:border-gray-400 focus:outline-none focus:ring-2 focus:ring-gray-100 bg-white text-gray-700"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("label",{className:"text-xs font-medium text-gray-600 flex items-center gap-1.5",children:[e.jsx(us,{size:12,className:"text-gray-500"}),"Source Column (Dependency)"]}),e.jsxs("select",{value:i,onChange:d=>c(d.target.value),className:"w-full text-sm border border-gray-200 rounded-md px-3 py-2 focus:border-gray-400 focus:outline-none focus:ring-2 focus:ring-gray-100 bg-white text-gray-700",children:[e.jsx("option",{value:"",children:"No depen
418dency (optional)"}),l.map(d=>e.jsxs("option",{value:d.id,children:[d.title,d.system_name?` (${d.system_name})`:""]},d.id))]}),e.jsx("p",{className:"text-[10px] text-gray-400",children:"Select a column to use as seed data for keyword generation"})]}),i&&e.jsx("div",{className:"mt-3 p-2.5 bg-gray-50 rounded-md border border-gray-200",children:e.jsx(Pk,{dependencyColumnId:i,columns:s})})]}),n==="competitors"&&e.jsxs("div",{className:"p-2.5 bg-blue-50 border border-blue-200 rounded-md",children:[e.jsxs("div",{className:"flex items-center gap-2 text-blue-700 text-sm",children:[e.jsx(zi,{size:14}),e.jsx("span",{className:"font-medium",children:"Keywords Opportunity Mode"})]}),e.jsx("p",{className:"text-[10px] text-blue-600 mt-1",children:"Cell values will be selected from geo/aeo Keywords Tracking data using the keyword selector dialog."})]})]})},Pk=({dependencyColumnId:t,columns:s})=>{const a=s.find(n=>n.id===t||n.system_name===t);return a?e.jsxs("div",{children:[e.jsx("div",{className:"flex items-center gap-2 mb-1.5",children:e.jsx("span",{className:"text-xs font-medium text-gray-500",children:"Dependency Column"})}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:e.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded text-xs bg-gray-100 text-gray-700 border border-gray-200",children:[e.jsx(zi,{size:10,className:"text-green-500"}),e.jsx("span",{children:a.title}),a.system_name&&e.jsxs("span",{className:"text-[10px] opacity-60",children:["(",a.system_name,")"]})]})}),e.jsx("p",{className:"text-[10px] text-gray-400 mt-1.5",children:"Rows must have a value in this column to generate keywords"})]}):e.jsx("div",{className:"flex items-center gap-2 text-red-600 text-xs",children:e.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded bg-red-50 border border-red-200",children:[e.jsx(mt,{size:10}),e.jsx("span",{className:"line-through",children:t}),e.jsx("span",{className:"text-[10px] opacity-70",children:"(not found)"})]})})},Ik=({col:t,allColumns:s,updateConfig:a})=>{const[n,o]=r.useState(!1),[i,l]=r.useState(null),[c,d]=r.useState(!1),[m,h]=r.useState(!1),[p,f]=r.useState(!1);r.useEffect(()=>{n&&!i&&!c&&(d(!0),Vt.getSEOAnalysisDefaultPrompts().then(x=>{l(x)}).catch(x=>{console.error("Failed to load default SEO prompts:",x)}).finally(()=>{d(!1)}))},[n,i,c]);const b=t.config?.seo_analysis?.system_prompt_override||i?.system_prompt||"",y=t.config?.seo_analysis?.user_prompt_override||i?.user_prompt||"";return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("label",{className:"text-xs font-medium text-gray-600 flex items-center gap-1.5",children:[e.jsx(Li,{size:12,className:"text-gray-500"}),"URL Source Column"]}),e.jsxs("select",{value:t.config?.seo_analysis?.url_source_column_id||"",onChange:x=>{const u=x.target.value,w=s?.find(_=>_.id===u)?.title||"";a({seo_analysis:{...t.config?.seo_analysis,url_source_column_id:u,url_source_column:w||t.config?.seo_analysis?.url_source_column||"",model:t.config?.seo_analysis?.model||"gemini-3-pro",max_steps:t.config?.seo_analysis?.max_steps||5}})},className:"w-full text-sm border border-gray-200 rounded-md px-3 py-2 focus:border-gray-400 focus:outline-none focus:ring-2 focus:ring-gray-100 bg-white text-gray-700",children:[e.jsx("option",{value:"",children:"Select URL column..."}),s?.filter(x=>x.type==="url").map(x=>e.jsx("option",{value:x.id,children:x.title},x.id))]})]}),e.jsx("div",{className:"mt-4 border-t border-gray-100 pt-3",children:e.jsxs("button",{type:"button",onClick:()=>o(x=>!x),className:"w-full flex items-center justify-between px-2.5 py-2 rounded-md hover:bg-gray-50 text-xs text-gray-600 transition-colors",children:[e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(fo,{size:12,className:"text-gray-500"}),e.jsx("span",{className:"font-medium",children:"Advanced configuration (optional)"})]}),e.jsx("span",{className:"text-[11px] text-gray-400",children:n?"Hide":"Show"})]})}),n&&e.jsxs("div",{className:"mt-2 space-y-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("label",{className:"text-xs font-medium text-gray-600 flex items-center gap-1.5",children:[e.jsx(fo,{size:12,className:"text-gray-500"}),"Model"]}),e.jsx("select",{value:t.config?.seo_analysis?.model||"gemini-3-pro",onChange:x=>a({seo_analysis:{...t.config?.seo_analysis,url_source_column_id:t.config?.seo_analysis?.url_source_column_id||"",url_source_column:t.config?.seo_analysis?.url_source_column,model:x.target.value,max_steps:t.config?.seo_analysis?.max_steps||5}}),className:"w-full text-sm border border-gray-200 rounded-md px-3 py-2 focus:border-gray-400 focus:outline-none focus:ring-2 focus:ring-gray-100 bg-white text-gray-700",children:Ii.map(x=>
418e.jsxs("option",{value:x.id,children:[x.name," (",x.provider,")"]},x.id))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("label",{className:"text-xs font-medium text-gray-600 flex items-center gap-1.5",children:[e.jsx(mc,{size:12,className:"text-gray-500"}),"Max Analysis Steps"]}),e.jsx("input",{type:"number",value:t.config?.seo_analysis?.max_steps??5,onChange:x=>a({seo_analysis:{...t.config?.seo_analysis,url_source_column_id:t.config?.seo_analysis?.url_source_column_id||"",url_source_column:t.config?.seo_analysis?.url_source_column,model:t.config?.seo_analysis?.model||"gemini-3-pro",max_steps:parseInt(x.target.value)||5}}),min:1,max:20,className:"w-full text-sm border border-gray-200 rounded-md px-3 py-2 focus:border-gray-400 focus:outline-none focus:ring-2 focus:ring-gray-100 bg-white text-gray-700"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("label",{className:"text-xs font-medium text-gray-600 flex items-center gap-1.5",children:[e.jsx(Na,{size:12,className:"text-gray-500"}),"System Prompt Override (Optional)"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[!t.config?.seo_analysis?.system_prompt_override&&i?.system_prompt&&e.jsx("span",{className:"text-[10px] text-blue-500 bg-blue-50 px-1.5 py-0.5 rounded",children:"Using default"}),e.jsx("button",{type:"button",onClick:()=>h(!0),className:"p-1 text-gray-400 hover:text-gray-600 hover:bg-gray-100 rounded transition-colors",title:"Expand editor",children:e.jsx(er,{size:14})})]})]}),c?e.jsxs("div",{className:"flex items-center gap-2 text-xs text-gray-400 py-2",children:[e.jsx(He,{size:12,className:"animate-spin"}),"Loading default prompts..."]}):e.jsx("textarea",{value:b,onChange:x=>a({seo_analysis:{...t.config?.seo_analysis,url_source_column_id:t.config?.seo_analysis?.url_source_column_id||"",url_source_column:t.config?.seo_analysis?.url_source_column,model:t.config?.seo_analysis?.model||"gemini-3-pro",max_steps:t.config?.seo_analysis?.max_steps||5,system_prompt_override:x.target.value||void 0,user_prompt_override:t.config?.seo_analysis?.user_prompt_override}}),placeholder:"Loading default prompt...",rows:5,className:"w-full text-sm border border-gray-200 rounded-md px-3 py-2 focus:border-gray-400 focus:outline-none focus:ring-2 focus:ring-gray-100 bg-white text-gray-700 resize-none font-mono"}),e.jsx("p",{className:"text-[10px] text-gray-400",children:"Edit the system prompt above to customize how the AI analyzes pages."})]}),m&&gs.createPortal(e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 bg-black/50 z-[10100]",onClick:()=>h(!1)}),e.jsxs("div",{className:"fixed inset-4 md:inset-12 lg:inset-20 bg-white rounded-xl shadow-2xl z-[10101] flex flex-col",children:[e.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-gray-200",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Na,{size:18,className:"text-gray-600"}),e.jsx("h3",{className:"text-lg font-semibold text-gray-800",children:"System Prompt Override"}),!t.config?.seo_analysis?.system_prompt_override&&i?.system_prompt&&e.jsx("span",{className:"text-xs text-blue-500 bg-blue-50 px-2 py-0.5 rounded",children:"Using default"})]}),e.jsx("button",{onClick:()=>h(!1),className:"p-2 text-gray-400 hover:text-gray-600 hover:bg-gray-100 rounded-lg transition-colors",children:e.jsx(mt,{size:20})})]}),e.jsx("div",{className:"flex-1 p-6 overflow-hidden",children:e.jsx("textarea",{value:b,onChange:x=>a({seo_analysis:{...t.config?.seo_analysis,url_source_column_id:t.config?.seo_analysis?.url_source_column_id||"",url_source_column:t.config?.seo_analysis?.url_source_column,model:t.config?.seo_analysis?.model||"gemini-3-pro",max_steps:t.config?.seo_analysis?.max_steps||5,system_prompt_override:x.target.value||void 0,user_prompt_override:t.config?.seo_analysis?.user_prompt_override}}),onKeyDown:x=>{x.stopPropagation(),x.key==="Escape"&&h(!1)},placeholder:"Enter system prompt...",className:"w-full h-full text-sm border border-gray-200 rounded-lg px-4 py-3 focus:border-gray-400 focus:outline-none focus:ring-2 focus:ring-gray-100 bg-white text-gray-700 resize-none font-mono",autoF
418ocus:!0})}),e.jsx("div",{className:"flex justify-end gap-3 px-6 py-4 border-t border-gray-200 bg-gray-50",children:e.jsx("button",{onClick:()=>h(!1),className:"px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors",children:"Done"})})]})]}),document.body),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("label",{className:"text-xs font-medium text-gray-600 flex items-center gap-1.5",children:[e.jsx(_a,{size:12,className:"text-gray-500"}),"User Prompt Override (Optional)"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[!t.config?.seo_analysis?.user_prompt_override&&i?.user_prompt&&e.jsx("span",{className:"text-[10px] text-blue-500 bg-blue-50 px-1.5 py-0.5 rounded",children:"Using default"}),e.jsx("button",{type:"button",onClick:()=>f(!0),className:"p-1 text-gray-400 hover:text-gray-600 hover:bg-gray-100 rounded transition-colors",title:"Expand editor",children:e.jsx(er,{size:14})})]})]}),c?e.jsxs("div",{className:"flex items-center gap-2 text-xs text-gray-400 py-2",children:[e.jsx(He,{size:12,className:"animate-spin"}),"Loading default prompts..."]}):e.jsx("textarea",{value:y,onChange:x=>a({seo_analysis:{...t.config?.seo_analysis,url_source_column_id:t.config?.seo_analysis?.url_source_column_id||"",url_source_column:t.config?.seo_analysis?.url_source_column,model:t.config?.seo_analysis?.model||"gemini-3-pro",max_steps:t.config?.seo_analysis?.max_steps||5,system_prompt_override:t.config?.seo_analysis?.system_prompt_override,user_prompt_override:x.target.value||void 0}}),placeholder:"Loading default prompt...",rows:5,className:"w-full text-sm border border-gray-200 rounded-md px-3 py-2 focus:border-gray-400 focus:outline-none focus:ring-2 focus:ring-gray-100 bg-white text-gray-700 resize-none font-mono"}),e.jsx("p",{className:"text-[10px] text-gray-400",children:"Edit the user prompt above to customize what analysis to perform."})]}),p&&gs.createPortal(e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 bg-black/50 z-[10100]",onClick:()=>f(!1)}),e.jsxs("div",{className:"fixed inset-4 md:inset-12 lg:inset-20 bg-white rounded-xl shadow-2xl z-[10101] flex flex-col",children:[e.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-gray-200",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(_a,{size:18,className:"text-gray-600"}),e.jsx("h3",{className:"text-lg font-semibold text-gray-800",children:"User Prompt Override"}),!t.config?.seo_analysis?.user_prompt_override&&i?.user_prompt&&e.jsx("span",{className:"text-xs text-blue-500 bg-blue-50 px-2 py-0.5 rounded",children:"Using default"})]}),e.jsx("button",{onClick:()=>f(!1),className:"p-2 text-gray-400 hover:text-gray-600 hover:bg-gray-100 rounded-lg transition-colors",children:e.jsx(mt,{size:20})})]}),e.jsx("div",{className:"flex-1 p-6 overflow-hidden",children:e.jsx("textarea",{value:y,onChange:x=>a({seo_analysis:{...t.config?.seo_analysis,url_source_column_id:t.config?.seo_analysis?.url_source_column_id||"",url_source_column:t.config?.seo_analysis?.url_source_column,model:t.config?.seo_analysis?.model||"gemini-3-pro",max_steps:t.config?.seo_analysis?.max_steps||5,system_prompt_override:t.config?.seo_analysis?.system_prompt_override,user_prompt_override:x.target.value||void 0}}),onKeyDown:x=>{x.stopPropagation(),x.key==="Escape"&&f(!1)},placeholder:"Enter user prompt...",className:"w-full h-full text-sm border border-gray-200 rounded-lg px-4 py-3 focus:border-gray-400 focus:outline-none focus:ring-2 focus:ring-gray-100 bg-white text-gray-700 resize-none font-mono",autoFocus:!0})}),e.jsx("div",{className:"flex justify-end gap-3 px-6 py-4 border-t border-gray-200 bg-gray-50",children:e.jsx("button",{onClick:()=>f(!1),className:"px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors",children:"Done"})})]})]}),document.body)]})]})},Mk=({col:t,allColumns:s,updateConfig:a})=>{const[n,o]=r.useState([]),[i,l]=r.useState([]),[c,d]=r.useState(!0);v.useEffect(()=>{let p=!1;return(async()=>{d(!0);try{const y=((await bo())?.shops||[]).filter(g=>g.status==="connected"),u=(await Mi.getCollectionTypes())?.collections||[];p||(o(y),l(u))}catch(b){console.error("Failed to load geo/aeo Action targets:",b),p||(o([]),l([]))}finally{p||d(!1)}})(),()=>{p=!0}},[]);const m=v.useMemo(()=>{const p=t.config?.seo_action;return p?.shop_id?`shop:${p.shop_id}`:p?.webflow_collection_slug?`wf:${p.webflow_collection_slug}`:""},[t.config?.seo_action]),h=p=>{const f=t.config?.seo_action||{};if(!p){a({seo_action:{...f,shop_id:void 0,webflow_collection_slug:void 0,mode:void 0}});return}if(p.startsWith("shop:")){const b=p.replace("shop:","");a({seo_action:{...f,shop_id:b,webflow_collection_slug:void 0,mode:"shopify"}});return}if(p.startsWith("wf:")){const b=p.replace("wf:","");a({seo_action:{...f,webflow_collection_slug:b,shop_id:void 0,mode:"webflow"}}
418);return}};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("label",{className:"text-xs font-medium text-gray-600 flex items-center gap-1.5",children:[e.jsx(us,{size:12,className:"text-gray-500"}),"Action Page"]}),e.jsxs("select",{value:m,onChange:p=>h(p.target.value),disabled:c,className:"w-full text-sm border border-gray-200 rounded-md px-3 py-2 focus:border-gray-400 focus:outline-none focus:ring-2 focus:ring-gray-100 bg-white text-gray-700 disabled:opacity-50",children:[e.jsx("option",{value:"",children:c?"Loading targets...":"Select a Shopify shop or Webflow collection"}),n.map(p=>e.jsxs("option",{value:`shop:${p.id}`,children:["Shopify: ",p.display_name||p.shop_name||p.id]},p.id)),i.map(p=>e.jsxs("option",{value:`wf:${p.slug}`,children:["Webflow: ",p.display_name," (",p.slug,")"]},p.collection_id))]}),e.jsx("p",{className:"text-[10px] text-gray-400",children:"Select either a Shopify shop or Webflow collection as the action target."})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("label",{className:"text-xs font-medium text-gray-600 flex items-center gap-1.5",children:[e.jsx(Di,{size:12,className:"text-gray-500"}),"Advice Source Column"]}),e.jsxs("select",{value:t.config?.seo_action?.advice_source_column||"",onChange:p=>a({seo_action:{...t.config?.seo_action,advice_source_column:p.target.value}}),className:"w-full text-sm border border-gray-200 rounded-md px-3 py-2 focus:border-gray-400 focus:outline-none focus:ring-2 focus:ring-gray-100 bg-white text-gray-700",children:[e.jsx("option",{value:"",children:"Select geo/aeo analysis column..."}),s?.filter(p=>p.type==="seo_analysis"||p.type==="ai_seo_analysis").map(p=>e.jsx("option",{value:p.system_name||p.title,children:p.title},p.id))]}),e.jsx("p",{className:"text-[10px] text-gray-400",children:"Select the column containing geo/aeo optimization advice (e.g., from geo/aeo Analysis)."})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("label",{className:"text-xs font-medium text-gray-600 flex items-center gap-1.5",children:[e.jsx(Li,{size:12,className:"text-gray-500"}),"Page URL Column"]}),e.jsxs("select",{value:t.config?.seo_action?.page_url_column||"",onChange:p=>a({seo_action:{...t.config?.seo_action,page_url_column:p.target.value}}),className:"w-full text-sm border border-gray-200 rounded-md px-3 py-2 focus:border-gray-400 focus:outline-none focus:ring-2 focus:ring-gray-100 bg-white text-gray-700",children:[e.jsx("option",{value:"",children:"Select URL column..."}),s?.filter(p=>p.type==="url").map(p=>e.jsx("option",{value:p.system_name||p.title,children:p.title},p.id))]}),e.jsx("p",{className:"text-[10px] text-gray-400",children:"Select the URL column containing page URLs to be optimized."})]}),e.jsxs("div",{className:"bg-blue-50 border border-blue-100 rounded-md p-3 mt-3",children:[e.jsx("h4",{className:"text-xs font-semibold text-blue-900 mb-1.5",children:"How geo/aeo Action works"}),e.jsxs("ul",{className:"text-[10px] text-blue-800 space-y-0.5 list-disc list-inside",children:[e.jsx("li",{children:"Reads optimization advice from the selected advice column"}),e.jsx("li",{children:"Matches the page URL to a page in the selected shop/collection"}),e.jsx("li",{children:"Uses AI to optimize the page content based on the advice"}),e.jsx("li",{children:"Updates the page with the optimized content"})]})]})]})},Rk=({col:t,allColumns:s,updateConfig:a})=>{const[n,o]=r.useState([]),[i,l]=r.useState(!0),[c,d]=r.useState(!1),[m,h]=r.useState(null);return v.useEffect(()=>{let p=!1;return(async()=>{try{const{getWebflowCredentialExists:b}=await Bt(async()=>{const{getWebflowCredentialExists:x}=await Promise.resolve().then(()=>no);return{getWebflowCredentialExists:x}},void 0),y=await b();p||(h(y.exists),y.exists||d(!0))}catch(b){console.error("Failed to check Webflow integration:",b),p||(h(!1),d(!0))}})(),()=>{p=!0}},[]),v.useEffect(()=>{let p=!1;return(async()=>{l(!0);try{const b=await Mi.getCollectionTypes();if(typeof window<"u"&&Array.isArray(b.customDomains)&&b.customDomains.length>0)try{sessionStorage.setItem("webflow_custom_domains",JSON.stringify(b.customDomains))}catch{}p||o(b.collections||[])}catch(b){if(console.error("Failed to load collection types:",b),
418!p&&(o([]),b instanceof zr)){const y=b.errorInfo.statusCode;(y===401||y===403)&&d(!0)}}finally{p||l(!1)}})(),()=>{p=!0}},[]),e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("label",{className:"text-xs font-medium text-gray-600 flex items-center gap-1.5",children:[e.jsx(Qt,{size:12,className:"text-gray-500"}),"Collection Type"]}),i?e.jsxs("div",{className:"flex items-center gap-2 text-xs text-gray-400 py-2",children:[e.jsx(He,{size:12,className:"animate-spin"}),"Loading collections..."]}):m===!1?e.jsxs("div",{className:"flex items-center gap-2 text-xs text-amber-600 py-2",children:[e.jsx(Ja,{size:12}),e.jsx("span",{children:"Webflow not connected."}),e.jsx("button",{onClick:()=>d(!0),className:"text-blue-600 hover:underline font-medium",children:"Connect now"})]}):e.jsxs("select",{value:t.config?.webflow?.collection_type||"",onChange:p=>a({webflow:{...t.config?.webflow,collection_type:p.target.value,content_column:t.config?.webflow?.content_column||""}}),className:"w-full text-sm border border-gray-200 rounded-md px-3 py-2 focus:border-gray-400 focus:outline-none focus:ring-2 focus:ring-gray-100 bg-white text-gray-700",children:[e.jsx("option",{value:"",children:"Select a collection..."}),n.map(p=>e.jsx("option",{value:p.collection_id,children:p.display_name},p.collection_id))]}),t.config?.webflow?.collection_type&&m!==!1&&e.jsxs("p",{className:"text-[10px] text-gray-400",children:["Selected:"," ",n.find(p=>p.collection_id===t.config?.webflow?.collection_type)?.display_name||t.config?.webflow?.collection_type]})]}),m!==!1&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("label",{className:"text-xs font-medium text-gray-600 flex items-center gap-1.5",children:[e.jsx(_a,{size:12,className:"text-gray-500"}),"Content Column"]}),e.jsxs("select",{value:t.config?.webflow?.content_column||"",onChange:p=>a({webflow:{...t.config?.webflow,collection_type:t.config?.webflow?.collection_type||"",content_column:p.target.value}}),className:"w-full text-sm border border-gray-200 rounded-md px-3 py-2 focus:border-gray-400 focus:outline-none focus:ring-2 focus:ring-gray-100 bg-white text-gray-700",children:[e.jsx("option",{value:"",children:"Select content column..."}),s?.filter(p=>p.id!==t.id).map(p=>e.jsxs("option",{value:p.system_name||p.title||p.id,children:[p.title,p.system_name?` (${p.system_name})`:""]},p.id))]}),e.jsx("p",{className:"text-[10px] text-gray-400",children:"Select the column containing the content to publish"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-gray-600",children:"Topic Column (Optional)"}),e.jsxs("select",{value:t.config?.webflow?.topic_column||"",onChange:p=>a({webflow:{...t.config?.webflow,collection_type:t.config?.webflow?.collection_type||"",content_column:t.config?.webflow?.content_column||"",topic_column:p.target.value||void 0}}),className:"w-full text-sm border border-gray-200 rounded-md px-3 py-2 focus:border-gray-400 focus:outline-none focus:ring-2 focus:ring-gray-100 bg-white text-gray-700",children:[e.jsx("option",{value:"",children:"None"}),s?.filter(p=>p.id!==t.id).map(p=>e.jsxs("option",{value:p.system_name||p.title||p.id,children:[p.title,p.system_name?` (${p.system_name})`:""]},p.id))]}),e.jsx("p",{className:"text-[10px] text-gray-400",children:"Optional: Select a column for the article title/topic"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("label",{className:"text-xs font-medium text-gray-600 flex items-center gap-1.5",children:[e.jsx(rn,{size:12,className:"text-gray-500"}),"Main Image Column (Optional)"]}),e.jsxs("select",{value:t.config?.webflow?.main_image_column||"",onChange:p=>a({webflow:{...t.config?.webflow,collection_type:t.config?.webflow?.collection_type||"",content_column:t.config?.webflow?.content_column||"",topic_column:t.config?.webflow?.topic_column,main_image_column:p.target.value||void 0}}),className:"w-full text-sm border border-gray-200 rounded-md px-3 py-2 focus:border-gray-400 focus:outline-none focus:ring-2 focus:ring-gray-100 bg-white text-gray-700",children:[e.jsx("option",{value:"",children:"None"}),s?.filter(p=>p.id!==t.id&&(p.type==="image"||p.type==="ai_image")).map(p=>e.jsxs("option",{value:p.system_name||p.title||p.id,children:[p.title,p.system_name?` (${p.system_name})`:""]},p.id))]}),e.jsx("p",{className:"text-[10px] text-gray-400",children:"Optional: Select an image column for the main image"})]})]}),c&&typeof document<"u"&&gs.createPortal(e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 bg-black/40 z-[
41810000]",onClick:()=>d(!1)}),e.jsx("div",{className:"fixed inset-0 flex items-center justify-center z-[10001] p-4",children:e.jsxs("div",{className:"bg-white rounded-xl shadow-2xl w-full max-w-md overflow-hidden",children:[e.jsxs("div",{className:"px-6 py-5",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-3",children:[e.jsx("div",{className:"w-10 h-10 bg-blue-50 rounded-lg flex items-center justify-center",children:e.jsx(Qt,{size:20,className:"text-blue-600"})}),e.jsx("h3",{className:"text-lg font-semibold text-gray-900",children:"Webflow connection required"})]}),e.jsx("p",{className:"text-sm text-gray-600 mb-3",children:"To use Webflow columns, you need to connect your Webflow account first. Please go to Integration page and complete the Webflow connection setup."}),e.jsx("p",{className:"text-xs text-gray-500",children:"You'll need your Webflow API key to establish the connection."})]}),e.jsxs("div",{className:"px-6 pb-5 flex justify-end gap-2",children:[e.jsx("button",{onClick:()=>d(!1),className:"px-3 py-1.5 text-xs text-gray-600 hover:bg-gray-100 rounded-md transition-colors",children:"Cancel"}),e.jsxs("button",{onClick:()=>{window.location.href="/app/integration"},className:"px-3 py-1.5 text-xs font-medium text-white bg-gray-700 hover:bg-gray-600 rounded-md transition-colors flex items-center gap-1.5",children:[e.jsx(ns,{size:12}),"Go to Integration"]})]})]})})]}),document.body)]})},Dk=({col:t,allColumns:s,updateConfig:a})=>(()=>{const[n,o]=r.useState([]),[i,l]=r.useState(!1),[c,d]=r.useState([]),[m,h]=r.useState(!1),[p,f]=r.useState(null),[b,y]=r.useState([]),[x,u]=r.useState(!1),[g,w]=r.useState(null),[_,E]=r.useState(!1),[N,S]=r.useState(!1),k=t.config?.shopify||{shop_id:"",content_type:"article",article:{},page:{}},D=k.content_type||"article",F=k.article||{},R=k.page||{},L=C=>{if(C instanceof zr){const I=C.errorInfo.statusCode,j=(C.errorInfo.message||"").toLowerCase();if(I===401||I===403||I===400&&j.includes("shopify"))return!0}return!1},[$,H]=r.useState(null);v.useEffect(()=>{let C=!1;return(async()=>{l(!0);try{const j=await bo();if(!C){const q=j?.shops||[];o(q),q.length===0?(H(!1),E(!0)):H(!0)}}catch(j){C||(o([]),H(!1),L(j),E(!0))}finally{C||l(!1)}})(),()=>{C=!0}},[]),v.useEffect(()=>{const C=k.shop_id;if(!C||N)return;let I=!1;return(async()=>{try{const q=await gi(C);!I&&(!q||q.status!=="connected")&&E(!0)}catch(q){!I&&L(q)&&E(!0)}finally{I||S(!0)}})(),()=>{I=!0}},[k.shop_id,N]),v.useEffect(()=>{let C=!1;if(!k.shop_id||D!=="article"){d([]),f(null);return}return(async()=>{h(!0),f(null);try{const j=await g0(k.shop_id);C||d(j.blogs||[])}catch(j){C||(d([]),f(j?.message||"Failed to load blogs"))}finally{C||h(!1)}})(),()=>{C=!0}},[k.shop_id,D]),v.useEffect(()=>{let C=!1;if(!k.shop_id||D!=="page"){y([]),w(null);return}return(async()=>{u(!0),w(null);try{const j=await f0(k.shop_id);C||y(j.page_suffixes||[])}catch(j){C||(y([]),w(j?.message||"Failed to load template suffixes"))}finally{C||u(!1)}})(),()=>{C=!0}},[k.shop_id,D]);const K=async C=>
418{const I={...k,shop_id:C,content_type:k.content_type||"article"};if(C!==k.shop_id&&(I.article={...F,blog_id:"",blog_handle:""},I.page={...R,template_suffix:""}),a({shopify:I}),!!C)try{const j=await gi(C);(!j||j.status!=="connected")&&E(!0)}catch(j){L(j)&&E(!0)}},X=C=>{const I={...k,shop_id:k.shop_id||"",content_type:C,article:F,page:R};a({shopify:I})},V=C=>{const I=c.find(j=>j.id===C);a({shopify:{...k,article:{...F,blog_id:C,blog_handle:I?.handle||""},page:R}})},P=s.filter(C=>C.type==="text"||C.type==="ai"),A=s.filter(C=>C.type==="image");return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("label",{className:"text-xs font-medium text-gray-600 flex items-center gap-1.5",children:[e.jsx(dc,{size:12,className:"text-gray-500"}),"Shopify store"]}),i?e.jsxs("div",{className:"flex items-center gap-2 text-xs text-gray-400 py-2",children:[e.jsx(He,{size:12,className:"animate-spin"}),"Loading connected stores..."]}):$===!1?e.jsxs("div",{className:"flex items-center gap-2 text-xs text-amber-600 py-2",children:[e.jsx(Ja,{size:12}),e.jsx("span",{children:"No Shopify store connected."}),e.jsx("button",{onClick:()=>E(!0),className:"text-blue-600 hover:underline font-medium",children:"Connect now"})]}):e.jsxs("select",{value:k.shop_id||"",onChange:C=>K(C.target.value),className:"w-full text-sm border border-gray-200 rounded-md px-3 py-2 focus:border-gray-400 focus:outline-none focus:ring-2 focus:ring-gray-100 bg-white text-gray-700",children:[e.jsx("option",{value:"",children:"Select a connected store"}),n.map(C=>e.jsx("option",{value:C.id,children:C.display_name||C.shop_name},C.id))]}),$!==!1&&e.jsxs("p",{className:"text-[10px] text-gray-400",children:["Only Shopify stores with status"," ",e.jsx("span",{className:"font-semibold",children:"connected"})," are listed here."]})]}),k.shop_id&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("label",{className:"text-xs font-medium text-gray-600 flex items-center gap-1.5",children:[e.jsx(sp,{size:12,className:"text-gray-500"}),"Content type"]}),e.jsx("div",{className:"flex gap-2",children:["article","page"].map(C=>e.jsx("button",{onClick:()=>X(C),className:`flex-1 px-3 py-2 text-xs font-medium rounded-md border transition-all ${D===C?"bg-gray-600 border-gray-600 text-white":"bg-white border-gray-200 text-gray-600 hover:bg-gray-50"}`,children:C==="article"?"Blog article":"Page"},C))}),e.jsx("p",{className:"text-[10px] text-gray-400",children:"Choose whether this column publishes a blog article or a page to Shopify."})]}),k.shop_id&&D==="article"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-gray-600",children:"Blog"}),e.jsxs("select",{value:F.blog_id||"",onChange:C=>V(C.target.value),disabled:!k.shop_id||m,className:"w-full text-sm border border-gray-200 rounded-md px-3 py-2 focus:border-gray-400 focus:outline-none focus:ring-2 focus:ring-gray-100 bg-white text-gray-700 disabled:bg-gray-50 disabled:cursor-not-allowed disabled:opacity-70",children:[e.jsx("option",{value:"",children:k.shop_id?m?"Loading blogs...":"Select a blog":"Select a store first"}),c.map(C=>e.jsxs("option",{value:C.id,children:[C.title," ",C.handle?`(${C.handle})`:""]},C.id))]}),p?e.jsx("p",{className:"text-[10px] text-red-600",children:p}):e.jsx("p",{className:"text-[10px] text-gray-400",children:"Blog is required for publishing Shopify articles."})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-gray-600",children:"Title column"}),e.jsxs("select",{value:F.title_column||"",onChange:C=>a({shopify:{...k,article:{...F,blog_id:F.blog_id,blog_handle:F.blog_handle,title_column:C.target.value||""},page:R}}),className:"w-full text-sm border border-gray-200 rounded-md px-3 py-2 focus:border-gray-400 focus:outline-none focus:ring-2 focus:ring-gray-100 bg-white text-gray-700",children:[e.jsx("option",{value:"",children:"Select a column..."}),P.map(C=>e.jsxs("option",{value:C.system_name||C.title||C.id,children:[C.title,C.system_name?` (${C.system_name})`:""]},C.id))]}),e.jsxs("p",{className:"text-[10px] text-gray-400",children:["Used as Shopify article"," ",e.jsx("code",{className:"bg-gray-100 px-1 rounded",children:"title"}),". Required."]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-gray-600",children:"Content column"}),e.jsxs("select",{value:F.content_column||"",onChange:C=>a({shopify:{...k,article:{...F,blog_id:F.blog_id,blog_handle:F.blog_handle,content_column:C.target.value||""},page:R}}),className:"w-full text-sm border border-gray-200 rounded-md px-3 py-2 focus:border-gray-400 focus:outline-none focus:ring-2 focus:ring-gray-100 bg-white text-gray-700",children:[e.jsx("option",{value:"",children:"Select a column..."}),P.map(C=>
418e.jsxs("option",{value:C.system_name||C.title||C.id,children:[C.title,C.system_name?` (${C.system_name})`:""]},C.id))]}),e.jsxs("p",{className:"text-[10px] text-gray-400",children:["Used as Shopify article"," ",e.jsx("code",{className:"bg-gray-100 px-1 rounded",children:"body_html"}),". Required."]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-gray-600",children:"Cover image column"}),e.jsxs("select",{value:F.image_column||"",onChange:C=>a({shopify:{...k,article:{...F,blog_id:F.blog_id,blog_handle:F.blog_handle,image_column:C.target.value||void 0},page:R}}),className:"w-full text-sm border border-gray-200 rounded-md px-3 py-2 focus:border-gray-400 focus:outline-none focus:ring-2 focus:ring-gray-100 bg-white text-gray-700",children:[e.jsx("option",{value:"",children:"Select an image column (optional)"}),A.map(C=>e.jsxs("option",{value:C.system_name||C.title||C.id,children:[C.title,C.system_name?` (${C.system_name})`:""]},C.id))]}),e.jsx("p",{className:"text-[10px] text-gray-400",children:"Optional. Used as Shopify article cover image."})]})]}),k.shop_id&&D==="page"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-gray-600",children:"Title column"}),e.jsxs("select",{value:R.title_column||"",onChange:C=>a({shopify:{...k,article:F,page:{...R,title_column:C.target.value||""}}}),className:"w-full text-sm border border-gray-200 rounded-md px-3 py-2 focus:border-gray-400 focus:outline-none focus:ring-2 focus:ring-gray-100 bg-white text-gray-700",children:[e.jsx("option",{value:"",children:"Select a column..."}),P.map(C=>e.jsxs("option",{value:C.system_name||C.title||C.id,children:[C.title,C.system_name?` (${C.system_name})`:""]},C.id))]}),e.jsxs("p",{className:"text-[10px] text-gray-400",children:["Used as Shopify page"," ",e.jsx("code",{className:"bg-gray-100 px-1 rounded",children:"title"}),". Required."]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-gray-600",children:"Content column (Markdown)"}),e.jsxs("select",{value:R.content_column||"",onChange:C=>a({shopify:{...k,article:F,page:{...R,content_column:C.target.value||""}}}),className:"w-full text-sm border border-gray-200 rounded-md px-3 py-2 focus:border-gray-400 focus:outline-none focus:ring-2 focus:ring-gray-100 bg-white text-gray-700",children:[e.jsx("option",{value:"",children:"Select a column..."}),P.map(C=>e.jsxs("option",{value:C.system_name||C.title||C.id,children:[C.title,C.system_name?` (${C.system_name})`:""]},C.id))]}),e.jsxs("p",{className:"text-[10px] text-gray-400",children:["Used as Shopify page"," ",e.jsx("code",{className:"bg-gray-100 px-1 rounded",children:"body_html"}
418)," ","source (Markdown). Required."]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-gray-600",children:"Template suffix"}),e.jsxs("select",{value:R.template_suffix||"",onChange:C=>a({shopify:{...k,article:F,page:{...R,template_suffix:C.target.value||void 0}}}),disabled:!k.shop_id||x||(b||[]).length===0,className:"w-full text-sm border border-gray-200 rounded-md px-3 py-2 focus:border-gray-400 focus:outline-none focus:ring-2 focus:ring-gray-100 bg-white text-gray-700 disabled:bg-gray-50 disabled:cursor-not-allowed disabled:opacity-70",children:[e.jsx("option",{value:"",children:k.shop_id?x?"Loading template suffixes...":b.length>0?"Select a template suffix (optional)":"No custom page templates (using default)":"Select a store first"}),b.map(C=>e.jsx("option",{value:C,children:C},C))]}),g?e.jsx("p",{className:"text-[10px] text-red-600",children:g}):e.jsxs("p",{className:"text-[10px] text-gray-400",children:["Optional. Maps to theme files like"," ",e.jsxs("code",{className:"bg-gray-100 px-1 rounded",children:["templates/page.","{suffix}",".json"]}),"."]})]})]}),_&&typeof document<"u"&&gs.createPortal(e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 bg-black/40 z-[10000]",onClick:()=>E(!1)}),e.jsx("div",{className:"fixed inset-0 flex items-center justify-center z-[10001] p-4",children:e.jsxs("div",{className:"bg-white rounded-xl shadow-2xl w-full max-w-md overflow-hidden",children:[e.jsxs("div",{className:"px-6 py-5",children:[e.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-2",children:"Shopify connection required"}),e.jsx("p",{className:"text-sm text-gray-600 mb-3",children:"Your Shopify token seems invalid or missing. Please go to Integration and reconnect Shopify, then return to this page."}),e.jsx("p",{className:"text-xs text-gray-500",children:"We detected an authentication error while validating your Shopify store."})]}),e.jsxs("div",{className:"px-6 pb-5 flex justify-end gap-2",children:[e.jsx("button",{onClick:()=>E(!1),className:"px-3 py-1.5 text-xs text-gray-600 hover:bg-gray-100 rounded-md transition-colors",children:"Cancel"}),e.jsx("button",{onClick:()=>{window.location.href="/app/integration"},className:"px-3 py-1.5 text-xs font-medium text-white bg-gray-700 hover:bg-gray-600 rounded-md transition-colors",children:"Go to Integration"})]})]})})]}),document.body)]})})(),kl=t=>{const s={},a=[];return t.forEach(n=>{if(!n.name)return;let o={};switch(n.type){case"text":o={type:"string"};break;case"number":o={type:"number"};break;case"boolean":o={type:"boolean"};break;case"date":o={type:"string",format:"date"};break;case"url":o={type:"string",format:"uri"};break;case"email":o={type:"string",format:"email"};break;default:o={type:"string"}}s[n.name]=o,a.push(n.name)}),{type:"object",properties:s,required:a}},_l=t=>{if(!t||!t.properties)return[];const s=[];return Object.entries(t.properties).forEach(([a,n])=>{let o="text";n.type==="number"?o="number":n.type==="boolean"?o="boolean":n.format==="date"?o="date":n.format==="uri"?o="url":n.format==="email"&&(o="email"),s.push({name:a,type:o})}),s},Lk=t=>{if(!t.trim())return{valid:!1,message:""};try{const s=JSON.parse(t);return typeof s!="object"||s===null?{valid:!1,message:"❌ Schema must be an object"}:s.type!=="object"?{valid:!1,message:"❌ Root type must be 'object'"}:!s.properties||typeof s.properties!="object"?{valid:!1,message:"❌ Schema must have 'properties'"}:{valid:!0,message:"✅ Valid JSON Schema"}}catch{return{valid:!1,message:"❌ Invalid JSON syntax"}}},zk=v.forwardRef(({col:t,allColumns:s,updateAIConfig:a,onSave:n,footerLeftContainer:o},i)=>{const l=t.type==="ai_image",c=t.config?.ai||t.ai_config||{},d=W=>l?!1:typeof W.use_websearch=="boolean"?W.use_websearch:!1,m=W=>{const ke=W?.context,qe=ke?.knowledges&&typeof ke.knowledges=="object"?ke.knowledges:ke?.knowledge&&typeof ke.knowledge=="object"?ke.knowledge:null;return qe&&typeof qe.enabled=="boolean"?qe.enabled:typeof W.use_knowledge=="boolean"?W.use_knowledge:!!W.use_knowledge_base},h=(W,ke)=>l?"gemini-3-pro-image-preview":W.model?W.model:ke?"gemini-3-pro-preview":"gemini-3-pro",[p,f]=v.useState(()=>d(c)),[b,y]=v.useState(()=>h(c,d(c))),[x,u]=v.useState(c.system_prompt||""),[g,w]=v.useState(c.user_prompt||""),[_,E]=v.useState(c.temperature??.7),[N,S]=v.useState(c.max_tokens??1e3),[k,D]=v.useState(c.output_format||"text"),[F,R]=v.useState(c.json_schema?JSON.stringify(c.json_schema,null,2):""),[L,$]=v.useState(()=>{if(c.json_schema){const W=_l(c.json_schema);return W.length>0?W:[{name:"field_1",type:"text"}]}return[{name:"field_1",type:"text"}]}),[H,K]=v.useState(c.image_input_column_id||""),[X,V]=v.useState(m(c)),[P,A]=v.useState(c.output_language||""),[C,I]=v.useState(c.display_mode||"default"),[j,q]=v.useState(!0),[T,M]=v.useState("all"),[Z,B]=v.useState([]),[ae,de]=v.useState("all"),[fe,se]=v.useState(!1),[z,U]=v.useState([]),[Q,me]=v.useState([]),[le,O]=v.useState([]),[ne,ge]=v.useState(!1),[ze,Ke]=v.useState(null),[ie,ve]=v.useState(!1),[we,Pe]=v.useState(!1),[Ae,ye]=v.useState(!1),[Te,Ie]=v.useState(""),Oe=v.useRef(null),[J,re]=v.useState("llm");v.useEffect(()=>{const W=ke=>{ke.key==="Escape"&&(Ae&&(ye(!1),ke.stopPropagation()),we&&(Pe(!1),ke.stopPropagation()))};if(we||Ae)return document.addEventListener("keydown",W),()=>document.removeEventListener("keydown",W)},[we,Ae]),v.useEffect(()=>{const W=t.config?.ai||t.ai_config||{},ke=d(W);f(ke),y(h(W,ke)),u(l?"":W.system_prompt||""),w(W.user_prompt||""),E(W.temperature??.7),S(W.max_tokens??1e3),D(l?"text":W.output_format||"text"),R(l?"":W.json_schema?JSON.stringify(W.json_schema,null,2):""),K(l?"":W.image_input_column_id||""),V(m(W)),A(l?"":W.output_language||""),I(W.display_mode||"default");const qe=Va({rawContext:W.context,legacyUseKnowledgeBase:m(W)});if(q(!!qe.company),M(qe.knowledges.scope_ids===void 0?"all":"selected"),B(qe.knowledges.scope_ids||[]),de(qe.competitors.scope_domains===void 0?"all":"selected"),se(!!qe.competitors.enabled),U(qe.competitors.scope_domains||[]),!l&&W.json_schema){const Qe=_l(W.json_schema);$(Qe.length>0?Qe:[{name:"field_1",type:"text"}])}else $([{name:"field_1",type:"text"}])},[t.id,t.config?.ai,t.ai_config,l]),v.useEffect(()=>{let W=!1;return ge(!0),Ke(null),Promise.all([qi().catch(()=>[]),Tn().then(ke=>ke?.details?.map(qe=>qe.competitor)||[]).catch(()=>[])]).then(([ke,qe])=>{W||(me(ke||[]),O(qe||[]))}).catch(ke=>{W||Ke(ke?.message?String(ke.message):"Failed to load context options.")}).finally(()=>{W||ge(!1)}),()=>{W=!0}},[]);const Se=r.useCallback((W,ke,qe)=>{const Qe=new Set(ke);Qe.has(W)?Qe.delete(W):Qe.add(W),qe(Array.from(Qe))},[]),je=r.useCallback(()=>{const W=Va({rawContext:c.context,legacyUseKnowledgeBase:X}),ke={...W.knowledges,enabled:X,...T==="selected"&&Z.length>0?{scope_ids:Z}:{}},qe={...W.competitors,enabled:!!fe,...fe&&ae==="selected"&&z.length>0?{scope_domains:z}:{}};return{company:!!j,knowledges:ke,competitors:qe}},[c,ae,j,T,z,Z,fe,X]),he=r.useCallback(W=>{if(W==="fields"&&k==="json_schema"){if(F.trim())try{const ke=JSON.parse(F),qe=_l(ke);qe.length>0&&$(qe)}catch{}}else if(W==="json_schema"&&k==="fields"){const ke=kl(L.filter(qe=>qe.name.trim()));R(JSON.stringify(ke,null,2))}D(W),Ie("")},[k,F,L]),Re=r.useCallback(()=>{$(W=>[...W,{name:`field_${W.length+1}`,type:"text"}])},[]),Me=r.useCallback(W=>{$(ke=>ke.filter((qe,Qe)=>Qe!==W))},[]),Ze=r.useCallback((W,ke)=>{$(qe=>qe.map((Qe,ct)=>ct===W?{...Qe,...ke}:Qe))},[]),Be=r.useCallback(()=>{const W=Lk(F);Ie(W.message)},[F]),et=r.useCallback(async()=>{ve(!0);try{const W=l?"gemini-3-pro-image-preview":b,ke=l?!1:p,qe=l?"text":k;let Qe=null;if(!l&&k==="json_schema"&&F.trim())try{Qe=JSON.parse(F)}
418catch{console.error("Invalid JSON schema")}else if(!l&&k==="fields"){const pt=L.filter(At=>At.name.trim());pt.length>0&&(Qe=kl(pt))}const ct={model:W,system_prompt:x,user_prompt:g,temperature:_,max_tokens:N,output_format:qe,json_schema:Qe,use_knowledge_base:X,use_websearch:ke,context:je(),image_input_column_id:l?null:H||null,output_language:l?null:P||null,display_mode:C};a(ct)}catch(W){console.error("Failed to save AI config:",W)}finally{ve(!1)}},[b,x,g,_,N,k,F,L,X,p,P,H,C,a,je,l]),$e=r.useCallback(()=>{const W=l?"gemini-3-pro-image-preview":b,ke=l?!1:p,qe=l?"text":k;let Qe=null;if(!l&&k==="json_schema"&&F.trim())try{Qe=JSON.parse(F)}catch{console.error("Invalid JSON schema")}else if(!l&&k==="fields"){const ct=L.filter(pt=>pt.name.trim());ct.length>0&&(Qe=kl(ct))}return{model:W,system_prompt:x,user_prompt:g,temperature:_,max_tokens:N,output_format:qe,json_schema:Qe,use_knowledge_base:X,use_websearch:ke,context:je(),image_input_column_id:l?null:H||null,output_language:l?null:P||null,display_mode:C}},[b,x,g,_,N,k,F,L,X,p,H,P,C,je,l]),ue=p?Nl:Ii;return v.useImperativeHandle(i,()=>({save:et,getConfig:$e}),[et,$e]),e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 p-1 bg-gray-100 rounded-lg mb-4",children:[e.jsx("button",{type:"button",onClick:()=>re("llm"),className:`flex-1 py-1.5 text-xs font-medium rounded-md transition-all ${J==="llm"?"bg-white text-gray-800 shadow-sm":"text-gray-500 hover:text-gray-700"}`,children:"LLM Config"}),e.jsx("button",{type:"button",onClick:()=>re("context"),className:`flex-1 py-1.5 text-xs font-medium rounded-md transition-all ${J==="context"?"bg-white text-gray-800 shadow-sm":"text-gray-500 hover:text-gray-700"}`,children:"Context"})]}),e.jsxs("div",{className:J==="llm"?"space-y-4":"hidden",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("label",{className:"text-xs font-medium text-gray-600 flex items-center gap-1.5",children:[e.jsx(fo,{size:12,className:"text-gray-500"}),"Model"]}),l?e.jsx("div",{className:"w-full text-sm border border-gray-200 rounded-md px-3 py-2 bg-gray-50 text-gray-700",children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"font-medium",children:"nanobanana"}),e.jsx("span",{className:"text-[11px] text-gray-400 font-mono",children:"gemini-3-pro-image-preview"})]})}):e.jsx("select",{value:b,onChange:W=>y(W.target.value),className:"w-full text-sm border border-gray-200 rounded-md px-3 py-2 focus:border-gray-400 focus:outline-none focus:ring-2 focus:ring-gray-100 bg-white text-gray-700",children:ue.map(W=>e.jsxs("option",{value:W.id,children:[W.name," (",W.provider,")"]},W.id))})]}),!l&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("label",{className:"text-xs font-medium text-gray-600 flex items-center gap-1.5",children:[e.jsx(Na,{size:12,className:"text-gray-500"}),"System Prompt"]}),e.jsx("button",{type:"button",onClick:()=>Pe(!0),className:"p-1 text-gray-400 hover:text-gray-600 hover:bg-gray-100 rounded transition-colors",title:"Expand editor",children:e.jsx(er,{size:14})})]}),e.jsx("textarea",{value:x,onChange:W=>u(W.target.value),onMouseDown:W=>W.stopPropagation(),onClick:W=>W.stopPropagation(),onFocus:W=>W.stopPropagation(),onKeyDown:W=>W.stopPropagation(),placeholder:"You are a helpful assistant that...",rows:3,className:"w-full text-sm border border-gray-200 rounded-md px-3 py-2 focus:border-gray-400 focus:outline-none focus:ring-2 focus:ring-gray-100 bg-white text-gray-700 resize-none font-mono"})]}),!l&&we&&gs.createPortal(e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 bg-black/50 z-[10100]",onClick:()=>Pe(!1)}),e.jsxs("div",{className:"fixed inset-4 md:inset-12 lg:inset-20 bg-white rounded-xl shadow-2xl z-[10101] flex flex-col",children:[e.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-gray-200",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Na,{size:18,className:"text-gray-600"}),e.jsx("h3",{className:"text-lg font-semibold text-gray-800",children:"System Prompt"})]}),e.jsx("button",{onClick:()=>Pe(!1),className:"p-2 text-gray-400 hover:text-gray-600 hover:bg-gray-100 rounded-lg transition-colors",children:e.jsx(mt,{size:20})})]}),e.jsx("div",{className:"flex-1 p-6 overflow-hidden",children:e.jsx("textarea",{value:x,onChange:W=>u(W.target.value),onMouseDown:W=>W.stopPropagation(),onClick:W=>W.stopPropagation(),onFocus:W=>W.stopPropagation(),onKeyDown:W=>{W.stopPropagation(),W.key==="Escape"&&Pe(!1)},placeholder:"You are a helpful assistant that...",className:"w-full h-full text-sm border border-gray-200 rounded-lg px-4 py-3 focus:border-gray-400 focus:outline-none focus:ring-2 focus:ring-gray-100 bg-white text-gray-700 resize-none font-mono",autoF
418ocus:!0})}),e.jsx("div",{className:"flex justify-end gap-3 px-6 py-4 border-t border-gray-200 bg-gray-50",children:e.jsx("button",{onClick:()=>Pe(!1),className:"px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors",children:"Done"})})]})]}),document.body),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("label",{className:"text-xs font-medium text-gray-600 flex items-center gap-1.5",children:[e.jsx(_a,{size:12,className:"text-gray-500"}),"User Prompt Template"]}),e.jsx("button",{type:"button",onClick:()=>ye(!0),className:"p-1 text-gray-400 hover:text-gray-600 hover:bg-gray-100 rounded transition-colors",title:"Expand editor",children:e.jsx(er,{size:14})})]}),e.jsx(Gm,{value:g,onChange:w,columns:s.filter(W=>W.id!==t.id).map(W=>({id:W.id,name:W.title,system_name:W.system_name||W.id})),placeholder:"Type / to insert column reference",minHeight:100}),l?e.jsxs("div",{className:"p-3 bg-blue-50 border border-blue-200 rounded-md space-y-2",children:[e.jsx("p",{className:"text-xs text-blue-800 font-medium",children:"💡 Image Generation Prompt Requirements"}),e.jsxs("p",{className:"text-[11px] text-blue-700 leading-relaxed",children:["Provide ",e.jsx("strong",{children:"visual descriptions"})," for the AI to generate images. Avoid pure text or conceptual prompts."]}),e.jsxs("div",{className:"text-[11px] text-blue-600 space-y-1",children:[e.jsx("div",{children:'✅ Good: "A modern office desk with laptop, coffee, and plants. Natural lighting, minimalist style, high quality photo."'}),e.jsx("div",{children:'✅ Good: "Photo of a nano banana on a white plate. Restaurant dessert setting, soft lighting, professional photography."'}),e.jsxs("div",{children:['❌ Bad: "Write about $',"{topic}",'" or "Generate content for..."']})]}),e.jsxs("p",{className:"text-[10px] text-gray-500",children:["Use"," ",e.jsxs("code",{className:"bg-white px-1 rounded",children:["$","{COLUMN_NAME}"]})," ","to reference other columns"]})]}):e.jsxs("p",{className:"text-[10px] text-gray-400",children:["Use"," ",e.jsxs("code",{className:"bg-gray-100 px-1 rounded",children:["$","{COLUMN_NAME}"]})," ","or type ",e.jsx("code",{className:"bg-gray-100 px-1 rounded",children:"/"})," to reference other columns"]}),g&&!l&&e.jsx("div",{className:"mt-3 p-2.5 bg-gray-50 rounded-md border border-gray-200",children:e.jsx(Wm,{prompt:g,columns:s.filter(W=>W.id!==t.id)})})]}),Ae&&gs.createPortal(e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 bg-black/50 z-[10100]",onClick:()=>ye(!1)}),e.jsxs("div",{className:"fixed inset-4 md:inset-12 lg:inset-20 bg-white rounded-xl shadow-2xl z-[10101] flex flex-col",children:[e.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-gray-200",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(_a,{size:18,className:"text-gray-600"}),e.jsx("h3",{className:"text-lg font-semibold text-gray-800",children:"User Prompt Template"})]}),e.jsx("button",{onClick:()=>ye(!1),className:"p-2 text-gray-400 hover:text-gray-600 hover:bg-gray-100 rounded-lg transition-colors",children:e.jsx(mt,{size:20})})]}),e.jsxs("div",{className:"flex-1 p-6 overflow-hidden flex flex-col min-h-0",children:[e.jsx("div",{className:"flex-1 min-h-0 overflow-hidden",style:{display:"flex",flexDirection:"column"},children:e.jsx(Gm,{value:g,onChange:w,columns:s.filter(W=>W.id!==t.id).map(W=>({id:W.id,name:W.title,system_name:W.system_name||W.id})),placeholder:"Type / to insert column reference",minHeight:200,fillHeight:!0})}),e.jsxs("p",{className:"flex-shrink-0 mt-3 text-xs text-gray-500",children:["Use"," ",e.jsxs("code",{className:"bg-gray-100 px-1.5 py-0.5 rounded",children:["$","{COLUMN_NAME}"]})," ","or type"," ",e.jsx("code",{className:"bg-gray-100 px-1.5 py-0.5 rounded",children:"/"})," ","to reference other columns. Press"," ",e.jsx("code",{className:"bg-gray-100 px-1.5 py-0.5 rounded",children:"Esc"})," ","to close."]}),g&&e.jsx("div",{className:"flex-shrink-0 mt-4 p-3 bg-gray-50 rounded-lg border border-gray-200",children:e.jsx(Wm,{prompt:g,columns:s.filter(W=>W.id!==t.id)})})]}),e.jsx("div",{className:"flex justify-end gap-3 px-6 py-4 border-t border-gray-200 bg-gray-50",children:e.jsx("button",{onClick:()=>ye(!1),className:"px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors",children:"Done"})})]})]}),document.body),!l&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("label",{className:"text-xs font-medium text-gray-600 flex items-center gap-1.5",children:[e.jsx(ep,{size:12,className:"text-gray-500"}),"Temperature"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"range",min:"0",max:"2",step:"0.1",value:_,onCh
418ange:W=>E(parseFloat(W.target.value)),onMouseDown:W=>W.stopPropagation(),className:"flex-1 h-2 bg-gray-200 rounded-lg appearance-none cursor-pointer accent-gray-600"}),e.jsx("span",{className:"text-xs font-mono text-gray-600 w-8",children:_})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("label",{className:"text-xs font-medium text-gray-600 flex items-center gap-1.5",children:[e.jsx(qn,{size:12,className:"text-gray-500"}),"Max Tokens"]}),e.jsx("input",{type:"number",value:N,onChange:W=>S(parseInt(W.target.value)||1e3),onKeyDown:W=>W.stopPropagation(),className:"w-full text-sm border border-gray-200 rounded-md px-3 py-2 focus:border-gray-400 focus:outline-none focus:ring-2 focus:ring-gray-100 bg-white text-gray-700"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("label",{className:"text-xs font-medium text-gray-600 flex items-center gap-1.5",children:[e.jsx(Qt,{size:12,className:"text-gray-500"}),"Output Language",e.jsx("span",{className:"text-[10px] text-gray-400 font-normal",children:"(optional)"})]}),e.jsxs("select",{value:P,onChange:W=>A(W.target.value),className:"w-full text-sm border border-gray-200 rounded-md px-3 py-2 focus:border-gray-400 focus:outline-none focus:ring-2 focus:ring-gray-100 bg-white text-gray-700",children:[e.jsx("option",{value:"",children:"Auto (follow prompt)"}),e.jsx("option",{value:"English",children:"English"}),e.jsx("option",{value:"Chinese",children:"中文 (Chinese)"}),e.jsx("option",{value:"Japanese",children:"日本語 (Japanese)"}),e.jsx("option",{value:"Korean",children:"한국어 (Korean)"}),e.jsx("option",{value:"Spanish",children:"Español (Spanish)"}),e.jsx("option",{value:"French",children:"Français (French)"}),e.jsx("option",{value:"German",children:"Deutsch (German)"}),e.jsx("option",{value:"Portuguese",children:"Português (Portuguese)"}),e.jsx("option",{value:"Italian",children:"Italiano (Italian)"}),e.jsx("option",{value:"Russian",children:"Русский (Russian)"}),e.jsx("option",{value:"Arabic",children:"العربية (Arabic)"}),e.jsx("option",{value:"Hindi",children:"हिन्दी (Hindi)"}),e.jsx("option",{value:"Thai",children:"ไทย (Thai)"}),e.jsx("option",{value:"Vietnamese",children:"Tiếng Việt (Vietnamese)"}),e.jsx("option",{value:"Indonesian",children:"Bahasa Indonesia (Indonesian)"})]}),e.jsx("p",{className:"text-[10px] text-gray-400",children:"If set, the AI will output in the specified language."})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("label",{className:"text-xs font-medium text-gray-600 flex items-center gap-1.5",children:[e.jsx(Dr,{size:12,className:"text-gray-500"}),"Score Display Mode"]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("button",{type:"button",onClick:()=>I(C==="score"?"default":"score"),className:`relative inline-flex h-5 w-9 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none ${C==="score"?"bg-blue-600":"bg-gray-200"}`,children:e.jsx("span",{className:`pointer-events-none inline-block h-4 w-4 transform rounded-full bg-white shadow ring-0 transition duration-200 ease-in-out ${C==="score"?"translate-x-4":"translate-x-0"}`})}),e.jsx("span",{className:"text-xs text-gray-600",children:C==="score"?"Enabled":"Disabled"})]}),e.jsx("p",{className:"text-[10px] text-gray-400",children:"When enabled, displays a score badge in cells and detailed scoring breakdown in the sidebar. Best for SEO/AEO/GEO content scoring with structured JSON output."})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("label",{className:"text-xs font-medium text-gray-600 flex items-center gap-1.5",children:[e.jsx(tp,{size:12,className:"text-gray-500"}),"Output Format"]}),e.jsx("div",{className:"flex gap-2",children:["text","fields","json_schema"].map(W=>e.jsx("button",{onClick:()=>he(W),className:`flex-1 px-3 py-2 text-xs font-medium rounded-md border transition-all ${k===W?"bg-gray-600 border-gray-600 text-white":"bg-white border-gray-200 text-gray-600 hover:bg-gray-50"}`,children:W==="text"?"Text":W==="fields"?"Fields":"JSON Schema"},W))})]})]}),!l&&e.jsxs(e.Fragment,{children:[k==="text"&&e.jsx("div",{className:"p-3 bg-gray-50 border border-gray-200 rounded-md",children:e.jsx("p",{className:"text-xs text-gray-600",children:"The AI will generate free-form text output without any structure constraints."})}),k==="fields"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-xs font-medium text-gray-600",children:"Define Output Fields"}),e.jsx("div",{className:"space-y-2",children:L.map((W,ke)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx("input",{type:"text",value:W.name,onChange:qe=>Ze(ke,{name:qe.target.value}),onKeyDown:qe=>
418qe.stopPropagation(),placeholder:"Field name",className:"flex-1 text-sm border border-gray-200 rounded-md px-3 py-1.5 focus:border-gray-400 focus:outline-none focus:ring-2 focus:ring-gray-100 bg-white text-gray-700"}),e.jsxs("select",{value:W.type,onChange:qe=>Ze(ke,{type:qe.target.value}),className:"text-sm border border-gray-200 rounded-md px-2 py-1.5 focus:border-gray-400 focus:outline-none focus:ring-2 focus:ring-gray-100 bg-white text-gray-700",children:[e.jsx("option",{value:"text",children:"Text"}),e.jsx("option",{value:"number",children:"Number"}),e.jsx("option",{value:"boolean",children:"Boolean"}),e.jsx("option",{value:"date",children:"Date"}),e.jsx("option",{value:"url",children:"URL"}),e.jsx("option",{value:"email",children:"Email"})]}),e.jsx("button",{onClick:()=>Me(ke),disabled:L.length<=1,className:"p-1.5 text-red-500 hover:bg-red-50 rounded transition-colors disabled:opacity-30 disabled:cursor-not-allowed",title:"Remove field",children:e.jsx(es,{size:14})})]},ke))}),e.jsx("button",{onClick:Re,className:"w-full px-3 py-1.5 text-xs font-medium text-gray-600 bg-gray-50 border border-gray-200 hover:bg-gray-100 rounded-md transition-colors",children:"+ Add Field"}),e.jsx("p",{className:"text-[10px] text-gray-400",children:"Fields will be converted to JSON Schema format when saved."})]}),k==="json_schema"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-gray-600",children:"JSON Schema"}),e.jsx("textarea",{value:F,onChange:W=>{R(W.target.value),Ie("")},onKeyDown:W=>W.stopPropagation(),placeholder:`{
419  "type": "object",
420  "properties": {
421    "field_name": { "type": "string" }
422  },
423  "required": ["field_name"]
424}`,rows:8,className:"w-full text-sm border border-gray-200 rounded-md px-3 py-2 focus:border-gray-400 focus:outline-none focus:ring-2 focus:ring-gray-100 bg-white text-gray-700 resize-none font-mono"}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:`text-[10px] ${Te.startsWith("✅")?"text-green-600":Te.startsWith("❌")?"text-red-500":"text-gray-400"}`,children:Te||"Define the structure of AI output"}),e.jsx("button",{onClick:Be,className:"px-2 py-1 text-[10px] font-medium text-gray-600 bg-gray-50 border border-gray-200 hover:bg-gray-100 rounded transition-colors",children:"Validate"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("label",{className:"text-xs font-medium text-gray-600 flex items-center gap-1.5",children:[e.jsx(rn,{size:12,className:"text-gray-500"}),"Image Input Column (Optional)"]}),e.jsxs("select",{value:H,onChange:W=>K(W.target.value),className:"w-full text-sm border border-gray-200 rounded-md px-3 py-2 focus:border-gray-400 focus:outline-none focus:ring-2 focus:ring-gray-100 bg-white text-gray-700",children:[e.jsx("option",{value:"",children:"None"}),s?.filter(W=>W.type==="image"||W.type==="url").map(W=>e.jsx("option",{value:W.id,children:W.title},W.id))]})]}),e.jsxs("div",{className:"flex items-center justify-between py-2 px-3 bg-gray-50 rounded-md",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Qt,{size:14,className:"text-gray-500"}),e.jsx("span",{className:"text-sm text-gray-700",children:"Use Websearch"})]}),e.jsx("button",{onClick:()=>{f(W=>{const ke=!W;if(ke)new Set(Nl.map(Qe=>Qe.id)).has(b)||(Oe.current=b,y(Nl[0]?.id||"gemini-3-pro-preview"));else{const qe=new Set(Ii.map(ct=>ct.id)),Qe=Oe.current;Qe&&qe.has(Qe)?y(Qe):qe.has(b)||y("gemini-3-pro")}return ke})},className:`w-10 h-5 rounded-full transition-colors ${p?"bg-gray-600":"bg-gray-300"}`,children:e.jsx("div",{className:`w-4 h-4 bg-white rounded-full shadow transform transition-transform ${p?"translate-x-5":"translate-x-0.5"}`})})]})]})]}),e.jsxs("div",{className:J==="context"?"space-y-4":"hidden",children:[e.jsxs("div",{className:"space-y-2 pt-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("label",{className:"text-xs font-medium text-gray-600 flex items-center gap-1.5",children:[e.jsx(Qs,{size:12,className:"text-gray-500"}),"Context"]}),ne&&e.jsxs("span",{className:"text-[10px] text-gray-400 flex items-center gap-1",children:[e.jsx(He,{size:10,
424className:"animate-spin"}),"Loading"]})]}),ze&&e.jsx("div",{className:"text-[11px] text-amber-700 bg-amber-50 border border-amber-200 rounded-md px-2 py-1",children:ze}),e.jsxs("label",{className:"flex items-center justify-between gap-3 text-xs text-gray-700",children:[e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"checkbox",checked:j,onChange:W=>q(W.target.checked)}),"Company"]}),e.jsx("span",{className:"text-[10px] text-gray-400",children:"Campaign info"})]})]}),e.jsxs("div",{className:"flex items-center justify-between py-2 px-3 bg-gray-50 rounded-md",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ks,{size:14,className:"text-gray-500"}),e.jsx("span",{className:"text-sm text-gray-700",children:"Use Knowledge Base"})]}),e.jsx("button",{onClick:()=>V(!X),className:`w-10 h-5 rounded-full transition-colors ${X?"bg-gray-600":"bg-gray-300"}`,children:e.jsx("div",{className:`w-4 h-4 bg-white rounded-full shadow transform transition-transform ${X?"translate-x-5":"translate-x-0.5"}`})})]}),X&&e.jsxs("div",{className:"pl-3 pr-1 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-4 text-xs text-gray-600",children:[e.jsxs("label",{className:"flex items-center gap-1.5",children:[e.jsx("input",{type:"radio",name:`kb_scope_${t.id}`,checked:T==="all",onChange:()=>M("all")}),"All"]}),e.jsxs("label",{className:"flex items-center gap-1.5",children:[e.jsx("input",{type:"radio",name:`kb_scope_${t.id}`,checked:T==="selected",onChange:()=>M("selected")}),"Selected"]})]}),T==="selected"&&e.jsx("div",{className:"max-h-32 overflow-auto border border-gray-200 rounded-md bg-white",children:(Q||[]).length===0?e.jsx("div",{className:"px-3 py-2 text-[11px] text-gray-400",children:"No knowledge bases found."}):(Q||[]).map(W=>e.jsxs("label",{className:"flex items-center gap-2 px-3 py-1.5 text-xs text-gray-700 hover:bg-gray-50",children:[e.jsx("input",{type:"checkbox",checked:Z.includes(W.id),onChange:()=>Se(W.id,Z,B)}),e.jsx("span",{className:"truncate",children:W.name})]},W.id))})]}),e.jsxs("div",{className:"flex items-center justify-between py-2 px-3 bg-gray-50 rounded-md",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Qs,{size:14,className:"text-gray-500"}),e.jsx("span",{className:"text-sm text-gray-700",children:"Use Competitors"})]}),e.jsx("button",{onClick:()=>se(!fe),className:`w-10 h-5 rounded-full transition-colors ${fe?"bg-gray-600":"bg-gray-300"}`,children:e.jsx("div",{className:`w-4 h-4 bg-white rounded-full shadow transform transition-transform ${fe?"translate-x-5":"translate-x-0.5"}`})})]}),fe&&e.jsxs("div",{className:"pl-3 pr-1 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-4 text-xs text-gray-600",children:[e.jsxs("label",{className:"flex items-center gap-1.5",children:[e.jsx("input",{type:"radio",name:`comp_scope_${t.id}`,checked:ae==="all",onChange:()=>de("all")}),"All"]}),e.jsxs("label",{className:"flex items-center gap-1.5",children:[e.jsx("input",{type:"radio",name:`comp_scope_${t.id}`,checked:ae==="selected",onChange:()=>de("selected")}),"Selected"]})]}),ae==="selected"&&e.jsx("div",{className:"max-h-32 overflow-auto border border-gray-200 rounded-md bg-white",children:(le||[]).length===0?e.jsx("div",{className:"px-3 py-2 text-[11px] text-gray-400",children:"No competitors found."}):(le||[]).map(W=>e.jsxs("label",{className:"flex items-center gap-2 px-3 py-1.5 text-xs text-gray-700 hover:bg-gray-50",children:[e.jsx("input",{type:"checkbox",checked:z.includes(W),onChange:()=>Se(W,z,U)}),e.jsx("span",{className:"truncate",children:W})]},W))})]})]}),o&&!l?gs.createPortal(e.jsx(wk,{variant:"footer",model:b,systemPrompt:x,userPrompt:g,maxTokens:N,outputFormat:k,jsonSchemaText:F,fields:L,useWebsearch:p,useKnowledgeBase:X,outputLanguage:P}),o):null]})}),$k=({onAdd:t})=>{const[s,a]=r.useState(!1);return e.jsxs("th",{className:"w-10 px-0 border-b border-gray-200 bg-gray-50/30 relative h-10 min-h-[40px]","data-onboarding":"add-column-btn",children:[e.jsx("button",{onClick:()=>a(!0),className:"flex items-center justify-center w-full h-full text-gray-400 hover:text-gray-600 hover:bg-gray-100 transition-colors",children:e.jsx($t,{size:16})}),s&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-30",onClick:()=>a(!1)}),e.jsx("div",{className:"absolute top-full left-0 mt-2 w-48 bg-white border border-gray-200 shadow-lg rounded-lg z-40 overflow-hidden flex flex-col",children:ck.map(n=>e.jsxs("div",{className:"py-1 border-b border-gray-50 last:border-0",children:[e.jsx("div",{className:"px-3 py-1 text-[10px] text-gray-400 font-bold uppercase tracking-wider",children:n.name}),n.types.map(o=>{const i=mn[o];return e.jsxs("button",{onClick:()=>{t(o),a(!1)},className:"w-full flex items-center gap-3 px-3 py-1.5 hover:bg-gray-50 text-left transition-colors",children:[e.jsx(i,{size:12,className:"text-gray-500"}),e.jsx("span",{className:"text-xs font-medium text-gray-600",children:kr[o]})]},o)})]},n.name))})]})]})},Fk=({col:t,row:s,allColumns:a,onChildClick:n,onChildDoubleClick:o,selectedChildId:i,onRunAI:l,onExpand:c,onPublish:d,onApply:m,onUpdate:h})=>{const[p,f]=r.useState(null),[b,y]=r.useState(""),[x,u]=r.useState([]),[g,w]=r.useState(null),_=r.useRef(null),E=r.useRef(new Map),[N,S]=r.useState(null),[k,D]=r.useState(""),[F,R]=r.useState([]),[L,$]=r.useState([]),[H,K]=r.useState(!1),[X,V]=r.useState(null),P=r.useRef(null),A=r.useRef(new Map),C=r.useMemo(()=>t.config?.composite?.children||[],[t.config?.composite?.children]),I=r.useCallback(U=>{const Q=Array.isArray(U)?U:U?[U]:[],le=(Q.flat?Q.flat(2):[].concat(...Q.map(O=>Array.isArray(O)?O:[O]))).map(O=>typeof O=="string"?O.trim():String(O??"").trim()).filter(O=>!!O);return Array.from(new Set(le))},[]),j=r.useCallback(U=>{if(!U)return[];if(typeof U=="object"&&!Array.isArray(U)){const Q=U.kb_ids;if(Array.isArray(Q))return Array.from(new Set(Q.map(me=>
424String(me||"").trim()).filter(Boolean)))}if(Array.isArray(U))return Array.from(new Set(U.map(Q=>String(Q||"").trim()).filter(Boolean)));if(typeof U=="string"){const Q=U.trim();return Q?[Q]:[]}return[]},[]),q=r.useCallback(U=>{const Q=Array.from(new Set((U||[]).map(String).filter(Boolean))),me=new Map((L||[]).map(O=>[O.id,O])),le=[];for(const O of Q){const ne=me.get(O);ne?.name&&le.push(ne.name)}return{kb_ids:Q,names:le}},[L]),T=r.useMemo(()=>C.sort((U,Q)=>U.order-Q.order).map(U=>{const Q=a.find(O=>O.id===U.column_id);if(!Q)return null;const me=s.cells[U.column_id]||{value:null},le=U.label_override||Q.title;return{config:U,column:Q,cellData:me,displayLabel:le}}).filter(Boolean),[C,a,s.cells]);r.useEffect(()=>{if(!p)return;const U=me=>{const le=me.target;if(le&&!_.current?.contains(le)){for(const O of E.current.values())if(O?.contains(le))return;f(null),y("")}},Q=me=>{me.key==="Escape"&&(f(null),y(""))};return document.addEventListener("mousedown",U),document.addEventListener("keydown",Q),()=>{document.removeEventListener("mousedown",U),document.removeEventListener("keydown",Q)}},[p]),r.useEffect(()=>{if(!N)return;const U=me=>{const le=me.target;if(le&&!P.current?.contains(le)){for(const O of A.current.values())if(O?.contains(le))return;S(null),D("")}},Q=me=>{me.key==="Escape"&&(S(null),D(""))};return document.addEventListener("mousedown",U),document.addEventListener("keydown",Q),()=>{document.removeEventListener("mousedown",U),document.removeEventListener("keydown",Q)}},[N]),r.useEffect(()=>{N&&(L.length>0||H||(K(!0),qi().then(U=>$(Array.isArray(U)?U:[])).catch(()=>$([])).finally(()=>K(!1))))},[N,L.length,H]);const M=(U,Q)=>{if(U==null||U==="")return null;if(U&&typeof U=="object"){if(U.__pending===!0)return"Generating...";const me=typeof U.status=="string"?String(U.status).toLowerCase():"";if(me==="waiting"||U.__pipeline_waiting===!0)return"Waiting...";if(me==="running"||me==="pending")return"Generating..."}if((Q==="ai"||Q==="seo_analysis"||Q==="ai_seo_analysis")&&typeof U=="object"&&"result"in U){const me=U.result;return me==null?U.status==="running"?"Generating...":null:na(me)}if(Q==="keywords"||Q==="ai_keywords"){if(Array.isArray(U))return U.length>0?`${U.length} keywords`:null;if(typeof U=="object"&&U.result){const me=U.result;if(Array.isArray(me))return me.length>0?`${me.length} keywords`:null}}return Q==="image"&&typeof U=="object"&&Array.isArray(U.images)?U.images.length>0?`${U.images.length} images`:null:(Q==="webflow"||Q==="shopify")&&typeof U=="object"&&U.status?U.status==="published"?"Published":U.status:na(U)},Z=(U,Q=30)=>U.length<=Q?U:U.slice(0,Q)+"...",B=U=>
424(U.type==="keywords"||U.type==="ai_keywords")&&U.config?.keywords?.source==="competitors",ae=(U,Q)=>{if(!ko.includes(U.type)||B(U))return!1;const me=Q.value;if(me&&typeof me=="object"){const le=String(me?.status||"").toLowerCase();if(me.__pending===!0||le==="running"||le==="pending"||le==="waiting")return!1}if(me==null||me==="")return!0;if(typeof me=="object"&&"status"in me){const le=me.status,O=me.result;if(typeof le=="string"&&le.toLowerCase()==="waiting")return!1;const ne=O==null||O===""||Array.isArray(O)&&O.length===0;return le==="error"||le==="idle"||ne}return!1},de=(U,Q)=>{if(!ko.includes(U.type)||B(U))return!1;const me=Q.value;if(me&&typeof me=="object"){const le=String(me?.status||"").toLowerCase();if(me.__pending===!0||le==="running"||le==="pending"||le==="waiting")return!1}if(me==null)return!1;if(typeof me=="object"&&"result"in me){const le=me.result;return le==null||le===""?!1:Array.isArray(le)?le.length>0:!0}return typeof me=="string"&&me.length>0},fe=(U,Q)=>{if(U.type!=="webflow"&&U.type!=="shopify")return!1;const me=Q.value;if(me&&typeof me=="object"){const le=String(me?.status||"").toLowerCase();if(me.__pending===!0||le==="publishing"||le==="waiting")return!1}return!0},se=(U,Q)=>{if(U.type!=="seo_action")return!1;const me=Q.value;if(me&&typeof me=="object"){const le=String(me?.status||"").toLowerCase();if(me.__pending===!0||le==="executing"||le==="waiting")return!1}return!0};if(T.length===0)return e.jsx("div",{className:"px-3 py-2 text-xs text-gray-300 italic",children:"No columns configured"});const z=r.useMemo(()=>{for(const U of Object.keys(s.cells)){const Q=s.cells[U];if(Q?.value!==null&&Q?.value!==void 0&&Q?.value!=="")if(typeof Q.value=="object"){if("result"in Q.value&&Q.value.result||Object.values(Q.value).some(le=>le!=null&&le!==""))return!0}else return!0}return!1},[s.cells]);return e.jsx("div",{className:"flex flex-col h-full",children:T.map(({column:U,cellData:Q,displayLabel:me},le)=>{const O=mn[U.type]||mn.text,ne=M(Q.value,U.type),ge=i===U.id,ze=ne!==null,Ke=ae(U,Q),ie=!Ke&&de(U,Q),ve=fe(U,Q),we=se(U,Q),Pe=U.type==="select"||U.type==="status"||U.type==="enumerate",Ae=Pe&&U.config?.multiple===!0,ye=Pe&&U.config?.multiple!==!0,Te=U.type==="knowledge",Ie=()=>{if(!h)return null;const re=I(Q.value),Se=U.options||U.config?.options||[],je=($e,ue)=>{ue.stopPropagation(),ue.preventDefault(),h(s.id,U.id,re.filter(W=>W!==$e))},he=$e=>{$e.stopPropagation(),$e.preventDefault(),h(s.id,U.id,[])},Re=$e=>{$e.stopPropagation(),$e.preventDefault();const ue=E.current.get(U.id);if(ue){const W=ue.getBoundingClientRect();w({top:W.bottom+window.scrollY+4,left:W.left+window.scrollX})}u(re),f(U.id)},Me=(Se||[]).filter($e=>String($e||"").toLowerCase().includes(b.trim().toLowerCase())),Ze=$e=>{u(ue=>{const ke=ue.includes($e)?ue.filter(qe=>qe!==$e):[...ue,$e];return Array.from(new Set(ke))})},Be=()=>{h(s.id,U.id,I(x)),f(null),y("")},et=()=>{f(null),y("")};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{ref:$e=>{$e&&E.current.set(U.id,$e)},className:"flex items-center gap-2 min-w-0 w-full",children:[re.length>0?e.jsxs("div",{className:"flex items-center gap-0.5 flex-1 min-w-0 overflow-hidden",children:[re.slice(0,2).map(($e,ue)=>e.jsxs("span",{className:"inline-flex items-center gap-0.5 px-1 py-0.5 rounded text-[9px] font-medium bg-purple-50 text-purple-700 border border-purple-200 max-w-[80px] group/pill",children:[e.jsx("span",{className:"truncate",children:$e}),e.jsx("button",{onClick:W=>je($e,W),onMouseDown:W=>W.stopPropagation(),className:"opacity-0 group-hover/pill:opacity-100 hover:bg-purple-100 rounded-full p-0.5 transition-opacity flex-shrink-0",title:"Remove",children:e.jsx(mt,{size:7})})]},`${$e}-${ue}`)),re.length>2&&e.jsxs("span",{className:"text-[9px] text-gray-500 flex-shrink-0",title:re.slice(2).join(", "),children:["+",re.length-2," more"]})]}):e.jsx("span",{className:"text-gray-300 text-[9px] italic",children:"Select..."}),e.jsxs("div",{className:`flex items-center gap-0.5 ${re.length>0?"flex-shrink-0":""}`,children:[re.length>0&&e.jsx("button",{onClick:he,onMouseDown:$e=>$e.stopPropagation(),className:"p-0.5 text-slate-400 hover:text-red-500 transition-colors",title:"Clear all",children:e.jsx(mt,{size:10})}),e.jsxs("button",{type:"button",onMouseDown:$e=>$e.stopPropagation(),onClick:Re,className:"inline-flex items-center gap-0.5 rounded-md border border-slate-200 bg-white px-1 py-0.5 text-[9px] font-semibold text-slate-600 hover:bg-slate-50 hover:text-slate-900 transition-colors",title:"Add",children:[e.jsx($t,{size:8,className:"text-slate-400"}),e.jsx("span",{children:"Add"})]})]})]}),p===U.id&&g&&Ha.createPortal(e.jsxs("div",{ref:_,className:"fixed z-[9999] w-[260px] bg-white border border-gray-200 rounded shadow-lg",style:{to
424p:g.top,left:g.left},onMouseDown:$e=>$e.stopPropagation(),children:[e.jsx("div",{className:"p-2 border-b border-gray-100",children:e.jsxs("div",{className:"flex items-center gap-2 px-2 py-1.5 border border-gray-200 rounded bg-white",children:[e.jsx(Pt,{size:12,className:"text-gray-400"}),e.jsx("input",{value:b,onChange:$e=>y($e.target.value),placeholder:"Search...",className:"flex-1 text-[11px] outline-none text-gray-700",autoFocus:!0})]})}),e.jsx("div",{className:"max-h-48 overflow-y-auto p-2 space-y-1",children:Me.length===0?e.jsx("div",{className:"text-[11px] text-gray-400 px-2 py-2",children:"No options"}):Me.map($e=>e.jsxs("label",{className:"flex items-center gap-2 px-2 py-1 hover:bg-gray-50 rounded cursor-pointer text-xs",children:[e.jsx("input",{type:"checkbox",checked:x.includes($e),onChange:()=>Ze($e),className:"rounded border-gray-300"}),e.jsx("span",{className:"truncate",children:$e})]},$e))}),e.jsxs("div",{className:"border-t px-2 py-1.5 flex justify-end gap-2",children:[e.jsx("button",{onClick:et,className:"text-xs text-gray-500 hover:text-gray-700",children:"Cancel"}),e.jsx("button",{onClick:Be,className:"text-xs bg-blue-500 text-white px-2 py-0.5 rounded hover:bg-blue-600",children:"Done"})]})]}),document.body)]})},Oe=()=>{if(!h)return null;const re=U.options||U.config?.options||[],Se=je=>{je.stopPropagation(),h(s.id,U.id,je.target.value)};return e.jsxs("select",{value:Q.value||"",onChange:Se,onClick:je=>je.stopPropagation(),onMouseDown:je=>je.stopPropagation(),className:"w-full text-[11px] border border-gray-200 rounded px-2 py-1 bg-white text-gray-700 focus:outline-none focus:ring-1 focus:ring-gray-200",children:[e.jsx("option",{value:"",children:"Select..."}),re.map(je=>e.jsx("option",{value:je,children:je},je))]})},J=()=>{if(!h)return null;const re=j(Q.value),Se=Q.value&&typeof Q.value=="object"&&!Array.isArray(Q.value)?Array.isArray(Q.value.names)?Q.value.names.map(ue=>String(ue||"").trim()).filter(Boolean):[]:[],je=Se.length>0?Se:re,he=(ue,W)=>{W.stopPropagation(),W.preventDefault();const ke=je.indexOf(ue);if(ke!==-1){const qe=[...re],Qe=[...je];qe.splice(ke,1),Qe.splice(ke,1),h(s.id,U.id,{kb_ids:qe,names:Qe})}},Re=ue=>{ue.stopPropagation(),ue.preventDefault(),h(s.id,U.id,{kb_ids:[],names:[]})},Me=ue=>{ue.stopPropagation(),ue.preventDefault();const W=A.current.get(U.id);if(W){const ke=W.getBoundingClientRect();V({top:ke.bottom+window.scrollY+4,left:ke.left+window.scrollX})}R(re),S(U.id)},Ze=(L||[]).filter(ue=>`${ue.name||""}`.toLowerCase().includes(k.trim().toLowerCase())),Be=ue=>{R(W=>{const qe=W.includes(ue)?W.filter(Qe=>Qe!==ue):[...W,ue];return Array.from(new Set(qe))})},et=()=>{h(s.id,U.id,q(F)),S(null),D("")},$e=()=>{S(null),D("")};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{ref:ue=>{ue&&A.current.set(U.id,ue)},className:"flex items-center gap-2 min-w-0 w-full",children:[je.length>0?e.jsxs("div",{className:"flex items-center gap-0.5 flex-1 min-w-0 overflow-hidden",children:[je.slice(0,2).map((ue,W)=>e.jsxs("span",{className:"inline-flex items-center gap-0.5 px-1 py-0.5 rounded text-[9px] font-medium bg-indigo-50 text-indigo-700 border border-indigo-200 max-w-[80px] group/pill",children:[e.jsx("span",{className:"truncate",children:ue}),e.jsx("button",{onClick:ke=>he(ue,ke),onMouseDown:ke=>ke.stopPropagation(),className:"opacity-0 group-hover/pill:opacity-100 hover:bg-indigo-100 rounded-full p-0.5 transition-opacity flex-shrink-0",title:"Remove",children:e.jsx(mt,{size:7})})]},`${ue}-${W}`)),je.length>2&&e.jsxs("span",{className:"text-[9px] text-gray-500 flex-shrink-0",title:je.slice(2).join(", "),children:["+",je.length-2," more"]})]}):e.jsx("span",{className:"text-gray-300 text-[9px] italic",children:"Select..."}),e.jsxs("div",{className:`flex items-center gap-0.5 ${je.length>0?"flex-shrink-0":""}`,children:[je.length>0&&e.jsx("button",{onClick:Re,onMouseDown:ue=>ue.stopPropagation(),className:"p-0.5 text-slate-400 hover:text-red-500 transition-colors",title:"Clear all",children:e.jsx(mt,{size:10})}),e.jsxs("button",{type:"button",onMouseDown:ue=>ue.stopPropagation(),onClick:Me,className:"inline-flex items-center gap-0.5 rounded-md border border-slate-200 bg-white px-1 py-0.5 text-[9px] font-semibold text-slate-600 hover:bg-slate-50 hover:text-slate-900 transition-colors",title:"Add knowledge base",children:[e.jsx($t,{size:8,className:"text-slate-400"}),e.jsx("span",{children:"Add"})]})]})]}),N===U.id&&X&&Ha.createPortal(e.jsxs("div",{ref:P,className:"fixed z-[9999] w-[360px] bg-white border border-gray-200 rounded shadow-xl max-h-[420px] overflow-hidden",style:{to
424p:X.top,left:X.left},onMouseDown:ue=>ue.stopPropagation(),children:[e.jsx("div",{className:"p-2 border-b border-gray-100",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Pt,{size:14,className:"text-gray-400"}),e.jsx("input",{value:k,onChange:ue=>D(ue.target.value),placeholder:"Search knowledge bases...",className:"w-full text-xs outline-none",autoFocus:!0})]})}),e.jsx("div",{className:"max-h-[300px] overflow-y-auto p-2 space-y-1",children:H?e.jsxs("div",{className:"text-xs text-gray-500 flex items-center gap-2 p-2",children:[e.jsx(He,{size:14,className:"animate-spin"}),"Loading..."]}):Ze.length===0?e.jsx("div",{className:"text-xs text-gray-400 p-2",children:"No knowledge bases"}):Ze.map(ue=>{const W=F.includes(ue.id);return e.jsxs("label",{className:"flex items-start gap-2 p-2 rounded hover:bg-gray-50 cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:W,onChange:()=>Be(ue.id)}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"text-xs text-gray-700 truncate",children:[ue.name,typeof ue.document_count=="number"?` (${ue.document_count})`:""]}),ue.description?e.jsx("div",{className:"text-[10px] text-gray-400 truncate",children:ue.description}):null]})]},ue.id)})}),e.jsxs("div",{className:"p-2 border-t border-gray-100 flex items-center justify-end gap-2",children:[e.jsx("button",{onClick:$e,className:"text-xs px-3 py-1.5 rounded border border-gray-200 bg-white text-gray-600 hover:bg-gray-50",children:"Cancel"}),e.jsx("button",{onClick:et,className:"text-xs px-3 py-1.5 rounded border border-gray-700 bg-gray-700 text-white hover:bg-gray-600",children:"Apply"})]})]}),document.body)]})};return e.jsxs("div",{className:`group/child relative px-3 flex-1 min-h-[44px] flex items-center cursor-pointer transition-colors ${le<T.length-1?"border-b border-gray-100":""} ${ge?"bg-blue-50 ring-1 ring-inset ring-blue-400":"hover:bg-gray-50"}`,onMouseDown:re=>{re.stopPropagation(),re.preventDefault(),n?.(U,re)},onClick:re=>{re.stopPropagation(),n?.(U,re)},onDoubleClick:re=>{re.stopPropagation(),o?.(U)},children:[z?Te?e.jsxs("div",{className:"flex items-center min-w-0 pr-6 w-full",children:[e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[e.jsx(O,{size:10,className:"text-gray-400"}),e.jsxs("span",{className:"text-[10px] font-bold italic text-gray-600 whitespace-nowrap",children:[me,":"]})]}),e.jsx("div",{className:"flex-1 min-w-0 ml-1.5",children:J()})]}):Ae?e.jsxs("div",{className:"flex items-center min-w-0 pr-6 w-full",children:[e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[e.jsx(O,{size:10,className:"text-gray-400"}),e.jsxs("span",{className:"text-[10px] font-bold italic text-gray-600 whitespace-nowrap",children:[me,":"]})]}),e.jsx("div",{className:"flex-1 min-w-0 ml-1.5",children:Ie()})]}):ye?e.jsxs("div",{className:"flex items-center min-w-0 pr-6 w-full",children:[e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[e.jsx(O,{size:10,className:"text-gray-400"}),e.jsxs("span",{className:"text-[10px] font-bold italic text-gray-600 whitespace-nowrap",children:[me,":"]})]}),e.jsx("div",{className:"flex-1 min-w-0 ml-1.5",children:Oe()})]}):e.jsxs("div",{className:"flex items-center min-w-0 pr-6 w-full",children:[e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[e.jsx(O,{size:10,className:"text-gray-400"}),e.jsxs("span",{className:"text-[10px] font-bold italic text-gray-600 whitespace-nowrap",children:[me,":"]})]}),e.jsx("span",{className:`text-[11px] truncate flex-1 min-w-0 ml-1.5 ${ze?"text-gray-700":"text-gray-400 italic"}`,title:ne||"-",children:ze?Z(ne,25):"-"})]}):null,Ke&&l&&e.jsx("button",{onClick:re=>{re.stopPropagation(),l(U)},className:"absolute right-1 top-1/2 -translate-y-1/2 p-1 bg-white hover:bg-gray-100 border border-gray-200 rounded shadow-sm z-10",title:"Run",children:e.jsx(so,{size:8,className:"text-gray-600"})}),ie&&c&&e.jsx("button",{onClick:re=>{re.stopPropagation(),c(U)},className:"absolute right-1 top-1/2 -translate-y-1/2 p-1 bg-white hover:bg-gray-100 border border-gray-200 rounded shadow-sm z-10",title:"Expand",children:e.jsx(er,{size:8,className:"text-gray-600"})}),ve&&d&&e.jsx("button",{onClick:re=>{re.stopPropagation(),d(U)},className:"absolute right-1 top-1/2 -translate-y-1/2 p-1 bg-white hover:bg-gray-100 border border-gray-200 rounded shadow-sm z-10",title:"Publish",children:e.jsx(Ri,{size:8,className:"text-gray-600"})}),we&&m&&e.jsx("button",{onClick:re=>{re.stopPropagation(),m(U)},className:"absolute right-1 top-1/2 -translate-y-1/2 p-1 bg-white hover:bg-gray-100 border border-gray-200 rounded shadow-sm z-10",title:"Ap
424ply",children:e.jsx(us,{size:8,className:"text-gray-600"})})]},U.id)})})};function po(t){if(!t)return"Column not found";if((t.type==="seo_analysis"||t.type==="ai_seo_analysis")&&!t.config?.seo_analysis?.url_source_column_id)return"Please select a URL Source Column for SEO Analysis.";if(t.type==="seo_action"){const s=t.config?.seo_action;if(!s?.advice_source_column)return"Please select an Advice Source Column for SEO Action.";if(!s?.page_url_column)return"Please select a Page URL Column for SEO Action.";if(!s?.shop_id&&!s?.webflow_collection_slug)return"Please select an Action Page (Shopify Shop or Webflow Collection)."}if(t.type==="webflow"){const s=t.config?.webflow;if(!s?.content_column)return"Please select a Content Column for Webflow publishing.";if(!s?.collection_type)return"Please select a Collection Type for Webflow publishing."}if(t.type==="shopify"){const s=t.config?.shopify;if(!s?.shop_id)return"Please select a Shopify Shop.";if(!s?.content_type)return"Please select a Content Type (Article or Page).";if(s?.content_type==="article"){if(!s?.article?.blog_id)return"Please select a Blog for Shopify Article publishing.";if(!s?.article?.content_column)return"Please select a Content Column for Shopify Article publishing."}if(s?.content_type==="page"&&!s?.page?.content_column)return"Please select a Content Column for Shopify Page publishing."}return null}const Cl=t=>{if(!t||typeof t!="string")return!1;try{const s=new URL(t);return s.protocol==="http:"||s.protocol==="https:"}catch{return!1}},Ok=t=>{if(!t||typeof t!="string")return null;try{const s=typeof window<"u"?sessionStorage.getItem("webflow_custom_domains"):null;if(!s)return null;const a=JSON.parse(s);if(!Array.isArray(a)||a.length===0)return null;const n=a[0];if(!n||!n.url)return null;let o=String(n.url||"").trim();if(!o)return null;!o.startsWith("http://")&&!o.startsWith("https://")&&(o=`https://${o}`),o=o.replace(/\/+$/,"");const i=t.startsWith("/")?t:`/${t}`;return`${o}${i}`}catch{return null}},Bk=({rowId:t,col:s,data:a,row:n,columns:o,onUpdate:i})=>{const[l,c]=r.useState(!1),[d,m]=r.useState(a.value),[h,p]=r.useState(!1),[f,b]=r.useState(!1),[y,x]=r.useState(!1),[u,g]=r.useState(""),[w,_]=r.useState([]),[E,N]=r.useState(null),S=r.useRef(null),k=r.useRef(null),[D,F]=r.useState(!1),[R,L]=r.useState(""),[$,H]=r.useState([]),[K,X]=r.useState([]),[V,P]=r.useState(!1),[A,C]=r.useState(null),I=r.useRef(null),j=r.useRef(null),q=r.useRef(null),T=r.useRef(null),M=r.useRef(null),Z=r.useRef(null),[B,ae]=r.useState(!1),{isCellSelected:de,selectCell:fe,startDragSelect:se,extendDragSelect:z,selection:U,expandCell:Q,editingCell:me,startEditingCell:le,stopEditingCell:O}=dk(),ne=r.useRef(t);r.useEffect(()=>{ne.current=t},[t]);const ge=de(t,s.id),ze=r.useMemo(()=>da(),[]),{checkAndShowError:Ke,showToast:ie}=Xi({columns:o}),ve=r.useCallback(G=>!!G&&typeof G=="object"&&G.__pending===!0&&typeof G.__task_id=="string",[]);r.useEffect(()=>{m(a.value)},[a.value]),r.useEffect(()=>{l&&q.current&&q.current.focus()},[l]),r.useEffect(()=>{if(!l)return;const G=q.current||T.current||M.current;requestAnimationFrame(()=>G?.focus())},[l]);const we=G=>{if(G.button!==0)return;const ce=navigator.platform.toUpperCase().indexOf("MAC")>=0?G.metaKey:G.ctrlKey,Y=G.shiftKey;Y||ce?(G.preventDefault(),fe(t,s.id,Y,ce)):se(t,s.id)},Pe=()=>{U.isSelecting&&z(t,s.id)},Ae=G=>{if(G.stopPropagation(),G.preventDefault(),fe(t,s.id,!1,!1),Q(t,s.id),s.type==="knowledge"){if(F(!0),j.current){const pe=j.current.getBoundingClientRect();C({top:pe.bottom+window.scrollY+4,left:pe.left+window.scrollX})}return}if((s.type==="select"||s.type==="status"||s.type==="enumerate")&&s.config?.multiple===!0){x(!0);return}J()},ye=ge?"bg-blue-50 ring-2 ring-blue-400 ring-inset":"bg-white hover:bg-gray-50/50",Te=(s.type==="select"||s.type==="status"||s.type==="enumerate")&&s.config?.multiple===!0,Ie=s.type==="knowledge",Oe=me?.rowId===t&&me?.colId===s.id;r.useEffect(()=>{l&&(Te||Ie)&&(c(!1),O())},[l,Te,Ie]),r.useEffect(()=>{Oe&&(Te||Ie||l||c(!0))},[Oe,Te,Ie,l]);const J=r.useCallback(G=>{G&&(G.stopPropagation(),G.preventDefault()),fe(t,s.id,!1,!1);const pe=a.value,ce=xe=>{if(xe==null)return"";if(typeof xe=="string")return xe;try{return JSON.stringify(xe,null,2)}catch{return String(xe)}};m((()=>
424{if(s.type==="checkbox")return!!pe;if(s.type==="keywords"||s.type==="ai_keywords")return Array.isArray(pe)?pe.map(String).join(`
425`):typeof pe=="string"?pe:"";if(s.type==="ai"||s.type==="seo_analysis"||s.type==="ai_seo_analysis"){const xe=pe,Ee=xe&&typeof xe=="object"&&!Array.isArray(xe)&&"result"in xe?xe.result:xe;return Array.isArray(Ee)?Ee.map(String).join(`
426`):Ee==null?"":typeof Ee=="string"?Ee:ce(Ee)}return typeof pe=="object"?ce(pe):pe??""})()),le(t,s.id)},[fe,t,s.id,le,a.value,s.type]),re=r.useCallback(async G=>{const pe=ne.current;if(!ze||!s.id||h)return;const ce=po(s);if(ce){ie("error",ce,[]);return}if(G==="keywords"||G==="ai_keywords"){const Y=Zr(s.config);if(Y.length>0&&!lo(n,o,Y).valid){Ke(n,Y);return}}else{let Y=[];if(G==="seo_analysis"||G==="ai_seo_analysis")Y=jr(s);else{const xe=s.config?.ai||s.ai_config;Y=xe?.user_prompt?Rr(xe.user_prompt):[]}if(Y.length>0&&!Ke(n,Y).valid)return}p(!0),i(pe,s.id,{status:"running",result:null});try{let Y;if(G==="keywords"||G==="ai_keywords"){const Ee=Zr(s.config),Ne={};if(Ee.length>0){const Ce={};for(const De of Ee){const Ge=o.find(ee=>ee.id===De||ee.system_name===De);if(Ge){const ee=n.cells[Ge.id]?.value;if(ee!=null&&ee!==""){const Fe=Ge.system_name||Ge.title;Ce[Fe]=typeof ee=="object"&&ee.result?ee.result:ee}}}Object.keys(Ce).length>0&&(Ne[pe]={dependencies:Ce})}Y=await Vt.generateKeywordsValue({campaign_id:ze,column_id:s.id,row_ids:[pe],row_data_map:Object.keys(Ne).length>0?Ne:void 0})}else Y=await Vt.generateAIValue({campaign_id:ze,column_id:s.id,row_ids:[pe]});const xe=Y.results?.[0];if(xe&&xe.status==="pending"&&xe.placeholder){const Ee=xe.row_id;
426if(pe&&typeof pe=="string"&&pe.startsWith("empty_")&&Ee&&Ee!==pe){const Ce={...xe.placeholder,__real_row_id:Ee,__original_row_id:pe};i(pe,s.id,Ce)}else i(pe,s.id,xe.placeholder)}else xe&&xe.status==="failed"&&i(pe,s.id,{status:"error",result:xe.error||"Generation failed"})}catch(Y){console.error("AI generation error:",Y),i(pe,s.id,{status:"error",result:Y?.message||"Generation failed"})}finally{p(!1)}},[ze,s,n,i,h,Ke,o]),Se=s.type==="composite",je="px-3 text-xs truncate h-9 flex items-center w-full",he=r.useCallback(G=>{const pe=Array.isArray(G)?G:G?[G]:[],Y=(pe.flat?pe.flat(2):[].concat(...pe.map(xe=>Array.isArray(xe)?xe:[xe]))).map(xe=>typeof xe=="string"?xe.trim():String(xe??"").trim()).filter(xe=>!!xe);return Array.from(new Set(Y))},[]),Re=r.useCallback(G=>{if(!G)return[];if(typeof G=="object"&&!Array.isArray(G)){const pe=G.kb_ids;if(Array.isArray(pe))return Array.from(new Set(pe.map(ce=>String(ce||"").trim()).filter(Boolean)))}if(Array.isArray(G))return Array.from(new Set(G.map(pe=>String(pe||"").trim()).filter(Boolean)));if(typeof G=="string"){const pe=G.trim();return pe?[pe]:[]}return[]},[]),Me=r.useCallback(G=>{const pe=Array.from(new Set((G||[]).map(String).filter(Boolean))),ce=new Map((K||[]).map(xe=>[xe.id,xe])),Y=[];for(const xe of pe){const Ee=ce.get(xe);Ee?.name&&Y.push(Ee.name)}return{kb_ids:pe,names:Y}},[K]);r.useEffect(()=>{y&&_(he(a.value))},[y,a.value,he]),r.useEffect(()=>{if(!y)return;const G=ce=>{const Y=ce.target;Y&&(S.current?.contains(Y)||k.current?.contains(Y)||(x(!1),g("")))},pe=ce=>{ce.key==="Escape"&&(x(!1),g(""))};return document.addEventListener("mousedown",G),document.addEventListener("keydown",pe),()=>{document.removeEventListener("mousedown",G),document.removeEventListener("keydown",pe)}},[y]),r.useEffect(()=>{D&&(H(Re(a.value)),!(K.length>0||V)&&(P(!0),qi().then(G=>X(Array.isArray(G)?G:[])).catch(()=>X([])).finally(()=>P(!1))))},[D,a.value,Re,K.length,V]),r.useEffect(()=>{if(!D)return;const G=ce=>{const Y=ce.target;Y&&(I.current?.contains(Y)||j.current?.contains(Y)||(F(!1),L("")))},pe=ce=>{ce.key==="Escape"&&(F(!1),L(""))};return document.addEventListener("mousedown",G),document.addEventListener("keydown",pe),()=>{document.removeEventListener("mousedown",G),document.removeEventListener("keydown",pe)}},[D]);const Ze=()=>{if(!l||Te)return null;const G=Y=>(Y||"").split(/[\n,]+/g).map(xe=>xe.trim()).filter(Boolean),pe=Y=>{const xe=(Y??"").trim();if(!xe)return"";try{return JSON.parse(xe)}catch{return Y}},ce=()=>{let Y=d;const xe=a.value;if(s.type==="checkbox")Y=!!d;else if(s.type==="number")Y=typeof d=="number"?d:parseFloat(String(d))||0;else if(s.type==="keywords"||s.type==="ai_keywords")Y=Array.isArray(d)?d:G(String(d));else if(s.type==="ai"||s.type==="seo_analysis"||s.type==="ai_seo_analysis"){const Ee=xe&&typeof xe=="object"&&!Array.isArray(xe)?xe:{},Ce=Array.isArray(xe)||!!xe&&typeof xe=="object"&&!Array.isArray(xe)&&"result"in xe&&Array.isArray(xe.result)?G(String(d)):String(d??"");Y={...Ee,status:"complete",result:Ce}}else s.type==="webflow"||s.type==="shopify"||s.type==="seo_action"?Y=typeof d=="string"?pe(d):d:s.type==="system"?Y=String(d??""):typeof d=="string"&&typeof xe=="object"?Y=pe(d):Y=d;c(!1),O(),i(t,s.id,Y)};if(s.type==="select"||s.type==="status"||s.type==="enumerate"){const Y=s.config?.multiple===!0,xe=s.options||s.config?.options||[];return Y?e.jsx("td",{className:"p-0 border-r-2 border-gray-200 relative h-9",children:e.jsx("div",{className:`${je} text-gray-400 italic`,children:"Use Add to select..."})}):e.jsx("td",{className:"p-0 border-r-2 border-gray-200 relative h-9",children:e.jsxs("select",{ref:M,className:"w-full h-full px-2 text-xs bg-white focus:outline-none focus:ring-2 focus:ring-blue-400 appearance-none text-gray-700",value:d,onChange:Ee=>m(Ee.target.value),onBlur:ce,onKeyDown:Ee=>{Ee.key==="Enter"&&ce(),Ee.key==="Escape"&&(m(a.value),c(!1),O())},autoFocus:!0,children:[e.jsx("option",{value:"",children:"Select..."}),xe.map(Ee=>e.jsx("option",{value:Ee,children:Ee},Ee))]})})}return s.type==="checkbox"?e.jsx("td",{className:"p-0 border-r-2 border-gray-200 relative h-9",children:e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx("input",{ref:q,type:"checkbox",checked:!!d,onChange:Y=>m(Y.target.checked),onBlur:ce,onKeyDown:Y=>
426{Y.key==="Enter"&&ce(),Y.key==="Escape"&&(m(!!a.value),c(!1),O())},autoFocus:!0})})}):s.type==="date"?e.jsx("td",{className:"p-0 border-r-2 border-gray-200 relative h-9",children:e.jsx("input",{ref:q,type:"date",className:"w-full h-full px-3 text-xs bg-white focus:outline-none focus:ring-2 focus:ring-blue-400 absolute inset-0 z-10 text-gray-700",value:String(d??""),onChange:Y=>m(Y.target.value),onBlur:ce,onKeyDown:Y=>{Y.key==="Enter"&&ce(),Y.key==="Escape"&&(m(a.value??""),c(!1),O())}})}):s.type==="ai"||s.type==="seo_analysis"||s.type==="ai_seo_analysis"||s.type==="keywords"||s.type==="ai_keywords"||s.type==="webflow"||s.type==="shopify"||s.type==="seo_action"||s.type==="system"||typeof a.value=="object"?e.jsx("td",{className:"p-0 border-r-2 border-gray-200 relative h-24 align-top",children:e.jsx("textarea",{ref:T,className:"w-full h-full px-3 py-2 text-xs bg-white focus:outline-none focus:ring-2 focus:ring-blue-400 absolute inset-0 z-10 text-gray-700 placeholder-gray-400 resize-none",value:String(d??""),onChange:Y=>m(Y.target.value),onBlur:ce,onKeyDown:Y=>{(navigator.platform.toUpperCase().indexOf("MAC")>=0?Y.metaKey:Y.ctrlKey)&&Y.key==="Enter"&&(Y.preventDefault(),ce()),Y.key==="Escape"&&(m(a.value??""),c(!1),O())},autoFocus:!0,placeholder:s.type==="keywords"||s.type==="ai_keywords"?"One keyword per line (or comma-separated)":void 0})}):e.jsx("td",{className:"p-0 border-r-2 border-gray-200 relative h-9",children:e.jsx("input",{ref:q,type:s.type==="number"?"number":s.type==="email"?"email":"text",className:"w-full h-full px-3 text-xs bg-white focus:outline-none focus:ring-2 focus:ring-blue-400 absolute inset-0 z-10 text-gray-700 placeholder-gray-400",value:String(d??""),onChange:Y=>m(Y.target.value),onBlur:ce,onKeyDown:Y=>{Y.key==="Enter"&&ce(),Y.key==="Escape"&&(m(a.value??""),c(!1),O())}})})};let Be;const et=(G,pe)=>{const ce=ve(G);let Y="idle",xe=null;return ce?Y="running":G==null||G===""?(Y="idle",xe=null):typeof G=="string"?(Y="complete",xe=G):typeof G=="object"&&"status"in G&&"result"in G?(Y=G.status||"complete",xe=G.result):(Y="complete",xe=G),e.jsx("div",{className:je,children:Y==="running"||ce||h?e.jsxs("div",{className:"flex items-center gap-2 text-gray-600",children:[e.jsx(He,{size:12,className:"animate-spin"}),e.jsx("span",{className:"text-[11px]",children:"Generating..."})]}):Y==="waiting"?e.jsxs("div",{className:"flex items-center gap-2 text-gray-500",children:[e.jsx(Ra,{size:12}),e.jsx("span",{className:"text-[11px]",children:"Waiting..."})]}):Y==="error"||Y==="failed"?e.jsxs("div",{className:"flex items-center gap-2 text-red-500",title:typeof G=="object"&&G?.error?G.error:void 0,children:[e.jsx(Ss,{size:12}),e.jsx("span",{className:"text-[11px] truncate",children:xe||"Error"})]}):xe?e.jsx("span",{className:"truncate text-gray-700 text-[11px]",children:na(xe)}):e.jsx("span",{className:"text-gray-300 text-[10px] italic",children:"Click to run"})})},$e=(G,pe)=>{const ce=ve(G),Y=G&&typeof G=="object"&&G.status==="running",xe=G&&typeof G=="object"&&G.status==="waiting",Ee=G&&typeof G=="object"&&G.status==="failed";let Ne=[];if(Array.isArray(G))Ne=G.map(De=>typeof De=="string"?De.trim():"").filter(De=>De.length>0);else if(typeof G=="string"&&G.trim())Ne=G.split(",").map(De=>De.trim()).filter(De=>De.length>0);else if(typeof G=="object"&&G?.result){const De=G.result;Array.isArray(De)?Ne=De.map(Ge=>typeof Ge=="string"?Ge.trim():"").filter(Ge=>Ge.length>0):typeof De=="string"&&(Ne=De.split(",").map(Ge=>Ge.trim()).filter(Ge=>Ge.length>0))}const Ce=async(De,Ge)=>{Ge.stopPropagation(),Ge.preventDefault();const ee=ne.current,Fe=Ne.filter(Xe=>Xe!==De);if(i(ee,s.id,Fe),ee&&!ee.startsWith("empty_")&&!ee.startsWith("new_")){const Xe="custom";try{await Wt.updateCustomData({campaign_id:ze||void 0,table_type:Xe,entity_id:ee,updates:{[s.id]:Fe}})}catch(yt){console.error("Failed to update keywords:",yt)}}};if(ce||Y||h)return e.jsx("div",{className:`${je} justify-between gap-2`,children:e.jsxs("div",{className:"flex items-center gap-2 text-gray-600",children:[e.jsx(He,{size:12,className:"animate-spin"}),e.jsx("span",{className:"text-[11px]",children:"Generating..."})]})});if(xe)return e.jsx("div",{className:je,children:e.jsxs("div",{className:"flex items-center gap-2 text-gray-500",children:[e.jsx(Ra,{size:12}),e.jsx("span",{className:"text-[11px]",children:"Waiting..."})]})});if(Ee){const De=G.error||"Generation failed";return e.jsx("div",{className:je,children:e.jsxs("div",{className:"flex items-center gap-2 text-red-500",title:De,children:[e.jsx(Ss,{size:12}),e.jsx("span",{className:"text-[11px]",children:"Failed"})]})})}return Ne.length>0?e.jsx("div",{className:je,children:e.jsxs("div",{className:"flex items-center gap-1 flex-1 min-w-0 overflow-hidden",children:[e.jsxs("span",{className:"inline-flex items-center gap-0.5 px-1.5 py-0.5 rounded text-[10px] font-medium bg-blue-50 text-blue-700 border border-blue-200 max-w-[120px] group/pill",children:[e.jsx("span",{className:"truncate",children:Ne[0]}),e.jsx("button",{onClick:De=>Ce(Ne[0],De),className:"opacity-0 group-hover/pill:opacity-100 hover:bg-blue-100 rounded-full p-0.5 transition-opacity flex-shrink-0",title:"Remove keyword",children:e.jsx(mt,{size:10})})]}),Ne.length>1&&e.jsxs("span",{className:"text-[10px] text-gray-400 flex-shrink-0",title:Ne.slice(1).join(", "),children:["+",Ne.length-1]})]})}):e.jsx("div",{className:je,children:e.jsx("span",{className:"text-gray-300 text-[10px] italic",children:"Click to generate"})})},[ue,W]=r.useState(!1),ke=r.useRef(null),qe=r.useRef([]),Qe=r.useCallback(G=>{const pe=ne.current,ce=G.map(Ee=>Ee.keyword),Y=qe.current,xe=[...new Set([...Y,...ce])];i(pe,s.id,xe),W(!1)},[s.id,i]),ct=(G,pe)=>{let ce=[];Array.isArray(G)?ce=G.filter(Ce=>typeof Ce=="string"&&Ce.trim()!==""):typeof G=="string"&&G.trim()&&(ce=[G.trim()]),qe.current=ce;const Y=Ce=>{Ce.stopPropagation(),Ce.preventDefault(),W(!0)},xe=(Ce,De)=>{De.stopPropagation(),De.preventDefault();const Ge=ne.current,ee=ce.filter(Fe=>Fe!==Ce);i(Ge,s.id,ee)},Ee=Ce=>{Ce.stopPropagation(),Ce.preventDefault();const De=ne.current;i(De,s.id,[])},Ne=new Set(ce);return e.jsxs(e.Fragment,{children:[e.jsx("div",{ref:ke,className:`${je} relative`,children:e.jsxs("div",{className:`flex items-center gap-2 min-w-0 
426w-full ${ce.length>0?"justify-between":"justify-center"}`,children:[ce.length>0&&e.jsxs("div",{className:"flex items-center gap-1 flex-1 min-w-0 overflow-hidden",children:[ce.slice(0,2).map((Ce,De)=>e.jsxs("span",{className:"inline-flex items-center gap-0.5 px-1.5 py-0.5 rounded text-[10px] font-medium bg-purple-50 text-purple-700 border border-purple-200 max-w-[80px] group/pill",children:[e.jsx("span",{className:"truncate",children:Ce}),e.jsx("button",{onClick:Ge=>xe(Ce,Ge),onMouseDown:Ge=>Ge.stopPropagation(),className:"opacity-0 group-hover/pill:opacity-100 hover:bg-purple-100 rounded-full p-0.5 transition-opacity flex-shrink-0",title:"Remove keyword",children:e.jsx(mt,{size:8})})]},`${Ce}-${De}`)),ce.length>2&&e.jsxs("span",{className:"text-[10px] text-gray-500 flex-shrink-0",children:["+",ce.length-2," more"]})]}),e.jsxs("div",{className:`flex items-center gap-1 ${ce.length>0?"flex-shrink-0":""}`,children:[ce.length>0&&e.jsx("button",{onClick:Ee,onMouseDown:Ce=>Ce.stopPropagation(),className:"p-0.5 text-slate-400 hover:text-red-500 transition-colors",title:"Clear all keywords",children:e.jsx(mt,{size:12})}),e.jsxs("button",{type:"button",onMouseDown:Ce=>Ce.stopPropagation(),onClick:Y,className:"inline-flex items-center gap-1 rounded-md border border-slate-200 bg-white px-1.5 py-0.5 text-[10px] font-semibold text-slate-600 hover:bg-slate-50 hover:text-slate-900 transition-colors",title:"Add keywords",children:[e.jsx($t,{size:10,className:"text-slate-400"}),e.jsx("span",{children:"Add"})]})]})]})}),e.jsx(Kc,{isOpen:ue,title:"Select Keywords",description:"Select keywords from your top rankings or competitors.",existingKeywords:Ne,onClose:()=>W(!1),onConfirm:Qe,skipConfirmation:!0})]})},pt=G=>{let pe=null,ce=null,Y=!1,xe=!1,Ee=!1;if(!(G==null||G==="")){if(G&&typeof G=="object")if(G.__pending===!0||G.status==="running")Y=!0;else if(G.status==="waiting"||G.__pipeline_waiting===!0)xe=!0;else if(G.status==="error"||G.status==="failed")Ee=!0;else if(G.status==="complete"&&G.result)try{pe=typeof G.result=="string"?JSON.parse(G.result):G.result,ce=pe?.total_score??null}catch{ce=G.result?.total_score??null}else"total_score"in G&&(pe=G,ce=G.total_score);else if(typeof G=="string")try{pe=JSON.parse(G),ce=pe?.total_score??null}catch{}}const Ne=Ce=>Ce>=86?{bg:"bg-emerald-100",text:"text-emerald-700",ring:"ring-emerald-200"}:Ce>=64?{bg:"bg-amber-100",text:"text-amber-700",ring:"ring-amber-200"}:{bg:"bg-red-100",text:"text-red-700",ring:"ring-red-200"};return e.jsx("div",{className:je,children:Y||h?e.jsxs("div",{className:"flex items-center gap-2 text-gray-600",children:[e.jsx(He,{size:12,className:"animate-spin"}),e.jsx("span",{className:"text-[11px]",children:"Scoring..."})]}):xe?e.jsxs("div",{className:"flex items-center gap-2 text-gray-500",children:[e.jsx(Ra,{size:12}),e.jsx("span",{className:"text-[11px]",children:"Waiting..."})]}):Ee?e.jsxs("div",{className:"flex items-center gap-2 text-red-500",children:[e.jsx(Ss,{size:12}),e.jsx("span",{className:"text-[11px]",children:"Error"})]}):ce!==null?e.jsx("div",{className:"flex items-center justify-center w-full",children:e.jsx("div",{className:`inline-flex items-center justify-center px-2.5 py-1 rounded-full text-xs font-bold ring-1 ${Ne(ce).bg} ${Ne(ce).text} ${Ne(ce).ring}`,children:ce})}):e.jsx("span",{className:"text-gray-400 text-[11px] italic",children:"—"})})},At=(G,pe,ce)=>{const xe=G&&typeof G=="object"&&G.__pending===!0?"publishing":G&&typeof G=="object"?G.status:"idle",Ee=G&&typeof G=="object"?G.url||G.article_url:null,Ne=async Ce=>{Ce.stopPropagation();const De=ne.current;if(!ze){ie("error","Campaign ID not found",[]);return}const Ge=jr(s);if(!(Ge.length>0&&!Ke(n,Ge).valid)){i(De,s.id,{status:"publishing",__pending:!0});try{let ee;ce==="shopify"?ee=await Vt.publishShopifyAsync({campaign_id:ze,column_id:s.id,row_ids:[De]}):ee=await Vt.publishWebflowAsync({campaign_id:ze,column_id:s.id,row_ids:[De]});const Fe=ee.results?.[0];if(Fe&&Fe.status==="pending"&&Fe.placeholder){const Xe=Fe.row_id;if(De&&typeof De=="string"&&De.startsWith("empty_")&&Xe&&Xe!==De){const ut={...Fe.placeholder,__real_row_id:Xe,__original_row_id:De};i(De,s.id,ut)}else i(De,s.id,Fe.placeholder)}else Fe&&Fe.status==="failed"&&(i(De,s.id,{status:"failed",error:Fe.error}),ie("error","Publish failed",[Fe.error||"Unknown error"]))}catch(ee){console.error("Publish error:",ee),i(De,s.id,{status:"failed",error:ee?.message}),ie("error","Publish failed",[ee?.message||"Unknown error"])}}};return e.jsxs("div",{className:`${je} gap-2 pr-6`,style:{position:"relative"},children:[xe==="publishing"?e.jsxs("div",{className:"flex items-center gap-2 text-gray-600",children:[e.jsx(He,{size:12,className:"animate-spin"}),e.jsx("span",{className:"text-[11px]",children:"Publishing..."})]}):xe==="published"?e.jsxs("div",{className:"flex items-center gap-2 text-green-600",children:[e.jsx(wt,{size:12}),Ee?e.jsx("a",{href:Ee,target:"_blank",className:"text-[11px] hover:underline truncate",onClick:Ce=>Ce.stopPropagation(),children:"Published"}):e.jsx("span",{className:"text-[11px]",children:"Published"})]}):xe==="failed"?e.jsxs("div",{className:"flex items-center gap-2 text-red-500",title:typeof G=="object"&&G?.error?G.error:void 0,children:[e.jsx(Ss,{size:12}),e.jsx("span",{className:"text-[11px]",children:"Failed"})]}):e.jsx("span",{className:"text-gray-300 text-[10px] italic",children:"Not published"}),xe!=="publishing"&&e.jsx("button",{onClick:Ne,className:"p-1 bg-white hover:bg-gray-100 border border-gray-200 rounded opacity-0 group-hover:opacity-100 transition-opacity shadow-sm",style:{position:"absolute",top:"4px",right:"4px",zIndex:20},title:xe==="published"?"Re-publish":"Publish",children:e.jsx(Ri,{size:8,className:"text-gray-600"})})]})},te=G=>{const pe=ve(G),ce=G,Y=pe?"executing":typeof ce=="object"?ce.status:"idle",xe=typeof ce=="object"&&(ce.url||ce.article_url)||null,Ee=async Ne=>{Ne.stopPropagation();const Ce=ne.current;if(!ze){ie("error","Campaign ID not found",[]);return}
426if(!Ce||Ce.startsWith("empty_")||Ce.startsWith("new_")){ie("error","Please save the row first",[]);return}const De=jr(s);if(!(De.length>0&&!Ke(n,De).valid)){i(Ce,s.id,{status:"executing",__pending:!0});try{const ee=(await Vt.executeSEOActionAsync({campaign_id:ze,column_id:s.id,row_ids:[Ce]})).results?.[0];ee&&ee.status==="pending"&&ee.placeholder?i(Ce,s.id,ee.placeholder):ee&&ee.status==="failed"&&(i(Ce,s.id,{status:"failed",error:ee.error||"SEO Action failed"}),ie("error","SEO Action failed",[ee.error||"Unknown error"]))}catch(Ge){console.error("SEO Action error:",Ge),i(Ce,s.id,{status:"failed",error:Ge?.message||"SEO Action failed"}),ie("error","SEO Action failed",[Ge?.message||"Unknown error"])}}};return e.jsxs("div",{className:`${je} gap-2 pr-6`,style:{position:"relative"},children:[Y==="executing"||pe?e.jsxs("div",{className:"flex items-center gap-2 text-gray-600",children:[e.jsx(He,{size:12,className:"animate-spin"}),e.jsx("span",{className:"text-[11px]",children:"Applying..."})]}):Y==="applied"||Y==="published"?e.jsxs("div",{className:"flex items-center gap-2 text-green-600",children:[e.jsx(wt,{size:12}),xe?e.jsx("a",{href:xe,target:"_blank",rel:"noopener noreferrer",className:"text-[11px] hover:underline truncate",onClick:Ne=>Ne.stopPropagation(),children:"Applied"}):e.jsx("span",{className:"text-[11px]",children:"Applied"})]}):Y==="failed"?e.jsxs("div",{className:"flex items-center gap-2 text-red-500",title:typeof ce=="object"&&ce?.error?ce.error:void 0,children:[e.jsx(Ss,{size:12}),e.jsx("span",{className:"text-[11px]",children:"Failed"})]}):e.jsx("span",{className:"text-gray-300 text-[10px] italic",children:"Not applied"}),Y!=="executing"&&!pe&&e.jsx("button",{onClick:Ee,className:"p-1 bg-white hover:bg-gray-100 border border-gray-200 rounded opacity-0 group-hover:opacity-100 transition-opacity shadow-sm",style:{position:"absolute",top:"4px",right:"4px",zIndex:20},title:Y==="applied"||Y==="published"?"Re-apply":"Apply",children:e.jsx(us,{size:8,className:"text-gray-600"})})]})};switch(s.type){case"url":{const G=s.config?.url;let pe=a.value;if(G?.mode==="integration"){const Ee=G.integration_type;let Ne=null,Ce=null;if(Ee==="webflow"&&G.webflow_source_column_id?(Ne=G.webflow_source_column_id,Ce="site_url_path"):Ee==="shopify"&&G.shopify_source_column_id&&(Ne=G.shopify_source_column_id,Ce="url"),Ne&&Ce){const De=n.cells[Ne]?.value;if(De&&typeof De=="object"&&De.status==="published"){const Ge=De[Ce];Ge&&(pe=Ge)}}}let ce=typeof pe=="string"?pe:"";if(s.type==="url"&&((s.system_name||"").toLowerCase()==="article_url"||G?.preview_from_webflow_domain===!0)&&ce&&!Cl(ce)){const Ee=Ok(ce);Ee&&(ce=Ee)}Be=e.jsx("div",{className:`${je} group`,children:ce?Cl(ce)?e.jsxs("a",{href:ce,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-2 text-blue-600 hover:text-blue-800 hover:underline decoration-blue-300 underline-offset-2 font-mono",onClick:Ee=>Ee.stopPropagation(),children:[e.jsx(Qt,{size:10,className:"text-blue-400"}),e.jsx("span",{className:"truncate",children:ce.replace(/^https?:\/\//,"").substring(0,40)})]}):e.jsxs("span",{className:"flex items-center gap-2 text-gray-600 font-mono",children:[e.jsx(Qt,{size:10,className:"text-gray-400"}),e.jsx("span",{className:"truncate",children:ce})]}):e.jsx("span",{className:"text-gray-300 text-[10px] italic",children:G?.mode==="integration"?"Waiting for publish...":"Empty"})});break}case"checkbox":Be=e.jsx("div",{className:`${je} justify-center`,children:e.jsx("button",{onClick:G=>{G.stopPropagation(),i(t,s.id,!a.value)},className:`w-4 h-4 rounded border-2 flex items-center justify-center transition-colors ${a.value?"bg-gray-600 border-gray-600 text-white":"border-gray-300 hover:border-gray-400"}`,children:a.value&&e.jsx(wt,{size:10})})});break;case"date":Be=e.jsx("div",{className:`${je} font-mono text-gray-600`,children:a.value?e.jsx("span",{className:"truncate text-gray-700 text-[11px]",children:na(a.value)}):e.jsx("span",{className:"text-gray-300 text-[10px] italic",children:"No date"})});break;case"email":Be=e.jsx("div",{className:`${je} group`,children:typeof a.value=="string"&&a.value?e.jsxs("a",{href:`mailto:${a.value}`,className:"flex items-center gap-2 text-gray-600 hover:text-gray-800 hover:underline",onClick:G=>
426G.stopPropagation(),children:[e.jsx(ui,{size:10,className:"text-gray-400"}),a.value]}):a.value?e.jsxs("span",{className:"flex items-center gap-2 text-gray-600",children:[e.jsx(ui,{size:10,className:"text-gray-400"}),e.jsx("span",{className:"truncate text-gray-700 text-[11px]",children:na(a.value)})]}):e.jsx("span",{className:"text-gray-300 text-[10px] italic",children:"Empty"})});break;case"ai_image":{const G=a.value,pe=ve(G),ce=!!G&&typeof G=="object"&&!Array.isArray(G)&&(G.status==="running"||G.__pending===!0),Y=!!G&&typeof G=="object"&&!Array.isArray(G)&&(G.status==="failed"||G.status==="error"),xe=Y?G.error||"Generation failed":null,Ee=typeof G=="string"&&Cl(G)?G:null,Ne=Ce=>{Ce.stopPropagation();const De=ne.current;Q(De,s.id)};Be=e.jsx("div",{className:`${je} gap-2 justify-between cursor-pointer`,onClick:Ne,children:pe||ce?e.jsxs("div",{className:"flex items-center gap-2 text-gray-500 text-[11px]",children:[e.jsx(He,{size:12,className:"animate-spin"}),e.jsx("span",{className:"truncate",children:"Generating..."})]}):Y?e.jsxs("div",{className:"flex items-center gap-2 text-red-500 text-[11px]",children:[e.jsx(Ss,{size:12,className:"flex-shrink-0"}),e.jsx("span",{className:"truncate",title:xe||void 0,children:xe&&xe.length>30?`${xe.slice(0,30)}...`:xe||"Failed"})]}):Ee?e.jsx("div",{className:"flex items-center min-w-0 flex-1",children:e.jsx("div",{className:"w-7 h-7 rounded bg-gray-100 border border-gray-200 flex items-center justify-center overflow-hidden flex-shrink-0",children:e.jsx("img",{src:Ee,alt:"",className:"w-full h-full object-cover"})})}):e.jsx("span",{className:"text-gray-300 text-[10px] italic",children:"Empty"})});break}case"image":{const G=Array.isArray(a.value?.images)?a.value.images:[],pe=!0,ce=Ee=>{Ee.stopPropagation();const Ne=ne.current;Q(Ne,s.id)},Y=async Ee=>{const Ne=Array.from(Ee.target.files||[]);if(Ne.length===0)return;const Ce=ne.current;if(!ze){ie?.("error","Campaign ID not found");return}const De=Array.isArray(a.value?.images)?a.value.images:[],Ge=Math.min(Ne.length,6-De.length);if(Ge<=0){ie?.("warning","You have reached the maximum number of images");return}ae(!0);try{const ee=[];for(let ut=0;ut<Ge;ut++){const It=Ne[ut];if(!It.type.startsWith("image/"))throw new Error(`${It.name} is not an image file`);if(It.size>10*1024*1024)throw new Error(`${It.name} is too large (max 10MB)`);const Ct=await Vt.uploadImage({campaign_id:ze,column_id:s.id,entity_id:Ce,table_type:"custom",file:It});if(!Ct.success||!Ct.image)throw new Error(Ct.error||"Upload failed");ee.push(Ct)}const Xe=ee[ee.length-1]?.row_data?.custom_data?.[s.id]?.images,yt=Array.isArray(Xe)?Xe:[...De,...ee.map(ut=>ut.image).filter(Boolean)];i(Ce,s.id,{images:yt}),Q(Ce,s.id),ie?.("info",`Successfully uploaded ${ee.length} image(s)`)}catch(ee){console.error("Upload error:",ee),ie?.("error",ee?.message||"Upload failed")}finally{ae(!1),Z.current&&(Z.current.value="")}},xe=Ee=>{Ee.stopPropagation(),!B&&Z.current&&Z.current.click()};Be=e.jsx("div",{className:`${je} gap-2 justify-between cursor-pointer`,onClick:ce,children:G.length>0?e.jsxs("div",{className:"flex items-center gap-2 min-w-0 flex-1",children:[e.jsx("div",{className:"w-7 h-7 rounded bg-gray-100 border border-gray-200 flex items-center justify-center overflow-hidden flex-shrink-0",children:e.jsx("img",{src:G[0]?.url,alt:"",className:"w-full h-full object-cover"})}),e.jsxs("div",{className:"flex items-center gap-1 min-w-0",children:[e.jsx("span",{className:"text-[11px] text-gray-700 truncate",children:G[0]?.image_name||"Image"}),G.length>1&&pe&&e.jsxs("span",{className:"text-[10px] text-gray-400 flex-shrink-0",children:["+",G.length-1]})]})]}):e.jsxs(e.Fragment,{children:[e.jsx("input",{ref:Z,type:"file",accept:"image/jpeg,image/jpg,image/png,image/gif,image/webp",multiple:!0,onChange:Y,className:"hidden"}),e.jsx("button",{onClick:xe,disabled:B,className:"inline-flex items-center justify-center gap-1 px-2.5 py-1 border border-dashed border-gray-300 rounded-md text-[10px] text-gray-500 bg-gray-50 hover:bg-gray-100 transition-colors disabled:opacity-50 disabled:cursor-not-allowed",children:B?e.jsxs(e.Fragment,{children:[e.jsx(He,{size:10,
426className:"animate-spin"}),"Uploading..."]}):e.jsxs(e.Fragment,{children:[e.jsx(rc,{size:10}),"Upload Images"]})})]})});break}case"status":case"enumerate":Be=e.jsx("div",{className:je,children:a.value&&e.jsx("span",{className:"inline-flex items-center px-2 py-0.5 rounded text-[10px] font-medium border bg-gray-50 text-gray-600 border-gray-200",children:na(a.value)})});break;case"select":{const G=s.options||s.config?.options||[];if(s.config?.multiple===!0){const ce=he(a.value),Y=(ee,Fe)=>{Fe.stopPropagation(),Fe.preventDefault();const Xe=ne.current;i(Xe,s.id,ce.filter(yt=>yt!==ee))},xe=ee=>{ee.stopPropagation(),ee.preventDefault();const Fe=ne.current;i(Fe,s.id,[])},Ee=ee=>{if(ee.stopPropagation(),ee.preventDefault(),k.current){const Fe=k.current.getBoundingClientRect();N({top:Fe.bottom+window.scrollY+4,left:Fe.left+window.scrollX})}x(!0)},Ne=(G||[]).filter(ee=>String(ee||"").toLowerCase().includes(u.trim().toLowerCase())),Ce=ee=>{_(Fe=>{const yt=Fe.includes(ee)?Fe.filter(ut=>ut!==ee):[...Fe,ee];return Array.from(new Set(yt))})},De=()=>{const ee=ne.current;i(ee,s.id,he(w)),x(!1),g("")},Ge=()=>{x(!1),g(""),_(he(a.value))};Be=e.jsx(e.Fragment,{children:e.jsxs("div",{ref:k,className:`${je} relative`,children:[e.jsxs("div",{className:`flex items-center gap-2 min-w-0 w-full ${ce.length>0?"justify-between":"justify-center"}`,children:[ce.length>0?e.jsxs("div",{className:"flex items-center gap-1 flex-1 min-w-0 overflow-hidden",children:[ce.slice(0,2).map((ee,Fe)=>e.jsxs("span",{className:"inline-flex items-center gap-0.5 px-1.5 py-0.5 rounded text-[10px] font-medium bg-purple-50 text-purple-700 border border-purple-200 max-w-[90px] group/pill",children:[e.jsx("span",{className:"truncate",children:ee}),e.jsx("button",{onClick:Xe=>Y(ee,Xe),onMouseDown:Xe=>Xe.stopPropagation(),className:"opacity-0 group-hover/pill:opacity-100 hover:bg-purple-100 rounded-full p-0.5 transition-opacity flex-shrink-0",title:"Remove",children:e.jsx(mt,{size:8})})]},`${ee}-${Fe}`)),ce.length>2&&e.jsxs("span",{className:"text-[10px] text-gray-500 flex-shrink-0",title:ce.slice(2).join(", "),children:["+",ce.length-2," more"]})]}):e.jsx("span",{className:"text-gray-300 text-[10px] italic",children:"Select..."}),e.jsxs("div",{className:`flex items-center gap-1 ${ce.length>0?"flex-shrink-0":""}`,children:[ce.length>0&&e.jsx("button",{onClick:xe,onMouseDown:ee=>ee.stopPropagation(),className:"p-0.5 text-slate-400 hover:text-red-500 transition-colors",title:"Clear all",children:e.jsx(mt,{size:12})}),e.jsxs("button",{type:"button",onMouseDown:ee=>ee.stopPropagation(),onClick:Ee,className:"inline-flex items-center gap-1 rounded-md border border-slate-200 bg-white px-1.5 py-0.5 text-[10px] font-semibold text-slate-600 hover:bg-slate-50 hover:text-slate-900 transition-colors",title:"Add",children:[e.jsx($t,{size:10,className:"text-slate-400"}),e.jsx("span",{children:"Add"})]})]})]}),y&&E&&Ha.createPortal(e.jsxs("div",{ref:S,className:"fixed z-[9999] w-[260px] bg-white border border-gray-200 rounded shadow-lg",style:{top:E.top,left:E.left},onMouseDown:ee=>ee.stopPropagation(),children:[e.jsx("div",{className:"p-2 border-b border-gray-100",children:e.jsxs("div",{className:"flex items-center gap-2 px-2 py-1.5 border border-gray-200 rounded bg-white",children:[e.jsx(Pt,{size:12,className:"text-gray-400"}),e.jsx("input",{value:u,onChange:ee=>g(ee.target.value),placeholder:"Search...",className:"flex-1 text-[11px] outline-none text-gray-700",autoFocus:!0})]})}),e.jsx("div",{className:"max-h-48 overflow-y-auto p-2 space-y-1",children:Ne.length===0?e.jsx("div",{className:"text-[11px] text-gray-400 px-2 py-2",children:"No options"}):Ne.map(ee=>e.jsxs("label",{className:"flex items-center gap-2 px-2 py-1 hover:bg-gray-50 rounded cursor-pointer text-xs",children:[e.jsx("input",{type:"checkbox",checked:w.includes(ee),onChange:()=>Ce(ee),className:"rounded border-gray-300"}),e.jsx("span",{className:"truncate",children:ee})]},ee))}),e.jsxs("div",{className:"border-t px-2 py-1.5 flex justify-end gap-2",children:[e.jsx("button",{onClick:Ge,className:"text-xs text-gray-500 hover:text-gray-700",children:"Cancel"}),e.jsx("button",{onClick:De,className:"text-xs bg-blue-500 text-white px-2 py-0.5 rounded hover:bg-blue-600",children:"Done"})]})]}),document.body)]})})}else{const ce=Y=>{const xe=Y.target.value;c(!1),i(t,s.id,xe)};Be=e.jsx("div",{className:`${je} pr-1`,children:e.jsxs("select",{value:a.value||"",onChange:ce,onClick:Y=>Y.stopPropagation(),onMouseDown:Y=>Y.stopPropagation(),className:"w-full text-[11px] border border-gray-200 rounded px-2 py-1 bg-white text-gray-700 focus:outline-none focus:ring-1 focus:ring-gray-200",children:[e.jsx("option",{value:"",children:"Select..."}),G.map(Y=>e.jsx("option",{value:Y,children:Y},Y))]})})}break}case"knowledge":{const G=Re(a.value),pe=a.value&&typeof a.value=="object"&&!Array.isArray(a.value)?Array.isArray(a.value.names)?a.value.names.map(ee=>
426String(ee||"").trim()).filter(Boolean):[]:[],ce=pe.length>0?pe:G,Y=(ee,Fe)=>{Fe.stopPropagation(),Fe.preventDefault();const Xe=ne.current,yt=ce.indexOf(ee);if(yt!==-1){const ut=[...G],It=[...ce];ut.splice(yt,1),It.splice(yt,1),i(Xe,s.id,{kb_ids:ut,names:It})}},xe=ee=>{ee.stopPropagation(),ee.preventDefault();const Fe=ne.current;i(Fe,s.id,{kb_ids:[],names:[]})},Ee=ee=>{if(ee.stopPropagation(),ee.preventDefault(),j.current){const Fe=j.current.getBoundingClientRect();C({top:Fe.bottom+window.scrollY+4,left:Fe.left+window.scrollX})}F(!0)},Ne=(K||[]).filter(ee=>`${ee.name||""}`.toLowerCase().includes(R.trim().toLowerCase())),Ce=ee=>{H(Fe=>{const yt=Fe.includes(ee)?Fe.filter(ut=>ut!==ee):[...Fe,ee];return Array.from(new Set(yt))})},De=()=>{const ee=ne.current;i(ee,s.id,Me($)),F(!1),L("")},Ge=()=>{F(!1),L(""),H(Re(a.value))};Be=e.jsxs(e.Fragment,{children:[e.jsx("div",{className:`${je} relative`,ref:j,children:e.jsxs("div",{className:`flex items-center gap-2 min-w-0 w-full ${ce.length>0?"justify-between":"justify-center"}`,children:[ce.length>0?e.jsxs("div",{className:"flex items-center gap-1 flex-1 min-w-0 overflow-hidden",children:[ce.slice(0,2).map((ee,Fe)=>e.jsxs("span",{className:"inline-flex items-center gap-0.5 px-1.5 py-0.5 rounded text-[10px] font-medium bg-indigo-50 text-indigo-700 border border-indigo-200 max-w-[90px] group/pill",children:[e.jsx("span",{className:"truncate",children:ee}),e.jsx("button",{onClick:Xe=>Y(ee,Xe),onMouseDown:Xe=>Xe.stopPropagation(),className:"opacity-0 group-hover/pill:opacity-100 hover:bg-indigo-100 rounded-full p-0.5 transition-opacity flex-shrink-0",title:"Remove",children:e.jsx(mt,{size:8})})]},`${ee}-${Fe}`)),ce.length>2&&e.jsxs("span",{className:"text-[10px] text-gray-500 flex-shrink-0",children:["+",ce.length-2," more"]})]}):e.jsx("span",{className:"text-gray-300 text-[10px] italic",children:"Select knowledge bases"}),e.jsxs("div",{className:`flex items-center gap-1 ${ce.length>0?"flex-shrink-0":""}`,children:[ce.length>0&&e.jsx("button",{onClick:xe,onMouseDown:ee=>ee.stopPropagation(),className:"p-0.5 text-slate-400 hover:text-red-500 transition-colors",title:"Clear all",children:e.jsx(mt,{size:12})}),e.jsxs("button",{type:"button",onMouseDown:ee=>ee.stopPropagation(),onClick:Ee,className:"inline-flex items-center gap-1 rounded-md border border-slate-200 bg-white px-1.5 py-0.5 text-[10px] font-semibold text-slate-600 hover:bg-slate-50 hover:text-slate-900 transition-colors",title:"Select knowledge bases",children:[e.jsx($t,{size:10,className:"text-slate-400"}),e.jsx("span",{children:"Add"})]})]})]})}),D&&A&&Ha.createPortal(e.jsxs("div",{ref:I,className:"z-[9999] bg-white border border-gray-200 shadow-xl rounded-md w-[360px] max-h-[420px] overflow-hidden",style:{position:"absolute",top:A.top,left:A.left},onClick:ee=>ee.stopPropagation(),children:[e.jsx("div",{className:"p-2 border-b border-gray-100",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Pt,{size:14,className:"text-gray-400"}),e.jsx("input",{value:R,onChange:ee=>L(ee.target.value),placeholder:"Search knowledge bases...",className:"w-full text-xs outline-none",autoFocus:!0})]})}),e.jsx("div",{className:"max-h-[300px] overflow-auto p-2 space-y-1",children:V?e.jsxs("div",{className:"text-xs text-gray-500 flex items-center gap-2 p-2",children:[e.jsx(He,{size:14,className:"animate-spin"}),"Loading..."]}):Ne.length===0?e.jsx("div",{className:"text-xs text-gray-400 p-2",children:"No knowledge bases"}):Ne.map(ee=>{const Fe=$.includes(ee.id);return e.jsxs("label",{className:"flex items-start gap-2 p-2 rounded hover:bg-gray-50 cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:Fe,onChange:()=>Ce(ee.id)}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"text-xs text-gray-700 truncate",children:[ee.name,typeof ee.document_count=="number"?` (${ee.document_count})`:""]}),ee.description?e.jsx("div",{className:"text-[10px] text-gray-400 truncate",children:ee.description}):null]})]},ee.id)})}),e.jsxs("div",{className:"p-2 border-t border-gray-100 flex items-center justify-end gap-2",children:[e.jsx("button",{onClick:Ge,className:"text-xs px-3 py-1.5 rounded border border-gray-200 bg-white text-gray-600 hover:bg-gray-50",children:"Cancel"}),e.jsx("button",{onClick:De,className:"text-xs px-3 py-1.5 rounded border border-gray-700 bg-gray-700 text-white hover:bg-gray-600",children:"Apply"})]})]}),document.body)]});break}case"number":Be=e.jsx("div",{className:`${je} font-mono text-gray-600`,children:a.value!==void 0&&a.value!==null&&a.value!==0?a.value.toLocaleStr
426ing():e.jsx("span",{className:"text-gray-300",children:"0"})});break;case"ai":s.config?.ai?.display_mode==="score"?Be=pt(a.value):Be=et(a.value);break;case"keywords":case"ai_keywords":s.config?.keywords?.source==="competitors"?Be=ct(a.value):Be=$e(a.value,s.type);break;case"seo_analysis":case"ai_seo_analysis":Be=et(a.value);break;case"seo_action":Be=te(a.value);break;case"webflow":Be=At(a.value,"Publish","webflow");break;case"shopify":Be=At(a.value,"Publish","shopify");break;case"system":Be=e.jsx("div",{className:`${je} text-gray-400 italic`,children:a.value||"System"});break;case"composite":Be=e.jsx(Fk,{col:s,row:n,allColumns:o,onChildClick:(G,pe)=>{const Y=navigator.platform.toUpperCase().indexOf("MAC")>=0?pe.metaKey:pe.ctrlKey,xe=pe.shiftKey;fe(t,G.id,xe,Y)},onChildDoubleClick:G=>{Q(t,G.id)},selectedChildId:s.config?.composite?.children?.find(G=>de(t,G.column_id))?.column_id||null,onUpdate:(G,pe,ce)=>{i(G,pe,ce)},onRunAI:async G=>{if(!ze)return;const pe=ne.current,ce=G.type,Y=po(G);if(Y){ie("error",Y,[]);return}if(ce==="keywords"||ce==="ai_keywords"){const xe=Zr(G.config);if(xe.length>0&&!lo(n,o,xe).valid){Ke(n,xe);return}}else{let xe=[];if(ce==="seo_analysis"||ce==="ai_seo_analysis")xe=jr(G);else{const Ee=G.config?.ai||G.ai_config;xe=Ee?.user_prompt?Rr(Ee.user_prompt):[]}if(xe.length>0&&!Ke(n,xe).valid)return}i(pe,G.id,{status:"running",result:null});try{if(ce==="keywords"||ce==="ai_keywords"){const xe=Zr(G.config),Ee={};if(xe.length>0){const Ne={};for(const Ce of xe){const De=o.find(Ge=>Ge.id===Ce||Ge.system_name===Ce);if(De){const Ge=n.cells[De.id]?.value;if(Ge!=null&&Ge!==""){const ee=De.system_name||De.title;Ne[ee]=typeof Ge=="object"&&Ge.result?Ge.result:Ge}}}Object.keys(Ne).length>0&&(Ee[pe]={dependencies:Ne})}await Vt.generateKeywordsValue({campaign_id:ze,column_id:G.id,row_ids:[pe],row_data_map:Object.keys(Ee).length>0?Ee:void 0})}else await Vt.generateAIValue({campaign_id:ze,column_id:G.id,row_ids:[pe]})}catch(xe){console.error("Failed to run AI for child column:",xe),i(pe,G.id,{status:"error",result:null})}},onExpand:G=>{Q(t,G.id)},onPublish:async G=>{if(!ze)return;const pe=ne.current;i(pe,G.id,{status:"publishing"});try{if(G.type==="webflow"){const ce=await Vt.publishWebflow({campaign_id:ze,column_id:G.id,row_id:pe});i(pe,G.id,{status:ce.status,article_id:ce.article_id,article_url:ce.article_url})}else if(G.type==="shopify"){const ce=await Vt.publishShopify({campaign_id:ze,column_id:G.id,row_id:pe});i(pe,G.id,{status:ce.status,shopify_article_id:ce.shopify_article_id,url:ce.url})}}catch(ce){console.error("Failed to publish for child column:",ce),i(pe,G.id,{status:"error"})}},onApply:async G=>{if(!ze)return;const pe=ne.current;i(pe,G.id,{status:"executing"});try{const ce=await Vt.executeSEOAction({campaign_id:ze,column_id:G.id,row_id:pe});i(pe,G.id,{status:ce.status,page_id:ce.page_id,title:ce.title,url:ce.url})}catch(ce){console.error("Failed to execute SEO action for child column:",ce),i(pe,G.id,{status:"error"})}}});break;default:Be=e.jsx("div",{className:`${je} text-gray-600`,children:na(a.value)})}return l&&!Te?Ze():e.jsxs("td",{className:`border-r-2 border-gray-200 cursor-cell group select-none transition-all ${ye} ${Se?"cell-expanded":"cell-collapsed"}`,style:{position:"relative"},onMouseDown:we,onMouseEnter:G=>{b(!0),Pe()},onMouseLeave:()=>b(!1),onDoubleClick:Ae,children:[Be,ko.includes(s.type)&&!((s.type==="
426keywords"||s.type==="ai_keywords")&&s.config?.keywords?.source==="competitors")&&!l&&!h&&!a.value&&e.jsx("button",{onClick:G=>{G.stopPropagation(),re(s.type)},disabled:h,className:"p-1 bg-white hover:bg-gray-100 border border-gray-200 rounded opacity-0 group-hover:opacity-100 transition-opacity shadow-sm",style:{position:"absolute",top:"4px",right:"4px",zIndex:20},title:"Run",children:e.jsx(so,{size:10,className:"text-gray-600"})}),ko.includes(s.type)&&!((s.type==="keywords"||s.type==="ai_keywords")&&s.config?.keywords?.source==="competitors")&&!l&&!h&&a.value&&e.jsx("button",{onClick:G=>{G.stopPropagation(),Q(ne.current,s.id)},className:"p-1 bg-white hover:bg-gray-100 border border-gray-200 rounded opacity-0 group-hover:opacity-100 transition-opacity shadow-sm",style:{position:"absolute",top:"4px",right:"4px",zIndex:20},title:"Expand",children:e.jsx(er,{size:10,className:"text-gray-600"})})]})},Uk=({html:t,className:s=""})=>{const a=r.useRef(null);return r.useRef(!1),r.useEffect(()=>{if(!a.current)return;let n=a.current.shadowRoot;for(n||(n=a.current.attachShadow({mode:"open"}));n.firstChild;)n.removeChild(n.firstChild);const o=document.head;o&&o.querySelectorAll("style, link[rel='stylesheet']").forEach(m=>{if(m.tagName.toLowerCase()==="style"){const h=m;if(!h.textContent||h.textContent.trim().length===0)return}n.appendChild(m.cloneNode(!0))});const i=document.createElement("style");i.textContent=`
427      :host {
428        display: block;
429        font-family: 'Inter', ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto;
430        font-size: 14px;
431        line-height: 1.75;
432        color: rgb(51, 65, 85);
433      }
434      h1 { font-size: 2rem; font-weight: bold; margin-top: 0; margin-bottom: 1rem; color: rgb(15, 23, 42); border-bottom: 1px solid rgb(226, 232, 240); padding-bottom: 0.5rem; }
435      h2 { font-size: 1.5rem; font-weight: 600; margin-top: 2rem; margin-bottom: 0.75rem; color: rgb(15, 23, 42); }
436      h3 { font-size: 1.25rem; font-weight: 600; margin-top: 1.5rem; margin-bottom: 0.5rem; color: rgb(15, 23, 42); }
437      p { line-height: 1.75; margin-bottom: 1rem; color: rgb(51, 65, 85); }
438      ul, ol { margin-bottom: 1rem; padding-left: 1.5rem; color: rgb(51, 65, 85); }
439      li { margin-bottom: 0.25rem; }
440      ul { list-style-type: disc; }
441      ol { list-style-type: decimal; }
442      blockquote { border-left: 4px solid rgb(99, 102, 241); padding-left: 1rem; font-style: italic; color: rgb(71, 85, 105); margin: 1rem 0; }
443      a { color: rgb(37, 99, 235); text-decoration: underline; }
444      a:hover { color: rgb(29, 78, 216); }
445      code { background-color: rgb(241, 245, 249); padding: 0.125rem 0.375rem; border-radius: 0.25rem; font-family: monospace; font-size: 0.875rem; color: rgb(15, 23, 42); }
446      pre { background-color: rgb(30, 41, 59); color: rgb(241, 245, 249); padding: 1rem; border-radius: 0.5rem; overflow-x: auto; margin-bottom: 1rem; }
447      pre code { background-color: transparent; color: inherit; padding: 0; }
448      table { width: 100%; border-collapse: collapse; margin: 1rem 0; }
449      th, td { border: 1px solid rgb(226, 232, 240); padding: 0.5rem; text-align: left; }
450      th { background-color: rgb(241, 245, 249); font-weight: 600; }
451      img { max-width: 100%; height: auto; border-radius: 0.5rem; margin: 1rem 0; }
452      hr { border: none; border-top: 1px solid rgb(226, 232, 240); margin: 1.5rem 0; }
453      strong { font-weight: 600; color: rgb(15, 23, 42); }
454      em { font-style: italic; }
455    `,n.appendChild(i);const l=document.createElement("div"),c=ap.sanitize(t??"",{USE_PROFILES:{html:!0},FORBID_TAGS:["script","iframe","object","embed"],ADD_TAGS:["style"],ADD_ATTR:["style","class"],FORBID_ATTR:["onerror","onload","onclick","onmouseover","onmouseenter","onmouseleave"]});l.innerHTML=c,n.appendChild(l)},[t]),e.jsx("div",{ref:a,className:s})};function Kk({showSourceMode:t,onToggleSourceMode:s}){const[a]=uc(),[n,o]=r.useState(!1),[i,l]=r.useState(!1),[c,d]=r.useState(!1),[m,h]=r.useState(!1),[p,f]=r.useState(!1),b=r.useCallback(()=>{const _=Qo();Zo(_)&&(o(_.hasFormat("bold")),l(_.hasFormat("italic")),d(_.hasFormat("underline")),h(_.hasFormat("strikethrough")),f(_.hasFormat("code")))},[]);r.useEffect(()=>a.registerUpdateListener(({editorState:_})=>{_.read(()=>{b()})}),[a,b]);const y=_=>{a.update(()=>{const E=Qo();Zo(E)&&Zc(E,()=>Gp(_))})},x=()=>{a.update(()=>{const _=Qo();Zo(_)&&Zc(_,()=>Wp())})},u=()=>{const _=prompt("Enter URL:");_&&a.dispatchCommand(Kp,_)},g=_=>`p-1.5 rounded transition-colors ${_?"bg-slate-200 text-slate-900":"text-slate-500 hover:bg-slate-100 hover:text-slate-700"}`,w="w-px h-5 bg-slate-200 mx-1";return e.jsxs("div",{className:"flex items-center gap-0.5 px-2 py-1.5 border-b border-slate-200 bg-slate-50 flex-wrap",children:[e.jsx("button",{type:"button",onClick:()=>a.dispatchCommand(Ep,void 0),className:g(!1),title:"Undo",children:e.jsx(Sp,{size:16})}),e.jsx("button",{type:"button",onClick:()=>a.dispatchCommand(Tp,void 0),className:g(!1),title:"Redo",children:e.jsx(Ap,{size:16})}),e.jsx("div",{className:w}),e.jsx("button",{type:"button",onClick:()=>a.dispatchCommand(Kr,"bold"),className:g(n),title:"Bold (Ctrl+B)",children:e.jsx(Pp,{size:16})}),e.jsx("button",{type:"button",onClick:()=>a.dispatchCommand(Kr,"italic"),className:g(i),title:"Italic (Ctrl+I)",children:e.jsx(Ip,{size:16})}),e.jsx("button",{type:"button",onClick:()=>a.dispatchCommand(Kr,"underline"),className:g(c),title:"Underline (Ctrl+U)",children:e.jsx(Mp,{size:16})}),e.jsx("button",{type:"button",onClick:()=>
455a.dispatchCommand(Kr,"strikethrough"),className:g(m),title:"Strikethrough",children:e.jsx(Rp,{size:16})}),e.jsx("button",{type:"button",onClick:()=>a.dispatchCommand(Kr,"code"),className:g(p),title:"Inline Code",children:e.jsx(yu,{size:16})}),e.jsx("div",{className:w}),e.jsx("button",{type:"button",onClick:()=>y("h1"),className:g(!1),title:"Heading 1",children:e.jsx(Dp,{size:16})}),e.jsx("button",{type:"button",onClick:()=>y("h2"),className:g(!1),title:"Heading 2",children:e.jsx(Lp,{size:16})}),e.jsx("button",{type:"button",onClick:()=>y("h3"),className:g(!1),title:"Heading 3",children:e.jsx(zp,{size:16})}),e.jsx("div",{className:w}),e.jsx("button",{type:"button",onClick:()=>a.dispatchCommand($p,void 0),className:g(!1),title:"Bullet List",children:e.jsx(_o,{size:16})}),e.jsx("button",{type:"button",onClick:()=>a.dispatchCommand(Fp,void 0),className:g(!1),title:"Numbered List",children:e.jsx(mc,{size:16})}),e.jsx("button",{type:"button",onClick:x,className:g(!1),title:"Quote",children:e.jsx(Op,{size:16})}),e.jsx("div",{className:w}),e.jsx("button",{type:"button",onClick:u,className:g(!1),title:"Insert Link",children:e.jsx(di,{size:16})}),e.jsx("button",{type:"button",onClick:()=>a.dispatchCommand(Bp,void 0),className:g(!1),title:"Horizontal Rule",children:e.jsx(Ps,{size:16})}),e.jsx("div",{className:w}),e.jsx("button",{type:"button",onClick:s,className:g(t),title:t?"Switch to Preview":"View Markdown Source",children:t?e.jsx(Ga,{size:16}):e.jsx(Up,{size:16})})]})}function Gk({markdown:t}){const[s]=uc(),[a,n]=r.useState(t);return r.useEffect(()=>{t!==a&&(n(t),s.update(()=>{try{ei(t||"",yr)}catch{const i=Yr();i.clear();const l=ti();l.append(si(t||"")),i.append(l)}}))},[t,a,s]),null}function Wk({onEditorReady:t}){const[s]=uc();return r.useEffect(()=>{t(s)},[s,t]),null}const Vk={paragraph:"mb-2 text-slate-700",heading:{h1:"text-2xl font-bold text-slate-900 mb-3 mt-4",h2:"text-xl font-bold text-slate-900 mb-2 mt-3",h3:"text-lg font-semibold text-slate-900 mb-2 mt-3"},text:{bold:"font-bold",italic:"italic",underline:"underline",strikethrough:"line-through",code:"bg-slate-100 text-pink-600 px-1 py-0.5 rounded text-sm font-mono"},list:{ul:"list-disc list-inside mb-2 ml-4",ol:"list-decimal list-inside mb-2 ml-4",listitem:"mb-1"},quote:"border-l-4 border-slate-300 pl-4 italic text-slate-600 my-2",link:"text-blue-600 hover:underline cursor-pointer",code:"bg-slate-800 text-slate-100 p-3 rounded-md font-mono text-sm overflow-x-auto my-2",horizontalRule:"border-t border-slate-300 my-4"},Ah=r.forwardRef(({markdown:t,onChange:s,readOnly:a=!1,placeholder:n="Enter content...",className:o="",minHeight:i=200,showToolbar:l=!0},c)=>{const[d,m]=r.useState(null),[h,p]=r.useState(t||""),[f,b]=r.useState(!1);r.useImperativeHandle(c,()=>({getMarkdown:()=>h,setMarkdown:u=>{p(u),d&&d.update(()=>{try{ei(u||"",yr)}catch{const w=Yr();w.clear();const _=ti();_.append(si(u||"")),w.append(_)}})},insertMarkdown:u=>{d&&d.update(()=>{const g=Qo();Zo(g)&&g.insertText(u)})},focus:()=>{d?.focus()}}));const y=r.useCallback(u=>{u.read(()=>{try{const g=np(yr);p(g),s?.(g)}catch{const _=Yr().getTextContent();p(_),s?.(_)}})},[s]),x={namespace:"MarkdownEditor",theme:Vk,onError:u=>{console.error("[Lexical Error]",u)},nodes:[op,ip,lp,cp,dp,mp,up,xp,hp,pp,gp,fp],editable:!a,editorState:()=>{try{ei(t||"",yr)}catch{const g=Yr(),w=ti();w.append(si(t||"")),g.append(w)}}};return e.jsxs("div",{className:`lexical-editor-wrapper ${o}`,children:[e.jsx("style",{children:`
456          .lexical-editor-wrapper {
457            display: flex;
458            flex-direction: column;
459            height: 100%;
460            background: #fff;
461          }
462          .lexical-editor-content {
463            flex: 1;
464            overflow-y: auto;
465            min-height: ${i}px;
466          }
467          .lexical-editor-content:focus {
468            outline: none;
469          }
470          .lexical-editor-placeholder {
471            color: #94a3b8;
472            position: absolute;
473            top: 12px;
474            left: 12px;
475            pointer-events: none;
476            user-select: none;
477          }
478          .lexical-content-editable {
479            min-height: ${i}px;
480            padding: 12px;
481            outline: none;
482            font-size: 14px;
483            line-height: 1.7;
484          }
485          .lexical-content-editable:focus {
486            outline: none;
487          }
488          .lexical-source-textarea {
489            flex: 1;
490            min-height: ${i}px;
491            padding: 12px;
492            outline: none;
493            font-size: 13px;
494            line-height: 1.6;
495            font-family: ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace;
496            background: #fafafa;
497            border: none;
498            resize: none;
499            color: #334155;
500          }
501          .lexical-source-textarea:focus {
502            outline: none;
503            background: #f8fafc;
504          }
505        `}),e.jsxs(rp,{initialConfig:x,children:[l&&!a&&e.jsx(Kk,{showSourceMode:f,onToggleSourceMode:()=>b(!f)}),f?e.jsx("textarea",{className:"lexical-source-textarea",value:h,onChange:u=>{const g=u.target.value;p(g),s?.(g),d&&d.update(()=>{try{ei(g||"",yr)}catch{const w=Yr();w.clear();const _=ti();_.append(si(g||"")),w.append(_)}})},readOnly:a,placeholder:n,spellCheck:!1}):e.jsx("div",{className:"lexical-editor-content relative",children:e.jsx(yp,{contentEditable:e.jsx(wp,{className:"lexical-content-editable"}),placeholder:e.jsx("div",{className:"lexical-editor-placeholder",children:n}),ErrorBoundary:bp})}),e.jsx(jp,{}),e.jsx(vp,{}),e.jsx(Np,{}),e.jsx(kp,{transformers:yr}),e.jsx(_p,{}),e.jsx(Cp,{onChange:y}),e.jsx(Gk,{markdown:t}
505),e.jsx(Wk,{onEditorReady:m})]})]})});Ah.displayName="MarkdownEditor";const Hk=t=>`
506<!DOCTYPE html>
507<html>
508<head>
509  <meta charset="UTF-8">
510  <meta name="viewport" content="width=device-width, initial-scale=1.0">
511  <style>
512    * { box-sizing: border-box; }
513    body { 
514      font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
515      font-size: 14px;
516      line-height: 1.6;
517      color: #334155;
518      margin: 0;
519      padding: 12px;
520    }
521    a { color: #2563eb; }
522    img { max-width: 100%; height: auto; }
523    table { border-collapse: collapse; width: 100%; }
524    th, td { border: 1px solid #e2e8f0; padding: 8px; text-align: left; }
525    th { background: #f8fafc; }
526    pre { background: #1e293b; color: #e2e8f0; padding: 12px; border-radius: 6px; overflow-x: auto; }
527    code { background: #f1f5f9; padding: 2px 6px; border-radius: 3px; font-size: 0.9em; }
528    pre code { background: transparent; padding: 0; }
529    blockquote { border-left: 3px solid #cbd5e1; padding-left: 12px; margin: 12px 0; color: #64748b; }
530    h1, h2, h3, h4, h5, h6 { color: #1e293b; margin-top: 1em; margin-bottom: 0.5em; }
531    h1 { font-size: 1.5em; }
532    h2 { font-size: 1.25em; }
533    h3 { font-size: 1.1em; }
534    ul, ol { padding-left: 1.5em; }
535    hr { border: none; border-top: 1px solid #e2e8f0; margin: 1em 0; }
536  </style>
537</head>
538<body>
539${t}
540</body>
541</html>
542  `.trim(),Wc=r.forwardRef(({html:t,onChange:s,readOnly:a=!1,placeholder:n="Enter HTML content...",className:o="",minHeight:i=300,showToolbar:l=!0,showCodeButton:c=!0},d)=>{const[m,h]=r.useState(t||""),[p,f]=r.useState(!1),[b,y]=r.useState(""),[x,u]=r.useState(!0),g=r.useRef(null);r.useEffect(()=>{t!==m&&h(t||"")},[t]),r.useEffect(()=>{u(!0);const N=setTimeout(()=>{y(Hk(m)),u(!1)},300);return()=>clearTimeout(N)},[m]),r.useImperativeHandle(d,()=>({getHtml:()=>m,setHtml:N=>{h(N),s?.(N)},enterEditMode:()=>f(!0),enterPreviewMode:()=>f(!1)}));const w=r.useCallback(N=>{const S=N||"";h(S),s?.(S)},[s]),_=r.useCallback(()=>{f(N=>!N)},[]),E=r.useCallback(()=>{s?.(m),f(!1)},[m,s]);return e.jsxs("div",{className:`html-live-editor flex flex-col h-full bg-white ${o}`,style:{minHeight:i},children:[l&&e.jsxs("div",{className:"flex-none flex items-center justify-between px-3 py-2 border-b border-slate-200 bg-slate-50",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs font-medium text-slate-500 uppercase tracking-wide",children:p?"Edit Mode":"Preview"}),p&&e.jsx("span",{className:"text-[10px] text-slate-400",children:"Monaco Editor"})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[p&&!a&&e.jsxs("button",{type:"button",onClick:E,className:"flex items-center gap-1 px-2 py-1 text-xs font-medium text-white bg-blue-600 hover:bg-blue-500 rounded transition-colors",children:[e.jsx(pu,{size:12}),"Save"]}),c&&e.jsx("button",{type:"button",onClick:_,disabled:a&&!p,className:`flex items-center gap-1.5 px-2.5 py-1 text-xs font-medium rounded transition-colors ${p?"text-slate-600 bg-white border border-slate-200 hover:bg-slate-100":"text-white bg-slate-700 hover:bg-slate-600"}`,children:p?e.jsxs(e.Fragment,{children:[e.jsx(Ga,{size:12}),"Preview"]}):e.jsxs(e.Fragment,{children:[e.jsx(yu,{size:12}),"Code"]})})]})]}),e.jsx("div",{className:"flex-1 relative overflow-hidden",children:p?e.jsx(Vp,{height:"100%",defaultLanguage:"html",theme:"vs-dark",value:m,onChange:w,options:{minimap:{enabled:!1},fontSize:13,fontFamily:"ui-monospace, SFMono-Regular, 'SF Mono', Menlo, Consolas, monospace",wordWrap:"on",lineNumbers:"on",tabSize:2,automaticLayout:!0,scrollBeyondLastLine:!1,padding:{top:12},readOnly:a},loading:e.jsxs("div",{className:"flex items-center justify-center h-full text-slate-400",children:[e.jsx(He,{size:20,className:"animate-spin mr-2"}),"Loading editor..."]})}):e.jsxs("div",{className:"w-full h-full relative",children:[x&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-white/80 z-10",children:e.jsx(He,{size:20,className:"animate-spin text-slate-400"})}),e.jsx("iframe",{ref:g,srcDoc:b,title:"HTML Preview",sandbox:"allow-scripts",frameBorder:"0",className:"w-full h-full bg-white",onLoad:()=>u(!1)}),!m.trim()&&!x&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center text-slate-400 pointer-events-none",children:e.jsx("span",{className:"text-sm",children:n})})]})}),!p&&!a&&e.jsx("div",{className:"flex-none px-3 py-1.5 border-t border-slate-100 bg-slate-50/50",children:e.jsxs("p",{className:"text-[10px] text-slate-400 text-center",children:["Click ",e.jsx("strong",{children:"Code"})," to edit HTML"]})})]})});Wc.displayName="HtmlLiveEditor";const Vm={active:{bg:"bg-emerald-50",text:"text-emerald-700",dot:"bg-emerald-500"},completed:{bg:"bg-emerald-50",text:"text-emerald-700",dot:"bg-emerald-500"},done:{bg:"bg-emerald-50",text:"text-emerald-700",dot:"bg-emerald-500"},published:{bg:"bg-emerald-50",text:"text-emerald-700",dot:"bg-emerald-500"},yes:{bg:"bg-emerald-50",text:"text-emerald-700",dot:"bg-emerald-500"},true:{bg:"bg-emerald-50",text:"text-emerald-700",dot:"bg-emerald-500"},low:{bg:"bg-emerald-50",text:"text-emerald-700",dot:"bg-emerald-500"},"in progress":{bg:"bg-blue-50",text:"text-blue-700",dot:"bg-blue-500"},in_progress:{bg:"bg-blue-50",text:"text-blue-700",dot:"bg-blue-500"},running:{bg:"bg-blue-50",text:"text-blue-700",dot:"bg-blue-500"}
542,pending:{bg:"bg-amber-50",text:"text-amber-700",dot:"bg-amber-500"},medium:{bg:"bg-amber-50",text:"text-amber-700",dot:"bg-amber-500"},waiting:{bg:"bg-amber-50",text:"text-amber-700",dot:"bg-amber-500"},cancelled:{bg:"bg-red-50",text:"text-red-600",dot:"bg-red-500"},failed:{bg:"bg-red-50",text:"text-red-600",dot:"bg-red-500"},error:{bg:"bg-red-50",text:"text-red-600",dot:"bg-red-500"},high:{bg:"bg-red-50",text:"text-red-600",dot:"bg-red-500"},inactive:{bg:"bg-slate-100",text:"text-slate-600",dot:"bg-slate-400"},todo:{bg:"bg-slate-100",text:"text-slate-600",dot:"bg-slate-400"},draft:{bg:"bg-slate-100",text:"text-slate-500",dot:"bg-slate-400"},archived:{bg:"bg-slate-100",text:"text-slate-500",dot:"bg-slate-400"},no:{bg:"bg-slate-100",text:"text-slate-600",dot:"bg-slate-400"},false:{bg:"bg-slate-100",text:"text-slate-600",dot:"bg-slate-400"}},Sl=[{bg:"bg-indigo-50",text:"text-indigo-700",dot:"bg-indigo-500"},{bg:"bg-purple-50",text:"text-purple-700",dot:"bg-purple-500"},{bg:"bg-pink-50",text:"text-pink-700",dot:"bg-pink-500"},{bg:"bg-cyan-50",text:"text-cyan-700",dot:"bg-cyan-500"},{bg:"bg-teal-50",text:"text-teal-700",dot:"bg-teal-500"},{bg:"bg-orange-50",text:"text-orange-700",dot:"bg-orange-500"},{bg:"bg-rose-50",text:"text-rose-700",dot:"bg-rose-500"}],Hm=t=>{if(!t)return Sl[0];const s=t.toLowerCase().trim();if(Vm[s])return Vm[s];let a=0;for(let n=0;n<t.length;n++)a=t.charCodeAt(n)+((a<<5)-a);return Sl[Math.abs(a)%Sl.length]},qk=({value:t,options:s,onChange:a,multiple:n=!1,placeholder:o="Select an option",disabled:i=!1,className:l=""})=>{const[c,d]=r.useState(""),m=r.useRef(null),h=r.useMemo(()=>Array.isArray(t)?t:t&&typeof t=="string"?[t]:[],[t]),p=r.useMemo(()=>{if(!c.trim())return s;const x=c.toLowerCase();return s.filter(u=>u.toLowerCase().includes(x))},[s,c]),f=s.length>4,b=x=>{if(!i)if(n){const u=h.includes(x);a(u?h.filter(g=>g!==x):[...h,x])}else h.includes(x)?a(""):a(x)},y=()=>{i||(a(n?[]:""),d(""))};return e.jsxs("div",{className:`flex flex-col h-full bg-white ${l}`,children:[e.jsxs("div",{className:"flex-none",children:[h.length>0&&e.jsxs("div",{className:"px-4 py-3 bg-slate-100 border-b border-slate-200",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("span",{className:"text-[11px] font-semibold text-slate-600 uppercase tracking-wider",children:["Selected (",h.length,")"]}),e.jsx("button",{type:"button",onClick:y,disabled:i,className:"text-[11px] text-slate-400 hover:text-red-500 transition-colors disabled:opacity-50",children:"Clear all"})]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:h.map(x=>{const u=Hm(x);return e.jsxs("span",{className:`inline-flex items-center gap-1.5 px-2.5 py-1 rounded-md text-xs font-medium shadow-sm ${u.bg} ${u.text} border border-white/50`,children:[e.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${u.dot}`}),e.jsx("span",{className:"truncate max-w-[120px]",children:x}),!i&&e.jsx("button",{type:"button",onClick:g=>{g.stopPropagation(),b(x)},className:"ml-0.5 p-0.5 rounded-full hover:bg-black/10 transition-colors",children:e.jsx(mt,{size:10})})]},x)})})]}),f&&e.jsx("div",{className:"px-4 py-3 bg-slate-50 border-b border-slate-100",children:e.jsxs("div",{className:"relative",children:[e.jsx(Pt,{size:14,className:"absolute left-3 top-1/2 -translate-y-1/2 text-slate-400"}),e.jsx("input",{ref:m,type:"text",value:c,onChange:x=>d(x.target.value),placeholder:"Search options...",disabled:i,className:"w-full pl-9 pr-9 py-2 text-sm bg-white border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-slate-300 focus:border-slate-300 transition-all placeholder:text-slate-400"}),c&&e.jsx("button",{type:"button",onClick:()=>d(""),className:"absolute right-3 top-1/2 -translate-y-1/2 p-0.5 text-slate-400 hover:text-slate-600 rounded",children:e.jsx(mt,{size:14})})]})})]}),e.jsx("div",{className:"flex-1 overflow-y-auto bg-white",children:p.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-slate-400",children:[e.jsx(Pt,{size:24,className:"mb-2 opacity-50"}),e.jsx("span",{className:"text-sm",children:c?"No matching options":"No options available"})]}):e.jsxs("div",{className:"py-2 px-2",children:[!c&&e.jsx("div",{className:"px-2 py-1.5 mb-1",children:e.jsx("span",{className:"text-[11px] font-semibold text-slate-400 uppercase tracking-wider",children:h.length>0?"All Options":"Options"})}),p.map(x=>{const u=h.includes(x),g=Hm(x);return e.jsxs("div",{onClick:()=>b(x),className:`
543                    group flex items-center justify-between px-3 py-2.5 rounded-lg cursor-pointer mb-0.5
544                    transition-all duration-150
545                    ${i?"opacity-50 cursor-not-allowed":""}
546                    ${u?`${g.bg} ring-1 ring-inset ring-slate-200`:"hover:bg-slate-50 active:bg-slate-100"}
547                  `,children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[n&&e.jsx("div",{className:`
548                          w-4 h-4 rounded border-2 flex items-center justify-center flex-shrink-0
549                          transition-all duration-150
550                          ${u?"bg-slate-700 border-slate-700":"border-slate-300 group-hover:border-slate-400"}
551                        `,children:u&&e.jsx(wt,{size:10,className:"text-white",strokeWidth:3})}),e.jsx("span",{className:`w-2.5 h-2.5 rounded-full flex-shrink-0 ${g.dot}`}),e.jsx("span",{className:`text-sm truncate ${u?`font-medium ${g.text}`:"text-slate-700"}`,children:x})]}),u&&e.jsx(wt,{size:16,className:`flex-shrink-0 ${g.text}`,strokeWidth:2.5})]},x)})]})}),h.length===0&&p.length>0&&!c&&e.jsx("div",{className:"flex-none px-4 py-2.5 border-t border-slate-100 bg-slate-50/50",children:e.jsx("p",{className:"text-xs text-slate-400 text-center",children:"Click an option to select"})})]})},Zl=355,en=`calc(100vh - ${Zl}px)`,Yk=t=>{if(!t||typeof t!="string")return!1;const a=[/^#{1,6}\s/m,/\*\*.*?\*\*/,/\*[^\*].*?\*/,/\[.*?\]\(.*?\)/,/!\[.*?\]\(.*?\)/,/`[^`]+`/,/^```/m,/^\|.*?\|/m,/^[-*+]\s/m,/^\d+\.\s/m,/^>\s/m].some(l=>l.test(t)),n=t.match(/<[a-z][\s\S]*?>/gi),o=n?n.length:0,i=t.match(/#{1,6}\s|^\s*[-*+]\s|^\s*\d+\.\s|\*\*|`{3}/gm)?.length||0;return a&&i>o},Jk=t=>!t||typeof t!="string"?!1:[/<html[\s>]/i,/<body[\s>]/i,/<div[\s>]/i,/<p[\s>]/i,/<span[\s>]/i,/<h[1-6][\s>]/i,/<ul[\s>]/i,/<ol[\s>]/i,/<li[\s>]/i,/<a[\s>]/i,/<img[\s>]/i,/<table[\s>]/i,/<br\s*\/?>/i,/<strong[\s>]/i,/<em[\s>]/i].some(a=>a.test(t)),Xk=({value:t,plainTextContainerRef:s})=>{const a=r.useMemo(()=>t==null?"":na(t,{pretty:!0}),[t]);return a?Yk(a)?e.jsx("div",{className:"markdown-content prose prose-sm max-w-none text-gray-700",children:e.jsx(Wn,{remarkPlugins:[Vn],children:a})}):Jk(a)?e.jsx(Uk,{html:a}):e.jsx("div",{ref:s,className:"text-sm text-gray-700 whitespace-pre-wrap break-words leading-relaxed",children:a}):e.jsx("div",{className:"flex items-center justify-center py-12 text-gray-300",children:e.jsxs("div",{className:"text-center",children:[e.jsx(_a,{size:24,className:"mx-auto mb-2 opacity-50"}),e.jsx("span",{className:"text-sm italic",children:"Empty"})]})})},Qk=({value:t})=>{const s=r.useMemo(()=>{if(t==null||t==="")return null;const n=parseFloat(t);return isNaN(n)?null:n},[t]);if(s===null)return e.jsx("div",{className:"flex items-center justify-center py-12 text-gray-300",children:e.jsxs("div",{className:"text-center",children:[e.jsx(qn,{size:24,className:"mx-auto mb-2 opacity-50"}),e.jsx("span",{className:"text-sm italic",children:"No value"})]})});const a=s.toLocaleString("en-US",{maximumFractionDigits:4});return e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"text-4xl font-bold text-gray-800 font-mono tracking-tight",children:a}),e.jsx("div",{className:"text-xs text-gray-400 mt-2 uppercase tracking-wider",children:"Numeric Value"})]})})},Zk=({value:t})=>{const s=r.useMemo(()=>{if(!t)return null;try{const a=new Date(t);return isNaN(a.getTime())?null:{formatted:a.toLocaleDateString("en-US",{weekday:"long",year:"numeric",month:"long",day:"numeric"}),time:a.toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit"}),relative:s1(a)}}catch{return null}},[t]);return s?e.jsx("div",{className:"py-6",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"w-12 h-12 rounded-xl bg-blue-50 flex items-center justify-center flex-shrink-0",children:e.jsx(ka,{size:20,className:"text-blue-500"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"text-lg font-semibold text-gray-800",children:s.formatted}),e.jsx("div",{className:"text-sm text-gray-500 mt-1",children:s.time}),e.jsx("div",{className:"text-xs text-gray-400 mt-2",children:s.relative})]})]})}):e.jsx("div",{className:"flex items-center justify-center py-12 text-gray-300",children:e.jsxs("div",{className:"text-center",children:[e.jsx(ka,{size:24,className:"mx-auto mb-2 opacity-50"}),e.jsx("span",{className:"text-sm italic",children:"No date"})]})})},e1=({value:t})=>{const s=r.useMemo(()=>!t||typeof t!="string"?null:t.trim(),[t]);if(!s)return e.jsx("div",{className:"flex items-center justify-center py-12 text-gray-300",children:e.jsxs("div",{className:"text-center",children:[e.jsx(di,{size:24,className:"mx-auto mb-2 opacity-50"}),e.jsx("span",{className:"text-sm italic",children:"No URL"})]})});let a="";try{a=new URL(s.startsWith("http")?s:`https://${s}`).hostname}catch{a=s}return e.jsx("div",{className:"py-6",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"w-12 h-12 rounded-xl bg-emerald-50 flex items-center justify-center flex-shrink-0",children:e.jsx(di,{size:20,className:"text-emerald-500"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"text-sm font-medium text-gray-500 mb-1",children:a}),e.jsxs("a",{href:s.startsWith("http")?s:`https://${s}`,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:text-blue-700 text-sm break-all hover:underline inline-flex items-center gap-1.5 group",children:[e.jsx("span",{children:s}),e.jsx(ns,{size:12,className:"opacity-50 group-hover:opacity-100 flex-shrink-0"})]})]})]})})},t1=({value:t,onChange:s})=>{const a=r.useMemo(()=>typeof t=="boolean"?t:t==="true"||t===1||t==="1",[t]);return e.jsx("div",{className:"flex items-center justify-center py-10",children:e.jsxs("button",{onClick:()=>s?.(!a),className:`flex items-center gap-3 px-6 py-4 rounded-2xl transition-all ${a?"bg-emerald-50 text-emerald-700 hover:bg-emerald-100":"bg-gray-50 text-gray-400 hover:bg-gray-100"}`,children:[a?e.jsx(Rs,{size:28,className:"text-emerald-500"}):e.jsx(Hp,{size:28,className:"text-gray-300"}),e.jsx("span",{className:"text-lg font-medium",children:a?"Checked":"Unchecked"})]})})},s1=t=>{const a=new Date().getTime()-t.getTime(),n=Math.floor(a/(1e3*60*60*24));return n===0?"Today":n===1?"Yesterday":n===-1?"Tomorrow":n>0&&n<7?`${n} days ago`:n<0&&n>-7?`In ${Math.abs(n)} days`:n>0&&n<30?`${Math.floor(n/7)} weeks ago`:n<0&&n>-30?`In ${Math.floor(Math.abs(n)/7)} weeks`:t.toLocaleDateString()},a1=({value:t,rowId:s,colId:a,onUpdate:n})=>{const o=da(),i=m=>{if(Array.isArray(m))return m.map(h=>typeof h=="string"?h.trim():"").filter(h=>h.length>0);if(typeof m=="string"&&m.trim())return m.split(",").map(h=>h.trim()).filter(h=>h.length>0);if(typeof m=="object"&&m?.result){const h=m.result;if(Array.isArray(h))return h.map(p=>typeof p=="string"?p.trim():"").filter(p=>p.length>0);if(typeof h=="string")return h.split(",").map(p=>p.trim()).filter(p=>p.length>0)}return[]},[l,c]=r.useState(()=>i(t));r.useEffect(()=>{c(i(t))},[t]);const d=async m=>{const h=l.filter(p=>p!==m);if(c(h),n(s,a,h),s&&!s.startsWith("empty_")&&!s.startsWith("new_")&&o)try{await Wt.updateCustomData({campaign_id:o,table_type:"custom",entity_id:s,updates:{[a]:h}})}catch(p){console.error("Failed to update keywords:",p)}};return l.length===0?e.jsx("div",{className:"flex items-center justify-center py-12 text-gray-300",children:e.jsxs("div",{className:"text-center",children:[e.jsx(_a,{size:24,className:"mx-auto mb-2 opacity-50"}),e.jsx("span",{className:"text-sm italic",children:"No keywords"})]})}):e.jsxs("div",{className:"py-4",children:[e.jsx("div",{className:"flex items-center gap-2 mb-3",children:e.jsxs("span",{className:"text-xs font-medium text-gray-500 uppercase tracking-wider",children:[l.length," keyword",l.length!==1?"s":""]})}),e.jsx("div",{className:"flex flex-wrap gap-2",children:l.map((m,h)=>e.jsxs("span",{className:"inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-sm font-medium bg-gradient-to-r from-blue-50 to-indigo-50 text-blue-700 shadow-sm hover:shadow transition-shadow group",children:[e.jsx("span",{children:m}),e.jsx("button",{onClick:()=>d(m),className:"opacity-40 hover:opacity-100 hover:bg-blue-100 rounded-full p-0.5 transition-all",title:"Remove keyword",children:e.jsx(mt,{size:12})})]},`${m}-${h}`))})]})},n1=({value:t})=>{const s=r.useMemo(()=>{const a=n=>Array.from(new Set(n.map(o=>
551o.trim()).filter(Boolean)));if(!t)return[];if(typeof t=="object"&&!Array.isArray(t)){const n=t.names;if(Array.isArray(n))return a(n.map(i=>String(i||"")));const o=t.kb_ids;if(Array.isArray(o))return a(o.map(i=>String(i||"")))}if(Array.isArray(t))return a(t.map(n=>String(n||"")));if(typeof t=="string"){const n=t.trim();return n?[n]:[]}return[]},[t]);return s.length===0?e.jsx("div",{className:"flex items-center justify-center py-12 text-gray-300",children:e.jsxs("div",{className:"text-center",children:[e.jsx(_a,{size:24,className:"mx-auto mb-2 opacity-50"}),e.jsx("span",{className:"text-sm italic",children:"No knowledge base"})]})}):e.jsxs("div",{className:"py-4",children:[e.jsx("div",{className:"flex items-center gap-2 mb-3",children:e.jsxs("span",{className:"text-xs font-medium text-gray-500 uppercase tracking-wider",children:[s.length," knowledge base",s.length!==1?"s":""]})}),e.jsx("div",{className:"flex flex-wrap gap-2",children:s.map((a,n)=>e.jsx("span",{className:"inline-flex items-center px-3 py-1.5 rounded-lg text-sm font-medium bg-indigo-50 text-indigo-700 border border-indigo-200",title:a,children:e.jsx("span",{className:"truncate max-w-[260px]",children:a})},`${a}-${n}`))})]})},r1=({value:t,rowId:s,colId:a,allowMultiple:n,onUpdate:o})=>{const i=da(),l=r.useRef(null),{showToast:c}=Xi({columns:[]}),[d,m]=r.useState(!1),[h,p]=r.useState(!1),[f,b]=r.useState(null),[y,x]=r.useState(!1),u=r.useMemo(()=>t&&typeof t=="object"&&Array.isArray(t.images)?t.images:[],[t]),g=async N=>new Promise(S=>{const k=new FileReader;k.onload=D=>{const F=new Image;F.onload=()=>{const R=document.createElement("canvas");let{width:L,height:$}=F;const H=1200;(L>H||$>H)&&(L>$?($=$/L*H,L=H):(L=L/$*H,$=H)),R.width=L,R.height=$,R.getContext("2d")?.drawImage(F,0,0,L,$),R.toBlob(X=>{S(X?new File([X],N.name,{type:"image/jpeg"}):N)},"image/jpeg",.85)},F.src=D.target?.result},k.readAsDataURL(N)}),w=async N=>{const S=Array.from(N.target.files||[]);if(S.length===0)return;if(!i){c?.("error","Campaign ID not found");return}const k=Math.min(S.length,6-u.length);if(S.length>k){c?.("warning",`You can only upload ${k} more image(s)`);return}m(!0);try{const D=[];for(let $=0;$<k;$++){const H=S[$];if(!H.type.startsWith("image/"))throw new Error(`${H.name} is not an image file`);if(H.size>10*1024*1024)throw new Error(`${H.name} is too large (max 10MB)`);const K=await g(H),X=D.length>0&&D[D.length-1]?.row_data?.id?D[D.length-1].row_data.id:s,V=await Vt.uploadImage({campaign_id:i,column_id:a,entity_id:X,table_type:"custom",file:K});if(!V.success||!V.image)throw new Error(V.error||"Upload failed");D.push(V)}const R=D[D.length-1]?.row_data?.custom_data?.[a]?.images,L=Array.isArray(R)?R:[...u,...D.map($=>$.image).filter(Boolean)];o(s,a,{images:L}),c?.("info",`Successfully uploaded ${D.length} image(s)`)}catch(D){console.error("Upload error:",D),c?.("error",D?.message||"Upload failed")}finally{m(!1),l.current&&(l.current.value="")}},_=N=>{b(N),p(!0)},E=async()=>{if(!(!i||!f)){x(!0),p(!1);try{const N=await Vt.deleteImage({campaign_id:i,column_id:a,entity_id:s,oss_key:f==="all"?null:f});if(!N.success)throw new Error(N.error||"Delete failed");const S=f==="all"?[]:u.filter(k=>k.oss_key!==f);o(s,a,S.length>0?{images:S}:null),c?.("info",`Deleted ${N.deleted_count} image(s)`)}catch(N){console.error("Delete error:",N),c?.("error",N?.message||"Delete failed")}finally{x(!1),b(null)}}};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"text-xs text-gray-500",children:[u.length," / 6 images"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[u.length>0&&n&&e.jsxs("button",{onClick:()=>{b("all"),p(!0)},disabled:y,className:"px-3 py-1.5 text-xs text-red-600 hover:bg-red-50 border border-red-200 rounded-md transition-colors disabled:opacity-50 flex items-center gap-1.5",children:[e.jsx(es,{size:12}),"Delete All"]}),e.jsx("input",{ref:l,type:"file",accept:"image/jpeg,image/jpg,image/png,image/gif,image/webp",multiple:!0,onChange:w,className:"hidden",disabled:d||u.length>=6}),e.jsx("button",{onClick:()=>l.current?.click(),disabled:d||u.length>=6,className:"px-3 py-1.5 text-xs font-medium text-white bg-gray-600 hover:bg-gray-500 rounded-md transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-1.5",children:d?e.jsxs(e.Fragment,{children:[e.jsx(He,{size:12,className:"animate-spin"}),"Uploading..."]}):e.jsxs(e.Fragment,{children:[e.jsx(rc,{size:12}),u.length>=6?"Maximum reached":"Upload"]})})]})]}),u.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12",children:[e.jsx("div",{className:"w-16 h-16 rounded-2xl bg-gray-50 flex items-center justify-center mb-3",children:e.jsx(rn,{size:28,className:"text-gray-300"})}),e.jsx("span",{className:"text-sm text-gray-400 mb-1",children:"No images yet"}),e.jsxs("span",{className:"text-xs text-gray-300",children:["Click ",e.jsx("span",{className:"font-medium",children:"Upload"})," to add images"]})]}):e.jsx("div",{className:"grid grid-cols-3 gap-3",children:u.map((N,S)=>e.jsxs("figure",{className:"relative rounded-lg overflow-hidden border border-gray-200 bg-gray-50 group",children:[e.jsx("img",{src:N.url,alt:N.image_name||`Image ${S+1}`,className:"w-full h-24 object-cover"}),e.jsx("button",{onClick:()=>_(N.oss_key),className:"absolute top-1 right-1 p-1 bg-red-500 hover:bg-red-600 text-white rounded opacity-0 group-hover:opacity-100 transition-opacity shadow",title:"Delete this image",children:e.jsx(es,{size:12})}),e.jsx("figcaption",{className:"px-2 py-1 bg-white/90 text-[11px] text-gray-600 truncate border-t border-gray-100",children:N.image_name||N.url})]},N.oss_key||N.url||S))}),e.jsxs("p",{className:"text-[10px] text-gray-400 border-t border-gray-100 pt-2",children:["• Supported formats: JPEG, PNG, GIF, WebP",e.jsx("br",{}),"• Maximum file size: 10MB per image",e.jsx("br",{}),"• Maximum 6 images per cell"]})]}),h&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 bg-black/30 z-[9998]",onClick:()=>p(!1)}),e.jsxs("div",{className:"fixed top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 w-96 bg-white border border-gray-200 shadow-2xl rounded-lg z-[9999]",children:[e.jsx("div",{className:"px-4 py-3 border-b border-gray-200",children:e.jsx("h3",{className:"text-sm font-semibold text-gray-800",children:f==="all"?"Delete All Images?":"Delete Image?"})}),e.jsx("div",{className:"px-4 py-4",children:e.jsx("p",{className:"text-sm text-gray-600",children:f==="all"?`Are you sure you want to delete all ${u.length} image(s)? This action cannot be undone.`:"Are you sure you want to delete this image? This action cannot be undone."})}),e.jsxs("div",{className:"px-4 py-3 border-t border-gray-200 flex justify-end gap-2",children:[e.jsx("button",{onClick:()=>p(!1),disabled:y,className:"px-3 py-1.5 text-xs text-gray-600 hover:bg-gray-100 border border-gray-300 rounded-md transition-colors disabled:opacity-50",children:"Cancel"}),e.jsx("button",{onClick:E,disabled:y,className:"px-3 py-1.5 text-xs font-medium text-white bg-red-600 hover:bg-red-700 rounded-md transition-colors disabled:opacity-50 flex items-center gap-1.5",children:y?e.jsxs(e.Fragment,{children:[e.jsx(He,{size:12,className:"animate-spin"}),"Deleting..."]}):e.jsxs(e.Fragment,{children:[e.jsx(es,{size:12}),"Delete"]})})]})]})]})]})},o1=t=>{if(!t||typeof t!="object")return"";const s=t.extra_info;if(s){if(typeof s=="string"){if(s.startsWith("{"))try{const a=JSON.parse(s);return a.body||a.html||a.body_html||a.content||a.markdown||""}catch{const a=s.match(/"body"\s*:\s*"([\s\S]*?)"(?=\s*[,\}])/),n=s.match(/"html"\s*:\s*"([\s\S]*?)"(?=\s*[,\}])/);
551return(a&&a[1]||n&&n[1]||"").replace(/\\n/g,`
552`).replace(/\\t/g,"	").replace(/\\r/g,"\r").replace(/\\"/g,'"')}return s}else if(typeof s=="object")return s.body||s.html||s.body_html||s.content||s.markdown||""}return t.body||t.html_content||t.html||t.body_html||t.content||""},qm=[{key:"entity_clarity",label:"Entity Clarity",icon:us,maxScore:10,color:"blue",description:"Clear definition and consistent entity naming"},{key:"quotable_facts",label:"Quotable Facts",icon:Na,maxScore:10,color:"purple",description:"Specific numbers, statistics, and verifiable claims"},{key:"faq_coverage",label:"FAQ Coverage",icon:Qs,maxScore:10,color:"teal",description:"Comprehensive FAQ addressing user intent"},{key:"comparison_positioning",label:"Comparison Positioning",icon:ed,maxScore:10,color:"orange",description:"Fair comparisons and alternatives"},{key:"structural_clarity",label:"Structural Clarity",icon:ed,maxScore:10,color:"green",description:"Clear hierarchy, short paragraphs, and summaries"},{key:"authority_signals",label:"Authority Signals",icon:nc,maxScore:10,color:"indigo",description:"Credentials, case studies, and trust signals"}],i1=({value:t})=>{const[s,a]=r.useState(new Set(qm.map(m=>m.key))),n=r.useMemo(()=>{if(!t)return null;try{if(typeof t=="object"&&t.status==="complete"&&t.result){const m=t.result;return typeof m=="string"?JSON.parse(m):m}if(typeof t=="string")return JSON.parse(t);if(typeof t=="object"&&"total_score"in t)return t}catch(m){console.error("Failed to parse score data:",m)}return null},[t]),o=m=>{a(h=>{const p=new Set(h);return p.has(m)?p.delete(m):p.add(m),p})},i=(m,h)=>{const p=m/h*100;return p>=85.7?{bg:"bg-emerald-500",text:"text-emerald-700"}:p>=64.3?{bg:"bg-amber-500",text:"text-amber-700"}:{bg:"bg-red-500",text:"text-red-700"}},l=m=>m>=86?{ring:"stroke-emerald-500",text:"text-emerald-600",bg:"bg-emerald-50"}:m>=64?{ring:"stroke-amber-500",text:"text-amber-600",bg:"bg-amber-50"}:m>=43?{ring:"stroke-orange-500",text:"text-orange-600",bg:"bg-orange-50"}:{ring:"stroke-red-500",text:"text-red-600",bg:"bg-red-50"};if(t&&typeof t=="object"&&(t.__pending||t.status==="running"))return e.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-gray-400",children:[e.jsx(He,{size:32,className:"animate-spin mb-4"}),e.jsx("span",{className:"text-sm font-medium",children:"Analyzing content..."}),e.jsx("p",{className:"text-xs text-gray-300 mt-1",children:"This may take a moment"})]});if(t&&typeof t=="object"&&(t.status==="error"||t.status==="failed"))return e.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-red-400",children:[e.jsx("div",{className:"w-12 h-12 rounded-full bg-red-50 flex items-center justify-center mb-4",children:e.jsx(mt,{size:24,className:"text-red-500"})}),e.jsx("span",{className:"text-sm font-medium",children:"Scoring Failed"}),e.jsx("p",{className:"text-xs text-gray-400 mt-1",children:t.error||"An error occurred during scoring"})]});if(!n)return e.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-gray-300",children:[e.jsx(Dr,{size:32,className:"mb-3 opacity-50"}),e.jsx("span",{className:"text-sm italic",children:"No score data"}),e.jsx("p",{className:"text-xs text-gray-300 mt-1",children:"Run AI to generate score"})]});const c=n.total_score,d=l(c);return e.jsxs("div",{className:"py-4 space-y-6",children:[e.jsxs("div",{className:`flex items-center gap-6 p-4 rounded-xl ${d.bg}`,children:[e.jsxs("div",{className:"relative w-20 h-20 flex-shrink-0",children:[e.jsxs("svg",{className:"w-20 h-20 transform -rotate-90",viewBox:"0 0 36 36",children:[e.jsx("circle",{cx:"18",cy:"18",r:"15.5",fill:"none",stroke:"currentColor",strokeWidth:"3",className:"text-gray-200"}),e.jsx("circle",{cx:"18",cy:"18",r:"15.5",fill:"none",strokeWidth:"3",strokeLinecap:"round",className:d.ring,strokeDasharray:`${c/100*97.4} 97.4`})]}),e.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:e.jsx("span",{className:`text-2xl font-bold ${d.text}`,children:c})})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-sm font-semibold text-gray-800",children:n.rating||(c>=86?"Excellent GEO readiness":c>=64?"Good, needs optimization":c>=43?"Fair, significant gaps":"Poor, major overhaul needed")}),e.jsx("div",{className:"text-xs text-gray-500 mt-0.5",children:"GEO Score (100-point scale)"})]})]}),(n.priority_fixes||n.quick_wins)&&e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[n.priority_fixes&&n.priority_fixes.length>0&&e.jsxs("div",{className:"p-3 bg-red-50 rounded-lg border border-red-100",children:[e.jsx("div",{className:"text-xs font-medium text-red-700 uppercase tracking-wider mb-2",children:"Priority Fixes"}),e.jsx("ul",{className:"space-y-1.5",children:n.priority_fixes.map((m,h)=>e.jsxs("li",{className:"text-[11px] text-red-600 leading-relaxed flex gap-1.5",children:[e.jsx("span",{className:"text-red-400",children:"•"}),e.jsx("span",{children:m})]},h))})]}),n.quick_wins&&n.quick_wins.length>0&&e.jsxs("div",{className:"p-3 bg-green-50 rounded-lg border border-green-100",children:[e.jsx("div",{className:"text-xs font-medium text-green-700 uppercase tracking-wider mb-2",children:"Qu
552ick Wins"}),e.jsx("ul",{className:"space-y-1.5",children:n.quick_wins.map((m,h)=>e.jsxs("li",{className:"text-[11px] text-green-600 leading-relaxed flex gap-1.5",children:[e.jsx("span",{className:"text-green-400",children:"•"}),e.jsx("span",{children:m})]},h))})]})]}),e.jsx("div",{className:"space-y-3",children:qm.map(m=>{const h=n.dimension_scores?.[m.key];if(!h)return null;const p=h.subtotal||0,f=h.items||[],b=s.has(m.key),y=m.icon,x=i(p,m.maxScore);return e.jsxs("div",{className:"border border-gray-200 rounded-lg overflow-hidden",children:[e.jsxs("button",{onClick:()=>o(m.key),className:"w-full flex items-center gap-3 px-4 py-3 bg-white hover:bg-gray-50 transition-colors",children:[e.jsx(y,{size:16,className:"text-gray-400 flex-shrink-0"}),e.jsxs("div",{className:"flex-1 text-left",children:[e.jsx("span",{className:"text-sm font-medium text-gray-700",children:m.label}),e.jsx("p",{className:"text-[10px] text-gray-400 mt-0.5",children:m.description})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:`text-sm font-bold ${x.text}`,children:[p,"/",m.maxScore]}),e.jsx("div",{className:"w-16 h-1.5 bg-gray-200 rounded-full overflow-hidden",children:e.jsx("div",{className:`h-full ${x.bg} rounded-full transition-all`,style:{width:`${p/m.maxScore*100}%`}})}),b?e.jsx(mu,{size:14,className:"text-gray-400"}):e.jsx(Gs,{size:14,className:"text-gray-400"})]})]}),b&&e.jsx("div",{className:"border-t border-gray-100 bg-gray-50/50 divide-y divide-gray-100",children:f.map((u,g)=>{const w=u.score||0,_=i(w,2);return e.jsxs("div",{className:"px-4 py-3",children:[e.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[e.jsx("span",{className:"text-xs font-medium text-gray-600",children:u.item}),e.jsxs("span",{className:`text-xs font-bold ${_.text}`,children:[w,"/2"]})]}),e.jsx("div",{className:"w-full h-1 bg-gray-200 rounded-full overflow-hidden mb-2",children:e.jsx("div",{className:`h-full ${_.bg} rounded-full transition-all`,style:{width:`${w/2*100}%`}})}),u.notes&&e.jsx("p",{className:"text-[11px] text-gray-500 leading-relaxed",children:u.notes})]},g)})})]},m.key)})})]})},l1=({value:t,className:s=""})=>{const a=o1(t);return a?e.jsx(Wc,{html:a,readOnly:!0,showToolbar:!1,showCodeButton:!1,minHeight:300,placeholder:"No HTML content",className:`h-full ${s}`}):e.jsx("div",{className:`flex items-center justify-center h-full text-gray-300 italic ${s}`,children:"No content"})},Vc=({expandedCell:t,onUpdate:s,onClose:a,allColumns:n=[],onUpdateColumn:o,onDeleteColumn:i})=>{const{row:l,col:c,rowId:d,colId:m}=t,h=l.cells[m]||{value:""},[p,f]=r.useState(!1),{toast:b}=_t(),y=c.type==="ai"&&c.config?.ai?.display_mode==="score",[x,u]=r.useState(!1),[g,w]=r.useState(null),_=r.useRef(null),E=r.useRef(null),N=r.useRef(null),S=r.useRef(null),k=r.useRef(null),[D,F]=r.useState(null),[R,L]=r.useState(()=>{const J=localStorage.getItem("cellDetailPanelWidth");return J?parseInt(J,10):384}),[$,H]=r.useState(!1),K=r.useRef(0),X=r.useRef(0),V=r.useRef(null),P=r.useRef(null),[A,C]=r.useState(!1),I=da(),j=r.useMemo(()=>["ai","ai_image","ai_seo_analysis","seo_analysis","keywords","ai_keywords"].includes(c.type),[c.type]),[q,T]=r.useState(!1),M=(c.type==="keywords"||c.type==="ai_keywords")&&c.config?.keywords?.source==="competitors",Z=r.useMemo(()=>{const J=g!==null?g:h.value;return Array.isArray(J)?J.filter(re=>typeof re=="string"&&re.trim()!==""):typeof J=="string"&&J.trim()?[J.trim()]:[]},[g,h.value]),B=r.useCallback(J=>{const re=J.map(je=>je.keyword),Se=[...new Set([...Z,...re])];s(d,m,Se),w(Se),T(!1)},[d,m,Z,s]),ae=r.useMemo(()=>{const J=g!==null?g:h.value;if(J==null)return"";if(typeof J=="string")return J;if(typeof J=="object"&&"result"in J){const re=J.result;return typeof re=="string"?re:na(re,{pretty:!0})}return na(J,{pretty:!0})},[g,h.value]),de=r.useMemo(()=>!ae||typeof ae!="string"||c.type==="seo_analysis"?!1:[/<html[\s>]/i,/<head[\s>]/i,/<body[\s>]/i,/<div[\s>]/i,/<span[\s>]/i,/<p[\s>]/i,/<h[1-6][\s>]/i,/<ul[\s>]/i,/<ol[\s>]/i,/<table[\s>]/i,/<tr[\s>]/i,/<td[\s>]/i,/<script[\s>]/i,/<style[\s>]/i,/<a\s+href/i,/<img\s+src/i,/<br\s*\/?>/i,/<hr\s*\/?>/i].some(re=>re.test(ae)),[ae]),fe=r.useMemo(()=>!ae||typeof ae!="string"||de?!1:["text","ai","seo_analysis","keywords","ai_keywords"].includes(c.type)?!0:[/^#{1,6}\s/m,/\*\*.*?\*\*/,/\[.*?\]\(.*?\)/,/^```/m,/^\|.*?\|/m,/^[-*+]\s/m].some(je=>je.test(ae)),[ae,c.type,de]),se=fe||de,z=c.type==="select"||c.type==="status",U=r.useMemo(()=>c.options||c.config?.options||[],[c.options,c.config?.options]),Q=z&&c.config?.multiple===!0,me=r.useCallback(J=>{if(J==null)return"";if(typeof J=="string")return J;if(Array.isArray(J))return J.map(re=>typeof re=="string"?re.trim():String(re??"").trim()).filter(re=>re.length>0).join(", ");
552if(typeof J=="object"){if("result"in J){const re=J.result;return Array.isArray(re)?re.map(Se=>typeof Se=="string"?Se.trim():String(Se??"").trim()).filter(Se=>Se.length>0).join(", "):typeof re=="string"?re:na(re,{pretty:!0})}return na(J,{pretty:!0})}return String(J)},[]),le=r.useCallback(J=>{const re=(J||"").trim();if(!re)return[];let Se=re;return Se.startsWith("[")&&Se.endsWith("]")&&(Se=Se.slice(1,-1).trim()),Se.split(/[,;\n\r]+/g).map(he=>he.trim()).map(he=>he.startsWith('"')&&he.endsWith('"')||he.startsWith("'")&&he.endsWith("'")?he.slice(1,-1).trim():he).filter(he=>he.length>0)},[]),O=r.useCallback(()=>c.type==="ai"||c.type==="keywords"||c.type==="ai_keywords",[c.type]),[ne,ge]=r.useState(O()?me(h.value):h.value);r.useEffect(()=>{const J=O()?me(h.value):h.value;ge(J),f(!1),w(null)},[d,m,h.value,c.type,O]),r.useEffect(()=>{if(p)return;const J=_.current;if(!J)return;const re=he=>{const Re=typeof window<"u"?Math.max(window.innerHeight-Zl,160):he;return Math.min(Math.max(Math.round(he),100),Re)},Se=()=>{const he=re(J.getBoundingClientRect().height);F(Re=>Re===he?Re:he)};Se();const je=new ResizeObserver(()=>Se());return je.observe(J),()=>je.disconnect()},[p,d,m,g,h.value,c.type]),r.useEffect(()=>{const J=()=>{F(re=>{if(re===null)return re;const Se=Math.max(window.innerHeight-Zl,160),he=Math.min(Math.max(re,100),Se);return he===re?re:he})};return window.addEventListener("resize",J),()=>window.removeEventListener("resize",J)},[]),r.useEffect(()=>{const J=re=>{if(re.key==="Escape")if(p){f(!1);const Se=O()?me(h.value):h.value;ge(Se)}else a()};return window.addEventListener("keydown",J),()=>window.removeEventListener("keydown",J)},[a,p,h.value,c.type,O]);const ze=J=>{J.preventDefault(),H(!0),K.current=J.clientX,X.current=R};r.useEffect(()=>{if(!$){document.body.classList.remove("resizing-active");return}document.body.classList.add("resizing-active");const J=Se=>{const je=K.current-Se.clientX,he=Math.min(Math.max(X.current+je,320),800);L(he)},re=()=>{H(!1),document.body.classList.remove("resizing-active"),localStorage.setItem("cellDetailPanelWidth",String(R))};return document.addEventListener("mousemove",J),document.addEventListener("mouseup",re),()=>{document.removeEventListener("mousemove",J),document.removeEventListener("mouseup",re),document.body.classList.remove("resizing-active")}},[$,R]);const Ke=r.useCallback(J=>{if(!o)return;const re=c.config||{},Se=re.ai||{};o(m,{config:{...re,ai:{...Se,...J}}})},[c.config,m,o]),ie=()=>{let J;if(c.type==="keywords"||c.type==="ai_keywords")J=le(ne);else if(c.type==="ai"){const re=h.value,je=Array.isArray(re)||!!re&&typeof re=="object"&&!Array.isArray(re)&&"result"in re&&Array.isArray(re.result)?le(ne):ne;J={...re&&typeof re=="object"&&!Array.isArray(re)?re:{},status:"complete",result:je}}else c.type==="number"?J=parseFloat(ne)||0:J=ne;w(J),s(d,m,J),f(!1),b({title:"✓ Saved",description:`${c.title} has been updated.`})},ve=()=>{const J=O()?me(h.value):h.value;ge(J),f(!1)},we=r.useCallback(J=>{w(J),ge(J),s(d,m,J),b({title:"✓ Saved",description:`${c.title} has been updated.`})},[d,m,c.title,s,b]),Pe=r.useCallback(async()=>{if(!(!I||!c.id||A)){C(!0),s(d,m,{status:"running",result:null}),w({status:"running",result:null});try{let J;if(c.type==="keywords"||c.type==="ai_keywords"){const re={},Se=new Set(["topic","title","prompts"]);for(const je of n)if(je.system_name&&Se.has(je.system_name)){const he=l.cells[je.id]?.value;he!=null&&typeof he!="object"?re[je.system_name]=he:Array.isArray(he)&&(re[je.system_name]=he.join(", "))}J=await Vt.generateKeywordsValue({campaign_id:I,column_id:c.id,row_ids:[d],row_data_map:Object.keys(re).length?{[d]:{dependencies:re}}:void 0})}else J=await Vt.generateAIValue({campaign_id:I,column_id:c.id,row_ids:[d]});if(J?.data?.rows){const re=J.data.rows[d];if(re){if(s(d,m,re),w(re),typeof re=="object"&&re.result){const Se=Array.isArray(re.result)?re.result.join(", "):re.result;ge(Se)}else typeof re=="string"&&ge(re);b({title:"✓ Generated",description:`${c.title} has been regenerated.`})}}else J?.task_id&&b({title:"⏳ Generating...",description:`${c.title} is being generated.`})}catch(J){console.error("[CellDetailPanel] Regenerate error:",J),s(d,m,{status:"error",result:null,error:J.message}),w({status:"error",result:null}),b({title:"✗ Error",description:J.message||"Failed to regenerate.",variant:"destructive"})}finally{C(!1)}}},[I,c.id,c.type,c.title,d,m,A,s,b,n,l]),Ae=mn[c.type]||_a,ye=()=>{if(g!==null)return c.type==="ai"&&typeof g=="object"&&"result"in g?g.result!==void 0?g.result:"":g;if(c.type==="url"&&c.config?.url?.mode==="integration"){const J=c.config.url,re=J.integration_type;let Se=null,je=null;if(re==="webflow"&&J.webflow_source_column_id?(Se=J.webflow_source_column_id,je="site_url_path"):re==="shopify"&&J.shopify_source_column_id&&(Se=J.shopify_source_column_id,je="url"),Se&&je){const he=l.cells[Se]?.value;if(he&&typeof he=="object"&&he.status==="published"){const Re=he[je];if(Re){if(re==="webflow"&&J.preview_from_webflow_domain)try{const Me=typeof window<"u"?sessionStorage.getItem("webflow_custom_domains"):null;if(Me){const Ze=JSON.parse(Me);
552if(Array.isArray(Ze)&&Ze.length>0&&Ze[0]?.url){let Be=Ze[0].url.trim();!Be.startsWith("http://")&&!Be.startsWith("https://")&&(Be=`https://${Be}`),Be=Be.replace(/\/+$/,"");const et=Re.startsWith("/")?Re:`/${Re}`;return`${Be}${et}`}}}catch{}return Re}}}return""}if(c.type==="ai"){const J=h.value;return J==null?"":typeof J=="object"?J?.status==="running"?"(Running...)":"result"in J?J.result!==void 0?J.result:"":J:J}return h.value},Te=r.useCallback(()=>na(ne,{pretty:!0}),[ne]),Ie=r.useMemo(()=>!(c.type==="select"||c.type==="status"||c.type==="number"||c.type==="webflow"||c.type==="shopify"||c.type==="image"||c.type==="ai_image"||c.type==="keywords"||c.type==="ai_keywords"||c.type==="knowledge"||se),[c.type,se]),Oe=r.useCallback(J=>{if(p||!Ie)return;const re=E.current;if(!re)return;const Se=window.getSelection();if(!Se||Se.rangeCount===0)return;const je=Se.getRangeAt(0);if(!re.contains(je.startContainer))return;const he=document.createRange();he.selectNodeContents(re),he.setEnd(je.startContainer,je.startOffset);const Re=he.toString().length;S.current=Re;const Me=_.current;if(Me){const et=Me.scrollHeight-Me.clientHeight;k.current=et>0?Me.scrollTop/et:0}else k.current=null;const Ze=ye(),Be=O()?me(Ze):Ze;ge(Be),f(!0),J.stopPropagation()},[p,Ie,ye,O,me]);return r.useEffect(()=>{if(!p)return;const J=S.current;if(J===null)return;const re=N.current;if(!re)return;const Se=Te(),je=Math.min(Math.max(J,0),Se.length);requestAnimationFrame(()=>{try{re.focus(),re.setSelectionRange(je,je);const he=k.current,Re=()=>{if(typeof he!="number")return;const Me=re.scrollHeight-re.clientHeight;re.scrollTop=Me>0?he*Me:0};Re(),setTimeout(()=>Re(),0)}catch{}finally{S.current=null,k.current=null}})},[p,Te]),e.jsxs("div",{"data-cell-detail-panel":!0,"data-onboarding":"cell-detail-panel",className:"relative border-l border-gray-200 bg-white flex flex-col h-full",style:{width:`${R}px`},children:[e.jsx("div",{className:`absolute left-0 top-0 bottom-0 w-1 cursor-col-resize hover:bg-blue-500 transition-colors ${$?"bg-blue-500":"bg-transparent"}`,onMouseDown:ze,style:{marginLeft:"-2px"},children:e.jsx("div",{className:"absolute left-1/2 top-1/2 transform -translate-x-1/2 -translate-y-1/2 w-1 h-12 bg-gray-300 rounded-full opacity-0 hover:opacity-100 transition-opacity"})}),e.jsxs("div",{className:"flex-none border-b border-gray-200 px-4 py-2.5 flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(Ae,{size:14,className:"text-gray-400 flex-shrink-0"}),e.jsx("span",{className:"text-sm font-medium text-gray-800 truncate",children:c.title})]}),e.jsxs("div",{className:"flex items-center gap-0.5",children:[o&&e.jsx("button",{onClick:()=>u(!0),className:"p-1.5 hover:bg-gray-100 rounded transition-colors",title:"Edit Column",children:e.jsx(_r,{size:14,className:"text-gray-400"})}),e.jsx("button",{onClick:a,className:"p-1.5 hover:bg-gray-100 rounded transition-colors",children:e.jsx(mt,{size:14,className:"text-gray-400"})})]})]}),e.jsx("div",{className:`flex-1 ${z||y||c.type==="webflow"||c.type==="shopify"?"overflow-hidden flex flex-col":"overflow-y-auto"} ${(se||y||c.type==="webflow"||c.type==="shopify")&&!(c.type==="url"&&c.config?.url?.mode==="integration")||z?"":"p-4"}`,children:e.jsx("div",{className:(se||y||c.type==="webflow"||c.type==="shopify")&&!(c.type==="url"&&c.config?.url?.mode==="integration")?"h-full flex-1 flex flex-col min-h-0":z?"flex-1 flex flex-col min-h-0":"mb-4",children:c.type==="webflow"||c.type==="shopify"?e.jsx(l1,{value:h.value,className:"flex-1"}):y?e.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-4",children:e.jsx(i1,{value:h.value})}):de&&!(c.type==="url"&&c.config?.url?.mode==="integration")?e.jsx("div",{className:"h-full",children:e.jsx(Wc,{ref:P,html:ae,onChange:J=>ge(J),placeholder:"Enter HTML content...",minHeight:300,showToolbar:!0,className:"h-full"})}):fe&&!(c.type==="url"&&c.config?.url?.mode==="integration")?e.jsx("div",{className:"h-full",children:e.jsx(Ah,{ref:V,markdown:ae,onChange:J=>ge(J),placeholder:"Enter content...",minHeight:300,maxHeight:"100%",showToolbar:!0,showDiffSource:!0,className:"h-full border-0"})}):z?e.jsx(qk,{value:g!==null?g:h.value||"",options:U,onChange:we,multiple:Q,placeholder:`Select ${c.title}...`,className:"flex-1"}):e.jsxs(e.Fragment,{children:[!p&&c.type!=="webflow"&&c.type!=="shopify"&&c.type!=="knowledge"&&!(c.type==="url"&&c.config?.url?.mode==="integration")&&e.jsxs("div",{className:"flex justify-end gap-1 mb-2",children:[M&&e.jsxs("button",{type:"button",onMouseDown:J=>J.stopPropagation(),onClick:J=>{J.stopPropagation(),T(!0)},className:"flex items-center gap-1 text-xs text-blue-600 hover:text-blue-700 px-2 py-1 hover:bg-blue-50 rounded border border-slate-200 transition-colors",children:[e.jsx($t,{size:12}),"Add"]}),e.jsx("button",{type:"button",onMouseDown:J=>J.stopPropagation(),onClick:J=>{J.stopPropagation(),f(!0)},className:"text-xs text-gray-500 hover:text-gray-700 px-2 py-1 hover:bg-gray-100 rounded transition-colors",children:"Edit"})]}),p?e.jsxs("div",{className:"space-y-3",children:[c.type==="number"?e.jsx("input",{type:"number",value:ne,onChange:J=>ge(J.target.value),className:"w-full text-sm border border-gray-200 rounded-lg px-3 py-2.5 focus:border-gray-400 focus:outline-none focus:ring-2 focus:ring-gray-100 bg-white text-gray-700 font-mono",autoF
552ocus:!0}):e.jsx("textarea",{ref:N,value:na(ne,{pretty:!0}),onChange:J=>ge(J.target.value),rows:1,style:{height:D!==null?`${D}px`:void 0,maxHeight:en,minHeight:100},className:"w-full text-sm border border-gray-200 rounded-lg px-3 py-2.5 focus:border-gray-400 focus:outline-none focus:ring-2 focus:ring-gray-100 bg-white text-gray-700 resize-none font-mono overflow-y-auto",placeholder:"Enter value...",autoFocus:!0}),e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[e.jsx("button",{onClick:ve,className:"px-3 py-1.5 text-xs text-gray-600 hover:bg-gray-100 rounded-md transition-colors",children:"Cancel"}),e.jsx("button",{onClick:ie,className:"px-3 py-1.5 text-xs font-medium text-white bg-gray-600 hover:bg-gray-500 rounded-md transition-colors",children:"Save"})]})]}):c.type==="image"?e.jsx("div",{className:"min-h-[100px] overflow-y-auto",style:{maxHeight:en},onMouseDown:J=>J.stopPropagation(),onClick:J=>J.stopPropagation(),children:e.jsx(r1,{value:h.value,rowId:d,colId:m,colType:c.type,allowMultiple:c.config?.allowMultiple!==!1,onUpdate:s})}):c.type==="ai_image"?e.jsx("div",{ref:_,className:"min-h-[100px] overflow-y-auto",style:{maxHeight:en},onMouseDown:J=>J.stopPropagation(),onClick:J=>J.stopPropagation(),children:h.value&&typeof h.value=="object"&&(h.value.__pending||h.value.status==="running")?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-gray-400",children:[e.jsx(He,{size:28,className:"animate-spin mx-auto mb-3"}),e.jsx("span",{className:"text-sm font-medium",children:"Generating..."}),e.jsx("p",{className:"text-xs text-gray-300 mt-1",children:"AI image is being generated"})]}):h.value&&typeof h.value=="object"&&(h.value.status==="failed"||h.value.status==="error")?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-red-400",children:[e.jsx("div",{className:"w-12 h-12 rounded-full bg-red-50 flex items-center justify-center mb-4",children:e.jsx(mt,{size:24,className:"text-red-500"})}),e.jsx("span",{className:"text-sm font-medium text-red-600",children:"Generation Failed"}),e.jsx("div",{className:"mt-3 px-4 max-w-md",children:e.jsx("div",{className:"text-xs text-gray-700 bg-red-50 border border-red-200 rounded-md px-3 py-2 leading-relaxed",children:h.value.error||"Unknown error"})}),e.jsx("p",{className:"text-xs text-gray-400 mt-4 text-center max-w-xs px-4",children:'💡 Tip: Image generation requires visual descriptions. Try prompts like "A modern office with..." or "Photo of a nano banana on a plate".'})]}):typeof h.value=="string"&&(h.value.startsWith("http://")||h.value.startsWith("https://"))?e.jsxs("div",{className:"space-y-3",children:[e.jsxs("figure",{className:"rounded-lg overflow-hidden border border-gray-200 bg-gray-50",children:[e.jsx("img",{src:h.value,alt:"AI generated",className:"w-full h-48 object-cover"}),e.jsx("figcaption",{className:"px-2 py-1 bg-white/90 text-[11px] text-gray-600 truncate border-t border-gray-100",children:h.value})]}),e.jsxs("a",{href:h.value,target:"_blank",rel:"noopener noreferrer",className:"text-xs text-blue-600 hover:text-blue-700 hover:underline inline-flex items-center gap-1.5",children:[e.jsx(ns,{size:12,className:"opacity-70"}),"Open image"]}),e.jsxs("div",{className:"bg-gray-50 border border-gray-200 rounded-md px-3 py-2",children:[e.jsx("div",{className:"text-[10px] text-gray-500 mb-1",children:"Image URL"}),e.jsx("div",{className:"text-[11px] font-mono text-gray-700 break-all select-text",children:h.value})]})]}):e.jsx("div",{className:"flex flex-col items-center justify-center py-12 text-gray-300",children:e.jsxs("div",{className:"text-center",children:[e.jsx(rn,{size:28,className:"mx-auto mb-2 opacity-50"}),e.jsx("span",{className:"text-sm italic",children:"No image"}),e.jsx("p",{className:"text-xs text-gray-300 mt-1",children:"Click Regenerate to generate an image"})]})})}):c.type==="number"?e.jsx("div",{ref:_,className:"min-h-[100px] overflow-y-auto",style:{maxHeight:en},onMouseDown:J=>J.stopPropagation(),onClick:J=>J.stopPropagation(),onDoubleClick:Oe,children:e.jsx(Qk,{value:ye()})}):c.type==="date"?e.jsx("div",{ref:_,className:"min-h-[100px] overflow-y-auto",style:{maxHeight:en},onMouseDown:J=>J.stopPropagation(),onClick:J=>J.stopPropagation(),onDoubleClick:Oe,children:e.jsx(Zk,{value:ye()})}):c.type==="url"?e.jsx("div",{ref:_,className:"min-h-[100px] overflow-y-auto",style:{maxHeight:en},onMouseDown:J=>J.stopPropagation(),onClick:J=>J.stopPropagation(),onDoubleClick:Oe,children:e.jsx(e1,{value:ye()})}):c.type==="checkbox"?e.jsx("div",{ref:_,className:"min-h-[100px] overflow-y-auto",style:{maxHeight:en},onMouseDown:J=>J.stopPropagation(),onClick:J=>J.stopPropagation(),children:e.jsx(t1,{value:ye(),onChange:J=>{w(J),s(d,m,J),b({title:"✓ Saved",description:`${c.title} has been updated.`})}})}
552):c.type==="knowledge"?e.jsx("div",{ref:_,className:"min-h-[100px] overflow-y-auto",style:{maxHeight:en},onMouseDown:J=>J.stopPropagation(),onClick:J=>J.stopPropagation(),children:e.jsx(n1,{value:ye()})}):e.jsx("div",{ref:_,className:"min-h-[100px] overflow-y-auto",style:{maxHeight:en},onMouseDown:J=>J.stopPropagation(),onClick:J=>J.stopPropagation(),onDoubleClick:Oe,children:c.type==="ai"&&typeof h.value=="object"&&h.value?.status==="running"?e.jsx("div",{className:"flex items-center justify-center py-12 text-gray-400",children:e.jsxs("div",{className:"text-center",children:[e.jsx(He,{size:28,className:"animate-spin mx-auto mb-3"}),e.jsx("span",{className:"text-sm font-medium",children:"Generating..."}),e.jsx("p",{className:"text-xs text-gray-300 mt-1",children:"AI is working on your request"})]})}):c.type==="keywords"||c.type==="ai_keywords"?e.jsx(a1,{value:ye(),rowId:d,colId:m,onUpdate:s}):e.jsx(Xk,{value:ye(),plainTextContainerRef:E})})]})})}),e.jsxs("div",{className:"flex-none border-t border-gray-200 px-4 py-2 flex items-center justify-between bg-gray-50/50",children:[e.jsx("span",{className:"text-[10px] text-gray-400",children:"ESC to close"}),e.jsxs("div",{className:"flex items-center gap-2",children:[j&&e.jsx("button",{onClick:Pe,disabled:A,className:"px-3 py-1.5 text-xs font-medium text-white bg-blue-600 hover:bg-blue-500 disabled:bg-blue-300 disabled:cursor-not-allowed rounded-md transition-colors flex items-center gap-1.5",children:A?e.jsxs(e.Fragment,{children:[e.jsx(He,{size:12,className:"animate-spin"}),"Generating..."]}):e.jsxs(e.Fragment,{children:[e.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M21 12a9 9 0 0 0-9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),e.jsx("path",{d:"M3 3v5h5"}),e.jsx("path",{d:"M3 12a9 9 0 0 0 9 9 9.75 9.75 0 0 0 6.74-2.74L21 16"}),e.jsx("path",{d:"M16 21h5v-5"})]}),"Regenerate"]})}),se&&c.type!=="webflow"&&c.type!=="shopify"&&!(c.type==="url"&&c.config?.url?.mode==="integration")&&e.jsx("button",{onClick:ie,className:"px-3 py-1.5 text-xs font-medium text-white bg-gray-600 hover:bg-gray-500 rounded-md transition-colors",children:"Save"}),e.jsx("button",{onClick:a,className:"text-xs text-gray-500 hover:text-gray-700 px-2 py-1 hover:bg-gray-100 rounded transition-colors",children:"Close"})]})]}),x&&o&&e.jsx(Gc,{col:c,allColumns:n,onClose:()=>u(!1),onUpdate:o,updateAIConfig:Ke}),M&&e.jsx(Kc,{isOpen:q,title:"Select Keywords",description:"Select keywords from your top rankings or competitors.",existingKeywords:new Set(Z),onClose:()=>T(!1),onConfirm:B,skipConfirmation:!0})]})},c1=({columns:t,rows:s,onCellUpdate:a,onColumnReorder:n,onApplyColumnOrder:o,onAddColumn:i,onUpdateColumn:l,onDeleteColumn:c,onCreateRow:d,onCreateMultipleRows:m,onEnsureEmptyRows:h,searchQuery:p,filters:f=[],sortConfig:b=null,onSelectionChange:y,showColumnConfigPanel:x,pendingColumnType:u,pendingColumnConfig:g,onCreateColumnFromConfig:w,onCancelColumnConfig:_,expandedCell:E,onExpandedCellChange:N,onDetailUpdate:S})=>{const[k,D]=r.useState({selectedCells:new Set,anchorCell:null,isSelecting:!1}),[F,R]=r.useState([]),[L,$]=r.useState(null),[H,K]=r.useState(null),X=E!==void 0?E:H,V=N||K,[P,A]=r.useState(null),C=r.useRef(null),{showToast:I}=Xi({columns:t}),j=r.useMemo(()=>t.filter(ie=>!ie.hidden_by_composite),[t]);r.useEffect(()=>{y?.(k.selectedCells)},[y,k.selectedCells]);const q=r.useCallback((ie,ve)=>{if(!ve.columnId)return!0;const we=Ba(ie,ve.columnId).toLowerCase(),Pe=ve.value.toLowerCase();switch(ve.operator){case"contains":return we.includes(Pe);case"equals":return we===Pe;case"not_equals":return we!==Pe;case"starts_with":return we.startsWith(Pe);case"ends_with":return we.endsWith(Pe);case"is_empty":return we.trim()==="";case"is_not_empty":return we.trim()!=="";default:return!0}},[]),T=r.useMemo(()=>{let ie=s.filter(ve=>{if(p){const we=p.toLowerCase();if(!t.some(Ae=>Ba(ve,Ae.id).toLowerCase().includes(we)))return!1}for(const we of f)if(!q(ve,we))return!1;return!0});return b&&(ie=[...ie].sort((ve,we)=>{const Pe=Ba(ve,b.columnId).toLowerCase(),Ae=Ba(we,b.columnId).toLowerCase(),ye=parseFloat(Pe),Te=parseFloat(Ae);let Ie=0;return!isNaN(ye)&&!isNaN(Te)?Ie=ye-Te:Ie=Pe.localeCompare(Ae),b.direction==="asc"?Ie:-Ie})),ie},[s,p,f,b,t,q]),M=r.useCallback(ie=>T.findIndex(ve=>ve.id===ie),[T]),Z=r.useCallback(ie=>j.findIndex(ve=>ve.id===ie),[j]),B=r.useCallback((ie,ve)=>k.selectedCells.has(Un(ie,ve)),[k.selectedCells]),ae=r.useCallback((ie,ve,we,Pe)=>{D(Ae=>{const ye=Un(ie,ve),Te=new Set(Ae.selectedCells);if(we&&Ae.anchorCell){Te.clear();
552const Ie=M(Ae.anchorCell.rowId),Oe=Z(Ae.anchorCell.colId),J=M(ie),re=Z(ve),Se=Math.min(Ie,J),je=Math.max(Ie,J),he=Math.min(Oe,re),Re=Math.max(Oe,re);for(let Me=Se;Me<=je;Me++)for(let Ze=he;Ze<=Re;Ze++)T[Me]&&j[Ze]&&Te.add(Un(T[Me].id,j[Ze].id));return{...Ae,selectedCells:Te}}else return Pe?(Te.has(ye)?Te.delete(ye):Te.add(ye),{selectedCells:Te,anchorCell:{rowId:ie,colId:ve},isSelecting:!1}):{selectedCells:new Set([ye]),anchorCell:{rowId:ie,colId:ve},isSelecting:!1}})},[M,Z,T,j]),de=r.useCallback((ie,ve)=>{$({rowId:ie,colId:ve}),D({selectedCells:new Set([Un(ie,ve)]),anchorCell:{rowId:ie,colId:ve},isSelecting:!0})},[]),fe=r.useCallback((ie,ve)=>{!L||!k.isSelecting||D(we=>{const Pe=new Set,Ae=M(L.rowId),ye=Z(L.colId),Te=M(ie),Ie=Z(ve),Oe=Math.min(Ae,Te),J=Math.max(Ae,Te),re=Math.min(ye,Ie),Se=Math.max(ye,Ie);for(let je=Oe;je<=J;je++)for(let he=re;he<=Se;he++)T[je]&&j[he]&&Pe.add(Un(T[je].id,j[he].id));return{...we,selectedCells:Pe}})},[L,k.isSelecting,M,Z,T,j]),se=r.useCallback(()=>{$(null),D(ie=>({...ie,isSelecting:!1}))},[]),z=r.useCallback(()=>{D({selectedCells:new Set,anchorCell:null,isSelecting:!1})},[]),U=r.useCallback(()=>{const ie=new Set;T.forEach(ve=>{j.forEach(we=>{ie.add(Un(ve.id,we.id))})}),D({selectedCells:ie,anchorCell:T[0]&&j[0]?{rowId:T[0].id,colId:j[0].id}:null,isSelecting:!1})},[T,j]),Q=r.useCallback(()=>{if(k.selectedCells.size===0)return;const ie=Array.from(k.selectedCells).map(Km),ve=ie.map(J=>M(J.rowId)).filter(J=>J>=0),we=ie.map(J=>Z(J.colId)).filter(J=>J>=0);if(ve.length===0||we.length===0)return;const Pe=Math.min(...ve),Ae=Math.max(...ve),ye=Math.min(...we),Te=Math.max(...we),Ie=[];for(let J=Pe;J<=Ae;J++){const re=[];for(let Se=ye;Se<=Te;Se++){const je=T[J],he=j[Se];je&&he&&k.selectedCells.has(Un(je.id,he.id))?re.push(Ba(je,he.id)):re.push("")}Ie.push(re)}R(Ie);const Oe=Ie.map(J=>J.join("	")).join(`
553`);navigator.clipboard.writeText(Oe).catch(()=>{})},[k.selectedCells,T,j,M,Z]),me=r.useCallback(async()=>{if(!k.anchorCell)return;let ie=F;try{const Te=await navigator.clipboard.readText();if(Te){const Ie=Te.split(`
554`);ie=Ie.map(Oe=>Oe.split("	")).filter((Oe,J)=>J<Ie.length-1||Oe.some(re=>re.trim()!==""))}}catch{}if(ie.length===0)return;const ve=M(k.anchorCell.rowId),we=Z(k.anchorCell.colId),Ae=ve+ie.length-T.length;let ye=[...T];if(Ae>0){const Te=await m(Ae);ye=[...T,...Te]}for(let Te=0;Te<ie.length;Te++)for(let Ie=0;Ie<ie[Te].length;Ie++){const Oe=ve+Te,J=we+Ie;if(Oe<ye.length&&J<j.length){const re=ye[Oe],Se=j[J],je=ie[Te][Ie];let he=je;if(Se.type==="number"){const Re=parseFloat(je);he=isNaN(Re)?0:Re}a(re.id,Se.id,he)}}setTimeout(()=>h(),100)},[k.anchorCell,F,T,j,M,Z,a,m,h]),le=r.useCallback(()=>{k.selectedCells.forEach(ie=>{const{rowId:ve,colId:we}=Km(ie),Ae=j.find(ye=>ye.id===we)?.type==="number"?0:"";a(ve,we,Ae)})},[k.selectedCells,j,a]);r.useEffect(()=>{const ie=ve=>{const Pe=navigator.platform.toUpperCase().indexOf("MAC")>=0?ve.metaKey:ve.ctrlKey,Ae=(ve.key||"").toLowerCase(),ye=document.activeElement,Te=ye?.tagName,Ie=Te==="INPUT"||Te==="TEXTAREA"||Te==="SELECT",Oe=!!ye?.isContentEditable;if(!((Ie||Oe)&&(Pe&&(Ae==="a"||Ae==="c"||Ae==="v"||Ae==="x")||Ae==="escape"))){if(Pe&&Ae==="c"){ve.preventDefault(),Q();return}if(Pe&&Ae==="v"){ve.preventDefault(),me();return}if(Pe&&Ae==="a"){ve.preventDefault(),U();return}if((ve.key==="Delete"||ve.key==="Backspace")&&!Ie&&!Oe){ve.preventDefault(),le();return}if(ve.key==="Enter"||ve.key==="F2"){if(Ie||Oe||!k.anchorCell||k.selectedCells.size!==1)return;const{rowId:J,colId:re}=k.anchorCell;ve.preventDefault(),A({rowId:J,colId:re});return}if(Ae==="escape"){z();return}}};return window.addEventListener("keydown",ie),()=>window.removeEventListener("keydown",ie)},[Q,me,U,le,z,k.anchorCell,k.selectedCells.size,t]);const O=r.useCallback((ie,ve)=>{A({rowId:ie,colId:ve})},[]),ne=r.useCallback(()=>{A(null)},[]);r.useEffect(()=>{const ie=()=>{k.isSelecting&&se()};return window.addEventListener("mouseup",ie),()=>window.removeEventListener("mouseup",ie)},[k.isSelecting,se]),r.useEffect(()=>{const ie=ve=>{if(k.selectedCells.size===0||C.current&&C.current.contains(ve.target))return;const we=document.querySelector("[data-cell-detail-panel]");if(we&&we.contains(ve.target))return;const Pe=ve.target;Pe&&Pe.closest('[role="dialog"]')||Pe?.closest(".fixed.z-\\[9998\\]")||Pe?.closest(".fixed.z-\\[9999\\]")||Pe?.closest("[data-preserve-selection]")||z()};return document.addEventListener("mousedown",ie),()=>document.removeEventListener("mousedown",ie)},[k.selectedCells.size,z]);const ge=r.useCallback((ie,ve)=>{const we=T.find(Ae=>Ae.id===ie),Pe=t.find(Ae=>Ae.id===ve);we&&Pe&&V({rowId:ie,colId:ve,row:we,col:Pe})},[T,t]);r.useEffect(()=>{if(!X||k.isSelecting||!k.anchorCell||k.selectedCells.size!==1)return;const{rowId:ie,colId:ve}=k.anchorCell;if(ie===X.rowId&&ve===X.colId)return;const we=s.find(Ae=>Ae.id===ie)||T.find(Ae=>Ae.id===ie),Pe=t.find(Ae=>Ae.id===ve);we&&Pe&&V({rowId:ie,colId:ve,row:we,col:Pe})},[X,k.isSelecting,k.anchorCell,k.selectedCells.size,s,T,t]);const ze=r.useCallback((ie,ve,we)=>{a(ie,ve,we);const Pe=Ae=>{if(!Ae||Ae.rowId!==ie||Ae.colId!==ve)return Ae;const ye=Ae.row,Te=ye.cells||{},Ie=Te[ve]||{value:void 0};return{...Ae,row:{...ye,cells:{...Te,[ve]:{...Ie,value:we}}}}};if(S&&X){const Ae=Pe(X);Ae&&S(ie,ve,we,Ae)}else V(Pe(X))},[a,S,X]),Ke=r.useMemo(()=>({selection:k,isCellSelected:B,selectCell:ae,startDragSelect:de,extendDragSelect:fe,endDragSelect:se,clearSelection:z,selectAll:U,copySelection:Q,pasteSelection:me,deleteSelection:le,clipboard:F,expandCell:ge,isExpanded:!!X,editingCell:P,startEditingCell:O,stopEditingCell:ne}),[k,B,ae,de,fe,se,z,U,Q,me,le,F,ge,X,P,O,ne]);return e.jsx(Sh.Provider,{value:Ke,children:e.jsxs("div",{className:"flex-1 flex overflow-hidden relative h-full",children:[e.jsx("div",{ref:C,className:`flex-1 overflow-auto bg-white relative transition-all ${X?"mr-0":""}`,onMouseLeave:()=>{k.isSelecting&&se()},children:e.jsxs("table",{className:"w-full text-left border-collapse table-fixed min-w-max",children:[e.jsx("thead",{className:"sticky top-0 bg-white z-10 shadow-[0_1px_0_rgba(0,0,0,0.05)]",children:e.jsxs("tr",{children:[e.jsx("th",{className:"w-12 border-b border-gray-200 bg-gray-50/80 backdrop-blur-sm z-20 sticky left-0 h-10 min-h-[40px]"}),j.map((ie,ve)=>{const we=ie.type,Pe=jr(ie),Ae=we==="keywords"||we==="ai_keywords",ye=Me=>{const Ze=Me.trim();if(Ze==="{}"||Ze==="[]"||Ze==='""'||Ze==="null")return!0;
554if(Ze.startsWith("{")||Ze.startsWith("["))try{const Be=JSON.parse(Ze);if(Be===null||Array.isArray(Be)&&Be.length===0||typeof Be=="object"&&Object.keys(Be).length===0)return!0}catch{}return!1},Te=Me=>{if(Me==null||Me==="")return!0;if(typeof Me=="string"){const Ze=Me.trim();return Ze===""?!0:ye(Ze)}if(Array.isArray(Me))return Me.length===0;if(Me&&typeof Me=="object"){if(Object.keys(Me).length===0||Me.status==="running"||Me.status==="pending"||Me.__pending||Me.status==="failed"||Me.status==="error")return!0;if("result"in Me){const Ze=Me.result;return!!(Ze==null||Ze===""||typeof Ze=="string"&&ye(Ze)||Array.isArray(Ze)&&Ze.length===0)}return!1}return!1},Ie=Ae&&ie.config?.keywords?.source==="competitors",Oe=(Me,Ze)=>{if(po(ie))return 0;const Be=Math.max(0,Me-1),et=Math.min(T.length,Ze);return T.slice(Be,et).filter(ue=>{if(!Ie&&Pe.length>0&&!(Ae?lo(ue,t,Pe):li(ue,t,Pe)).valid)return!1;const W=ue.cells[ie.id]?.value;return Te(W)}).length},J=(Me,Ze)=>{if(po(ie))return 0;const Be=Math.max(0,Me-1),et=Math.min(T.length,Ze);return T.slice(Be,et).filter(ue=>!Ie&&Pe.length>0?(Ae?lo(ue,t,Pe):li(ue,t,Pe)).valid:!0).length},re=Oe(1,T.length),Se=ve===0;["ai","keywords","ai_keywords","webflow","shopify","seo_action"].includes(ie.type);const je=t.findIndex(Me=>["ai","keywords","ai_keywords","webflow","shopify","seo_action"].includes(Me.type)),he=ve===je;let Re;return Se&&(Re="column-header-first"),he&&(Re=Re?`${Re} column-run-btn-first`:"column-run-btn-first"),e.jsx(jk,{col:ie,allColumns:t,onReorder:n,onApplyColumnOrder:o,onUpdate:l,onDelete:c,availableRowCount:re,totalRowCount:T.length,getAvailableRowCountForRange:Oe,getRunnableRowCountForRange:J,dataOnboarding:Re,onBatchRun:async(Me,Ze)=>{const Be=da();if(!Be){console.error("Campaign ID not found");return}const et=t.find(Ne=>Ne.id===Me);if(et){const Ne=po(et);if(Ne){I("error",Ne,[]);return}}const $e=et?.type||"ai",ue=$e==="keywords"||$e==="ai_keywords",W=ue&&et?.config?.keywords?.source==="competitors",ke=W?[]:et?jr(et):[],qe=Math.max(0,(Ze.startRow||1)-1),Qe=Math.min(T.length,Ze.endRow||T.length),ct=T.slice(qe,Qe);let pt;ke.length>0?pt=ct.filter(Ne=>(ue?lo(Ne,t,ke):li(Ne,t,ke)).valid):pt=ct;const At=!!Ze.overwrite;if(At&&ke.length>0){const Ne=Math.max(0,ct.length-pt.length);if(Ne>0){const Ce=ke.map(De=>t.find(ee=>ee.id===De||ee.system_name===De)?.title||De);I("warning",`Skipped ${Ne} row(s) due to missing dependencies`,[`Required: ${Ce.join(", ")}`],3e3)}}if(pt.length===0){const Ne=ke.map(Ce=>t.find(Ge=>Ge.id===Ce||Ge.system_name===Ce)?.title||Ce);I("error",`No rows available in range ${Ze.startRow}-${Ze.endRow}`,ke.length>0?[`All rows are missing required values in: ${Ne.join(", ")}`]:["No rows found in the specified range"]);return}const te=Ne=>{const Ce=Ne.trim();if(Ce==="{}"||Ce==="[]"||Ce==='""'||Ce==="null")return!0;if(Ce.startsWith("{")||Ce.startsWith("["))try{const De=JSON.parse(Ce);if(De===null||Array.isArray(De)&&De.length===0||typeof De=="object"&&Object.keys(De).length===0)return!0}catch{}return!1},G=Ne=>{if(Ne==null||Ne==="")return!0;if(typeof Ne=="string"){const Ce=Ne.trim();return Ce===""?!0:te(Ce)}if(Array.isArray(Ne))return Ne.length===0;if(typeof Ne=="object"){if(Object.keys(Ne).length===0||Ne.status==="running"||Ne.status==="pending"||Ne.__pending||Ne.status==="failed"||Ne.status==="error")return!0;if("result"in Ne){const Ce=Ne.result;return!!(Ce==null||Ce===""||typeof Ce=="string"&&te(Ce)||Array.isArray(Ce)&&Ce.length===0)}return!1}return!1},pe=At?pt:pt.filter(Ne=>{const Ce=Ne.cells[Me]?.value;return G(Ce)});if(!At&&pe.length===0){I("warning","All rows already have data",["No empty cells to generate. Use Row Range → Run range to regenerate."],3e3);return}const ce=Ze.count||pe.length,Y=Math.min(ce,pe.length),xe=pe.slice(0,Y);if(!At&&ce>pe.length){const Ne=pt.length-pe.length;I("warning",`Only ${pe.length} empty rows available in range`,[`Requested ${ce}, but ${Ne} rows already have data (skipped)`],3e3)}const Ee=xe.map(Ne=>Ne.id);if(W)try{const Ne=et?.config?.keywords?.competitor_domain,De=((await Cc(Ne))?.keywords||[]).map(Ct=>(Ct?.keyword??"").toString().trim()).filter(Ct=>Ct.length>0);if(De.length===0){I("warning","No competitor keywords available",["Please configure keywords in SEO Keywords Ranking first."],3e3);return}const Ge=xe[0],ee=T.findIndex(Ct=>Ct.id===Ge.id),Fe=Ct=>{if(Array.isArray(Ct)&&Ct.length>0){const cs=Ct[0];
554return typeof cs=="string"?cs.trim():null}if(typeof Ct=="string"&&Ct.trim())return Ct.trim();if(typeof Ct=="object"&&Ct?.result){const cs=Ct.result;if(Array.isArray(cs)&&cs.length>0&&typeof cs[0]=="string")return cs[0].trim();if(typeof cs=="string"&&cs.trim())return cs.trim()}return null};let Xe=null;if(ee>0)for(let Ct=ee-1;Ct>=0;Ct--){const cs=T[Ct]?.cells?.[Me]?.value,xa=Fe(cs);if(xa){Xe=xa;break}}const yt=Ct=>Ct.trim().toLowerCase(),ut=Xe?De.findIndex(Ct=>yt(Ct)===yt(Xe)):-1,It=ut>=0?(ut+1)%De.length:0;xe.forEach((Ct,cs)=>{const xa=De[(It+cs)%De.length];a(Ct.id,Me,[xa])}),I("info",`Filled ${xe.length} rows`,[],2e3);return}catch(Ne){console.error("Competitors keywords bulk fill error:",Ne),I("error","Failed to fill competitors keywords",[Ne?.message||"Unknown error"]);return}xe.forEach(Ne=>{$e==="webflow"||$e==="shopify"?a(Ne.id,Me,{status:"publishing",__pending:!0}):$e==="seo_action"?a(Ne.id,Me,{status:"executing",__pending:!0}):a(Ne.id,Me,{status:"running",result:null})});try{let Ne;if($e==="keywords"||$e==="ai_keywords"){const Ce={};if(ke.length>0)for(const De of xe){const Ge={};for(const ee of ke){const Fe=t.find(Xe=>Xe.id===ee||Xe.system_name===ee);if(Fe){const Xe=De.cells[Fe.id]?.value;if(Xe!=null&&Xe!==""){const yt=Fe.system_name||Fe.title;Ge[yt]=typeof Xe=="object"&&Xe.result?Xe.result:Xe}}}Object.keys(Ge).length>0&&(Ce[De.id]={dependencies:Ge})}Ne=await Vt.generateKeywordsValue({campaign_id:Be,column_id:Me,row_ids:Ee,row_data_map:Object.keys(Ce).length>0?Ce:void 0})}else if($e==="webflow"||$e==="shopify"||$e==="seo_action"){const Ce=$e==="shopify"?await Vt.publishShopifyAsync({campaign_id:Be,column_id:Me,row_ids:Ee}):$e==="webflow"?await Vt.publishWebflowAsync({campaign_id:Be,column_id:Me,row_ids:Ee}):await Vt.executeSEOActionAsync({campaign_id:Be,column_id:Me,row_ids:Ee});Ce.failed_count>0?I(Ce.pending_count>0?"warning":"error",`Enqueued ${Ce.pending_count} tasks, failed ${Ce.failed_count}`):I("info",`Enqueued ${Ce.pending_count} tasks`),Ce.results?.forEach(De=>{const Ge=De.original_row_id||De.row_id;if(De.status==="pending"&&De.placeholder){const ee={...De.placeholder,__real_row_id:De.row_id,__original_row_id:De.original_row_id};a(Ge,Me,ee)}else if(De.status==="failed"){const ee=De.error||($e==="seo_action"?"SEO Action failed":"Publish failed");a(Ge,Me,{status:"failed",error:ee})}else De.status==="skipped"&&a(Ge,Me,{status:"skipped"})})}else Ne=await Vt.generateAIValue({campaign_id:Be,column_id:Me,row_ids:Ee});Ne&&Ne.results&&Ne.results?.forEach(Ce=>{const De=Ce.original_row_id||Ce.row_id;if(Ce.status==="pending"&&Ce.placeholder){const Ge={...Ce.placeholder,__real_row_id:Ce.row_id,__original_row_id:Ce.original_row_id};a(De,Me,Ge)}else Ce.status==="failed"&&a(De,Me,{status:"error",result:Ce.error||"Generation failed"})})}catch(Ne){console.error("Batch AI generation error:",Ne),xe.forEach(Ce=>{a(Ce.id,Me,{status:"error",result:Ne?.message||"Generation failed"})})}}},ie.id)}),e.jsx($k,{onAdd:i}),e.jsx("th",{className:"border-b border-gray-200 bg-gray-50/50 w-full h-10 min-h-[40px]"})]})}),e.jsx("tbody",{className:"bg-white",children:T.map((ie,ve)=>e.jsxs("tr",{className:"group border-b-2 border-gray-200 transition-colors",children:[e.jsx("td",{className:"w-12 px-0 py-0 border-r-2 border-gray-200 text-center bg-gray-50/30 group-hover:bg-gray-100 sticky left-0 z-10 h-9 min-h-[36px]",children:e.jsx("div",{className:"text-[10px] text-gray-400 font-mono h-full flex items-center justify-center",children:ve+1})}),j.map(we=>e.jsx(Bk,{rowId:ie.id,col:we,data:ie.cells[we.id]||{value:""},row:ie,columns:t,onUpdate:a},`${ie.id}_${we.id}`)),e.jsx("td",{className:"px-4 py-2 h-9 min-h-[36px]"}),e.jsx("td",{className:"h-9 min-h-[36px]"})]},ie.id))})]})}),X&&!N&&e.jsxs("div",{className:"flex h-full",children:[e.jsx("div",{className:"flex-none flex items-center cursor-pointer group/handle",onClick:()=>V(null),title:"Close sidebar",children:e.jsx("div",{className:"w-4 h-12 bg-gray-400/40 hover:bg-gray-500/50 rounded-l-full flex items-center justify-center transition-all duration-200 group-hover/handle:w-5 group-hover/handle:shadow-lg -mr-px",style:{backdropFilter:"blur(4px)"},children:e.jsx(Qn,{size:12,className:"text-gray-600 group-hover/handle:text-gray-700 transition-colors"})})}),e.jsx(Vc,{expandedCell:X,onUpdate:ze,onClose:()=>V(null),allColumns:t,onUpdateColumn:l,onDeleteColumn:c}
554)]}),!X&&e.jsx("div",{className:"flex-none flex items-center cursor-pointer group/handle",style:{position:"absolute",right:0,top:"50%",transform:"translateY(-50%)",zIndex:50},onClick:()=>{if(k.anchorCell){const{rowId:ie,colId:ve}=k.anchorCell;ge(ie,ve)}else T.length>0&&t.length>0&&ge(T[0].id,t[0].id)},title:"Open sidebar",children:e.jsx("div",{className:"w-4 h-12 bg-gray-400/40 hover:bg-gray-500/50 rounded-l-full flex items-center justify-center transition-all duration-200 group-hover/handle:w-5 group-hover/handle:shadow-lg",style:{backdropFilter:"blur(4px)"},children:e.jsx(cn,{size:12,className:"text-gray-600 group-hover/handle:text-gray-700 transition-colors"})})}),x&&u&&g&&w&&_&&e.jsx(Gc,{col:g,allColumns:t,onClose:_,onUpdate:l,updateAIConfig:()=>{},mode:"create",onCreate:w})]})})},ec=r.forwardRef(({icon:t,label:s,onClick:a,active:n,badge:o},i)=>e.jsxs("button",{ref:i,onClick:a,className:`flex items-center gap-1.5 px-2.5 py-1.5 rounded-md text-xs font-medium transition-all ${n?"bg-gray-100 text-gray-900 border border-gray-300":"text-gray-600 hover:bg-gray-100 border border-transparent hover:border-gray-200"}`,children:[e.jsx(t,{size:14,className:n?"text-gray-700":"text-gray-500"}),s,o!==void 0&&o>0&&e.jsx("span",{className:"ml-1 px-1.5 py-0.5 text-[10px] font-medium bg-gray-200 text-gray-700 rounded-full",children:o})]}));ec.displayName="ToolbarBtn";const d1=[{target:'[data-onboarding="sheet-tabs"]',content:e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-semibold text-slate-900 mb-2",children:"View Tabs"}),e.jsx("p",{className:"text-sm text-slate-600 mb-2",children:"Each table supports multiple views. Click tabs to switch between different data configurations."}),e.jsxs("p",{className:"text-sm text-slate-600",children:["Use ",e.jsx("span",{className:"font-medium",children:"+"})," to add new views."]})]}),placement:"top",disableBeacon:!0,interactive:!0,actionHint:"Click on the tabs area to continue"},{target:'[data-onboarding="add-column-btn"]',content:e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-semibold text-slate-900 mb-2",children:"Add Column"}),e.jsx("p",{className:"text-sm text-slate-600 mb-2",children:"Available column types:"}),e.jsxs("ul",{className:"text-sm text-slate-600 space-y-0.5 list-disc list-inside",children:[e.jsxs("li",{children:[e.jsx("span",{className:"font-medium",children:"Text"})," - Plain text input"]}),e.jsxs("li",{children:[e.jsx("span",{className:"font-medium",children:"AI"})," - AI-generated content"]}),e.jsxs("li",{children:[e.jsx("span",{className:"font-medium",children:"Keywords"})," - SEO keywords"]}),e.jsx("li",{children:"URL, Number, Image, and more"})]})]}),placement:"right",disableBeacon:!0,interactive:!0,actionHint:"Click the + button to add a column"},{target:'[data-onboarding*="column-header-first"]',content:e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-semibold text-slate-900 mb-2",children:"Column Settings"}),e.jsx("p",{className:"text-sm text-slate-600 mb-2",children:"Click any column header to configure:"}),e.jsxs("ul",{className:"text-sm text-slate-600 space-y-0.5 list-disc list-inside",children:[e.jsx("li",{children:"AI prompts and model settings"}),e.jsx("li",{children:"Column dependencies"}),e.jsx("li",{children:"Width adjustment or deletion"})]}),e.jsx("p",{className:"text-sm text-slate-600 mt-2",children:"Drag headers to reorder columns."})]}),placement:"bottom",disableBeacon:!0,interactive:!0,actionHint:"Click on the column header to see options"},{target:'[data-onboarding*="column-run-btn-first"]',content:e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-semibold text-slate-900 mb-2",children:"Batch Run"}),e.jsx("p",{className:"text-sm text-slate-600 mb-2",children:"The run button executes AI generation on multiple rows simultaneously. Specify row count or range."})]}),placement:"bottom",disableBeacon:!0,interactive:!1},{target:"tbody tr:nth-child(10) td:nth-child(2)",content:e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-semibold text-slate-900 mb-2",children:"Detail Sidebar"}),e.jsx("p",{className:"text-sm text-slate-600 mb-2",children:"Double-click any cell to open the detail sidebar:"}),e.jsxs("ul",{className:"text-sm text-slate-600 space-y-0.5 list-disc list-inside",children:[e.jsx("li",{children:"View full content (Markdown/HTML)"}),e.jsx("li",{children:"Edit in expanded view"}),e.jsx("li",{children:"Access column settings"})]}),e.jsxs("p",{className:"text-sm text-slate-600 mt-2",children:["Press ",e.jsx("span",{className:"font-medium",children:"ESC"})," to close."]})]}),placement:"right",disableBeacon:!0,interactive:!0,interactionType:"dblclick",actionHint:"Double-click this cell to open the sidebar",keepOpenAfterInteraction:!0},{target:"body",content:e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-semibold text-slate-900 mb-2",children:"Additional Features"}),e.jsxs("ul",{className:"text-sm text-slate-600 space-y-1.5",children:[e.jsxs("li",{children:[e.jsx("span",{className:"font-medium",children:"Search"})," - Find data quickly"]}),e.jsxs("li",{children:[e.jsx("span",{className:"font-medium",children:"Filter/Sort"})," - Organize your data"]}),e.jsxs("li",{children:[e.jsx("span",{className:"font-medium",children:"Export"})," - CSV, Excel, JSON formats"]}),e.jsxs("li",{children:[e.jsx("span",{className:"font-medium",children:"Save as Template"})," - Reuse column configurations"]})]}),e.jsxs("p",{className:"text-sm text-slate-600 mt-3",children:["Click ",e.jsx("span",{className:"font-medium",children:"?"})," to restart this guide."]})]}),placement:"center",disableBeacon:!0,interactive:!1}],m1=({title:t="New Table Demo",subtitle:s="seo-poster / table / demo",noViews:a=!1,onAddTable:n})=>{const{toast:o}=_t(),[i,l]=r.useState([]),[c,d]=r.useState([]),[m,h]=r.useState(!0),[p,f]=r.useState(""),{runOnboarding:b,startOnboarding:y,completeOnboarding:x}=Uv({isLoading:m});r.useEffect(()=>{const oe=()=>{y()};return window.addEventListener("restartTableOnboarding",oe),()=>{window.removeEventListener("restartTableOnboarding",oe)}},[y]);const[u,g]=r.useState([]),[w,_]=r.useState(null),[E,N]=r.useState(!1),[S,k]=r.useState(!1),D=r.useRef(null),F=r.useRef(null),[R,L]=r.useState(null),[$,H]=r.useState(null),[K,X]=r.useState(()=>da()||""),[V,P]=r.useState([]),[A,C]=r.useState(!1),[I,j]=r.useState([]),[q,T]=r.useState(!1),[M,Z]=r.useState(null),[B,ae]=r.useState(null),[de,fe]=r.useState([]),[se,z]=r.useState(null),[U,Q]=r.useState(null),[me,le]=r.useState(!1),[O,ne]=r.useState(null),[ge,ze]=r.useState(!1),Ke=r.useRef(null),[ie,ve]=r.useState(null),[we,Pe]=r.useState([]),[Ae,ye]=r.useState(()=>new Set),[Te,Ie]=r.useState(!1),Oe=r.useRef(null),[J,re]=r.useState(null),[Se,je]=r.useState(!1),[he,Re]=r.useState(""),[Me,Ze]=r.useState([]),Be=r.useRef(null),et=r.useRef([]),$e=r.useRef(new Map);r.useEffect(()=>{ne(oe=>{if(!oe)return oe;const Ve=(typeof oe.rowId=="string"&&oe.rowId.startsWith("empty_")?$e.current.get(oe.rowId):null)||oe.rowId,Ye=c.find(xt=>xt.id===Ve),rt=i.find(xt=>xt.id===oe.colId)||oe.col;if(!Ye)return oe;const nt=oe.row!==Ye||oe.rowId!==Ye.id,lt=oe.col!==rt;return!nt&&!lt?oe:{...oe,rowId:Ye.id,row:Ye,col:rt}})},[c,i]);const ue=r.useRef(!1);r.useEffect(()=>{if(!ue.current&&c.length>0&&i.length>0&&!O){ue.current=!0;const oe=c[0],_e=i[0];ne({rowId:oe.id,colId:_e.id,row:oe,col:_e})}},[c,i,O]);const[W,ke]=r.useState(!1),[qe,Qe]=r.useState(""),[ct,pt]=r.useState(!1),[At,te]=r.useState(!1),[G,pe]=r.useState(!1),[ce,Y]=r.useState(""),[xe,Ee]=r.useState(!1),[Ne,Ce]=r.useState("single"),[De,Ge]=r.useState(""),[ee,Fe]=r.useState(""),[Xe,yt]=r.useState(!1),[ut,It]=r.useState(!1),[Ct,cs]=r.useState(!1),[xa,zs]=r.useState(!1),[hn,Ls]=r.useState(!1),la=V.find(oe=>oe.id===K),pn=r.useCallback(oe=>{if(!oe||oe.size===0){Pe([]),ye(new Set);return}ye(new Set(oe));const _e=new Set;oe.forEach(Ye=>{const rt=Ye.indexOf(":");rt>-1&&rt<Ye.length-1&&_e.add(Ye.slice(rt+1))});const Ve=i.filter(Ye=>_e.has(Ye.id)).map(Ye=>Ye.id);Pe(Ve)},[i]),gn=r.useCallback(()=>{const oe=Oe.current;if(!oe)return;const _e=oe.getBoundingClientRect();re({top:_e.bottom+8,left:_e.right-260}),Ie(!0)},[]),$s=r.useCallback(()=>{Ie(!1),re(null)},[]);r.useEffect(()=>{const oe=Ve=>{if(Ve.reason&&(Ve.reason.message?.includes("Extension context invalidated")||Ve.reason.message?.includes("extension"))){Ve.preventDefault(),console.warn("Caught browser extension error:",Ve.reason.message);return}},_e=Ve=>{if(Ve.filename?.includes("extensions/")||Ve.filename?.includes("all-frames.js")||Ve.message?.includes("Extension context invalidated")){Ve.preventDefault(),console.warn("Caught browser extension error:",Ve.message);return}};return window.addEventListener("unhandledrejection",oe),window.addEventListener("error",_e),()=>{window.removeEventListener("unhandledrejection",oe),window.removeEventListener("error",_e)}},[]),r.useEffect(()=>{const oe=()=>{const _e=da()||"";X(_e);const Ve=new URLSearchParams(window.location.search);Z(Ve.get("view"))};return window.addEventListener("popstate",oe),oe(),()=>window.removeEventListener("popstate",oe)},[]),r.useEffect(()=>{(async()=>{C(!0);try{const _e=await lr({page:1,page_size:1e3});P(_e.items.map(Ve=>({id:Ve.id,name:Ve.name})))}catch(_e){console.error("Failed to load campaigns:",_e),P([])}finally{C(!1)}})()},[]),r.useEffect(()=>{if(!K||ut||!de.some(Ye=>{if(Ye?.type==="webflow")return!0;const rt=Ye?.config?.url;return rt?.mode==="integration"&&rt?.integration_type==="webflow"}))return;const _e=`webflow_collections_domains_fetched:${K}`;if(typeof window<"u")try{if(sessionStorage.getItem(_e)==="1")return}catch{}(async()=>{try{if(!(await Cu())?.exists)return;const rt=await Mi.getCollectionTypes();if(typeof window<"u"&&Array.isArray(rt.customDomains)&&rt.customDomains.length>0)try{sessionStorage.setItem("webflow_custom_domains",JSON.stringify(rt.customDomains))}catch{}if(typeof window<"u")try{sessionStorage.setItem(_e,"1")}catch{}}catch(Ye){try{const rt=Ye,nt=rt?.errorInfo?.statusCode,lt=String(rt?.message||"");(nt===404||lt.includes("Not installedHook"))&&(cs(!0),It(!0))}catch{}console.debug("Skip webflow collections/domains:",Ye)}})()}
554,[K,de,ut]);const Ea=r.useCallback(async()=>{if(!K)return[];T(!0);try{const oe=await Wt.listViewConfigs({campaign_id:K});return j(oe.items),oe.items}catch(oe){return console.error("Failed to load views:",oe),j([]),[]}finally{T(!1)}},[K]);r.useEffect(()=>{if(!K){j([]);return}(async()=>{const _e=await Ea();if(!new URLSearchParams(window.location.search).get("view")&&_e.length>0){const rt=_e[0];Z(rt.id),jt("table-new",{campaign:K,view:rt.id})}})()},[K,Ea]);const Aa=r.useRef(null);r.useEffect(()=>{if(!K||!M)return;if(I.some(Ye=>Ye.id===M)){Aa.current=null;return}if(q)return;const oe=Aa.current;if(oe&&oe.viewId===M&&oe.attempts>=2)return;Aa.current={viewId:M,attempts:oe&&oe.viewId===M?oe.attempts+1:1};let _e=!1;return(async()=>{const Ye=await Ea();_e||Ye.some(rt=>rt.id===M)||window.setTimeout(()=>{_e||Ea()},400)})(),()=>{_e=!0}},[K,M,Ea,I,q]),r.useEffect(()=>{if(!M){ae(null);return}(async()=>{try{const _e=await Wt.getViewConfig(M);ae(_e)}catch(_e){console.error("Failed to load view config:",_e),ae(null)}})()},[M]),r.useEffect(()=>{if(!K||!M||!B){fe([]);return}(async()=>{try{const Ve=(await Vt.listColumns({campaign_id:K,view_config_id:M,is_active:!0,include_system_columns:!0,include_config:!0})).items||[];Ve.sort((Ye,rt)=>{const nt=Ye.display_order??999999,lt=rt.display_order??999999;return nt-lt}),fe(Ve)}catch(_e){console.error("Failed to load dynamic columns:",_e),fe([])}})()},[K,M,B]),r.useEffect(()=>{if(Ct||de.length===0||!de.some(Ye=>Ye.type==="webflow"))return;let _e=!1;return(async()=>{try{const{getWebflowCredentialExists:Ye}=await Bt(async()=>{const{getWebflowCredentialExists:nt}=await Promise.resolve().then(()=>no);return{getWebflowCredentialExists:nt}},void 0),rt=await Ye();_e||(cs(!0),rt.exists||It(!0))}catch(Ye){console.error("Failed to check Webflow integration:",Ye),_e||(cs(!0),It(!0))}})(),()=>{_e=!0}},[de,Ct]),r.useEffect(()=>{if(hn||de.length===0||!de.some(Ye=>Ye.type==="shopify"))return;let _e=!1;return(async()=>{try{const Ye=await bo();if(_e)return;if(!Ye.shops||Ye.shops.length===0){Ls(!0),zs(!0);return}const rt=await Promise.all(Ye.shops.map(async lt=>{try{return await gi(lt.id)}catch{return{...lt,status:"invalid"}}}));if(_e)return;Ls(!0),rt.some(lt=>lt.status==="connected")||zs(!0)}catch(Ye){console.error("Failed to check Shopify integration:",Ye),_e||(Ls(!0),zs(!0))}})(),()=>{_e=!0}},[de,hn]),r.useEffect(()=>{if(!K||!B){l([]),d([]),h(!1);return}(async()=>{h(!0);try{const Ve=[...de].sort((xt,zt)=>{const St=xt.display_order??999999,Mt=zt.display_order??999999;return St-Mt}).map((xt,zt)=>{let St="text";return xt.type in Om?St=Om[xt.type]:xt.type==="ai"||xt.type==="ai_text"?St="ai":xt.type==="select"||xt.type==="status"?St="status":xt.type==="number"?St="number":xt.type==="date"?St="date":xt.type==="checkbox"?St="checkbox":xt.type==="url"&&(St="url"),{id:xt.id,type:St,title:xt.name,width:xt.width||180,system_name:xt.system_name||null,config:xt.config||{},hidden_by_composite:xt.hidden_by_composite||null}});l(Ve);const Ye=B.view_system_name||"custom",rt=await Wt.listMetadata({campaign_id:K,table_type:Ye}),nt=rt.items.map(xt=>
554{const zt={},St=xt.custom_data||{};return Ve.forEach(Mt=>{let Ut=St[Mt.id]??"";if(Mt.type==="url"&&Mt.config?.url?.mode==="integration"){const gt=Mt.config.url,Rt=gt.integration_type;let Xt=null,ms=null;if(Rt==="webflow"&&gt.webflow_source_column_id?(Xt=gt.webflow_source_column_id,ms="site_url_path"):Rt==="shopify"&&gt.shopify_source_column_id&&(Xt=gt.shopify_source_column_id,ms="url"),Ut="",Xt&&ms){const As=St[Xt];if(As&&typeof As=="object"&&As.status==="published"){const Lo=As[ms];Lo&&(Ut=Lo)}}}zt[Mt.id]={value:Ut}}),{id:xt.entity_id,cells:zt,createdAt:xt.created_at||new Date().toISOString()}});nt.sort((xt,zt)=>{const St=rt.items.find(Rt=>Rt.entity_id===xt.id),Mt=rt.items.find(Rt=>Rt.entity_id===zt.id),Ut=St?.display_order??1/0,gt=Mt?.display_order??1/0;return Ut-gt});const lt=ys(nt);if(lt<Ho){const xt=Ho-lt;for(let zt=0;zt<xt;zt++){const St={id:`empty_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,cells:{},createdAt:new Date().toISOString()};Ve.forEach(Mt=>{St.cells[Mt.id]={value:""}}),nt.push(St)}}$e.current.clear(),d(nt)}catch(_e){console.error("Failed to load table data:",_e),l([]),d([]),$e.current.clear()}finally{h(!1)}})()},[K,B,de]);const ha=r.useCallback(()=>{if(ge&&Ke.current){const oe=Ke.current.getBoundingClientRect();ve({top:oe.bottom+4,left:oe.left})}else ve(null)},[ge]);r.useEffect(()=>{if(ha(),ge)return window.addEventListener("scroll",ha,!0),window.addEventListener("resize",ha),()=>{window.removeEventListener("scroll",ha,!0),window.removeEventListener("resize",ha)}},[ge,ha]);const Ln=oe=>{X(oe.id),ze(!1);try{localStorage.setItem("flowwriter.currentCampaign",JSON.stringify({id:oe.id,name:oe.name}))}catch{}jt("table-new",{campaign:oe.id})},zn=async()=>{ze(!0),C(!0);try{const oe=await lr({page:1,page_size:1e3});P(oe.items.map(_e=>({id:_e.id,name:_e.name})))}catch(oe){console.error("Failed to load campaigns:",oe)}finally{C(!1)}},$n=oe=>{Z(oe.id),K&&jt("table-new",{campaign:K,view:oe.id})},pa=r.useCallback(oe=>Object.values(oe.cells).every(_e=>{const Ve=_e.value;return Ve===""||Ve===null||Ve===void 0||Ve===0}),[]),ys=r.useCallback(oe=>{let _e=0;for(let Ve=oe.length-1;Ve>=0&&pa(oe[Ve]);Ve--)_e++;return _e},[pa]),fn=r.useCallback(()=>{d(oe=>{const _e=ys(oe);if(_e<Ho){const Ve=Ho-_e,Ye=[...oe];for(let rt=0;rt<Ve;rt++){const nt={id:`empty_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,cells:{},createdAt:new Date().toISOString()};i.forEach(lt=>{nt.cells[lt.id]={value:""}}),Ye.push(nt)}return Ye}return oe})},[ys,i]),ga=r.useCallback(oe=>{if(!oe||typeof oe!="object")return!1;if(oe.__pending===!0&&typeof oe.__task_id=="string")return!0;const _e=oe.status;return!!(typeof _e=="string"&&["running","pending","publishing","executing"].includes(_e.toLowerCase()))},[]),ur=r.useCallback(oe=>{if(ga(oe))return!0;if(!oe||typeof oe!="object")return!1;const _e=oe.status;return typeof _e=="string"&&_e.toLowerCase()==="waiting"||oe.__pipeline_waiting===!0},[ga]),Ue=1800*1e3,tt=r.useCallback(oe=>{if(!oe||typeof oe!="object")return!1;const _e=oe.status;if(!(typeof _e=="string"&&_e.toLowerCase()==="waiting"||oe.__pipeline_waiting===!0))return!1;const Ye=oe.__pipeline_started_at_ms;return typeof Ye!="number"||Ye<=0?!1:Date.now()-Ye<=Ue},[Ue]),st=r.useCallback(oe=>Object.values(oe.cells).some(_e=>{const Ve=_e?.value;return ga(Ve)||tt(Ve)}),[tt,ga]),ft=r.useCallback(oe=>`worksheet_pipeline_plan:${oe.campaignId}:${oe.tableType}`,[]),ht=r.useCallback(oe=>{try{const _e=localStorage.getItem(ft(oe)),Ve=_e?JSON.parse(_e):[],Ye=Date.now(),rt=1440*60*1e3;return(Array.isArray(Ve)?Ve:[]).filter(nt=>{if(!nt||typeof nt.row_id!="string"||!Array.isArray(nt.column_ids)||nt.column_ids.length===0)return!1;const lt=typeof nt.started_at_ms=="number"?nt.started_at_ms:0;return Ye-lt<=rt})}catch{return[]}},[ft]),Ot=r.useCallback(oe=>{try{localStorage.setItem(ft({campaignId:oe.campaignId,tableType:oe.tableType}),JSON.stringify(oe.items))}catch{}},[ft]),Tt=r.useCallback(oe=>{const _e=new Set(oe.colList.map(nt=>nt.id)),Ve=new Map(oe.planItems.map(nt=>[nt.row_id,nt])),Ye=new Map(Ve);return{nextRows:oe.rowList.map(nt=>{const lt=Ve.get(nt.id);if(!lt)return nt;const xt=(lt.column_ids||[]).filter(Mt=>_e.has(Mt));if(xt.length===0)return Ye.delete(nt.id),nt;
554const zt={...nt.cells};let St=!1;for(let Mt=0;Mt<xt.length;Mt+=1){const Ut=xt[Mt],gt=zt[Ut]?.value,Rt=ga(gt),ms=(gt&&typeof gt=="object"?String(gt.status||"").toLowerCase():"")==="waiting",As=gt==null||gt===""||gt&&typeof gt=="object"&&String(gt.status||"").toLowerCase()==="idle"&&(gt.result===null||gt.result===void 0||gt.result==="");if(Rt||ms){St=!0;continue}if(Mt===0&&lt.first_task_id){As&&(zt[Ut]={value:{__pending:!0,__task_id:lt.first_task_id,__pipeline_id:lt.pipeline_id??null,__pipeline_started_at_ms:typeof lt.started_at_ms=="number"?lt.started_at_ms:Date.now()}},St=!0);continue}Mt>0&&As&&(zt[Ut]={value:{status:"waiting",result:null,__pipeline_waiting:!0,__pipeline_id:lt.pipeline_id??null,__pipeline_step:Mt,__pipeline_started_at_ms:typeof lt.started_at_ms=="number"?lt.started_at_ms:Date.now()}},St=!0)}return St||Ye.delete(nt.id),{...nt,cells:zt}}),remainingItems:Array.from(Ye.values())}},[ga]);r.useEffect(()=>{if(!K||!B)return;const oe=B.view_system_name||"custom",_e=ht({campaignId:K,tableType:oe});_e.length!==0&&d(Ve=>{const Ye=Tt({rowList:Ve,planItems:_e,colList:i});return Ot({campaignId:K,tableType:oe,items:Ye.remainingItems}),Ye.nextRows})},[Tt,i,K,B,ht,Ot]),r.useEffect(()=>{if(!K||!B)return;const oe=B.view_system_name||"custom",_e=Ve=>{const Ye=Ve,rt=Ye?.detail?.payload,nt=Ye?.detail?.response;if(!rt||!nt||String(rt.campaign_id||"")!==String(K)||String(rt.table_type||"")!==String(oe))return;const lt=Date.now(),xt=(nt.results||[]).filter(Ut=>Ut?.status==="started"&&typeof Ut?.row_id=="string").map(Ut=>({row_id:String(Ut.row_id),column_ids:Array.isArray(rt.column_ids)?rt.column_ids.filter(gt=>typeof gt=="string"&&gt.trim()):[],pipeline_id:Ut.pipeline_id??rt.pipeline_id??null,first_task_id:Ut.first_task_id??null,started_at_ms:lt})).filter(Ut=>Ut.column_ids.length>0);if(xt.length===0)return;const zt=ht({campaignId:K,tableType:oe}),St=new Map;for(const Ut of zt)St.set(Ut.row_id,Ut);for(const Ut of xt)St.set(Ut.row_id,Ut);const Mt=Array.from(St.values());Ot({campaignId:K,tableType:oe,items:Mt}),d(Ut=>Tt({rowList:Ut,planItems:Mt,colList:i}).nextRows)};return window.addEventListener(ql,_e),()=>{window.removeEventListener(ql,_e)}},[Tt,i,K,B,ht,Ot]),r.useEffect(()=>{if(!K||!B){Be.current!==null&&(window.clearInterval(Be.current),Be.current=null),et.current=[];return}const oe=[];for(const _e of c){const Ve=_e?.id;!Ve||typeof Ve!="string"||st(_e)&&oe.push(Ve)}if(et.current=oe,oe.length===0){Be.current!==null&&(window.clearInterval(Be.current),Be.current=null);return}if(Be.current===null)return Be.current=window.setInterval(async()=>{try{const _e=et.current;if(_e.length===0)return;const Ve=await Wt.fetchByIds({campaign_id:K,table_type:B.view_system_name||"custom",entity_ids:_e}),Ye=new Map;for(const rt of Ve.items)Ye.set(rt.entity_id,rt);d(rt=>rt.map(nt=>{if(!nt||!nt.id)return nt;const lt=Ye.get(nt.id);if(!lt)return nt;const xt=lt.custom_data||{},zt={...nt.cells};for(const St of Object.keys(zt))if(xt[St]!==void 0){const Mt=xt[St],Ut=zt[St]?.value,gt=ga(Ut),Rt=ga(Mt);Rt&&!gt?zt[St]={value:Mt}:Rt||(zt[St]={value:Mt})}return i.forEach(St=>{if(St.type==="url"&&St.config?.url?.mode==="integration"){const Mt=St.config.url,Ut=Mt.integration_type;let gt=null,Rt=null;if(Ut==="webflow"&&Mt.webflow_source_column_id?(gt=Mt.webflow_source_column_id,Rt="site_url_path"):Ut==="shopify"&&Mt.shopify_source_column_id&&(gt=Mt.shopify_source_column_id,Rt="url"),gt&&Rt){const Xt=xt[gt]||zt[gt]?.value;if(Xt&&typeof Xt=="object"&&Xt.status==="published"){const ms=Xt[Rt];ms&&(zt[St.id]={value:ms})}}}}),{...nt,cells:zt}}))}catch(_e){console.error("Polling error:",_e)}},2e3),()=>{Be.current!==null&&(window.clearInterval(Be.current),Be.current=null)}},[K,B,c,st]);const vt=async(oe,_e,Ve)=>{const Ye=Ve&&typeof Ve=="object"&&Ve.__real_row_id,rt=Ve&&typeof Ve=="object"&&Ve.__original_row_id,nt=Ye&&rt===oe&&oe!==Ye;nt&&rt&&typeof rt=="string"&&rt.startsWith("empty_")&&$e.current.set(rt,Ye);const lt=typeof oe=="string"&&oe.startsWith("empty_"),xt=lt?$e.current.get(oe):null,zt=ur(Ve);let St=null;if(lt&&!xt&&!nt&&K&&B&&!zt)try{const gt=c.find(ms=>ms.id===oe),Rt=gt?c.indexOf(gt)+1:void 0,Xt=await Wt.batchUpdateCustomData({campaign_id:K,table_type:B.view_system_name||"custom",updates:[{entity_id:"",custom_data_updates:{[_e]:Ve},display_order:Rt}]});Xt&&Array.isArray(Xt.created_items)&&Xt.created_items.length>0&&(St=Xt.created_items[0].entity_id,St&&$e.current.set(oe,St))}catch(gt){console.error("Failed to create row:",gt)}const Mt=nt?Ye:St||xt||oe;if(d(gt=>gt.map(Rt=>{if(Rt.id!==oe)return Rt;const Xt=nt?Ye:St||xt||Rt.id;
554return{...Rt,id:Xt,cells:{...Rt.cells,[_e]:{...Rt.cells[_e],value:Ve}}}})),K&&B&&!zt&&!nt&&!(lt&&St))try{await Wt.updateCustomData({campaign_id:K,table_type:B.view_system_name||"custom",entity_id:Mt,updates:{[_e]:Ve}})}catch(gt){console.error("Failed to update cell:",gt)}fn()},Ft=r.useCallback((oe,_e,Ve,Ye)=>{vt(oe,_e,Ve),ne(Ye)},[vt]),ks=async(oe,_e)=>{const Ve=i.findIndex(lt=>lt.id===oe),Ye=i.findIndex(lt=>lt.id===_e);if(Ve===-1||Ye===-1)return;const rt=[...i],[nt]=rt.splice(Ve,1);if(rt.splice(Ye,0,nt),l(rt),K)try{await Vt.updateDisplayOrder({campaign_id:K,table_type:B?.view_system_name||"custom",orders:rt.map((lt,xt)=>({column_id:lt.id,display_order:xt}))})}catch(lt){console.error("Failed to reorder columns:",lt)}},Le=r.useCallback(async oe=>{l(_e=>{const Ve=new Map(_e.map(lt=>[lt.id,lt])),Ye=oe.map(lt=>Ve.get(lt)).filter(Boolean),rt=new Set(Ye.map(lt=>lt.id)),nt=_e.filter(lt=>!rt.has(lt.id));return[...Ye,...nt]}),fe(_e=>{const Ve=new Map(_e.map(lt=>[lt.id,lt])),Ye=[];oe.forEach((lt,xt)=>{const zt=Ve.get(lt);zt&&Ye.push({...zt,display_order:xt})});const rt=new Set(Ye.map(lt=>lt.id)),nt=_e.filter(lt=>!rt.has(lt.id)).map((lt,xt)=>({...lt,display_order:Ye.length+xt}));return[...Ye,...nt]}),K&&await Vt.updateDisplayOrder({campaign_id:K,table_type:B?.view_system_name||"custom",orders:oe.map((_e,Ve)=>({column_id:_e,display_order:Ve}))})},[K,B]);Xi({columns:i});const We=r.useCallback(()=>{try{const oe=we.length>0?i.filter(gt=>we.includes(gt.id)):i,_e=p.trim().toLowerCase(),Ve=_e?c.filter(gt=>Object.values(gt.cells).some(Rt=>String(Rt?.value??"").toLowerCase().includes(_e))):c,Ye=ys(Ve),nt=(Ye>0?Ve.slice(0,Math.max(0,Ve.length-Ye)):Ve).filter(gt=>!pa(gt)),lt=oe.map(gt=>gt.title||gt.id),xt=nt.map(gt=>oe.map(Rt=>Ba(gt,Rt.id))),zt=new Date().toISOString().replace(/[:.]/g,"-"),St=(B?.view_name||"table_export").replace(/[\\/:*?"<>|]+/g,"_").slice(0,80),Mt=mk({headers:lt,rows:xt}),Ut=`${St}_${zt}.csv`;uk({filename:Ut,csvContent:Mt,bom:!0}),o({title:"CSV exported",description:`${nt.length} rows • ${oe.length} columns`})}catch(oe){console.error("Export CSV failed:",oe),o({title:"Export CSV failed",description:oe?.message?String(oe.message):"Unknown error"})}},[i,ys,B?.view_name,pa,c,p,we,o]),at=r.useCallback(async oe=>{try{if(!K){o({title:"Export failed",description:"No campaign selected"});return}if(oe==="current"){if(!M){o({title:"Export failed",description:"No view selected"});return}o({title:"Exporting Excel...",description:"Please wait while we generate the file"}),await Wt.exportSingleViewToExcel({campaign_id:K,view_id:M}),o({title:"Excel exported",description:`Exported "${B?.view_name||"view"}" successfully`})}else o({title:"Exporting Excel...",description:`Exporting all views in "${la?.name||"campaign"}", please wait...`}),await Wt.exportCampaignAllViewsToExcel({campaign_id:K}),o({title:"Excel exported",description:`Exported all views in "${la?.name||"campaign"}" successfully`})}catch(_e){console.error("Export Excel failed:",_e),o({title:"Export Excel failed",description:_e?.message?String(_e.message):"Unknown error"})}},[la?.name,K,B?.view_name,M,o]),it=r.useCallback(async()=>{if(!K){o({title:"Save failed",description:"No campaign selected"});return}if(!De.trim()){o({title:"Save failed",description:"Please enter a template name"});return}yt(!0);try{await Ww({name:De.trim(),description:ee.trim()||void 0,campaign_id:K,view_id:Ne==="single"&&M||void 0,is_multi_view:Ne
554==="multi"}),o({title:"Template saved",description:`Template "${De}" saved successfully`}),Ee(!1),Ge(""),Fe(""),Ce("single")}catch(oe){console.error("Save template failed:",oe),o({title:"Save template failed",description:oe?.message?String(oe.message):"Unknown error"})}finally{yt(!1)}},[K,M,De,ee,Ne,o]),dt=r.useCallback(()=>{try{if(!Ae||Ae.size===0){We();return}const oe=p.trim().toLowerCase(),_e=oe?c.filter(gt=>i.some(Rt=>Ba(gt,Rt.id).toLowerCase().includes(oe))):c,Ve=new Set,Ye=new Set;Ae.forEach(gt=>{const Rt=gt.indexOf(":");Rt>-1&&Rt<gt.length-1&&(Ye.add(gt.slice(0,Rt)),Ve.add(gt.slice(Rt+1)))});const rt=i.filter(gt=>Ve.has(gt.id)),nt={};for(const gt of rt){const Rt=gt.title||gt.id;nt[Rt]=[]}for(const gt of _e)if(Ye.has(gt.id))for(const Rt of rt){const Xt=`${gt.id}:${Rt.id}`;if(!Ae.has(Xt))continue;const ms=ml(gt,Rt.id);ms!=null&&nt[Rt.title||Rt.id].push(ms)}Object.keys(nt).forEach(gt=>{(!Array.isArray(nt[gt])||nt[gt].length===0)&&delete nt[gt]});const lt=Object.keys(nt);if(lt.length===0){o({title:"Nothing to export",description:"No non-empty selected cells found"});return}const xt=lt.length===1?nt[lt[0]]:nt,zt=new Date().toISOString().replace(/[:.]/g,"-"),Mt=`${(B?.view_name||"table_export").replace(/[\\/:*?"<>|]+/g,"_").slice(0,80)}_custom_${zt}.json`;Um({filename:Mt,data:xt,pretty:!0});const Ut=Array.isArray(xt)?xt.length:Object.values(nt).reduce((gt,Rt)=>gt+Rt.length,0);o({title:"Custom data exported",description:`${lt.length} columns • ${Ut} cells`})}catch(oe){console.error("Export custom data failed:",oe),o({title:"Export custom data failed",description:oe?.message?String(oe.message):"Unknown error"})}},[i,ys,B?.view_name,We,c,p,Ae,o]),Et=r.useCallback(oe=>{try{const _e=oe.length>0?i.filter(Xt=>oe.includes(Xt.id)):i,Ve=Xt=>(Xt||"").trim().length===0,Ye=p.trim().toLowerCase(),rt=Ye?c.filter(Xt=>Object.values(Xt.cells).some(ms=>String(ms?.value??"").toLowerCase().includes(Ye))):c,nt=ys(rt),zt=(nt>0?rt.slice(0,Math.max(0,rt.length-nt)):rt).filter(Xt=>!pa(Xt)).filter(Xt=>{for(const ms of _e){const As=Ba(Xt,ms.id);if(!Ve(As))return!0}return!1});let St;if(_e.length===1){const Xt=_e[0];St=zt.map(As=>ml(As,Xt.id)).filter(As=>As!=null)}else St=zt.map(Xt=>{const ms={};for(const As of _e){const Lo=As.title||As.id;ms[Lo]=ml(Xt,As.id)}return ms});const Mt=Array.isArray(St)?St:[];if(Mt.length===0){o({title:"Nothing to export",description:"No non-empty data found for the selected columns"});return}const Ut=new Date().toISOString().replace(/[:.]/g,"-"),Rt=`${(B?.view_name||"table_export").replace(/[\\/:*?"<>|]+/g,"_").slice(0,80)}_columns_${Ut}.json`;Um({filename:Rt,data:St,pretty:!0}),o({title:"Columns exported",description:`${Mt.length} rows • ${_e.length} columns`})}catch(_e){console.error("Export columns JSON failed:",_e),o({title:"Export columns JSON failed",description:_e?.message?String(_e.message):"Unknown error"})}},[i,ys,B?.view_name,pa,c,p,o]),Dt=r.useCallback(async oe=>{const _e=kr[oe],Ve=new Set;i.forEach(xt=>{xt.title&&Ve.add(xt.title.toLowerCase()),xt.system_name&&Ve.add(xt.system_name.toLowerCase())});let Ye=_e,rt=2;for(;Ve.has(Ye.toLowerCase());)Ye=`${_e} ${rt}`,rt++;let nt={};if(oe==="seo_analysis"){const xt=i.find(zt=>zt.type==="url"&&(zt.config?.url?.mode===void 0||zt.config?.url?.mode==="manual"));xt?nt.seo_analysis={url_source_column:xt.title,url_source_column_id:xt.id,model:"gemini-3-pro",max_steps:5}:nt.seo_analysis={model:"gemini-3-pro",max_steps:5}}if(oe==="seo_action"){const xt={};try{const Ut=((await bo())?.shops||[]).filter(Xt=>Xt.status==="connected"),Rt=(await Mi.getCollectionTypes())?.collections||[];Ut.length>0?(xt.mode="shopify",xt.shop_id=Ut[0].id):Rt.length>0&&(xt.mode="webflow",xt.webflow_collection_slug=Rt[0].slug)}catch{}const zt=i.find(Mt=>Mt.type==="seo_analysis"||Mt.type==="ai_seo_analysis");zt&&(xt.advice_source_column=zt.system_name||zt.title);const St=i.find(Mt=>Mt.type==="url"&&(Mt.config?.url?.mode===void 0||Mt.config?.url?.mode==="manual"));St&&(xt.page_url_column=St.system_name||St.title),nt.seo_action=xt}return oe==="keywords"&&(nt.keywords={model:"gpt-4.1-mini",max_per_cell:10}),oe==="composite"&&(nt.composite={children:[]}),oe==="knowledge"&&(nt.knowledge={multiple:!0}),{id:"",type:oe,title:Ye,width:oe==="composite"?300:180,config:Object.keys(nt).length>0?nt:void 0}}
554,[i]),os=async oe=>{if(!K||!M)return;const _e=await Dt(oe);_e&&(z(oe),Q(_e),le(!0))},ts=async oe=>{if(!K||!M||!se)return!1;try{const _e=await Vt.createColumn({campaign_id:K,table_type:B?.view_system_name||"custom",name:oe.title||kr[se],type:se,view_config_id:M,display_order:i.length,...oe.config?{config:oe.config}:{}}),Ve={id:_e.id,type:se,title:_e.name,width:_e.width||180,system_name:_e.system_name||null,config:_e.config||{},hidden_by_composite:_e.hidden_by_composite||null};if(se==="composite"&&_e.config?.composite?.children){const Ye=_e.config.composite.children.filter(nt=>nt.hide_standalone);for(const nt of Ye)try{await Vt.updateColumn(nt.column_id,{hidden_by_composite:_e.id})}catch(lt){console.error(`Failed to hide child column ${nt.column_id}:`,lt)}const rt=new Set(Ye.map(nt=>nt.column_id));l(nt=>[...nt.map(lt=>rt.has(lt.id)?{...lt,hidden_by_composite:_e.id}:lt),Ve]),fe(nt=>nt.map(lt=>rt.has(lt.id)?{...lt,hidden_by_composite:_e.id}:lt))}else l([...i,Ve]);if(d(c.map(Ye=>({...Ye,cells:{...Ye.cells,[_e.id]:{value:""}}}))),fe(Ye=>[...Ye,_e]),se==="composite"){const rt=(oe.config?.composite?.children?.map(xt=>xt.column_id)||[]).map(xt=>i.findIndex(zt=>zt.id===xt)).filter(xt=>xt>=0),nt=rt.length>0?Math.min(...rt):i.length,lt=[...i.map(xt=>xt.id),_e.id];lt.splice(lt.indexOf(_e.id),1),lt.splice(nt,0,_e.id);try{await Le(lt)}catch(xt){console.error("Failed to apply composite column order:",xt)}}return le(!1),z(null),Q(null),!0}catch(_e){return console.error("Failed to create column:",_e),!1}},Es=r.useCallback(()=>{le(!1),z(null),Q(null)},[]),sa=async(oe,_e)=>{l(Ve=>Ve.map(Ye=>Ye.id===oe?{...Ye,..._e}:Ye));try{const Ve={};_e.title!==void 0&&(Ve.name=_e.title),_e.width!==void 0&&(Ve.width=_e.width),_e.config!==void 0&&(Ve.config=_e.config),_e.hidden_by_composite!==void 0&&(Ve.hidden_by_composite=_e.hidden_by_composite),_e.display_order!==void 0&&(Ve.display_order=_e.display_order),Object.keys(Ve).length>0&&await Vt.updateColumn(oe,Ve),fe(Ye=>Ye.map(rt=>rt.id!==oe?rt:{...rt,name:_e.title!==void 0?_e.title:rt.name,width:_e.width!==void 0?_e.width:rt.width,config:_e.config!==void 0?_e.config:rt.config,hidden_by_composite:_e.hidden_by_composite!==void 0?_e.hidden_by_composite:rt.hidden_by_composite,display_order:_e.display_order!==void 0?_e.display_order:rt.display_order}))}catch(Ve){console.error("Failed to update column:",Ve)}},fa=async oe=>{try{await Vt.deleteColumn(oe),l(_e=>_e.filter(Ve=>Ve.id!==oe)),d(_e=>_e.map(Ve=>{const Ye={...Ve.cells};return delete Ye[oe],{...Ve,cells:Ye}})),fe(_e=>_e.filter(Ve=>Ve.id!==oe))}catch(_e){throw console.error("Failed to delete column:",_e),_e}},hs=()=>{B&&(Qe(B.view_name),ke(!0))},xr=async()=>{if(!qe.trim()||!M){ke(!1);return}try{const oe=await Wt.updateViewConfig(M,{view_name:qe.trim()});ae(oe),j(I.map(_e=>_e.id===M?oe:_e)),ke(!1)}catch(oe){console.error("Failed to update view name:",oe),alert("Failed to update view name. Please try again.")}},Ur=()=>{ke(!1),Qe("")},Jt=()=>{la&&(Y(la.name),pe(!0))},qs=async()=>{if(!ce.trim()||!K){pe(!1);return}try{await Cx(K,{name:ce.trim()}),P(oe=>oe.map(_e=>_e.id===K?{..._e,name:ce.trim()}:_e));try{localStorage.setItem("flowwriter.currentCampaign",JSON.stringify({id:K,name:ce.trim()}))}catch{}pe(!1)}catch(oe){o({title:"Failed to rename worksheet",description:oe?.message||"Please try again"})}},Ta=()=>{pe(!1),Y("")},Fa=async()=>{if(!(!M||!K)){te(!0);try{await Wt.deleteViewConfig(M),j(I.filter(_e=>_e.id!==M)),pt(!1);const oe=I.filter(_e=>_e.id!==M);oe.length>0?jt("table-new",{campaign:K,view:oe[0].id}):jt("campaigns")}catch(oe){console.error("Failed to delete view:",oe),alert("Failed to delete view. Please try again.")}finally{te(!1)}}},yn=async()=>{const oe={id:`new_${Date.now()}`,cells:{},createdAt:new Date().toISOString()};i.forEach(_e=>{oe.cells[_e.id]={value:""}}),d([...c,oe])},Fn=async oe=>{const _e=[];for(let Ve=0;Ve<oe;Ve++){const Ye={id:`new_${Date.now()}_${Ve}`,cells:{},createdAt:new Date().toISOString()};i.forEach(rt=>{Ye.cells[rt.id]={value:""}}),_e.push(Ye)}return d(Ve=>[...Ve,..._e]),_e};return e.jsxs("div",{className:"table-app flex h-full w-full bg-white text-gray-700 font-sans tracking-tight",children:[e.jsxs("div",{className:"flex-1 flex flex-col h-full min-w-0 ",children:[e.jsx(Uc,{steps:d1,run:b,onComplete:x,onSkip:x}),e.jsxs("header",{className:"flex-none h-14 border-b border-gray-200 flex items-center justify-between px-6 bg-white z-20",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{onClick:()=>jt("worksheets"),className:"flex items-center gap-1.5 text-sm font-medium text-gray-500 hover:text-gray-700 transition-colors px-2 py-1 rounded hover:bg-gray-100",children:e.jsx("span",{children:"Worksheets"})}),e.jsx("span",{className:"text-gray-300 text-lg",children:"/"}),G?e.jsx("input",{type:"text",value:ce,onChange:oe=>Y(oe.target.value),onKeyDown:oe=>
554{oe.key==="Enter"?qs():oe.key==="Escape"&&Ta()},onBlur:()=>qs(),className:"text-sm font-medium text-gray-900 border border-gray-300 rounded px-2 py-1 focus:outline-none focus:ring-2 focus:ring-gray-400 w-48",autoFocus:!0}):e.jsxs("button",{ref:Ke,onClick:()=>{ge?ze(!1):zn()},onDoubleClick:oe=>{oe.preventDefault(),ze(!1),Jt()},className:"flex items-center gap-1.5 text-sm font-medium text-gray-700 hover:text-gray-900 transition-colors px-2 py-1 rounded hover:bg-gray-100",title:"Click to switch worksheet, double-click to rename",children:[e.jsx(on,{size:16,className:"text-gray-500"}),e.jsx("span",{children:A?"Loading...":la?.name||"Select Campaign"}),e.jsx(Gs,{size:14,className:"text-gray-400"})]}),e.jsx("span",{className:"text-gray-300 text-lg",children:"/"}),W?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"text",value:qe,onChange:oe=>Qe(oe.target.value),onKeyDown:oe=>{oe.key==="Enter"?xr():oe.key==="Escape"&&Ur()},onBlur:oe=>{const _e=oe.relatedTarget;(!_e||!_e.closest("[data-delete-button]"))&&xr()},className:"text-sm font-medium text-gray-900 border border-gray-300 rounded px-2 py-1 focus:outline-none focus:ring-2 focus:ring-gray-400 w-48",autoFocus:!0}),e.jsx("button",{"data-delete-button":!0,onMouseDown:oe=>{oe.preventDefault()},onClick:oe=>{oe.stopPropagation(),pt(!0)},className:"p-1 hover:bg-red-50 rounded transition-colors",title:"Delete view",children:e.jsx(mt,{size:14,className:"text-red-500"})})]}):e.jsxs("button",{onClick:hs,className:"flex items-center gap-1.5 text-sm font-medium text-gray-900 hover:text-gray-600 transition-colors px-2 py-1 rounded hover:bg-gray-100",title:"Click to edit view name",children:[e.jsx(Zn,{size:16,className:"text-gray-500"}),e.jsx("span",{children:B?.view_name||t})]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-gray-400",children:[e.jsx("div",{className:"w-2 h-2 rounded-full bg-emerald-500 ring-2 ring-emerald-100"}),e.jsx("span",{children:"Auto-saved"})]})]}),ge&&ie&&gs.createPortal(e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[9998]",onClick:()=>ze(!1)}),e.jsxs("div",{className:"fixed w-72 bg-white rounded-lg border border-gray-200 shadow-xl z-[9999] overflow-hidden",style:{top:ie.top,left:ie.left},children:[e.jsx("div",{className:"px-4 py-3 border-b border-gray-100 bg-gray-50",children:e.jsx("div",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Switch Campaign"})}),e.jsxs("div",{className:"max-h-64 overflow-y-auto py-1",children:[A&&e.jsx("div",{className:"px-4 py-3 text-sm text-gray-400",children:"Loading..."}),!A&&V.length===0&&e.jsx("div",{className:"px-4 py-3 text-sm text-gray-400",children:"No campaigns"}),!A&&V.map(oe=>e.jsxs("button",{onClick:()=>Ln(oe),className:`w-full flex items-center justify-between px-4 py-2.5 text-sm hover:bg-gray-50 transition-colors ${oe.id===K?"bg-gray-100":""}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(on,{size:14,className:oe.id===K?"text-gray-700":"text-gray-400"}),e.jsx("span",{className:oe.id===K?"font-medium text-gray-900":"text-gray-700",children:oe.name})]}),oe.id===K&&e.jsx(wt,{size:16,className:"text-gray-600"})]},oe.id))]})]})]}),document.body),E&&R&&gs.createPortal(e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[9998]",onClick:()=>{N(!1),L(null)}}),e.jsxs("div",{className:"fixed w-[460px] bg-white rounded-2xl border border-slate-200 shadow-[0_20px_50px_rgba(0,0,0,0.15)] ring-1 ring-black/5 z-[9999] overflow-hidden transition-all animate-in fade-in zoom-in-95 duration-200",style:{to
554p:R.top+8,left:R.left},children:[e.jsxs("div",{className:"px-6 py-4 border-b border-slate-100 flex items-center justify-between bg-white/80 backdrop-blur-sm sticky top-0 z-10",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-6 h-6 rounded-md bg-blue-50 flex items-center justify-center",children:e.jsx(eo,{size:12,className:"text-blue-600"})}),e.jsx("span",{className:"text-sm font-bold text-slate-800 tracking-tight",children:"Filters"})]}),u.length>0&&e.jsx("button",{onClick:()=>g([]),className:"text-[11px] font-semibold text-slate-400 hover:text-red-500 transition-colors uppercase tracking-wider",children:"Reset"})]}),e.jsx("div",{className:"px-2 py-3 max-h-[400px] overflow-y-auto bg-slate-50/30",children:u.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-10 opacity-40",children:[e.jsx(eo,{size:32,className:"text-slate-300 mb-2"}),e.jsx("p",{className:"text-xs text-slate-500 font-medium",children:"No filters active"})]}):e.jsx("div",{className:"space-y-1",children:u.map((oe,_e)=>e.jsxs("div",{className:"group flex items-center gap-2 px-3 py-2 hover:bg-white hover:shadow-sm rounded-xl transition-all border border-transparent hover:border-slate-200",children:[e.jsxs("select",{value:oe.columnId,onChange:Ve=>{const Ye=[...u];Ye[_e]={...oe,columnId:Ve.target.value},g(Ye)},className:"w-32 px-2 py-1.5 text-xs font-medium border-none bg-slate-100 rounded-md focus:ring-2 focus:ring-blue-100 transition-all cursor-pointer",children:[e.jsx("option",{value:"",children:"Column"}),i.map(Ve=>e.jsx("option",{value:Ve.id,children:Ve.title||Ve.id},Ve.id))]}),e.jsxs("select",{value:oe.operator,onChange:Ve=>{const Ye=[...u];Ye[_e]={...oe,operator:Ve.target.value},g(Ye)},className:"w-28 px-2 py-1.5 text-xs border-none bg-slate-100 rounded-md focus:ring-2 focus:ring-blue-100 transition-all cursor-pointer text-slate-600",children:[e.jsx("option",{value:"contains",children:"contains"}),e.jsx("option",{value:"equals",children:"is"}),e.jsx("option",{value:"not_equals",children:"is not"}),e.jsx("option",{value:"starts_with",children:"starts with"}),e.jsx("option",{value:"ends_with",children:"ends with"}),e.jsx("option",{value:"is_empty",children:"is empty"}),e.jsx("option",{value:"is_not_empty",children:"is not empty"})]}),!["is_empty","is_not_empty"].includes(oe.operator)&&e.jsx("input",{type:"text",value:oe.value,onChange:Ve=>{const Ye=[...u];Ye[_e]={...oe,value:Ve.target.value},g(Ye)},placeholder:"Type value...",className:"flex-1 min-w-0 px-3 py-1.5 text-xs border-none bg-slate-100 rounded-md focus:ring-2 focus:ring-blue-100 transition-all placeholder:text-slate-400"}),e.jsx("button",{onClick:()=>g(u.filter((Ve,Ye)=>Ye!==_e)),className:"opacity-0 group-hover:opacity-100 p-1.5 text-slate-300 hover:text-red-500 hover:bg-red-50 rounded-md transition-all",children:e.jsx(mt,{size:14})})]},oe.id))})}),e.jsx("div",{className:"p-3 border-t border-slate-100 bg-white",children:e.jsxs("button",{onClick:()=>{g([...u,{id:`filter-${Date.now()}`,columnId:i[0]?.id||"",operator:"contains",value:""}])},className:"w-full flex items-center justify-center gap-2 py-2 text-xs font-bold text-blue-600 hover:bg-blue-50 rounded-xl transition-all active:scale-[0.98]",children:[e.jsx($t,{size:14}),"Add filter condition"]})})]})]}),document.body),S&&$&&gs.createPortal(e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[9998]",onClick:()=>{k(!1),H(null)}}),e.jsxs("div",{className:"fixed w-72 bg-white rounded-2xl border border-slate-200 shadow-[0_20px_50px_rgba(0,0,0,0.15)] ring-1 ring-black/5 z-[9999] overflow-hidden transition-all animate-in fade-in zoom-in-95 duration-200",style:{to
554p:$.top+8,left:$.left},children:[e.jsxs("div",{className:"px-5 py-4 border-b border-slate-100 flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-6 h-6 rounded-md bg-amber-50 flex items-center justify-center",children:e.jsx(dn,{size:12,className:"text-amber-600"})}),e.jsx("span",{className:"text-sm font-bold text-slate-800 tracking-tight",children:"Sorting"})]}),w&&e.jsx("button",{onClick:()=>_(null),className:"text-[11px] font-semibold text-slate-400 hover:text-red-500 transition-colors uppercase tracking-wider",children:"Clear"})]}),e.jsx("div",{className:"py-2 max-h-[400px] overflow-y-auto bg-slate-50/30",children:e.jsx("div",{className:"px-2 space-y-0.5",children:i.map(oe=>{const _e=w?.columnId===oe.id;return e.jsxs("button",{onClick:()=>{_(_e?{columnId:oe.id,direction:w.direction==="asc"?"desc":"asc"}:{columnId:oe.id,direction:"asc"})},className:`w-full flex items-center justify-between px-3 py-2.5 rounded-xl text-xs transition-all group ${_e?"bg-white shadow-sm ring-1 ring-slate-200 z-10":"text-slate-600 hover:bg-white hover:shadow-sm"}`,children:[e.jsx("span",{className:`font-medium ${_e?"text-slate-900":"text-slate-600"}`,children:oe.title||oe.id}),_e?e.jsx("div",{className:"flex items-center gap-1.5 px-2 py-0.5 bg-blue-50 text-blue-600 rounded-lg font-bold",children:w.direction==="asc"?e.jsxs(e.Fragment,{children:[e.jsx(Is,{size:12,strokeWidth:3}),e.jsx("span",{className:"text-[9px] uppercase",children:"Asc"})]}):e.jsxs(e.Fragment,{children:[e.jsx(Ws,{size:12,strokeWidth:3}),e.jsx("span",{className:"text-[9px] uppercase",children:"Desc"})]})}):e.jsx("div",{className:"opacity-0 group-hover:opacity-100 transition-opacity",children:e.jsx(Is,{size:12,className:"text-slate-300"})})]},oe.id)})})})]})]}),document.body),e.jsxs("div",{className:"flex-none h-12 border-b border-gray-200 flex items-center justify-between px-6 bg-white z-20 relative","data-onboarding":"table-toolbar",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"relative group",children:[e.jsx(Pt,{className:"absolute left-2.5 top-1/2 transform -translate-y-1/2 text-gray-400",size:14}),e.jsx("input",{type:"text",placeholder:"Search campaigns...",value:p,onChange:oe=>f(oe.target.value),className:"pl-9 pr-3 py-1.5 text-xs w-64 border border-gray-200 rounded-md bg-gray-50 focus:bg-white focus:outline-none focus:border-gray-300 focus:ring-1 focus:ring-gray-100 transition-all placeholder-gray-400 text-gray-700"})]}),e.jsx("div",{className:"w-px h-4 bg-gray-200 mx-2"}),e.jsx(ec,{ref:D,icon:eo,label:"Filter",active:u.length>0,badge:u.length,onClick:()=>{if(E)N(!1),L(null);else{if(D.current){const oe=D.current.getBoundingClientRect();L({top:oe.bottom+4,left:oe.left})}N(!0),k(!1)}}}),e.jsx(ec,{ref:F,icon:dn,label:"Sort",active:w!==null,onClick:()=>{if(S)k(!1),H(null);else{if(F.current){const oe=F.current.getBoundingClientRect();H({top:oe.bottom+4,left:oe.left})}k(!0),N(!1)}}})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("button",{type:"button",onClick:()=>{Ge(""),Fe(""),Ce("single"),Ee(!0)},className:"inline-flex items-center gap-2 px-3 py-1.5 text-xs font-medium rounded-md border border-gray-300 bg-white text-gray-700 hover:bg-gray-50 transition-colors shadow-sm focus:outline-none focus:ring-2 focus:ring-gray-200",title:"Save as template","data-onboarding":"save-template-btn",children:[e.jsx(on,{size:14}),e.jsx("span",{children:"Save as template"})]}),e.jsxs("button",{ref:Oe,type:"button",onClick:()=>{Te?$s():gn()},className:"inline-flex items-center gap-2 px-3 py-1.5 text-xs font-medium rounded-md bg-gray-900 text-white hover:bg-gray-800 transition-colors shadow-sm focus:outline-none focus:ring-2 focus:ring-gray-300",title:"Export data","data-onboarding":"export-btn","data-preserve-selection":!0,children:[e.jsx(Vs,{size:14}),e.jsx("span",{children:"Export data"}),e.jsx(Gs,{size:14,className:"text-gray-300"})]})]})]}),Te&&J&&gs.createPortal(e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[9998]",onClick:()=>$s(),"data-preserve-selection":!0}),e.jsxs("div",{className:"fixed w-64 bg-white rounded-lg border border-gray-200 shadow-xl z-[9999] overflow-hidden",style:{to
554p:J.top,left:J.left},"data-preserve-selection":!0,children:[e.jsx("div",{className:"px-4 py-3 border-b border-gray-100 bg-gray-50",children:e.jsx("div",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Export"})}),e.jsxs("div",{className:"py-1",children:[e.jsxs("button",{onClick:()=>{$s(),We()},className:"w-full flex items-center justify-between px-4 py-2.5 text-sm hover:bg-gray-50 transition-colors text-gray-700",title:"Export all columns to CSV",children:[e.jsx("span",{children:"Export CSV"}),e.jsx("span",{className:"text-[11px] text-gray-400",children:".csv"})]}),e.jsxs("button",{onClick:()=>{Ae.size!==0&&($s(),dt())},className:`w-full flex items-center justify-between px-4 py-2.5 text-sm transition-colors ${Ae.size===0?"text-gray-300 cursor-not-allowed":"text-gray-700 hover:bg-gray-50"}`,title:Ae.size===0?"Select cells first":"Export selected cells as JSON",children:[e.jsx("span",{children:"Export custom data"}),e.jsx("span",{className:"text-[11px] text-gray-400",children:".json"})]}),e.jsxs("button",{onClick:()=>{$s(),Ze(i.map(oe=>oe.id)),Re(""),je(!0)},className:"w-full flex items-center justify-between px-4 py-2.5 text-sm hover:bg-gray-50 transition-colors text-gray-700",title:"Choose columns and export JSON",children:[e.jsx("span",{children:"Export columns data"}),e.jsx("span",{className:"text-[11px] text-gray-400",children:".json"})]}),e.jsx("div",{className:"my-1 border-t border-gray-100"}),e.jsxs("button",{onClick:()=>{$s(),at("current")},className:"w-full flex items-center justify-between px-4 py-2.5 text-sm hover:bg-gray-50 transition-colors text-gray-700",title:"Export current view to Excel",children:[e.jsx("span",{children:"Export Excel (Current View)"}),e.jsx("span",{className:"text-[11px] text-gray-400",children:".xlsx"})]}),e.jsxs("button",{onClick:()=>{$s(),at("all")},className:"w-full flex items-center justify-between px-4 py-2.5 text-sm hover:bg-gray-50 transition-colors text-gray-700",title:"Export all views in current campaign to Excel (each view as a separate sheet)",children:[e.jsx("span",{children:"Export Excel (All Views)"}),e.jsx("span",{className:"text-[11px] text-gray-400",children:".xlsx"})]})]})]})]}),document.body),Se&&gs.createPortal(e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 bg-black/30 z-[9998]",onClick:()=>je(!1)}),e.jsxs("div",{className:"fixed top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 w-full max-w-xl bg-white border border-gray-200 shadow-2xl rounded-lg z-[9999] overflow-hidden",children:[e.jsxs("div",{className:"px-6 py-4 border-b border-gray-200 flex items-center justify-between bg-gray-50",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-semibold text-gray-900",children:"Export columns data"}),e.jsx("div",{className:"text-xs text-gray-500",children:"Select columns to export"})]}),e.jsx("button",{onClick:()=>je(!1),className:"p-2 hover:bg-gray-200 rounded-md transition-colors",title:"Close",children:e.jsx(mt,{size:16,className:"text-gray-600"})})]}),e.jsxs("div",{className:"px-6 py-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"flex-1 relative",children:[e.jsx(Pt,{className:"absolute left-2.5 top-1/2 transform -translate-y-1/2 text-gray-400",size:14}),e.jsx("input",{type:"text",value:he,onChange:oe=>Re(oe.target.value),placeholder:"Search columns...",className:"w-full pl-9 pr-3 py-2 text-sm border border-gray-200 rounded-md bg-white focus:outline-none focus:ring-2 focus:ring-gray-100"})]}),e.jsx("button",{type:"button",onClick:()=>Ze(i.map(oe=>oe.id)),className:"px-3 py-2 text-sm text-gray-700 border border-gray-200 rounded-md hover:bg-gray-50",title:"Select all",children:"Select all"}),e.jsx("button",{type:"button",onClick:()=>Ze([]),className:"px-3 py-2 text-sm text-gray-700 border border-gray-200 rounded-md hover:bg-gray-50",title:"Clear",children:"Clear"})]}),e.jsx("div",{className:"border border-gray-200 rounded-lg max-h-72 overflow-y-auto",children:i.filter(oe=>{const _e=he.trim().toLowerCase();return _e?String(oe.title||"").toLowerCase().includes(_e)||String(oe.system_name||"").toLowerCase().includes(_e):!0}
554).map(oe=>{const _e=Me.includes(oe.id);return e.jsxs("label",{className:"flex items-center gap-3 px-4 py-2.5 border-b border-gray-100 last:border-b-0 hover:bg-gray-50 cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:_e,onChange:Ve=>{const Ye=Ve.target.checked?Array.from(new Set([...Me,oe.id])):Me.filter(rt=>rt!==oe.id);Ze(Ye)}}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"text-sm text-gray-800 truncate",children:oe.title||oe.id}),oe.system_name&&e.jsx("div",{className:"text-[11px] text-gray-400 font-mono truncate",children:oe.system_name})]}),e.jsx("div",{className:"text-[11px] text-gray-400",children:kr[oe.type]||oe.type})]},oe.id)})})]}),e.jsxs("div",{className:"px-6 py-4 border-t border-gray-200 flex items-center justify-between bg-gray-50",children:[e.jsxs("div",{className:"text-xs text-gray-500",children:[Me.length," selected"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{onClick:()=>je(!1),className:"px-3 py-2 text-sm text-gray-700 hover:bg-gray-100 rounded-md transition-colors",children:"Cancel"}),e.jsx("button",{onClick:()=>{Me.length!==0&&(Et(Me),je(!1))},disabled:Me.length===0,className:"px-4 py-2 text-sm font-medium text-white bg-gray-900 hover:bg-gray-800 rounded-md transition-colors disabled:opacity-50 disabled:cursor-not-allowed",children:"Export"})]})]})]})]}),document.body),xe&&gs.createPortal(e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 bg-black/30 z-[9998]",onClick:()=>Ee(!1)}),e.jsxs("div",{className:"fixed top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 w-full max-w-md bg-white border border-gray-200 shadow-2xl rounded-lg z-[9999] overflow-hidden",children:[e.jsxs("div",{className:"px-6 py-4 border-b border-gray-200 flex items-center justify-between bg-gray-50",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-semibold text-gray-900",children:"Save as Template"}),e.jsx("div",{className:"text-xs text-gray-500",children:"Save your table structure for reuse"})]}),e.jsx("button",{onClick:()=>Ee(!1),className:"p-2 hover:bg-gray-200 rounded-md transition-colors",title:"Close",children:e.jsx(mt,{size:16,className:"text-gray-600"})})]}),e.jsxs("div",{className:"px-6 py-4 space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium text-gray-700",children:"What to save"}),e.jsxs("div",{className:"flex gap-3",children:[e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[e.jsx("input",{type:"radio",name:"templateType",value:"single",checked:Ne==="single",onChange:()=>Ce("single"),className:"w-4 h-4 text-gray-900"}),e.jsx("span",{className:"text-sm text-gray-700",children:"Current view"})]}),e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[e.jsx("input",{type:"radio",name:"templateType",value:"multi",checked:Ne==="multi",onChange:()=>Ce("multi"),className:"w-4 h-4 text-gray-900"}),e.jsxs("span",{className:"text-sm text-gray-700",children:["All views (",I.length,")"]})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"text-sm font-medium text-gray-700",children:["Template name ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx("input",{type:"text",value:De,onChange:oe=>Ge(oe.target.value),placeholder:"Enter template name...",className:"w-full px-3 py-2 text-sm border border-gray-200 rounded-md bg-white focus:outline-none focus:ring-2 focus:ring-gray-200 focus:border-gray-300",autoFocus:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"text-sm font-medium text-gray-700",children:["Description"," ",e.jsx("span",{className:"text-gray-400",children:"(optional)"})]}),e.jsx("textarea",{value:ee,onChange:oe=>Fe(oe.target.value),placeholder:"Describe what this template is for...",rows:2,className:"w-full px-3 py-2 text-sm border border-gray-200 rounded-md bg-white focus:outline-none focus:ring-2 focus:ring-gray-200 focus:border-gray-300 resize-none"})]}),e.jsxs("div",{className:"text-xs text-gray-500 bg-gray-50 rounded-md p-3",children:["Templates save the table structure (columns, settings) but not the data.",Ne==="multi"&&e.jsxs("span",{className:"block mt-1 text-amber-600",children:["Multi-view templates will save all ",I.length," views in this spreadsheet."]})]})]}),e.jsxs("div",{className:"px-6 py-4 border-t border-gray-200 flex items-center justify-end gap-2 bg-gray-50",children:[e.jsx("button",{onClick:()=>Ee(!1),className:"px-3 py-2 text-sm text-gray-700 hover:bg-gray-100 rounded-md transition-colors",disabled:Xe,children:"Cancel"}),e.jsxs("button",{onClick:it,disabled:!De.trim()||Xe,className:"px-4 py-2 text-sm font-medium text-white bg-gray-900 hover:bg-gray-800 rounded-md transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2",children:[Xe&&e.jsx(He,{size:14,className:"animate-spin"}),Xe?"Saving...":"Save Template"]})]})]})]}),document.body),m?e.jsx("div",{className:"flex-1 flex items-center justify-center text-gray-400",children:e.jsxs("div",{className:"flex flex-col items-center gap-2",children:[e.jsx(He,{className:"animate-spin",size:24}),e.jsx("span",{className:"text-xs",children:"Loading data..."})]})}):a?e.jsx("div",{className:"flex-1 flex items-center justify-center",children:e.jsxs("div",{className:"text-center max-w-md mx-auto",children:[e.jsx("h2",{className:"text-lg font-semibold text-gray-900 mb-2",children:"No views yet"}),e.jsx("p",{className:"text-sm text-gray-500 mb-4",children:"Create your first table view to start organizing your SEO data."}),e.jsx("button",{className:"px-4 py-2 text-sm bg-gray-900 text-white rounded hover:bg-gray-800",onClick:n,children:"Add table"})]})}):e.jsx(c1,{columns:i,rows:c,onCellUpdate:vt,onColumnReorder:ks,onApplyColumnOrder:Le,onAddColumn:os,onUpdateColumn:sa,onDeleteColumn:fa,onCreateRow:yn,onCreateMultipleRows:Fn,onEnsureEmptyRows:fn,searchQuery:p,filters:u,sortConfig:w,onSelectionChange:pn,showColumnConfigPanel:me,pendingColumnType:se,pendingColumnConfig:U,onCreateColumnFromConfig:ts,onCancelC
554olumnConfig:Es,expandedCell:O,onExpandedCellChange:ne,onDetailUpdate:Ft}),e.jsxs("footer",{className:"flex-none h-9 border-t border-gray-200 flex items-center bg-gray-50/50 text-[10px] text-gray-500 select-none",children:[e.jsxs("div",{className:"flex items-center h-full overflow-x-auto scrollbar-hide","data-onboarding":"sheet-tabs",children:[e.jsx("div",{className:"flex items-center h-full",children:I.map(oe=>e.jsxs("button",{onClick:()=>$n(oe),className:`relative flex items-center gap-1.5 px-4 h-full text-xs font-medium border-r border-gray-200 transition-colors whitespace-nowrap ${oe.id===M?"bg-white text-gray-900 border-t-2 border-t-gray-900":"text-gray-500 hover:text-gray-700 hover:bg-gray-100"}`,children:[e.jsx(Zn,{size:12,className:oe.id===M?"text-gray-700":"text-gray-400"}),e.jsx("span",{children:oe.view_name})]},oe.id))}),e.jsx("button",{type:"button",onClick:()=>{n&&n()},className:"flex items-center justify-center w-8 h-full border-r border-gray-200 text-gray-400 hover:text-gray-600 hover:bg-gray-100 transition-colors",title:"Add new view","data-onboarding":"add-view-btn",children:e.jsx($t,{size:14})})]}),e.jsx("div",{className:"flex-1"}),e.jsxs("div",{className:"flex items-center gap-4 px-4 font-mono",children:[e.jsxs("span",{children:[c.length," ROWS"]}),e.jsxs("span",{children:[i.length," COLUMNS"]})]})]})]}),O&&e.jsxs("div",{className:"flex h-full",children:[e.jsx("div",{className:"flex-none flex items-center cursor-pointer group/handle",onClick:()=>ne(null),title:"Close sidebar",children:e.jsx("div",{className:"w-4 h-12 bg-gray-400/40 hover:bg-gray-500/50 rounded-l-full flex items-center justify-center transition-all duration-200 group-hover/handle:w-5 group-hover/handle:shadow-lg -mr-px",style:{backdropFilter:"blur(4px)"},children:e.jsx(Qn,{size:12,className:"text-gray-600 group-hover/handle:text-gray-700 transition-colors"})})}),e.jsx(Vc,{expandedCell:O,onUpdate:(oe,_e,Ve)=>{vt(oe,_e,Ve),ne(Ye=>!Ye||Ye.rowId!==oe||Ye.colId!==_e?Ye:{...Ye,row:{...Ye.row,cells:{...Ye.row.cells,[_e]:{...Ye.row.cells[_e],value:Ve}}}})},onClose:()=>ne(null),allColumns:i,onUpdateColumn:sa,onDeleteColumn:fa})]}),ct&&gs.createPortal(e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 bg-black/50 z-[9998]",onClick:()=>pt(!1)}),e.jsx("div",{className:"fixed top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 w-full max-w-md bg-white rounded-lg shadow-2xl z-[9999]",children:e.jsxs("div",{className:"px-6 py-5",children:[e.jsx("div",{className:"flex items-center justify-center mb-4",children:e.jsx("div",{className:"w-12 h-12 rounded-full bg-red-100 flex items-center justify-center",children:e.jsx(es,{className:"h-6 w-6 text-red-600"})})}),e.jsx("h3",{className:"text-lg font-semibold text-gray-900 text-center mb-2",children:"Delete View"}),e.jsxs("p",{className:"text-sm text-gray-600 text-center mb-6",children:['Are you sure you want to delete "',B?.view_name,'"? This action cannot be undone.']}),e.jsxs("div",{className:"flex gap-3",children:[e.jsx("button",{onClick:()=>pt(!1),disabled:At,className:"flex-1 px-4 py-2.5 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors disabled:opacity-50",children:"Cancel"}),e.jsx("button",{onClick:Fa,disabled:At,className:"flex-1 px-4 py-2.5 text-sm font-medium text-white bg-red-600 rounded-lg hover:bg-red-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2",children:At?e.jsxs(e.Fragment,{children:[e.jsx(He,{className:"h-4 w-4 animate-spin"}),"Deleting..."]}):"Delete"})]})]})})]}),document.body),ut&&!b&&gs.createPortal(e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 bg-black/40 z-[10000]",onClick:()=>It(!1)}),e.jsx("div",{className:"fixed inset-0 flex items-center justify-center z-[10001] p-4",children:e.jsxs("div",{className:"relative w-full max-w-md",children:[e.jsx("button",{onClick:()=>It(!1),className:"absolute -top-2 -right-2 z-10 w-8 h-8 bg-white rounded-full shadow-lg flex items-center justify-center text-gray-500 hover:text-gray-700 hover:bg-gray-50 transition-colors",title:"Dismiss",children:e.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})}),e.jsx(vh,{onStatusChange:oe=>{oe==="connected"&&It(!1)},fetchButtonText:"Fetch Sites"})]})})]}),document.body),xa&&!b&&gs.createPortal(e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 bg-black/40 z-[
55410000]",onClick:()=>zs(!1)}),e.jsx("div",{className:"fixed inset-0 flex items-center justify-center z-[10001] p-4",children:e.jsxs("div",{className:"relative w-full max-w-md",children:[e.jsx("button",{onClick:()=>zs(!1),className:"absolute -top-2 -right-2 z-10 w-8 h-8 bg-white rounded-full shadow-lg flex items-center justify-center text-gray-500 hover:text-gray-700 hover:bg-gray-50 transition-colors",title:"Dismiss",children:e.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})}),e.jsx(Nh,{})]})})]}),document.body)]})},u1=Array.from({length:25}).map((t,s)=>({id:Eh("row_"),createdAt:new Date().toISOString(),cells:{col_name:{value:s===0?"Q4 Marketing Push":s===1?"Blog Expansion":`Campaign ${2024+s}`},col_url:{value:s===0?"https://rankgale.ai":s===1?"https://asksurf.ai/blog":""},col_status:{value:s===0?"Active":s===2?"Paused":"Draft"},col_analysis:{value:s===0?"Score: 92/100":""},col_keywords:{value:s===0?"ai seo, ranking tools":""},col_budget:{value:s===0?5e3:0}}})),x1=Array.from({length:10}).map(()=>({id:Eh("row_"),createdAt:new Date().toISOString(),cells:{col_name:{value:""},col_url:{value:""},col_status:{value:""},col_analysis:{value:""},col_keywords:{value:""},col_budget:{value:0}}}));[...u1,...x1];function h1(){const{toast:t}=_t(),a=new URLSearchParams(window.location.search).get("workflow")||"seo",n=a==="aeo-geo",o=a==="content-refresh",i=n||o,[l]=r.useState([{id:"col_keywords",title:"Keywords or Keywords group",type:"text",width:350},{id:"col_topic",title:"Topic",type:"text",width:250},{id:"col_context",title:"Context",type:"text",width:350},{id:"col_content",title:"Content",type:"text",width:400},{id:"col_score",title:"Score",type:"text",width:200},{id:"col_publish",title:"Publish",type:"text",width:150}]),c=[{id:"keyword_optimization",label:"Keyword Optimization",maxScore:25},{id:"content_quality",label:"Content Quality",maxScore:25},{id:"seo_best_practices",label:"SEO Best Practices",maxScore:25},{id:"readability",label:"Readability",maxScore:25}],d=[{id:"ai_visibility",label:"AI Visibility",maxScore:30},{id:"prompt_relevance",label:"Prompt Relevance",maxScore:25},{id:"citation_quality",label:"Citation Quality",maxScore:25},{id:"content_quality",label:"Content Quality",maxScore:20}],m=()=>n?d:c,h=()=>m().reduce((R,L)=>R+L.maxScore,0),[p,f]=r.useState([]),[b,y]=r.useState(""),[x,u]=r.useState(null);r.useEffect(()=>{try{const R=sessionStorage.getItem("prototype_content_data");if(R){const $=JSON.parse(R).map((H,K)=>{const X=H.type==="group"&&H.keywords?JSON.stringify({type:"group",name:H.name,keywords:H.keywords}):H.name||H.keyword||"",V=i?{companyInfo:"",referenceLink:"",productInfo:"",knowledgeBase:"",trackingHistory:"",aiCitation:""}:{companyInfo:"",referenceLink:"",productInfo:"",knowledgeBase:""},P=H.context?JSON.stringify(H.context):JSON.stringify(V),A=H.content?JSON.stringify(H.content):JSON.stringify({title:"",slug:"",body:""}),C=m(),I={};
554return C.forEach(j=>{I[j.id]=0}),I.total=0,{id:`row_${Date.now()}_${K}`,createdAt:new Date().toISOString(),cells:{col_keywords:{value:X},col_topic:{value:H.topic||""},col_context:{value:P},col_content:{value:A},col_score:{value:H.score?JSON.stringify(H.score):JSON.stringify(I)},col_publish:{value:"Draft"}}}});f($),sessionStorage.removeItem("prototype_content_data")}else f([])}catch(R){console.error("Failed to load prototype data:",R),f([])}},[]);const g=(R,L,$)=>{f(H=>H.map(K=>K.id===R?{...K,cells:{...K.cells,[L]:{value:$}}}:K))},w=(R,L,$,H)=>{g(R,L,$),u(H)},_=R=>{if(!R)return e.jsx("span",{className:"text-gray-400",children:"-"});try{const L=typeof R=="string"?JSON.parse(R):R;return L.type==="group"&&L.keywords?e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("span",{className:"font-medium text-slate-900",children:L.name}),e.jsx("div",{className:"flex flex-wrap gap-1",children:L.keywords.map(($,H)=>e.jsx("span",{className:"text-xs px-2 py-0.5 bg-slate-100 text-slate-600 rounded",children:$},H))})]}):e.jsx("span",{className:"text-slate-900",children:L.name||L.keyword||R})}catch{return e.jsx("span",{className:"text-slate-900",children:R})}},E=R=>R?e.jsx("span",{className:"text-slate-900",children:R}):e.jsx("span",{className:"text-gray-400",children:"-"}),N=R=>{if(!R)return e.jsx("span",{className:"text-gray-400",children:"-"});try{const $=(typeof R=="string"?JSON.parse(R):R).total||0,H=h(),K=H>0?Math.round($/H*100):0;let X="text-gray-600",V="bg-gray-100";return K>=80?(X="text-green-700",V="bg-green-100"):K>=60?(X="text-blue-700",V="bg-blue-100"):K>=40?(X="text-yellow-700",V="bg-yellow-100"):(X="text-red-700",V="bg-red-100"),e.jsx("div",{className:`inline-flex items-center justify-center px-3 py-1 rounded-lg ${V}`,children:e.jsxs("span",{className:`text-sm font-semibold ${X}`,children:[$,"/",H]})})}catch{return e.jsx("span",{className:"text-gray-400",children:"-"})}},S=R=>{try{const L=typeof R=="string"&&R?JSON.parse(R):R||{},$=[{label:"Company Info",value:L.companyInfo||""},{label:"Reference link",value:L.referenceLink||""},{label:"Product Info",value:L.productInfo||""},{label:"Knowledge base",value:L.knowledgeBase||""}],H=i?[{label:"Tracking History",value:L.trackingHistory||""},{label:"AI Citation",value:L.aiCitation||""}]:[],K=[...$,...H];return e.jsx("div",{className:"flex flex-col gap-2 py-2 text-sm",children:K.map((X,V)=>e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsxs("div",{className:"text-gray-700",children:[e.jsxs("span",{className:"font-medium text-gray-900",children:[X.label,":"]})," ",e.jsx("span",{className:"text-gray-600",children:X.value?X.value.length>50?`${X.value.substring(0,50)}...`:X.value:e.jsx("span",{className:"text-gray-400 italic",children:"-"})})]}),V<K.length-1&&e.jsx("div",{className:"border-t border-gray-200 my-1"})]},V))})}catch{return e.jsxs("div",{className:"flex flex-col gap-2 py-2 text-sm",children:[e.jsxs("div",{className:"text-gray-700",children:[e.jsx("span",{className:"font-medium text-gray-900",children:"Company Info:"})," ",e.jsx("span",{className:"text-gray-400 italic",children:"-"})]}),e.jsx("div",{className:"border-t border-gray-200 my-1"}),e.jsxs("div",{className:"text-gray-700",children:[e.jsx("span",{className:"font-medium text-gray-900",children:"Reference link:"})," ",e.jsx("span",{className:"text-gray-400 italic",children:"-"})]}),e.jsx("div",{className:"border-t border-gray-200 my-1"}),e.jsxs("div",{className:"text-gray-700",children:[e.jsx("span",{className:"font-medium text-gray-900",children:"Product Info:"})," ",e.jsx("span",{className:"text-gray-400 italic",children:"-"})]}),e.jsx("div",{className:"border-t border-gray-200 my-1"}),e.jsxs("div",{className:"text-gray-700",children:[e.jsx("span",{className:"font-medium text-gray-900",children:"Knowledge base:"})," ",e.jsx("span",{className:"text-gray-400 italic",children:"-"})]})]})}},k=R=>{try{const L=typeof R=="string"&&R?JSON.parse(R):R||{},$=[{label:"Title",value:L.title||""},{label:"Slug",value:L.slug||""},{label:"Body",value:L.body||""}];return e.jsx("div",{className:"flex flex-col gap-2 py-2 text-sm",children:$.map((H,K)=>e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsxs("div",{className:"text-gray-700",children:[e.jsxs("span",{className:"font-medium text-gray-900",children:[H.label,":"]}
554)," ",e.jsx("span",{className:"text-gray-600",children:H.value?H.value.length>60?`${H.value.substring(0,60)}...`:H.value:e.jsx("span",{className:"text-gray-400 italic",children:"-"})})]}),K<$.length-1&&e.jsx("div",{className:"border-t border-gray-200 my-1"})]},K))})}catch{return e.jsxs("div",{className:"flex flex-col gap-2 py-2 text-sm",children:[e.jsxs("div",{className:"text-gray-700",children:[e.jsx("span",{className:"font-medium text-gray-900",children:"Title:"})," ",e.jsx("span",{className:"text-gray-400 italic",children:"-"})]}),e.jsx("div",{className:"border-t border-gray-200 my-1"}),e.jsxs("div",{className:"text-gray-700",children:[e.jsx("span",{className:"font-medium text-gray-900",children:"Slug:"})," ",e.jsx("span",{className:"text-gray-400 italic",children:"-"})]}),e.jsx("div",{className:"border-t border-gray-200 my-1"}),e.jsxs("div",{className:"text-gray-700",children:[e.jsx("span",{className:"font-medium text-gray-900",children:"Body:"})," ",e.jsx("span",{className:"text-gray-400 italic",children:"-"})]})]})}},D=()=>{if(!x)return null;const{row:R,col:L,rowId:$,colId:H}=x,K=R.cells[H]||{value:""};let X={};try{X=typeof K.value=="string"&&K.value?JSON.parse(K.value):K.value||{}}catch{X={}}if(H==="col_score"){const V=m(),[P,A]=r.useState(()=>{try{const T=typeof K.value=="string"&&K.value?JSON.parse(K.value):{},M={};return V.forEach(Z=>{M[Z.id]=T[Z.id]||0}),M.total=T.total||0,M}catch{const T={};return V.forEach(M=>{T[M.id]=0}),T.total=0,T}});r.useEffect(()=>{try{const T=typeof K.value=="string"&&K.value?JSON.parse(K.value):{},M={};V.forEach(Z=>{M[Z.id]=T[Z.id]||0}),M.total=T.total||0,A(M)}catch{const T={};V.forEach(M=>{T[M.id]=0}),T.total=0,A(T)}},[K.value]);const C=(T,M)=>{const Z=V.find(de=>de.id===T)?.maxScore||0,B=Math.max(0,Math.min(Z,M)),ae={...P,[T]:B};ae.total=V.reduce((de,fe)=>de+(ae[fe.id]||0),0),A(ae)},I=()=>{g($,H,JSON.stringify(P)),u(null)},j=h(),q=j>0?Math.round(P.total/j*100):0;return e.jsxs("div",{className:"fixed right-0 top-0 h-full w-96 bg-white border-l border-gray-200 shadow-xl z-50 flex flex-col",children:[e.jsxs("div",{className:"flex-none px-6 py-4 border-b border-gray-200 flex items-center justify-between",children:[e.jsx("h3",{className:"text-lg font-semibold text-gray-900",children:"Edit Score"}),e.jsx("button",{onClick:()=>u(null),className:"p-1 hover:bg-gray-100 rounded",children:e.jsx(mt,{size:20})})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto p-6 space-y-4",children:[V.map(T=>e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(Gt,{className:"text-sm font-medium text-gray-700",children:T.label}),e.jsxs("span",{className:"text-xs text-gray-500",children:[P[T.id]||0," / ",T.maxScore]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("input",{type:"range",min:"0",max:T.maxScore,value:P[T.id]||0,onChange:M=>C(T.id,parseInt(M.target.value)),className:"flex-1 h-2 bg-gray-200 rounded-lg appearance-none cursor-pointer"}),e.jsx(bt,{type:"number",min:"0",max:T.maxScore,value:P[T.id]||0,onChange:M=>C(T.id,parseInt(M.target.value)||0),className:"w-20 text-sm"})]})]},T.id)),e.jsxs("div",{className:"pt-4 mt-4 border-t border-gray-200",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(Gt,{className:"text-base font-semibold text-gray-900",children:"Total Score"}),e.jsxs("span",{className:"text-lg font-bold text-gray-900",children:[P.total," / ",j]})]}),e.jsx("div",{className:"w-full bg-gray-200 rounded-full h-3",children:e.jsx("div",{className:`h-3 rounded-full transition-all ${q>=80?"bg-green-500":q>=60?"bg-blue-500":q>=40?"bg-yellow-500":"bg-red-500"}`,style:{width:`${q}%`}})}),e.jsxs("p",{className:"text-xs text-gray-500 mt-1",children:[q,"%"]})]})]}),e.jsxs("div",{className:"flex-none px-6 py-4 border-t border-gray-200 flex justify-end gap-3",children:[e.jsx("button",{onClick:()=>u(null),className:"px-4 py-2 text-sm text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50",children:"Cancel"}),e.jsx("button",{onClick:I,className:"px-4 py-2 text-sm text-white bg-slate-800 rounded-lg hover:bg-slate-700",children:"Save"})]})]})}if(H==="col_topic"){const[V,P]=r.useState(K.value||"");r.useEffect(()=>{P(K.value||"")},[K.value]);const A=()=>{g($,H,V),u(null)};return e.jsxs("div",{className:"fixed right-0 top-0 h-full w-96 bg-white border-l border-gray-200 shadow-xl z-50 flex flex-col",children:[e.jsxs("div",{className:"flex-none px-6 py-4 border-b border-gray-200 flex items-center justify-between",children:[e.jsx("h3",{className:"text-lg font-semibold text-gray-900",children:"Edit Topic"}),e.jsx("button",{onClick:()=>u(null),className:"p-1 hover:bg-gray-100 rounded",children:e.jsx(mt,{size:20})})]}),e.jsx("div",{className:"flex-1 overflow-y-auto p-6 space-y-4",children:e.jsxs("div",{children:[e.jsx(Gt,{className:"text-sm font-medium text-gray-700 mb-2 block",children:"Topic"}),e.jsx(bt,{value:V,onChange:C=>P(C.target.value),placeholder:"Enter topic..."})]})}),e.jsxs("div",{className:"flex-none px-6 py-4 border-t border-gray-200 flex justify-end gap-3",children:[e.jsx("button",{onClick:()=>u(null),className:"px-4 py-2 text-sm text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50",children:"Cancel"}),e.jsx("button",{onClick:A,className:"px-4 py-2 text-sm text-white bg-slate-800 rounded-lg hover:bg-slate-700",children:"Save"})]})]})}if(H==="col_context"){const[V,P]=r.useState(X);r.useEffect(()=>{P(X)},[K.value]);const A=()=>{g($,H,JSON.stringify(V)),u(null)};return e.jsxs("div",{className:"fixed right-0 top-0 h-full w-96 bg-white border-l border-gray-200 shadow-xl z-50 flex flex-col",children:[e.jsxs("div",{className:"flex-none px-6 py-4 border-b border-gray-200 flex items-center justify-between",children:[e.jsx("h3",{className:"text-lg font-semibold text-gray-900",children:"Edit Context"}),e.jsx("button",{onClick:()=>u(null),className:"p-1 hover:bg-gray-100 rounded",children:e.jsx(mt,{size:20})})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto p-6 space-y-4",children:[e.jsxs("div",{children:[e.jsx(Gt,{className:"text-sm font-medium text-gray-700 mb-2 block",children:"Company Info"}),e.jsx(Js,{value:V.companyInfo||"",onChange:C=>P({...V,companyInfo:C.target.value}),placeholder:"Enter company information...",className:"min-h-[80px]"})]}),e.jsxs("div",{children:[e.jsx(Gt,{className:"text-sm font-medium text-gray-700 mb-2 block",children:"Reference Link"}),e.jsx(bt,{value:V.referenceLink||"",onChange:C=>P({...V,referenceLink:C.target.value}),placeholder:"Enter reference URL..."})]}),e.jsxs("div",{children:[e.jsx(Gt,{className:"text-sm font-medium text-gray-700 mb-2 block",children:"Product Info"}),e.jsx(Js,{value:V.productInfo||"",onChange:C=>P({...V,productInfo:C.target.value}),placeholder:"Enter product information...",className:"min-h-[80px]"})]}),e.jsxs("div",{children:[e.jsx(Gt,{className:"text-sm font-medium text-gray-700 mb-2 block",children:"Knowledge Base"}),e.jsx(Js,{value:V.knowledgeBase||"",onChange:C=>P({...V,knowledgeBase:C.target.value}),placeholder:"Enter knowledge base content...",className:"min-h-[120px]"})]}),i&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx(Gt,{className:"text-sm font-medium text-gray-700 mb-2 block",children:"Tracking History"}),e.jsx(Js,{value:V.trackingHistory||"",onChange:C=>P({...V,trackingHistory:C.target.value}),placeholder:"Enter tracking history...",className:"min-h-[80px]"})]}),e.jsxs("div",{children:[e.jsx(Gt,{className:"text-sm font-medium text-gray-700 mb-2 block",children:"AI Citation"}),e.jsx(Js,{value:V.aiCitation||"",onChange:C=>P({...V,aiCitation:C.target.value}),placeholder:"Enter AI citation information...",className:"min-h-[80px]"})]})]})]}),e.jsxs("div",{className:"flex-none px-6 py-4 border-t border-gray-200 flex justify-end gap-3",children:[e.jsx("button",{onClick:()=>u(null),className:"px-4 py-2 text-sm text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50",children:"Cancel"}),e.jsx("button",{onClick:A,className:"px-4 py-2 text-sm text-white bg-slate-800 rounded-lg hover:bg-slate-700",children:"Save"})]})]})}if(H==="col_content"){const[V,P]=r.useState(X);r.useEffect(()=>{P(X)},[K.value]);const A=()=>{g($,H,JSON.stringify(V)),u(null)};return e.jsxs("div",{className:"fixed right-0 top-0 h-full w-96 bg-white border-l border-gray-200 shadow-xl z-50 flex flex-col",children:[e.jsxs("div",{className:"flex-none px-6 py-4 border-b border-gray-200 flex items-center justify-between",children:[e.jsx("h3",{className:"text-lg font-semibold text-gray-900",children:"Edit Content"}),e.jsx("button",{onClick:()=>u(null),className:"p-1 hover:bg-gray-100 rounded",children:e.jsx(mt,{size:20})})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto p-6 space-y-4",children:[e.jsxs("div",{children:[e.jsx(Gt,{className:"text-sm font-medium text-gray-700 mb-2 block",children:"Title"}),e.jsx(bt,{value:V.title||"",onChange:C=>P({...V,title:C.target.value}),placeholder:"Enter content title..."})]}),e.jsxs("div",{children:[e.jsx(Gt,{className:"text-sm font-medium text-gray-700 mb-2 block",children:"Slug"}),e.jsx(bt,{value:V.slug||"",onChange:C=>P({...V,slug:C.target.value}),placeholder:"Enter URL slug..."})]}),e.jsxs("div",{children:[e.jsx(Gt,{className:"text-sm font-medium text-gray-700 mb-2 block",children:"Body"}),e.jsx(Js,{value:V.body||"",onChange:C=>P({...V,body:C.target.value}),placeholder:"Enter content body...",className:"min-h-[200px]"})]})]}),e.jsxs("div",{className:"flex-none px-6 py-4 border-t border-gray-200 flex justify-end gap-3",children:[e.jsx("button",{onClick:()=>u(null),className:"px-4 py-2 text-sm text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50",children:"Cancel"}),e.jsx("button",{onClick:A,className:"px-4 py-2 text-sm text-white bg-slate-800 rounded-lg hover:bg-slate-700",children:"Save"})]})]})}return e.jsx(Vc,{expandedCell:x,onUpdate:w,onClose:()=>u(null),allColumns:l})},F=()=>{n?window.location.href="/app/aeo_geo_flow?step=content":o?window.location.href="/app/content_refresh_flow?step=content":window.location.href="/app/seo_flow?step=content"};return e.jsxs("div",{className:"fixed inset-0 bg-white flex flex-col z-50",children:[e.jsxs("div",{className:"flex-none px-6 py-4 border-b border-gray-200 bg-white flex items-center gap-4",children:[e.jsx("button",{onClick:F,className:"flex items-center justify-center w-8 h-8 rounded-lg hover:bg-gray-100 transition-colors","aria-label":"Back to Content",children:e.jsx(un,{size:20,className:"text-gray-700"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-xl font-semibold text-gray-900",children:"Content Generation"}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"prototype / content / generation"})]})]}),e.jsx("div",{className:"flex-1 min-h-0 overflow-auto",children:e.jsx("div",{className:"relative",children:e.jsxs("table",{className:"w-full border-collapse",children:[e.jsx("thead",{className:"sticky top-0 bg-white z-10 border-b-2 border-gray-300",children:e.jsxs("tr",{children:[e.jsx("th",{className:"w-12 px-4 py-3 text-left text-xs font-semibold text-gray-600 bg-gray-50 border-r border-gray-200"}),l.map(R=>e.jsx("th",{className:"px-4 py-3 text-left text-xs font-semibold text-gray-600 bg-gray-50 border-r border-gray-200",style:{width:R.width},children:R.title},R.id))]})}),e.jsx("tbody",{className:"bg-white",children:p.map((R,L)=>{const $=R.cells.col_keywords||{value:""},H=R.cells.col_topic||{value:""},K=R.cells.col_context||{value:""},X=R.cells.col_content||{value:""},V=R.cells.col_score||{value:""},P=R.cells.col_publish||{value:""};return e.jsxs("tr",{className:"border-b border-gray-200 hover:bg-gray-50/50 transition-colors",children:[e.jsx("td",{className:"w-12 px-4 py-6 text-center text-xs text-gray-400 bg-gray-50/30 border-r border-gray-200",children:L+1}),e.jsx("td",{className:"px-4 py-6 border-r border-gray-200 cursor-pointer",onClick:()=>u({row:R,col:l[0],rowId:R.id,colId:"col_keywords"}),children:_($.value)}),e.jsx("td",{className:"px-4 py-6 border-r border-gray-200 cursor-pointer min-w-[250px]",onClick:()=>u({row:R,col:l[1],rowId:R.id,colId:"col_topic"}),children:E(H.value)}),e.jsx("td",{className:"px-4 py-6 border-r border-gray-200 cursor-pointer min-w-[350px]",onClick:()=>u({row:R,col:l[2],rowId:R.id,colId:"col_context"}),children:S(K.value)}),e.jsx("td",{className:"px-4 py-6 border-r border-gray-200 cursor-pointer min-w-[400px]",onClick:()=>u({row:R,col:l[3],rowId:R.id,colId:"col_content"}),children:k(X.value)}),e.jsx("td",{className:"px-4 py-6 border-r border-gray-200 cursor-pointer min-w-[200px] text-center",onClick:()=>u({row:R,col:l[4],rowId:R.id,colId:"col_score"}),children:N(V.value)}),e.jsx("td",{className:"px-4 py-6 text-center",children:e.jsx("button",{onClick:A=>{A.stopPropagation();const I=(P.value||"")==="Published"?"":"Published";g(R.id,"col_publish",I)},className:Lt("text-sm font-medium rounded-lg px-4 py-2 transition-colors",P.value==="Published"?"bg-green-100 text-green-700 hover:bg-green-200":"bg-gray-100 text-gray-700 hover:bg-gray-200"),children:P.value==="Published"?"Published":"Publish"})})]},R.id)})})]})})}),x&&D()]})}function Th(){const{toast:t}=_t(),[s,a]=r.useState(null),[n,o]=r.useState(null),[i,l]=r.useState(!1),[c,d]=r.useState(null),[m,h]=r.useState(!0),[p,f]=r.useState(!1),[b,y]=r.useState(""),[x,u]=r.useState("seo_content_webflow"),[g,w]=r.useState([]),[_,E]=r.useState(!1),[N,S]=r.useState("system:seo_content_webflow"),[k,D]=r.useState("template"),[F,R]=r.useState(""),[L,$]=r.useState(!1),[H,K]=r.useState([]),X=r.useMemo(()=>
554{if(!N.startsWith("user:"))return null;const z=N.slice(5);return g.find(U=>U.id===z)||null},[N,g]),V=!!X?.is_multi_view,[P,A]=r.useState(!1),[C,I]=r.useState([]),[j,q]=r.useState(""),[T,M]=r.useState(""),[Z,B]=r.useState([]);r.useEffect(()=>{const z=async()=>{const me=new URLSearchParams(window.location.search).get("view"),le=da();if(l(!1),!me){if(!le){const O=await lr({page:1,page_size:1e3});I(O.items.map(ne=>({id:ne.id,name:ne.name}))),A(!0),h(!1);return}try{const O=await Wt.listViewConfigs({campaign_id:le});if(O.items.length>0){const ge=[...O.items].sort((ze,Ke)=>{const ie=ze.display_order??0,ve=Ke.display_order??0;return ie-ve})[0];jt("table-new",{campaign:le,view:ge.id},{replace:!0})}else d(null),l(!0),a(null),o(null),h(!1)}catch(O){console.error("Failed to load views:",O),d("Failed to load views. Please try again."),h(!1)}return}if(me!==s){d(null),l(!1);try{const O=await Wt.getViewConfig(me);o(O),a(me),h(!1)}catch(O){console.error("Failed to load view config:",O),d("Failed to load view configuration. Please try again."),h(!1)}}else h(!1)};z();const U=()=>{z()};return window.addEventListener("popstate",U),()=>window.removeEventListener("popstate",U)},[s]);const ae=async z=>{if(q(z),M(""),!z){B([]);return}try{const U=await Wt.listViewConfigs({campaign_id:z});B(U.items),U.items.length>0&&M(U.items[0].id)}catch(U){console.error("Failed to load views:",U),B([])}},de=()=>{j&&T&&(jt("table-new",{campaign:j,view:T}),A(!1))};r.useEffect(()=>{p&&((async()=>{const Q=da();if(Q)try{const me=await Wt.listViewConfigs({campaign_id:Q});K(me.items)}catch(me){console.error("Failed to load existing views:",me),K([])}})(),(async()=>{E(!0);try{const Q=await io({page:1,page_size:200});w(Q.items||[])}catch(Q){console.error("Failed to load templates:",Q),w([])}finally{E(!1)}})(),D("template"),y(""),R(""),u("seo_content_webflow"),S("system:seo_content_webflow"),$(!1))},[p]);const fe=async()=>{if(!V&&!b.trim()||k==="copy"&&!F)return;const z=da();if(!z){t({title:"Error",description:"No campaign selected"});return}$(!0);try{let U;if(k==="copy"&&F)U=await Wt.copyViewConfig({source_view_id:F,new_view_name:b.trim(),target_campaign_id:z});else{if(N.startsWith("user:")&&X){const me=await Hw({campaign_id:z,template_id:X.id,new_view_name:X.is_multi_view?void 0:b.trim(),name_prefix:X.is_multi_view&&b.trim()||void 0}),le=me.view_ids?.[0];if(!le)throw new Error("No view created from template");f(!1),y(""),u("seo_content_webflow"),S("system:seo_content_webflow"),jt("table-new",{campaign:z,view:le}),t({title:"Created",description:X.is_multi_view?`Created ${me.view_ids.length} views from template "${X.name}"`:`Table view "${b.trim()}" has been created`});return}const Q=N.startsWith("system:")?N.slice(7):x;U=await Wt.createViewConfig({campaign_id:z,view_name:b.trim(),table_type:Q,is_default:!1,is_shared:!1})}f(!1),y(""),u("seo_content_webflow"),S("system:seo_content_webflow"),jt("table-new",{campaign:z,view:U.id}),t({title:"Created",description:`Table view "${U.view_name}" has been created`})}catch(U){console.error("Failed to create view:",U),t({title:"Create failed",description:"Please try again"})}finally{$(!1)}},se=!V&&!b.trim()||k==="copy"&&!F||L;return c?e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"text-red-600 mb-4",children:c}),e.jsx("button",{onClick:()=>{d(null),h(!0),window.location.reload()},className:"px-4 py-2 bg-slate-900 text-white rounded hover:bg-slate-800",children:"Retry"})]})}):m?e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx("div",{className:"text-slate-600",children:"Loading..."})}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"h-full w-full",children:e.jsx(m1,{title:"New Table Demo",subtitle:"seo-poster / table / demo",noViews:i,onAddTable:()=>f(!0)})}),e.jsx(Ht,{open:P,onOpenChange:A,children:e.jsxs(qt,{className:"max-w-lg",children:[e.jsxs(Zt,{children:[e.jsx("div",{className:"flex items-center justify-center mb-4",children:e.jsx("div",{className:"w-12 h-12 rounded-full bg-gray-100 flex items-center justify-center",children:e.jsx(Zn,{className:"h-6 w-6 text-gray-700"})})}),e.jsx(Yt,{className:"text-center",children:"Select Campaign & Table"}),e.jsx("p",{className:"text-sm text-gray-600 text-center mt-2",children:"Choose a campaign and table to get started"})]}
554),e.jsxs("div",{className:"space-y-4 mt-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-2",children:"Campaign"}),e.jsxs("select",{value:j,onChange:z=>ae(z.target.value),className:"w-full px-3 py-2 text-sm border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-gray-400 bg-white text-gray-700",children:[e.jsx("option",{value:"",children:"Select a campaign..."}),C.map(z=>e.jsx("option",{value:z.id,children:z.name},z.id))]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-2",children:"Table"}),e.jsxs("select",{value:T,onChange:z=>M(z.target.value),disabled:!j||Z.length===0,className:"w-full px-3 py-2 text-sm border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-gray-400 bg-white text-gray-700 disabled:opacity-50 disabled:cursor-not-allowed",children:[e.jsx("option",{value:"",children:j?Z.length===0?"No tables available":"Select a table...":"Select a campaign first..."}),Z.map(z=>e.jsx("option",{value:z.id,children:z.view_name},z.id))]})]}),j&&Z.length===0&&e.jsx("div",{className:"p-3 bg-gray-50 border border-gray-200 rounded-lg",children:e.jsx("p",{className:"text-sm text-gray-600 text-center",children:"No tables found for this campaign. Create a new table to get started."})})]}),e.jsxs("div",{className:"flex gap-3 mt-6",children:[e.jsx("button",{onClick:()=>{A(!1),jt("campaigns")},className:"flex-1 px-4 py-2.5 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors",children:"Cancel"}),e.jsx("button",{onClick:de,disabled:!j||!T,className:"flex-1 px-4 py-2.5 text-sm font-medium text-white bg-gray-900 rounded-lg hover:bg-gray-800 transition-colors disabled:opacity-50 disabled:cursor-not-allowed",children:"Open Table"})]})]})}),e.jsx(Ht,{open:p,onOpenChange:f,children:e.jsxs(qt,{className:"max-w-[520px] p-0 gap-0 overflow-hidden",children:[e.jsx(Zt,{variant:"full",density:"lg",children:e.jsx(Yt,{className:"text-[22px] font-semibold text-slate-900",children:"Create New View"})}),e.jsxs("div",{className:"px-7 pb-7 pt-6 space-y-5",children:[e.jsxs("div",{className:"flex gap-0 p-1 bg-slate-100 rounded-lg",children:[e.jsxs("button",{type:"button",onClick:()=>D("template"),className:`flex-1 flex items-center justify-center gap-2 px-4 py-2.5 text-[13px] font-medium rounded-md transition-all duration-200 ${k==="template"?"bg-white text-slate-900 shadow-sm":"text-slate-500 hover:text-slate-700"}`,children:[e.jsx(gu,{className:"w-4 h-4"}),e.jsx("span",{children:"From Template"})]}),e.jsxs("button",{type:"button",onClick:()=>D("copy"),className:`flex-1 flex items-center justify-center gap-2 px-4 py-2.5 text-[13px] font-medium rounded-md transition-all duration-200 ${k==="copy"?"bg-white text-slate-900 shadow-sm":"text-slate-500 hover:text-slate-700"}`,children:[e.jsx(Ys,{className:"w-4 h-4"}),e.jsx("span",{children:"Copy from Existing"})]})]}),k==="template"&&e.jsx("div",{className:"space-y-4 animate-in fade-in duration-200",children:e.jsxs("div",{children:[e.jsxs("label",{className:"flex items-center gap-2 text-sm font-medium text-slate-700 mb-2",children:["Select Template",e.jsxs("div",{className:"relative group",children:[e.jsx("div",{className:"flex items-center justify-center w-[14px] h-[14px] border-[1.5px] border-slate-400 rounded-full transition-colors group-hover:border-slate-600",children:e.jsx("span",{className:"text-[10px] font-semibold italic text-slate-400 group-hover:text-slate-600 font-serif leading-none pb-[1px]",children:"i"})}),e.jsxs("div",{className:"absolute left-full top-1/2 -translate-y-1/2 ml-2.5 px-3 py-2 bg-slate-800 text-white text-xs rounded-md opacity-0 invisible group-hover:opacity-100 group-hover:visible transition-all z-50 w-56 whitespace-normal leading-relaxed shadow-lg",children:["Templates include predefined columns optimized for common use cases",e.jsx("div",{className:"absolute right-full top-1/2 -translate-y-1/2 border-[6px] border-transparent border-r-slate-800"})]})]})]}),e.jsxs("div",{className:"relative",children:[e.jsxs("select",{className:"w-full px-3.5 py-2.5 text-sm text-slate-900 bg-white border border-slate-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-slate-900/10 focus:border-slate-400 transition-all appearance-none cursor-pointer pr-10 hover:border-slate-400",value:N,onChange:z=>{const U=z.target.value;S(U),U.startsWith("system:")&&u(U.slice(7))},children:[e.jsxs("optgroup",{label:"System templates",children:[e.jsx("option",{value:"system:seo_content_webflow",children:"Create New Content (Webflow)"}),e.jsx("option",{value:"system:seo_content_shopify",children:"Create New Content (Shopify)"}),e.jsx("option",{value:"system:seo_analysis_shopify",children:"Optimize Existing Content"}),e.jsx("option",{value:"system:none",children:"Create New Content"})]}),e.jsx("optgroup",{label:"Your saved templates",children:_?e.jsx("option",{value:"user:__loading",disabled:!0,children:"Loading..."}):g.length===0?e.jsx("option",{value:"user:__empty",disabled:!0,children:"No saved templates"}):g.map(z=>e.jsxs("option",{value:`user:${z.id}`,children:[z.name,z.is_multi_view?` (Multi • ${z.view_count} views)`:" (Single)"]},z.id))})]}),e.jsx("div",{className:"absolute right-3.5 top-1/2 -translate-y-1/2 pointer-events-none",children:e.jsx("svg",{width:"12",height:"8",viewBox:"0 0 12 8",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:e.jsx("path",{d:"M1 1.5L6 6.5L11 1.5",stroke:"#64748b",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})})]}),X?.is_multi_view&&e.jsxs("p",{className:"mt-2 text-xs text-slate-500",children:["This is a multi-view template. Creating will add"," ",X.view_count," views to this campaign."]})]})}),k==="copy"&&e.jsx("div",{className:"space-y-4 animate-in fade-in duration-200",children:e.jsxs("div",{children:[e.jsxs("label",{className:"flex items-center gap-2 text-sm font-medium text-slate-700 mb-2",children:["Source View",e.jsxs("div",{className:"relative group",children:[e.jsx("div",{className:"flex items-center justify-center w-[14px] h-[14px] border-[1.5px] border-slate-400 rounded-full transition-colors group-hover:border-slate-600",children:e.jsx("span",{className:"text-[10px] font-semibold italic text-slate-400 group-hover:text-slate-600 font-serif leading-none pb-[1px]",children:"i"})}),e.jsxs("div",{className:"absolute left-full top-1/2 -translate-y-1/2 ml-2.5 px-3 py-2 bg-slate-800 text-white text-xs rounded-md opacity-0 invisible group-hover:opacity-100 group-hover:visible transition-all z-50 w-52 whitespace-normal leading-relaxed shadow-lg",children:["Only column structure will be copied, not the data",e.jsx("div",{className:"absolute right-full top-1/2 -translate-y-1/2 border-[6px] border-transparent border-r-slate-800"})]})]})]}),e.jsxs("div",{className:"relative",children:[e.jsxs("select",{value:F,onChange:z=>R(z.target.value),className:"w-full px-3.5 py-2.5 text-sm text-slate-900 bg-white border border-slate-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-slate-900/10 focus:border-slate-400 transition-all appearance-none cursor-pointer pr-10 hover:border-slate-400",children:[e.jsx("option",{value:"",children:"Select a view to copy from"}),H.map(z=>e.jsx("option",{value:z.id,children:z.view_name},z.id))]}),e.jsx("div",{className:"absolute right-3.5 top-1/2 -translate-y-1/2 pointer-events-none",children:e.jsx("svg",{width:"12",height:"8",viewBox:"0 0 12 8",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:e.jsx("path",{d:"M1 1.5L6 6.5L11 1.5",stroke:"#64748b",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})})]}),H.length===0&&e.jsx("p",{className:"mt-2 text-xs text-slate-500",children:"No existing views available to copy from"})]})}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-slate-700 mb-2",children:V?"Name Prefix (optional)":"View Name"}),e.jsx("input",{type:"text",value:b,onChange:z=>y(z.target.value),onKeyDown:z=>{z.key==="Enter"&&!se&&fe()},placeholder:V?"Optional prefix for created views":"Enter view name",autoFocus:!0,className:"w-full px-3.5 py-2.5 text-sm text-slate-900 bg-white border border-slate-300 rounded-lg placeholder:text-slate-400 focus:outline-none focus:ring-2 focus:ring-slate-900/10 focus:border-slate-400 transition-all hover:border-slate-400"})]}),e.jsxs("div",{className:"flex justify-end gap-3 pt-2",children:[e.jsx("button",{type:"button",onClick:()=>{f(!1),y(""),u("seo_content_webflow"),S("system:seo_content_webflow")},className:"px-5 py-2.5 text-sm font-medium text-slate-600 bg-white border border-slate-300 rounded-lg hover:bg-slate-50 hover:border-slate-400 transition-colors",children:"Cancel"}),e.jsx("button",{type:"button",onClick:fe,disabled:se,className:"px-6 py-2.5 text-sm font-medium text-white bg-slate-900 rounded-lg hover:bg-slate-800 disabled:opacity-50 disabled:cursor-not-allowed transition-colors flex items-center gap-2",children:L?e.jsxs(e.Fragment,{children:[e.jsx(He,{className:"w-4 h-4 animate-spin"}),"Creating..."]}):"Create"})]})]})]})})]})}function p1(){return new URLSearchParams(window.location.search).get("prototype")==="true"?e.jsx(za,{children:e.jsx(h1,{})}):e.jsx(za,{children:e.jsx(Ex,{current:"table-new",onChange:a=>jt(a),children:e.jsx(Th,{})})})}function Ym({onContact:t,features:s}){return e.jsx("div",{className:"mt-8",children:e.jsxs("div",{className:"bg-white rounded-xl border border-slate-200 shadow-sm overflow-hidden",children:[e.jsxs("div",{className:"p-6 md:p-7 flex flex-col md:flex-row md:items-center md:justify-between gap-6",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"inline-flex items-center gap-1.5 bg-slate-100 text-slate-700 px-2 py-0.5 rounded text-xs font-bold uppercase tracking-wide",children:[e.jsx(Dr,{className:"w-3 h-3"}),"Enterprise"]}),e.jsx("h2",{className:"mt-2 text-2xl font-bold text-gray-900",children:"Full-scale growth with vetted talents"}),e.jsx("p",{className:"mt-1 text-sm text-gray-500",children:"Get a tailored plan and onboarding support."})]}),e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("div",{className:"text-3xl font-bold text-gray-900 leading-none",children:"Custom"}),e.jsx(be,{onClick:t,className:"bg-slate-900 hover:bg-slate-800 text-white md:w-[220px]",children:"Contact sales"})]})]}),e.jsx("div",{className:"border-t border-slate-200 bg-gray-50/50",children:e.jsx("div",{className:"p-6 md:p-7 grid grid-cols-1 md:grid-cols-2 gap-x-10",children:s.map(a=>e.jsxs("div",{className:"flex items-center justify-between gap-3 py-2 border-b border-slate-200/70 last:border-b-0",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx("div",{className:"flex-shrink-0 w-5 h-5 rounded-full flex items-center justify-center bg-blue-100",children:e.jsx(wt,{className:"w-3 h-3 text-blue-600"})}),e.jsx("div",{className:"text-sm text-slate-700 truncate",children:a.label})]}),e.jsx("div",{className:"text-sm font-semibold text-slate-900 flex-shrink-0",children:a.value})]},`${a.label}:${a.value}`))})})]})})}const g1=[{target:'[data-onboarding="pricing-intro"]',content:"Pricing displays available subscription plans and credit packages. Choose a plan that matches your usage needs or purchase additional credits as needed.",placement:"bottom",disableBeacon:!0},{target:'[data-onboarding="billing-toggle"]',content:"Switch between monthly and yearly billing. Yearly plans offer a discount compared to monthly payments.",placement:"bottom",disableBeacon:!0},{target:'[data-onboarding="subscription-plans"]',content:"Subscription plans provide monthly credits and feature access. Higher tiers include more credits and advanced capabilities.",placement:"top",disableBeacon:!0,spotlightClicks:!1,styles:{spotlight:{pointerEvents:"none"}}},{target:'[data-onboarding="payg-packages"]',content:"Pay-as-you-go packages allow purchasing credits without a subscription. Credits do not expire and can be used alongside subscription credits.",placement:"top",disableBeacon:!0}];function f1({subscription:t,plan:s,onCancel:a,onReactivate:n,onManagePortal:o}){if(!s)return null;if((s.plan_type||"").toLowerCase()==="enterprise")return e.jsxs("div",{className:"bg-white rounded-xl border border-fuchsia-200 shadow-sm p-6 mb-8 relative overflow-hidden",children:[e.jsx("div",{className:"absolute top-0 left-0 w-1 h-full bg-fuchsia-500"}),e.jsx("div",{className:"flex flex-col md:flex-row md:items-center justify-between gap-6",children:e.jsxs("div",{children:[e.jsx("div",{className:"flex items-center gap-2 mb-2",children:e.jsx("span",{className:"bg-fuchsia-100 text-fuchsia-700 px-2 py-0.5 rounded text-xs font-bold uppercase tracking-wide",children:"Enterprise"})}),e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-1",children:s.name}),e.jsx("div",{className:"text-sm text-gray-600",children:"This plan is managed by your admin. Self-serve billing is disabled."})]})})]});const l=t.cancel_at_period_end,d=new Date(t.current_period_end).toLocaleDateString(),m=t.billing_interval==="yearly"?"Yearly":"Monthly",h=t.pending_effective_at||t.current_period_end,p=h?new Date(h).toLocaleDateString():null,f=t.pending_billing_interval==="yearly"?"Yearly":"Monthly",b=!!t.pending_plan_id||!!t.pending_billing_interval,y=t.pending_plan?.name||(t.pen
554ding_plan_id?"New Plan":null),x=!!t.pending_plan_id&&t.pending_plan_id!==s.id,u=!!t.pending_billing_interval&&t.pending_billing_interval!==t.billing_interval;return e.jsxs("div",{className:"bg-white rounded-xl border border-blue-100 shadow-sm p-6 mb-8 relative overflow-hidden",children:[e.jsx("div",{className:"absolute top-0 left-0 w-1 h-full bg-blue-500"}),e.jsxs("div",{className:"flex flex-col md:flex-row md:items-center justify-between gap-6",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("span",{className:"bg-blue-100 text-blue-700 px-2 py-0.5 rounded text-xs font-bold uppercase tracking-wide",children:"Current Plan"}),l&&e.jsx("span",{className:"bg-orange-100 text-orange-700 px-2 py-0.5 rounded text-xs font-bold uppercase tracking-wide",children:"Cancels Soon"})]}),e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-1",children:s.name}),e.jsxs("div",{className:"text-sm text-gray-500 flex items-center gap-4",children:[e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(td,{size:14}),l?"Access until":"Renews on"," ",d]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Wa,{size:14}),m," Billing"]})]}),b&&p&&e.jsxs("div",{className:"mt-3 inline-flex items-center gap-2 rounded-lg border border-amber-200 bg-amber-50 px-3 py-2 text-xs text-amber-900",children:[e.jsx(td,{size:14,className:"text-amber-700"}),e.jsx("span",{className:"font-semibold",children:"Scheduled change:"}),e.jsxs("span",{className:"text-amber-800",children:[x&&y?`Switch to ${y}`:u?`Switch to ${f} billing`:"Update",` on ${p}`]})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(be,{variant:"outline",onClick:o,className:"border-slate-200 text-slate-700 hover:bg-slate-50 hover:text-slate-900",children:"Manage Subscription"}),l?e.jsx(be,{variant:"outline",onClick:n,className:"border-blue-200 text-blue-700 hover:bg-blue-50 hover:text-blue-800",children:"Reactivate Subscription"}):e.jsx(be,{variant:"ghost",onClick:a,className:"text-gray-500 hover:text-red-600 hover:bg-red-50",children:"Cancel Subscription"})]})]})]})}function Jm({packages:t,processingCode:s,discountCode:a,onBuy:n}){if(t.length===0)return null;const o=!!a,i=a?.percent_off??0,l=1-i/100;return e.jsxs("div",{className:"mb-10",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[e.jsx(vs,{className:"text-amber-500",size:20}),e.jsx("h3",{className:"text-lg font-semibold text-gray-900",children:"Pay As You Go Credits"})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-5",children:t.map(c=>e.jsxs("div",{className:"bg-white rounded-xl border border-stone-200 p-5 hover:border-amber-200 hover:shadow-sm transition-all",children:[e.jsxs("div",{className:"flex justify-between items-start mb-4",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"text-2xl font-bold text-gray-900",children:["$",o?(c.amount_usd*l).toFixed(1).replace(/\.0$/,""):String(c.amount_usd)]}),e.jsx("div",{className:"text-xs text-stone-500 font-medium uppercase tracking-wider mt-1",children:"One-time purchase"}),o&&e.jsxs("div",{className:"mt-2 inline-flex items-center gap-2",children:[e.jsxs("span",{className:"text-[11px] text-slate-400 line-through",children:["$",String(c.amount_usd)]}),e.jsxs("span",{className:"inline-flex items-center px-2 py-0.5 rounded-full text-[10px] font-bold border border-indigo-200 bg-indigo-50 text-indigo-700 whitespace-nowrap",children:["Your discount -",i,"% (1st purchase)"]})]})]}),e.jsxs("div",{className:"bg-amber-50 text-amber-700 px-3 py-1.5 rounded-lg text-sm font-bold flex items-center gap-1",children:[e.jsx(vs,{size:14}),c.credits_amount.toLocaleString()]})]}),e.jsxs("ul",{className:"space-y-2 mb-5",children:[e.jsxs("li",{className:"flex items-center gap-2 text-xs text-gray-600",children:[e.jsx(wt,{size:14,className:"text-green-500"}),"Credits never expire"]}),e.jsxs("li",{className:"flex items-center gap-2 text-xs text-gray-600",children:[e.jsx(wt,{size:14,className:"text-green-500"}),"Use for all AI features"]})]}),e.jsx(be,{onClick:()=>n(c.package_code),disabled:s!==null,className:"w-full bg-stone-600 hover:bg-stone-700 text-white",children:s===c.package_code?e.jsxs(e.Fragment,{children:[e.jsx(He,{size:16,className:"mr-2 animate-spin"}),"Processing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(vs,{size:14,className:"mr-2"}),"Buy Now"]})})]},c.id))})]})}function Xm({records:t}){return t.length===0?null:e.jsxs("div",{className:"mt-12",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[e.jsx(qp,{className:"text-gray-400",size:20}),e.jsx("h3",{className:"text-lg font-semibold text-gray-900",children:"Credit Increase History"})]}),e.jsx("div",{className:"bg-white rounded-xl border border-gray-200 overflow-hidden",children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-left text-sm",children:[e.jsx("thead",{className:"bg-gray-50 border-b border-gray-200",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-6 py-3 font-medium text-gray-500",children:"Date"}),e.jsx("th",{className:"px-6 py-3 font-medium text-gray-500",children:"Type"}),e.jsx("th",{className:"px-6 py-3 font-medium text-gray-500 text-right",children:"Amount"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-100",children:t.map(s=>e.jsxs("tr",{className:"hover:bg-gray-50/50",children:[e.jsxs("td",{className:"px-6 py-3.5 text-gray-600",children:[new Date(s.created_at||"").toLocaleDateString()," ",e.jsx("span",{className:"text-gray-400 text-xs ml-1",children:new Date(s.created_at||"").toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})})]}),e.jsx("td",{className:"px-6 py-3.5 text-gray-900 font-medium",children:s.is_increase&&(!s.biz_type||s.biz_type.toLowerCase()==="unknown")?"Credit Increase":Ch({bizType:s.biz_type,source:s.source})}),e.jsxs("td",{className:"px-6 py-3.5 text-right text-emerald-600 font-bold",children:["+",Math.round(s.credit_cost).toLocaleStr
554ing()]})]},s.id))})]})})})]})}function y1(){const[t,s]=r.useState([]),[a,n]=r.useState(null),[o,i]=r.useState(!0),[l,c]=r.useState(null),[d,m]=r.useState(!1),[h,p]=r.useState([]),[f,b]=r.useState(null),[y,x]=r.useState("yearly"),[u,g]=r.useState(!1),[w,_]=r.useState(null),E=Zs(Us.subscription),[N,S]=r.useState([]),{toast:k}=_t(),{confirm:D}=ia();r.useEffect(()=>{F()},[]),r.useEffect(()=>{let j=!0;const q=async()=>{try{const M=await yx();if(!j)return;_(M)}catch(M){if(console.warn("⚠️ [subscription] Failed to load discount code:",M),!j)return;_(null)}};q();const T=()=>{q()};return window.addEventListener("discount_code_updated",T),()=>{j=!1,window.removeEventListener("discount_code_updated",T)}},[]),r.useEffect(()=>{const j=q=>{q.persisted&&(console.log("🟢 [subscription] Restored from bfcache. Resetting state..."),c(null),b(null),F())};return window.addEventListener("pageshow",j),()=>window.removeEventListener("pageshow",j)},[]);async function F(){try{i(!0);const[j,q,T,M]=await Promise.all([fx(),Xa(),Ly(),_h({page:1,page_size:20,include_increase:!0})]),Z=[...j].sort((B,ae)=>{const de=B.price_usd||0,fe=ae.price_usd||0;return de-fe});s(Z),n(q),p(T),S(M.items.filter(B=>B.is_increase))}catch(j){console.error("Error loading subscription data:",j),k({title:"Error",description:"Failed to load subscription data"})}finally{i(!1)}}async function R(j){try{b(j);const q=`${window.location.pathname}${window.location.search}`,T=await Mc(j,q);if("checkout_url"in T)window.location.href=T.checkout_url;else throw new Error("Unexpected response from server")}catch(q){console.error("Error creating PAYG checkout session:",q),k({title:"Error",description:q instanceof Error?q.message:"Failed to create PAYG checkout session"}),b(null)}}async function L(j){if((a?.plan?.plan_type||"").toLowerCase()==="enterprise"){k({title:"Disabled",description:"Self-serve plan checkout is disabled for Enterprise users."});return}try{c(j);const M=`${window.location.pathname}${window.location.search}`,Z=await Ci(j,void 0,y,M);if("downgraded"in Z){k({title:"Success",description:Z.message||"Subscription updated successfully"}),await F(),c(null);return}if("scheduled"in Z){k({title:"Success",description:Z.message||"Subscription change scheduled (effective at period end)"}),await F(),c(null);return}if("checkout_url"in Z)window.location.href=Z.checkout_url;else throw new Error("Unexpected response from server")}catch(M){console.error("Error creating checkout session:",M),k({title:"Error",description:M instanceof Error?M.message:"Failed to create checkout session"}),c(null)}}async function $(j){if((a?.plan?.plan_type||"").toLowerCase()==="enterprise"){k({title:"Disabled",description:"Billing cycle changes are disabled for Enterprise users."});return}if(!a?.plan?.plan_type){k({title:"Error",description:"Unable to switch billing cycle: missing plan information"});return}if(j!==a.billing_interval)try{m(!0);const M=`${window.location.pathname}${window.location.search}`,Z=await Ci(a.plan.plan_type,void 0,j,M);if("checkout_url"in Z){window.location.href=Z.checkout_url;return}if("scheduled"in Z){k({title:"Success",description:Z.message||"Billing cycle change scheduled (effective at period end)"}),await F();return}throw new Error("Unexpected response from server")}catch(M){console.error("Error switching billing cycle:",M),k({title:"Error",description:M instanceof Error?M.message:"Failed to switch billing cycle"})}finally{m(!1)}}async function H(){if(await D({title:"Cancel subscription?",message:"Are you sure you want to cancel your subscription? You will still have access until the end of your billing period.",confirmText:"Cancel subscription",cancelText:"Keep subscription",variant:"warning"}))try{await My(!0),k({title:"Success",description:"Subscription canceled successfully"}),await F()}catch(q){console.error("Error canceling subscription:",q),k({title:"Error",description:q instanceof Error?q.message:"Failed to cancel subscription"})}}async function K(){try{await Ry(),k({title:"Success",description:"Subscription reactivated successfully"}),await F()}catch(j){console.error("Error reactivating subscription:",j),k({title:"Error",description:j instanceof Error?j.message:"Failed to reactivate subscription"})}}async function X(){try{const{portal_url:j}=await Dy();window.open(j,"_blank","noopener,noreferrer")||k({title:"Error",description:"Unable to open a new tab. Please allow pop-ups and try again."})}catch(j){console.error("Error opening Stripe portal:",j),k({title:"Error",description:j instanceof Error?j.message:"Failed to open subscription management page"})}}if(o)return e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx(He,{className:"h-8 w-8 animate-spin text-slate-400"})});const V=a?.plan?.plan_type,P=(V||"").toLowerCase()==="enterprise",A=t.filter(j=>j.plan_type!=="custom").sort((j,q)=>(q.price_usd||0)-(j.price_usd||0))[0],C=V===A?.plan_type;if(a&&a.status==="active")return e.jsxs("div",{className:"h-full overflow-y-auto bg-gray-50/50",children:[e.jsxs("div",{className:"max-w-7xl mx-auto px-6 py-10",children:[e.jsxs("div",{className:"mb-8",children:[e.jsx("h1",{className:"text-2xl font-bold text-gray-900",children:"Subscription & Billing"}),e.jsx("p",{className:"text-gray-500 mt-1",children:"Manage your plan and credits"})]}),e.jsx(f1,{subscription:a,plan:a.plan,onCancel:H,onReactivate:K,onManagePortal:X}),e.jsxs("div",{className:"mb-10",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("h3",{className:"text-lg font-semibold text-gray-900",children:C?"Your Pro Features":"Upgrade to Pro"}),e.jsx(Qm,{value:y,onChange:x,maxDiscount:A?vo(A):0})]}),w&&e.jsxs("div",{className:"mb-5 inline-flex items-center gap-2 rounded-full border border-indigo-200 bg-indigo-50 px-3 py-2 text-xs text-indigo-900 whitespace-nowrap",children:[e.jsx("span",{className:"font-semibold",children:"Your discount"}),e.jsx("span",{className:"opacity-70",children:"•"}),e.jsxs("span",{children:["-",w.percent_off,"% 1st"," ",y==="yearly"?"year":"month"]})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6",children:t.filter(j=>j.plan_type!=="payg"&&j.plan_type!=="free"&&j.is_active).map(j=>e.jsx(Gd,{plan:j,billingInterval:y,currentPlanType:V,currentSubscription:a,discountCode:w,isProcessing:l===j.plan_type,onSubscribe:L,onCancelSubscription:H,onReactivateSubscription:K,onEnterpriseContact:()=>g(!0),isComparison:!0,onSwitchBillingInterval:$,isSwitchingBillingInterval:d,checkoutDisabled:P,checkoutDisabledReason:"Self-serve plan checkout is disabled for Enterprise users."},j.id))}),e.jsx(Ym,{onContact:()=>g(!0),features:[{label:"Credits",value:"Custom"},{label:"Competitor Analysis",value:"Unlimited"}
554,{label:"Keywords Research",value:"Unlimited"},{label:"Page Creations",value:"Unlimited"},{label:"Page Optimizations (GEO)",value:"Unlimited"},{label:"Technical SEO QA",value:"Custom"},{label:"Crawlability & Indexation",value:"Custom"},{label:"Tracked Pages",value:"Unlimited"},{label:"Tracked Keywords",value:"Unlimited"},{label:"Tracked Prompts",value:"Unlimited"},{label:"AI Models",value:"Custom / All Models"},{label:"CMS & SEO Integrations",value:"Custom"},{label:"Knowledge Bases RAG",value:"Custom"},{label:"Content Strategy",value:"Expert-assisted"},{label:"Support",value:"Dedicated Vetted Operator"}]})]}),e.jsx(Jm,{packages:h,processingCode:f,discountCode:w,onBuy:R}),e.jsx(Xm,{records:N})]}),e.jsx(Hl,{open:u,onOpenChange:g,toast:k})]});const I=Math.max(0,...t.map(j=>vo(j)));return e.jsxs("div",{className:"h-full overflow-y-auto bg-gray-50/50","data-onboarding":"pricing-intro",children:[e.jsxs("div",{className:"max-w-7xl mx-auto px-6 py-8",children:[e.jsxs("div",{className:"flex items-center justify-between mb-6",children:[e.jsx("div",{children:e.jsx("h1",{className:"text-xl font-semibold text-gray-900",children:"Subscription Plans"})}),I>0&&e.jsx("div",{"data-onboarding":"billing-toggle",children:e.jsx(Qm,{value:y,onChange:x,maxDiscount:I})})]}),w&&e.jsxs("div",{className:"mb-5 inline-flex items-center gap-2 rounded-full border border-indigo-200 bg-indigo-50 px-3 py-2 text-xs text-indigo-900 whitespace-nowrap",children:[e.jsx("span",{className:"font-semibold",children:"Your discount"}),e.jsx("span",{className:"opacity-70",children:"•"}),e.jsxs("span",{children:["-",w.percent_off,"% 1st"," ",y==="yearly"?"year":"month"]})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 mb-4","data-onboarding":"subscription-plans",children:t.filter(j=>j.plan_type!=="payg"&&j.plan_type!=="free"&&j.is_active).map(j=>e.jsx(Gd,{plan:j,billingInterval:y,currentPlanType:V,currentSubscription:a,discountCode:w,isProcessing:l===j.plan_type,onSubscribe:L,onCancelSubscription:H,onReactivateSubscription:K,onEnterpriseContact:()=>g(!0),onSwitchBillingInterval:$,isSwitchingBillingInterval:d,checkoutDisabled:P,checkoutDisabledReason:"Self-serve plan checkout is disabled for Enterprise users."},j.id))}),e.jsx("div",{"data-onboarding":"payg-packages",children:e.jsx(Jm,{packages:h,processingCode:f,discountCode:w,onBuy:R})}),e.jsx(Ym,{onContact:()=>g(!0),features:[{label:"Credits",value:"Custom"},{label:"Competitor Analysis",value:"Unlimited"},{label:"Keywords Research",value:"Unlimited"},{label:"Page Creations",value:"Unlimited"},{label:"Page Optimizations (GEO)",value:"Unlimited"},{label:"Technical SEO QA",value:"Custom"},{label:"Crawlability & Indexation",value:"Custom"},{label:"Tracked Pages",value:"Unlimited"},{label:"Tracked Keywords",value:"Unlimited"},{label:"Tracked Prompts",value:"Unlimited"},{label:"AI Models",value:"Custom / All Models"},{label:"CMS & SEO Integrations",value:"Custom"},{label:"Knowledge Bases RAG",value:"Custom"},{label:"Content Strategy",value:"Expert-assisted"},{label:"Support",value:"Dedicated Vetted Operator"}]}),e.jsx("div",{className:"mt-8",children:e.jsx(Xm,{records:N})})]}),e.jsx(Hl,{open:u,onOpenChange:g,toast:k}),e.jsx("button",{onClick:E.startManual,className:"fixed bottom-5 right-5 z-50 h-8 w-8 rounded-full bg-white border border-slate-200 shadow-md hover:shadow-lg hover:bg-slate-50 transition-all hover:scale-105 hidden sm:flex items-center justify-center",title:"View navigation guide","aria-label":"View navigation guide",children:e.jsx(Hs,{className:"h-4 w-4 text-slate-600"})}),e.jsx(oa,{steps:g1,run:E.run,onComplete:E.stopAndMarkCompleted,onSkip:E.stopAndMarkCompleted})]})}function Qm({value:t,onChange:s,maxDiscount:a}){return e.jsxs("div",{className:"inline-flex items-center bg-gray-100 rounded-lg p-0.5",children:[e.jsx("button",{onClick:()=>s("monthly"),className:`px-3 py-1.5 text-[11px] font-medium rounded-l-md transition-all ${t==="monthly"?"bg-gray-900 text-white shadow-sm":"text-gray-600 hover:text-gray-900"}`,children:"Monthly"}),e.jsxs("button",{onClick:()=>s("yearly"),className:`px-3 py-1.5 text-[11px] font-medium rounded-r-md transition-all flex items-center gap-1.5 ${t==="yearly"?"bg-gray-900 text-white shadow-sm":"text-gray-600 hover:text-gray-900"}`,children:["Yearly",a>0&&e.jsxs("span",{className:"px-1.5 py-0.5 text-[9px] font-semibold bg-emerald-500 text-white rounded-full",children:["Save ",a,"%"]})]})]})}const b1=({data:t,title:s,xAxisLabel:a,yAxisLabel:n,height:o=400,className:i="",color:l="#000000",formatValue:c})=>{const d={title:s?{text:s,left:"center",textStyle:{fontSize:16,fontWeight:"bold",color:"#0f172a"}}:void 0,tooltip:{trigger:"axis",axisPointer:{type:"shadow"},formatter:m=>{const h=Array.isArray(m)?m[0]:m,p=c?c(h.value):h.value;return`${h.name}: ${p}`}},grid:{left:"3%",right:"4%",bottom:"10%",top:s?"15%":"10%",containLabel:!0},xAxis:{type:"category",data:t.map(m=>m.name),axisLabel:{color:"#64748b",show:!0,rotate:-45,interval:0,margin:8}
554,axisLine:{show:!0,lineStyle:{color:"#e2e8f0"}},axisTick:{show:!0,lineStyle:{color:"#e2e8f0"}},name:a,nameLocation:"middle",nameGap:30},yAxis:{type:"value",axisLabel:{show:!1},axisLine:{show:!1},axisTick:{show:!1},splitLine:{show:!1},name:n},series:[{name:n||"Value",type:"bar",data:t.map(m=>m.value),itemStyle:{color:l},barWidth:"60%",label:{show:!0,position:"top",color:"#000000",formatter:m=>c?c(m.value):m.value,fontSize:12,offset:[0,5]}}]};return e.jsx("div",{className:i,children:e.jsx(Cr,{option:d,style:{height:typeof o=="number"?`${o}px`:o},opts:{renderer:"canvas"}})})},w1=({data:t,title:s,xAxisLabel:a,yAxisLabel:n,height:o=400,className:i="",color:l="#000000",formatValue:c})=>{const d={title:s?{text:s,left:"center",textStyle:{fontSize:16,fontWeight:"bold",color:"#0f172a"}}:void 0,tooltip:{trigger:"axis",axisPointer:{type:"shadow"},formatter:m=>{const h=Array.isArray(m)?m[0]:m,p=c?c(h.value):h.value;return`${h.name}: ${p}`}},grid:{left:"3%",right:"4%",bottom:"3%",containLabel:!0},xAxis:{type:"value",axisLabel:{color:"#64748b",formatter:c||"{value}"},name:a,nameLocation:"middle",nameGap:50},yAxis:{type:"category",data:t.map(m=>m.name),axisLabel:{color:"#64748b"},name:n,nameLocation:"middle",nameGap:50},series:[{name:a||"Value",type:"bar",data:t.map(m=>m.value),itemStyle:{color:l},label:{show:!0,position:"right",color:"#000000",formatter:m=>c?c(m.value):m.value}}]};return e.jsx("div",{className:i,children:e.jsx(Cr,{option:d,style:{height:typeof o=="number"?`${o}px`:o},opts:{renderer:"canvas"}})})};function j1({value:t="",onSearch:s,placeholder:a="Search...",showClearButton:n=!0,className:o="",onKeyDown:i,...l}){const[c,d]=r.useState(t),m=r.useRef(null),h=r.useRef(!1);r.useEffect(()=>{(!h.current||t==="")&&d(t)},[t]);const p=r.useCallback(g=>{const w=g.target.value;d(w)},[]),f=r.useCallback(g=>{if(g.key==="Enter"){g.preventDefault();const w=c.trim();s(w);return}else if(g.key==="Escape"){g.preventDefault(),d(""),s("");return}i?.(g)},[c,s,i]),b=r.useCallback(()=>{h.current=!0},[]),y=r.useCallback(()=>{h.current=!1},[]),x=r.useCallback(()=>{d(""),s(""),m.current?.focus()},[s]),u=c.length>0;return e.jsxs("div",{className:"relative inline-flex items-center",children:[e.jsx("input",{ref:m,type:"text",className:`h-8 w-64 rounded border border-slate-200 bg-white px-2 pr-8 text-sm text-slate-700 outline-none transition-colors focus:border-slate-300 focus:ring-1 focus:ring-slate-300 ${o}`,placeholder:a,value:c,onChange:p,onKeyDown:f,onFocus:b,onBlur:y,...l}),n&&u&&e.jsx("button",{type:"button",className:"absolute right-2 flex h-4 w-4 items-center justify-center rounded-full text-slate-400 hover:bg-slate-100 hover:text-slate-600 transition-colors",onClick:x,"aria-label":"Clear search",title:"Clear search (Esc)",children:e.jsx("svg",{className:"h-3 w-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]})}function v1(){const[t,s]=v.useState(!1),[a,n]=v.useState({}),[o,i]=v.useState(!1),[l,c]=v.useState(!0),[d,m]=v.useState("Option A"),[h,p]=v.useState("tab1"),f=[1200,1400,1300,1600,1500,1800,1700,1900,2100,2200,2e3,2300,2400,2300,2500].map((y,x)=>({name:String(x+1),value:y})),b="#000000";return e.jsxs("div",{className:"p-6 space-y-6 max-w-6xl",children:[e.jsxs(xs,{children:[e.jsx(Bs,{children:e.jsx(Xs,{children:"Basics"})}),e.jsx(fs,{children:e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ls,{children:"Default"}),e.jsx(ls,{className:"bg-slate-900 text-white",children:"Solid"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(be,{size:"sm",children:"Small"}),e.jsx(be,{children:"Medium"}),e.jsx(be,{size:"lg",children:"Large"}),e.jsx(be,{variant:"outline",children:"Outline"}),e.jsx(be,{variant:"ghost",children:"Ghost"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Gt,{htmlFor:"name",children:"Name"}),e.jsx(bt,{id:"name",placeholder:"Your name"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Gt,{htmlFor:"desc",children:"Description"}),e.jsx(Js,{id:"desc",placeholder:"Write something..."})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(kh,{checked:l,onCheckedChange:c}),e.jsx("span",{className:"text-sm text-slate-700",children:"Enable feature"})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Gt,{children:"Search"}),e.jsx(j1,{onSearch:y=>console.log("🔎",y),placeholder:"Search..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Gt,{children:"Status"}),e.jsxs(nr,{value:d,onValueChange:m,children:[e.jsx(rr,{children:e.jsx(Ui,{placeholder:"Please select"})}),e.jsxs(or,{className:"w-56",children:[e.jsx(_s,{value:"Option A",children:"Option A"}),e.jsx(_s,{value:"Option B",children:"Option B"}),e.jsx(_s,{value:"Option C",children:"Option C"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Gt,{children:"Tabs"}),e.jsxs(ux,{value:h,onValueChange:p,children:[e.jsxs(xx,{children:[e.jsx(ki,{value:"tab1",children:"Tab One"}),e.jsx(ki,{value:"tab2",children:"Tab Two"})]}),e.jsxs("div",{className:"mt-3",children:[e.jsx(_i,{value:"tab1",children:"This is tab one content."}),e.jsx(_i,{value:"tab2",children:"This is tab two content."})]})]})]}),e.jsxs("div",{className:"relative p-4 border rounded-lg",children:[e.jsx(be,{size:"sm",onClick:()=>{i(!0),setTimeout(()=>i(!1),1200)},children:"Show Loading"}),e.jsx(Do,{visible:o,message:"Loading..."})]})]})]})})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[e.jsxs(xs,{children:[e.jsx(Bs,{children:e.jsx(Xs,{children:"Performance Trend (Last 15 Days)"})}),e.jsx(fs,{children:e.jsx(b1,{data:f,title:void 0,color:b,height:220,formatValue:y=>`${(y/1e3).toFixed(1)}K`})})]}),e.jsxs(xs,{children:[e.jsx(Bs,{children:e.jsx(Xs,{children:"Tutorial Queries"})}),e.jsxs(fs,{children:[e.jsx(ji,{title:void 0,value:78,max:100,showPercentage:!0,valueLabel:"8,234 clicks"}),e.jsx("div",{className:"mt-6",children:e.jsx(w1,{data:[{name:"Tutorial Queries",value:78}],xAxisLabel:"%",height:120,color:b,formatValue:y=>`${y}%`})})]})]})]}),e.jsxs(xs,{children:[e.jsx(Bs,{children:e.jsx(Xs,{children:"Controls"})}),e.jsx(fs,{children:e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4 items-start",children:[e.jsx("div",{className:"w-80",children:e.jsx(Sa,{value:a,onChange:n,label:"DATE RANGE"})}),e.jsx(be,{onClick:()=>s(!0),children:"Open Confirm"})]})})]}),e.jsx(hx,{open:t,onOpenChange:s,title:"Confirm Action",message:"Are you sure you want to proceed?",confirmText:"Yes",cancelText:"Cancel",onConfirm:()=>console.log("✅ Confirmed")})]})}const Zm=v.lazy(()=>Bt(()=>import("./KeywordsResearchPrototypeView-Do7pU-gA.js"),__vite__mapDeps([0,1,2]))),N1=v.lazy(()=>Bt(()=>Promise.resolve().then(()=>ub),void 0)),k1=v.lazy(()=>Bt(()=>import("./SeoNewFlowView-XXkq9XxY.js"),__vite__mapDeps([3,1,2]))),_1=v.lazy(()=>Bt(()=>import("./AeoGeoNewFlowView-BXyy8Y4q.js"),__vite__mapDeps([4,1,2]))),C1=v.lazy(()=>Bt(()=>import("./ContentRefreshNewFlowView-Dsl_IpDG.js"),__vite__mapDeps([5,1,2]))),eu=v.lazy(()=>Bt(()=>import("./ContentGenerationFlowView-By5pYiqM.js"),__vite__mapDeps([6,1,7,8,9,2]))),S1=v.lazy(()=>Bt(()=>import("./PrototypeHomeView-DQZPmlhA.js"),__vite__mapDeps([10,1]))),E1=v.lazy(()=>Bt(()=>import("./HomeWorkflowsView-VmWIc6Ed.js"),__vite__mapDeps([11,1]))),A1=v.lazy(()=>Bt(()=>import("./SeoFlowView-mo0OxcKg.js"),__vite__mapDeps([12,1,7,2]))),T1=v.lazy(()=>Bt(()=>import("./AeoGeoFlowView-BQcGPuHi.js"),__vite__mapDeps([13,1,8,7,2]))),P1=v.lazy(()=>Bt(()=>import("./ContentRefreshFlowView-DMXhVQG1.js"),__vite__mapDeps([14,1,7,9,2])));function tu(t){switch(t){case"landing":return e.jsx(pi,{});case"homepage":return e.jsx(rj,{onNavigate:n=>{jt(n)}});case"home":return e.jsx(v.Suspense,{fallback:e.jsx("div",{style:{padding:16,fontFamily:"Inter, system-ui, sans-serif"},children:"Loading..."}),children:e.jsx(E1,{})});case"workflow":return e.jsx($v,{});case"workflow_prototype":return e.jsx(v.Suspense,{fallback:e.jsx("div",{style:{padding:16,fontFamily:"Inter, system-ui, sans-serif"},children:"Loading prototype..."}),children:e.jsx(Zm,{})});case"setup_prototype":return e.jsx(v.Suspense,{fallback:e.jsx("div",{style:{padding:16,fontFamily:"Inter, system-ui, sans-serif"},children:"Loading prototype..."}),children:e.jsx(N1,{})});case"app_prototype":return e.jsx(v.Suspense,{fallback:e.jsx("div",{style:{padding:16,fontFamily:"Inter, system-ui, sans-serif"},children:"Loading prototype..."}),children:e.jsx(Zm,{})});case"seo_new_flow":return e.jsx(v.Suspense,{fallback:e.jsx("div",{style:{padding:16,fontFamily:"Inter, system-ui, sans-serif"},children:"Loading SEO flow..."}),children:e.jsx(k1,{})});case"aeo_geo_new_flow":return e.jsx(v.Suspense,{fallback:e.jsx("div",{style:{padding:16,fontFamily:"Inter, system-ui, sans-serif"},children:"Loading AEO/GEO flow..."}),children:e.jsx(_1,{})});case"content_refresh_new_flow":return e.jsx(v.Suspense,{fallback:e.jsx("div",{style:{padding:16,fontFamily:"Inter, system-ui, sans-serif"},children:"Loading Content Refresh flow..."}),children:e.jsx(C1,{})});case"content_generation_new_flow":return e.jsx(v.Suspense,{fallback:e.jsx("div",{style:{padding:16,fontFamily:"Inter, system-ui, sans-serif"},children:"Loading Content Generation flow..."}),children:e.jsx(eu,{})});case"prototype_home":return e.jsx(v.Suspense,{fallback:e.jsx("div",{style:{padding:16,fontFamily:"Inter, system-ui, sans-serif"},children:"Loading prototype home..."}),children:e.jsx(S1,{})});case"seo_flow":return e.jsx(v.Suspense,{fallback:e.jsx("div",{style:{padding:16,fontFamily:"Inter, system-ui, sans-serif"},children:"Loading SEO flow..."}),children:e.jsx(A1,{})});case"aeo_geo_flow":return e.jsx(v.Suspense,{fallback:e.jsx("div",{style:{padding:16,fontFamily:"Inter, system-ui, sans-serif"},children:"Loading AEO/GEO flow..."}),children:e.jsx(T1,{})});case"content_refresh_flow":return e.jsx(v.Suspense,{fallback:e.jsx("div",{style:{padding:16,fontFamily:"Inter, system-ui, sans-serif"},children:"Loading Content Refresh flow..."}),children:e.jsx(P1,{})});case"content_generation_flow":return e.jsx(v.Suspense,{fallback:e.jsx("div",{style:{padding:16,fontFamily:"Inter, system-ui, sans-serif"},children:"Loading Content Generation flow..."}),children:e.jsx(eu,{})});case"company":return e.jsx(Ov,{});case"worksheets":return e.jsx(Hv,{});case"keyword_research":return e.jsx(wm,{});case"keyword_gap":return e.jsx(wm,{});case"content":return e.jsx(lk,{});case"knowledge":return e.jsx(oN,{});case"data_report":return e.jsx(_N,{});case"integration":return e.jsx(IN,{});case"attribution_insight":return e.jsx(LN,{});case"subscription":return e.jsx(y1,{});case"usage_history":return e.jsx(ik,{});case"table-new":return new URLSearchParams(window.location.search).get("prototype")==="true"?e.jsx(p1,{}):e.jsx(Th,{});case"competitors":return e.jsx(mh,{});case"keywords_tracking":return e.jsx(ZN,{});case"page_tracking":return e.jsx(dh,{});case"geo_prompt":return e.jsx(ih,{});case"admin":try{window.location.pathname!=="/admin/referral"&&(window.history.replaceState({},"","/admin/referral"),window.dispatchEvent(new PopStateEvent("popstate")))}catch{}return e.jsx("div",{style:{padding:16,fontFamily:"Inter, system-ui, sans-serif"},children:"Redirecting to admin console..."});case"components_test":return e.jsx(v1,{});default:return e.jsx(pi,{})}}function su({tab:t}){const s=v.useCallback(n=>{jt(n)},[]);return v.useEffect(()=>{window.location.pathname==="/app/prototype/seo"&&window.location.replace("/app/prototype/seo/20260121")},[]),v.useEffect(()=>{window.location.pathname==="/app/prototype/aeo-geo"&&window.location.replace("/app/prototype/aeo-geo/20260121")},[]),v.useEffect(()=>{window.location.pathname==="/app/prototype/content-refresh"&&window.location.replace("/app/prototype/content-refresh/20260121")},[]),t==="table-new"&&new URLSearchParams(window.location.search).get("prototype")==="true"?e.jsx(za,{children:tu(t)}):e.jsx(za,{children:e.jsx(Ex,{current:t,onChange:s,children:tu(t)})})}const Hc="promotion_activation_marker_v1",qc="auto_activate",Ph="referral_code";function I1(){try{const t=sessionStorage.getItem(Hc);if(!t)return null;const s=JSON.parse(t);return s?.referralCode?s:null}catch{return null}}function M1(t){try{const s={referralCode:t,createdAtMs:Date.now()};sessionStorage.setItem(Hc,JSON.stringify(s))}catch{}}
554function qo(){try{sessionStorage.removeItem(Hc)}catch{}}function tc(t){return String(t||"").trim().toUpperCase()}function R1(){try{const t=new URLSearchParams(window.location.search),s=t.get(Ph),a=t.get(qc)==="1";return{referralCode:s?tc(s):null,autoActivate:a}}catch{return{referralCode:null,autoActivate:!1}}}function D1(t){try{const s=new URL(window.location.href);s.searchParams.set(Ph,t),s.searchParams.set(qc,"1"),window.history.replaceState({},"",`${s.pathname}${s.search}${s.hash}`),window.dispatchEvent(new PopStateEvent("popstate"))}catch{}}function Yo(){try{const t=new URL(window.location.href);t.searchParams.delete(qc),window.history.replaceState({},"",`${t.pathname}${t.search}${t.hash}`),window.dispatchEvent(new PopStateEvent("popstate"))}catch{}}function L1({referralCode:t}){const{toast:s}=_t(),a=r.useMemo(()=>tc(t),[t]),[n,o]=r.useState(!1),[i,l]=r.useState(!0),[c,d]=r.useState(!0),[m,h]=r.useState(null),[p,f]=r.useState(null),[b,y]=r.useState(null),[x,u]=r.useState(!1),[g,w]=r.useState(null),[_,E]=r.useState(!1),[N,S]=r.useState(0);r.useEffect(()=>{let $=!0;return(async()=>{try{const H=await rs.isAuthenticated();if(!$)return;o(H)}catch{if(!$)return;o(!1)}finally{$&&d(!1)}})(),()=>{$=!1}},[]),r.useEffect(()=>{let $=!0;return(async()=>{if(!a){l(!1),y("Invalid referral code.");return}l(!0),y(null);try{const H=await v0(a);if(!$)return;h(H)}catch(H){if(console.warn("⚠️ [PromotionPage] Failed to load public report:",H),!$)return;h(null),y(H?.message||"Failed to load report.");try{const K=await j0(a);if(!$)return;f(K)}catch(K){if(console.warn("⚠️ [PromotionPage] Failed to load status:",K),!$)return;f(null)}}finally{$&&l(!1)}})(),()=>{$=!1}},[a]);const k=r.useCallback(async()=>{if(a){u(!0),w(null);try{const $=await Tl(a);if(!$.success)throw new Error($.message||"Failed to activate referral code.");console.log("✅ [PromotionPage] Referral activated, redirecting to homepage"),s({title:"Unlocked.",description:"Referral activated. Redirecting to your homepage..."}),qo(),Yo(),setTimeout(()=>jt("homepage"),600)}catch($){console.error("❌ [PromotionPage] Activation failed:",$),qo(),Yo(),w($?.message||"Failed to activate referral code."),s({title:"Activation failed",description:$?.message||"Failed to activate referral code."})}finally{u(!1)}}},[a,s]),D=r.useCallback(async()=>{if(!a)return;E(!0),S(0);const $=7e3,H=100,K=$/H;let X=0;const V=setInterval(()=>{X++;const P=Math.min(95,X/K*100);S(P)},H);try{const P=await Tl(a);if(clearInterval(V),S(100),await new Promise(A=>setTimeout(A,500)),!P.success)throw new Error(P.message||"Failed to activate referral code.");console.log("✅ [PromotionPage] Auto-activation succeeded, redirecting"),s({title:"Unlocked.",description:"Referral activated. Redirecting to your homepage..."}),qo(),Yo(),setTimeout(()=>jt("homepage"),600)}catch(P){clearInterval(V),console.error("❌ [PromotionPage] Auto-activation failed:",P),qo(),Yo(),w(P?.message||"Failed to activate referral code."),s({title:"Activation failed",description:P?.message||"Failed to activate referral code."})}finally{E(!1),u(!1)}},[a,s]);r.useEffect(()=>{if(!n)return;const $=R1();if($.autoActivate&&$.referralCode&&$.referralCode===a){if(_||x)return;console.log("🔁 [PromotionPage] Auto-activation triggered from URL marker"),D();return}const K=I1();K&&tc(K.referralCode)===a&&(_||x||(console.log("🔁 [PromotionPage] Auto-activation triggered from session marker"),D()))},[x,_,n,a,D]);const F=r.useCallback(async()=>{w(null);try{const $=await rs.isAuthenticated();if(o($),$){try{if((await Dn())?.company){console.log("✅ [PromotionPage] User already has company, redirecting to homepage"),s({title:"Redirecting",description:"You already have a company. Redirecting to homepage..."}),setTimeout(()=>jt("homepage"),600);return}}catch(H){H?.response?.status!==404&&!H?.message?.includes("No active company")&&console.error("⚠️ [PromotionPage] Failed to check existing company:",H)}await k();return}D1(a),M1(a),console.log("🧩 [PromotionPage] Starting login for referral activation (url marker set)"),await An()}catch($){console.error("❌ [PromotionPage] Failed to start sign-in:",$),s({title:"Sign-in failed",description:$?.message||"Failed to start sign-in."})}},[a,k,s]),R=e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(be,{onClick:F,disabled:x||c,className:"bg-indigo-600 hover:bg-indigo-700 rounded-xl",size:"sm",children:x?e.jsxs(e.Fragment,{children:[e.jsx(He,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}),"Activating..."]}):"Claim & Start"})}),L=e.jsx(be,{onClick:F,disabled:x||c,className:"bg-indigo-600 hover:bg-indigo-700 rounded-xl",size:"lg",children:x?e.jsxs(e.Fragment,{children:[e.jsx(He,{className:"h-4 w-4 mr-2 animate-spin"}),"Activating..."]}):"Claim & Start"});return e.jsxs("div",{className:"min-h-screen bg-slate-50 flex flex-col",children:[e.jsx(ir,{showMarketSwitcher:!1,showCredits:!1,customRightContent:n?void 0:R}),e.jsx("div",{className:"flex-1 max-w-7xl mx-auto w-full px-4 py-8",children:e.jsxs("div",{className:"space-y-6",children:[_&&e.jsx(Nx,{progress:N}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("h1",{className:"text-3xl sm:text-4xl font-bold tracking-tight text-slate-900",children:"Stop guessing. This report shows exactly where you’re losing traffic."}),e.jsx("p",{className:"text-slate-600 leading-relaxed",children:"Your competitors won’t wait for you. Claim this report, activate the referral, and start the journey—now."}),p&&e.jsxs("div",{className:"text-[12px] text-slate-500",children:["Status:"," ",e.jsx("span",{className:"font-medium text-slate-700",children:p.analysis_status})," ","• Used"," ",e.jsx("span",{className:"font-medium text-slate-700",children:p.use_count})," ","times"]}),g&&e.jsx("div",{className:"text-[12px] text-red-600 bg-red-50 border border-red-200 rounded-lg px-3 py-2",children:g})]}),e.jsx("div",{children:i?e.jsx("div",{className:"bg-white border border-slate-100 rounded-xl p-10 flex items-center justify-center",children:e.jsx(He,{className:"h-7 w-7 animate-spin text-slate-800"})}):m?e.jsx(Wi,{analysisResult:m,showPlanMask:!1,showMarketTabs:!1,showContinueButton:!1,referralCode:a,customTopButton:L,customBottomButton:L}):e.jsxs("div",{className:"bg-white border border-slate-100 rounded-xl p-6",children:[e.jsx("div",{className:"text-slate-900 font-semibold",children:"Report unavailable"}),e.jsx("div",{className:"text-[12px] text-slate-600 mt-1",children:b||"This referral report is not ready yet. Please try again later."})]})})]})})]})}function z1(t){return e.jsx(za,{children:e.jsx(L1,{...t})})}const El={async analyzeUrl(t){return await Je("/structured_data/analyze_url",t)},async analyzeCode(t){return await Je("/structured_data/analyze_code",t)}};function au({status:t}){return t==="pass"?e.jsx(Rs,{className:"h-4 w-4 text-green-600"}):t==="warning"?e.jsx(Ja,{className:"h-4 w-4 text-amber-600"}):t==="error"?e.jsx(fu,{className:"h-4 w-4 text-red-600"}):e.jsx(Gs,{className:"h-4 w-4 text-slate-400"})}function $1(){const{toast:t}=_t(),[s,a]=r.useState("url"),[n,o]=r.useState(""),[i,l]=r.useState(""),[c,d]=r.useState(""),[m,h]=r.useState(!1),[p,f]=r.useState(null),b=r.useMemo(()=>
554p?.summary,[p]),y=async()=>{h(!0);try{let x;s==="url"?x=await El.analyzeUrl({url:n.trim(),options:{max_html_kb:512,timeout_seconds:15}}):s==="html"?x=await El.analyzeCode({code:i,code_type:"html"}):x=await El.analyzeCode({code:c,code_type:"json_ld"}),f(x),t({title:"Analysis completed",description:`Errors: ${x?.summary?.error_count??0} • Warnings: ${x?.summary?.warning_count??0}`})}catch(x){console.error("❌ [StructuredDataTestPage] analyze failed:",x),t({title:"Analysis failed",description:x?.message||"Unknown error"})}finally{h(!1)}};return e.jsx("div",{className:"min-h-screen bg-slate-50",children:e.jsxs("div",{className:"max-w-5xl mx-auto p-6 space-y-6",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-slate-900",children:"Structured Data Test"}),e.jsx("p",{className:"text-sm text-slate-600",children:"Analyze JSON-LD / Microdata / RDFa from an SEO, GEO, and AEO perspective."})]}),e.jsx("a",{className:"text-sm text-slate-600 hover:text-slate-900 underline",href:"/",children:"Back to Home"})]}),e.jsxs("div",{className:"bg-white border border-slate-200 rounded-xl p-4 space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("button",{className:`px-3 py-1.5 rounded-lg text-sm border ${s==="url"?"bg-slate-900 text-white border-slate-900":"bg-white text-slate-700 border-slate-200 hover:bg-slate-50"}`,onClick:()=>a("url"),children:"URL"}),e.jsx("button",{className:`px-3 py-1.5 rounded-lg text-sm border ${s==="html"?"bg-slate-900 text-white border-slate-900":"bg-white text-slate-700 border-slate-200 hover:bg-slate-50"}`,onClick:()=>a("html"),children:"HTML"}),e.jsx("button",{className:`px-3 py-1.5 rounded-lg text-sm border ${s==="json_ld"?"bg-slate-900 text-white border-slate-900":"bg-white text-slate-700 border-slate-200 hover:bg-slate-50"}`,onClick:()=>a("json_ld"),children:"JSON-LD"})]}),s==="url"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium text-slate-900",children:"URL"}),e.jsx("input",{value:n,onChange:x=>o(x.target.value),placeholder:"https://example.com/page",className:"w-full px-3 py-2 rounded-lg border border-slate-200 focus:outline-none focus:ring-2 focus:ring-slate-300"})]}),s==="html"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium text-slate-900",children:"HTML"}),e.jsx("textarea",{value:i,onChange:x=>l(x.target.value),placeholder:"<html>...</html>",className:"w-full h-44 px-3 py-2 rounded-lg border border-slate-200 font-mono text-xs focus:outline-none focus:ring-2 focus:ring-slate-300"})]}),s==="json_ld"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium text-slate-900",children:"JSON-LD"}),e.jsx("textarea",{value:c,onChange:x=>d(x.target.value),placeholder:'{"@context":"https://schema.org","@type":"Organization","name":"Example"}',className:"w-full h-44 px-3 py-2 rounded-lg border border-slate-200 font-mono text-xs focus:outline-none focus:ring-2 focus:ring-slate-300"})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"text-xs text-slate-500",children:b?e.jsxs(e.Fragment,{children:["Pass: ",b.pass_count," • Warnings: ",b.warning_count," • Errors: ",b.error_count," • Info:"," ",b.info_count]}):"Run an analysis to see results."}),e.jsx("button",{onClick:y,disabled:m,className:`px-4 py-2 rounded-lg text-sm font-medium ${m?"bg-slate-200 text-slate-500":"bg-slate-900 text-white hover:bg-slate-800"}`,children:m?"Analyzing...":"Analyze"})]})]}),p&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"bg-white border border-slate-200 rounded-xl p-4",children:[e.jsx("div",{className:"text-sm font-semibold text-slate-900 mb-2",children:"Detected Items"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:(p.detected_items||[]).length===0?e.jsx("div",{className:"text-sm text-slate-600",children:"No structured data types detected."}):p.detected_items.map((x,u)=>e.jsxs("span",{className:"text-xs px-2 py-1 rounded-full bg-slate-100 text-slate-700",title:x.source_syntax,children:[x.schema_type," × ",x.count]},`${x.schema_type}-${u}`))})]}),(p.categories||[]).map(x=>e.jsxs("details",{className:"bg-white border border-slate-200 rounded-xl p-4",open:!0,children:[e.jsxs("summary",{className:"cursor-pointer flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(au,{status:x.status}),e.jsx("span",{className:"text-sm font-semibold text-slate-900",children:x.title}),e.jsxs("span",{className:"text-xs text-slate-500",children:["(",(x.checks||[]).length,")"]})]}),e.jsx("span",{className:"text-xs text-slate-500",children:"Toggle"})]}),e.jsx("div",{className:"mt-3 space-y-2",children:(x.checks||[]).map(u=>e.jsxs("div",{className:"flex items-start gap-3 p-3 rounded-lg border border-slate-100",children:[e.jsx("div",{className:"mt-0.5",children:e.jsx(au,{status:u.status})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"text-sm font-medium text-slate-900 truncate",children:u.title}),e.jsx("div",{className:"text-sm text-slate-700",children:u.message}),u.recommendation&&e.jsxs("div",{className:"text-xs text-slate-500 mt-1",children:["Recommendation: ",u.recommendation]}),u.evidence&&e.jsxs("details",{className:"mt-2",children:[e.jsx("summary",{className:"text-xs text-slate-500 cursor-pointer",children:"Evidence"}),e.jsx("pre",{className:"text-xs bg-slate-50 border border-slate-200 rounded-lg p-2 overflow-auto",children:JSON.stringify(u.evidence,null,2)})]})]})]},u.id))})]},x.id)),p.raw_extracted&&e.jsxs("details",{className:"bg-white border border-slate-200 rounded-xl p-4",children:[e.jsx("summary",{className:"cursor-pointer text-sm font-semibold text-slate-900",children:"Raw Extracted (debug)"}),e.jsx("pre",{className:"mt-3 text-xs bg-slate-50 border border-slate-200 rounded-lg p-3 overflow-auto",children:JSON.stringify(p.raw_extracted,null,2)})]})]})]})})}function F1(){return e.jsx(za,{children:e.jsx($1,{})})}function O1(){const[t,s]=r.useState("loading"),[a,n]=r.useState("Completing Shopify authorization..."),[o,i]=r.useState("/app/integration");return r.useEffect(()=>{let l="/app/integration";try{const h=sessionStorage.getItem(Pi);h&&(l=h,sessionStorage.removeItem(Pi))}catch{}i(l);const d=new URLSearchParams(window.location.search).get("error");
554if(d){s("error"),n(decodeURIComponent(d)||"Authorization failed"),setTimeout(()=>{window.location.href=l},3e3);return}const m=setTimeout(()=>{s("success"),n("Shopify connected successfully!"),setTimeout(()=>{window.location.href=l},1500)},1e3);return()=>clearTimeout(m)},[]),e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-slate-50 to-slate-100 flex items-center justify-center p-4",children:e.jsxs("div",{className:"bg-white rounded-2xl shadow-xl p-8 max-w-md w-full text-center",children:[e.jsx("div",{className:"mb-6",children:e.jsx("div",{className:"w-16 h-16 mx-auto bg-green-50 rounded-2xl flex items-center justify-center",children:e.jsx("svg",{className:"w-10 h-10 text-green-600",viewBox:"0 0 24 24",fill:"currentColor",children:e.jsx("path",{d:"M15.337 23.979l7.216-1.561s-2.604-17.613-2.625-17.758c-.022-.145-.157-.236-.29-.252-.133-.016-2.947-.225-2.947-.225s-1.936-1.936-2.158-2.158c-.066-.066-.154-.1-.244-.108l-.992 22.062zM11.903 5.818l-.448-.048-.07-.002c-.1 0-.191.027-.276.073l-.395 1.217c-.587-1.788-1.633-3.429-3.478-3.429-.05 0-.1.002-.15.004C6.625 3.134 6.082 2.89 5.636 2.89c-3.194 0-4.722 3.993-5.2 6.018-.622.19-1.062.328-1.12.345-.348.108-.36.12-.405.451C-1.134 10.106 0 20.063 0 20.063l12.234 2.104V5.752l-.331.066z"})})})}),e.jsxs("div",{className:"mb-4",children:[t==="loading"&&e.jsx(He,{className:"w-12 h-12 mx-auto text-green-600 animate-spin"}),t==="success"&&e.jsx(Rs,{className:"w-12 h-12 mx-auto text-green-600"}),t==="error"&&e.jsx(Ss,{className:"w-12 h-12 mx-auto text-red-500"})]}),e.jsxs("h1",{className:`text-xl font-semibold mb-2 ${t==="error"?"text-red-700":"text-slate-900"}`,children:[t==="loading"&&"Processing...",t==="success"&&"Success!",t==="error"&&"Authorization Failed"]}),e.jsx("p",{className:"text-slate-600 mb-6",children:a}),t==="loading"&&e.jsxs("div",{className:"flex justify-center gap-1.5",children:[e.jsx("div",{className:"w-2 h-2 bg-green-400 rounded-full animate-bounce",style:{animationDelay:"0ms"}}),e.jsx("div",{className:"w-2 h-2 bg-green-400 rounded-full animate-bounce",style:{animationDelay:"150ms"}}),e.jsx("div",{className:"w-2 h-2 bg-green-400 rounded-full animate-bounce",style:{animationDelay:"300ms"}})]}),t!=="loading"&&e.jsx("p",{className:"text-xs text-slate-400 mt-4",children:"Redirecting..."})]})})}function B1(){return v.useEffect(()=>{setTimeout(()=>{window.location.href="https://zcal.co/i/uNBfCB0e"},50)},[]),e.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100vh",fontFamily:"Inter, system-ui, sans-serif"},children:"Redirecting..."})}class U1{static{this.initialized=!1}static initOnce(){if(this.initialized)return;const s=this.readProjectId();if(!s){console.log("🔕 Clarity disabled: VITE_CLARITY_PROJECT_ID is not set");return}try{Yp.init(s),this.initialized=!0,console.log("✅ Clarity initialized")}catch(a){console.warn("⚠️ Failed to initialize Clarity:",a)}}static readProjectId(){return String(wa.getString("VITE_CLARITY_PROJECT_ID")??"").trim()}}const Ih=document.getElementById("root");if(!Ih)throw new Error("Root element #root not found");U1.initOnce();window.addEventListener("unhandledrejection",t=>{if(t.reason&&(t.reason.message?.includes("Extension context invalidated")||t.reason.message?.includes("extension")||t.reason.stack?.includes("extensions/")||t.reason.stack?.includes("all-frames.js"))){t.preventDefault(),console.warn("🔕 Suppressed browser extension error:",t.reason.message||t.reason);return}});window.addEventListener("error",t=>{if(t.filename?.includes("extensions/")||t.filename?.includes("all-frames.js")||t.filename?.includes("chrome-extension://")||t.message?.includes("Extension context invalidated")){t.preventDefault(),console.warn("🔕 Suppressed browser extension error:",t.message);return}});function K1(){const[t,s]=v.useState(()=>({pathname:window.location.pathname,search:window.location.search})),a=t.pathname,[n,o]=v.useState(!1),i=v.useRef(null),l=v.useRef(new Set);if(v.useEffect(()=>{const f=()=>{s({pathname:window.location.pathname,search:window.location.search})};return window.addEventListener("popstate",f),()=>window.removeEventListener("popstate",f)},[]),v.useEffect(()=>{if(a==="/app/homepage"||a==="/app/homepage/"||a==="/app/workflow"||a==="/app/workflow/")try{window.history.replaceState({},"","/app"),window.dispatchEvent(new PopStateEvent("popstate"))}catch{window.location.href="/app"}}
554,[a]),v.useEffect(()=>{a.startsWith("/auth/google/callback")||a.startsWith("/auth/logto/callback")||Il.initOnce()},[a]),v.useEffect(()=>{if(a.startsWith("/admin")||a.startsWith("/app/admin")||a==="/app/setup"||a==="/app/setup/report"||a==="/app/landing"||a==="/"||a==="/app/prototype"||a==="/app/prototype/"||a==="/app/prototpye"||a==="/app/prototpye/"||a==="/app/subscription/checkout"||a==="/app/referral"||a==="/app/referral/report"||a==="/referral"||a.startsWith("/app/subscription/success")||a.startsWith("/app/subscription/cancel")||a==="/test/structured-data"||a==="/test/structured-data/"){l.current.add(a),i.current=null,o(!1);return}const f=hi(a);if(!f||f==="landing"){l.current.add(a),i.current=null,o(!1);return}if(l.current.has(a)||i.current===a)return;i.current=a,l.current.add(a),o(!0);let b=!0,y=!1;return(async()=>{try{if(!await rs.isAuthenticated()||!b){b&&(i.current=null,o(!1));return}const u=await Cs.getAccountCached({ttlMs:1e4});if(!b||y)return;if((u.setup_company_analysis_status!=="completed"||u.setup_init_status!=="completed")&&!y){if(console.log("⚠️ Setup incomplete, redirecting to /app/setup"),y=!0,window.location.pathname!=="/app/setup"){i.current=null,o(!1),window.location.href="/app/setup";return}}else{try{const w=await Xa();if(!!!(w&&w.status==="active")&&!y&&(console.log("💳 No active plan, redirecting to /app/setup"),y=!0,window.location.pathname!=="/app/setup")){i.current=null,o(!1),window.location.href="/app/setup";return}}catch(w){if(console.warn("⚠️ Failed to check subscription status:",w),!y){y=!0,i.current=null,o(!1),window.location.href="/app/setup";return}}console.log("✅ Setup complete + active plan, allowing access")}b&&!y&&(i.current=null,o(!1))}catch(x){console.error("Failed to check setup status:",x),b&&!y&&(i.current=null,o(!1))}})(),()=>{b=!1}},[a]),a.startsWith("/auth/google/callback"))return e.jsx(o0,{});if(a.startsWith("/auth/logto/callback"))return e.jsx(K0,{});if(a.startsWith("/auth/shopify/callback"))return e.jsx(O1,{});if(a==="/privacy")return e.jsx(G0,{});if(a==="/terms")return e.jsx(W0,{});if(a==="/sms"||a==="/sms-opt-in")return e.jsx(V0,{});if(a==="/booking")return e.jsx(B1,{});if(a==="/test/structured-data"||a==="/test/structured-data/")return e.jsx(F1,{});const d=(f=>{if(f.startsWith("/promotion/"))return f.split("/").filter(Boolean)[1]||null;if(f.startsWith("/geo-report/")){const b=f.split("/").filter(Boolean);return b.length<3?null:b[b.length-1]||null}return null})(a);if(d)return e.jsx(z1,{referralCode:d});if(a==="/blog"||a==="/blogs"||a==="/blogs/"||a==="/blog/")return e.jsx(sf,{});if(a.startsWith("/blog/")&&a!=="/blog"&&a!=="/blog/"){const f=a.replace("/blog/","");return e.jsx(af,{slug:f})}
554if(a==="/blog_upload"||a==="/blog_upload/")return window.history.replaceState({},"","/admin/blog_upload"),window.dispatchEvent(new PopStateEvent("popstate")),e.jsx(il,{});if(a==="/app/admin"||a.startsWith("/app/admin/"))return window.history.replaceState({},"","/admin/referral"),window.dispatchEvent(new PopStateEvent("popstate")),e.jsx(il,{});if(a==="/admin"||a.startsWith("/admin/"))return e.jsx(il,{});if(a==="/app/setup")return e.jsx(hb,{});if(a==="/app/setup/report")return e.jsx(qb,{});if(a==="/app/referral/report")return e.jsx(Jb,{});if(a==="/app/referral"||a==="/referral")return e.jsx(Vb,{});if(a==="/landingpage"||a==="/landingpage/")return e.jsx(pi,{});if(a.startsWith("/app/subscription/success")||a.startsWith("/app/subscription/cancel")||a.startsWith("/seo/subscription/success")||a.startsWith("/seo/subscription/cancel"))return e.jsx(wb,{});if(a==="/app/subscription/checkout")return e.jsx(Eb,{});const h=new URLSearchParams(window.location.search).get("domain");if(a==="/app/competitors/detail"&&h){const f=v.lazy(()=>Bt(()=>import("./CompetitorDetailPage-Def0LlbR.js"),__vite__mapDeps([15,1,2])));return e.jsx(v.Suspense,{fallback:e.jsx("div",{children:"Loading..."}),children:e.jsx(f,{})})}const p=hi(a);return p?p!=="landing"&&n&&!l.current.has(a)?e.jsx("div",{style:{padding:16,fontFamily:"Inter, system-ui, sans-serif"},children:"Checking setup status..."}):p==="report"?(window.history.replaceState({},"","/app/page_ranking?tab=report"),e.jsx(su,{tab:"data_report"})):e.jsx(su,{tab:p}):e.jsx(r0,{})}Jp.createRoot(Ih).render(e.jsx(K1,{}));export{Mo as $,mm as A,be as B,Nw as C,Ht as D,Ov as E,wm as F,mh as G,LN as H,bt as I,_N as J,oN as K,ih as L,dh as M,ZN as N,Ds as O,xn as P,Va as Q,fl as R,Ex as S,za as T,nd as U,wr as V,kw as W,ta as X,mo as Y,Io as Z,qx as _,_t as a,zc as a0,Ao as a1,Er as a2,ea as a3,Dn as a4,eh as a5,Ai as a6,sh as a7,Qx as a8,cj as a9,Zx as aa,Jx as ab,qi as ac,lr as ad,Lj as ae,ia as af,Bc as ag,Oc as ah,XN as ai,cr as aj,Vt as ak,Wt as al,fj as am,H1 as an,Ji as ao,Mi as ap,Gt as aq,yh as ar,am as as,Iu as at,bj as au,Ca as av,$r as aw,Cs as ax,ls as b,Kt as c,qt as d,Zt as e,Yt as f,Ns as g,Js as h,V1 as i,Je as j,ot as k,nr as l,rr as m,jt as n,Ui as o,or as p,_s as q,ds as r,Tn as s,ma as t,sg as u,$a as v,Pr as w,vi as x,Bi as y,IN as z};

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.