@cedros/pay-react 1.1.0 → 1.1.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/admin/types.d.ts +25 -7
- package/dist/admin/types.d.ts.map +1 -1
- package/dist/{index-D2d_ukkR.mjs → index-CUoeIbXT.mjs} +6 -6
- package/dist/{index-DGkSHjb1.js → index-CWbWPgXt.js} +1 -1
- package/dist/index.js +1 -1
- package/dist/index.mjs +1 -1
- package/dist/{sections-6IcZ6JeN.js → sections-D7gSCYck.js} +1 -1
- package/dist/{sections-a0Dz-MMz.mjs → sections-TiollkCu.mjs} +1 -1
- package/package.json +1 -1
package/dist/admin/types.d.ts
CHANGED
|
@@ -15,6 +15,8 @@ export interface AdminSectionConfig {
|
|
|
15
15
|
order?: number;
|
|
16
16
|
/** Required permission to view this section */
|
|
17
17
|
requiredPermission?: string;
|
|
18
|
+
/** Optional badge shown next to the label (e.g., count indicator) */
|
|
19
|
+
badge?: ReactNode;
|
|
18
20
|
}
|
|
19
21
|
/**
|
|
20
22
|
* Sidebar group configuration.
|
|
@@ -25,16 +27,22 @@ export interface AdminGroupConfig {
|
|
|
25
27
|
/** Display label */
|
|
26
28
|
label: string;
|
|
27
29
|
/** Sort order (lower = first) */
|
|
28
|
-
order
|
|
29
|
-
/** If true, group
|
|
30
|
-
|
|
30
|
+
order: number;
|
|
31
|
+
/** If true, group starts collapsed */
|
|
32
|
+
defaultCollapsed?: boolean;
|
|
33
|
+
/** Optional icon for the group header */
|
|
34
|
+
icon?: ReactNode;
|
|
31
35
|
}
|
|
32
36
|
/**
|
|
33
37
|
* Props passed to section components by the shell.
|
|
34
38
|
*/
|
|
35
39
|
export interface AdminSectionProps {
|
|
36
|
-
/** Plugin context with auth and config */
|
|
37
|
-
|
|
40
|
+
/** Plugin context with auth and config, passed by AdminShell as pluginContext */
|
|
41
|
+
pluginContext: PluginContext;
|
|
42
|
+
/** Number of items per page for paginated lists */
|
|
43
|
+
pageSize: number;
|
|
44
|
+
/** Auto-refresh interval in milliseconds (0 = disabled) */
|
|
45
|
+
refreshInterval: number;
|
|
38
46
|
}
|
|
39
47
|
/**
|
|
40
48
|
* Host context aggregated from all providers.
|
|
@@ -46,6 +54,8 @@ export interface HostContext {
|
|
|
46
54
|
user: {
|
|
47
55
|
id: string;
|
|
48
56
|
email?: string;
|
|
57
|
+
name?: string;
|
|
58
|
+
picture?: string;
|
|
49
59
|
} | null;
|
|
50
60
|
getAccessToken: () => string | null;
|
|
51
61
|
serverUrl: string;
|
|
@@ -62,6 +72,12 @@ export interface HostContext {
|
|
|
62
72
|
role: string;
|
|
63
73
|
permissions: string[];
|
|
64
74
|
};
|
|
75
|
+
/** Dashboard-level access control */
|
|
76
|
+
dashboard?: {
|
|
77
|
+
canAccess: (sectionId: string) => boolean;
|
|
78
|
+
};
|
|
79
|
+
/** Arbitrary extension data from host app */
|
|
80
|
+
custom?: Record<string, unknown>;
|
|
65
81
|
}
|
|
66
82
|
/**
|
|
67
83
|
* Plugin-specific context passed to section components.
|
|
@@ -109,7 +125,9 @@ export interface AdminPlugin {
|
|
|
109
125
|
checkPermission: (permission: string, hostContext: HostContext) => boolean;
|
|
110
126
|
/** CSS namespace for style isolation (e.g., 'cedros-admin') */
|
|
111
127
|
cssNamespace: string;
|
|
112
|
-
/**
|
|
113
|
-
|
|
128
|
+
/** Called when plugin is registered with the shell */
|
|
129
|
+
onRegister?: (hostContext: HostContext) => void;
|
|
130
|
+
/** Called when plugin is unregistered from the shell */
|
|
131
|
+
onUnregister?: () => void;
|
|
114
132
|
}
|
|
115
133
|
//# sourceMappingURL=types.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/admin/types.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,KAAK,EAAE,aAAa,EAAE,SAAS,EAAE,MAAM,OAAO,CAAC;AAEtD;;GAEG;AACH,MAAM,WAAW,kBAAkB;IACjC,gCAAgC;IAChC,EAAE,EAAE,MAAM,CAAC;IACX,+BAA+B;IAC/B,KAAK,EAAE,MAAM,CAAC;IACd,yBAAyB;IACzB,IAAI,EAAE,SAAS,CAAC;IAChB,uDAAuD;IACvD,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,8CAA8C;IAC9C,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,+CAA+C;IAC/C,kBAAkB,CAAC,EAAE,MAAM,CAAC;
|
|
1
|
+
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/admin/types.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,KAAK,EAAE,aAAa,EAAE,SAAS,EAAE,MAAM,OAAO,CAAC;AAEtD;;GAEG;AACH,MAAM,WAAW,kBAAkB;IACjC,gCAAgC;IAChC,EAAE,EAAE,MAAM,CAAC;IACX,+BAA+B;IAC/B,KAAK,EAAE,MAAM,CAAC;IACd,yBAAyB;IACzB,IAAI,EAAE,SAAS,CAAC;IAChB,uDAAuD;IACvD,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,8CAA8C;IAC9C,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,+CAA+C;IAC/C,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B,qEAAqE;IACrE,KAAK,CAAC,EAAE,SAAS,CAAC;CACnB;AAED;;GAEG;AACH,MAAM,WAAW,gBAAgB;IAC/B,uBAAuB;IACvB,EAAE,EAAE,MAAM,CAAC;IACX,oBAAoB;IACpB,KAAK,EAAE,MAAM,CAAC;IACd,iCAAiC;IACjC,KAAK,EAAE,MAAM,CAAC;IACd,sCAAsC;IACtC,gBAAgB,CAAC,EAAE,OAAO,CAAC;IAC3B,yCAAyC;IACzC,IAAI,CAAC,EAAE,SAAS,CAAC;CAClB;AAED;;GAEG;AACH,MAAM,WAAW,iBAAiB;IAChC,iFAAiF;IACjF,aAAa,EAAE,aAAa,CAAC;IAC7B,mDAAmD;IACnD,QAAQ,EAAE,MAAM,CAAC;IACjB,2DAA2D;IAC3D,eAAe,EAAE,MAAM,CAAC;CACzB;AAED;;;GAGG;AACH,MAAM,WAAW,WAAW;IAC1B,6CAA6C;IAC7C,WAAW,CAAC,EAAE;QACZ,IAAI,EAAE;YAAE,EAAE,EAAE,MAAM,CAAC;YAAC,KAAK,CAAC,EAAE,MAAM,CAAC;YAAC,IAAI,CAAC,EAAE,MAAM,CAAC;YAAC,OAAO,CAAC,EAAE,MAAM,CAAA;SAAE,GAAG,IAAI,CAAC;QAC7E,cAAc,EAAE,MAAM,MAAM,GAAG,IAAI,CAAC;QACpC,SAAS,EAAE,MAAM,CAAC;KACnB,CAAC;IACF,2CAA2C;IAC3C,SAAS,CAAC,EAAE;QACV,aAAa,CAAC,EAAE,MAAM,CAAC;QACvB,QAAQ,CAAC,EAAE,MAAM,CAAC;QAClB,SAAS,EAAE,MAAM,CAAC;KACnB,CAAC;IACF,0CAA0C;IAC1C,GAAG,CAAC,EAAE;QACJ,KAAK,EAAE,MAAM,CAAC;QACd,IAAI,EAAE,MAAM,CAAC;QACb,WAAW,EAAE,MAAM,EAAE,CAAC;KACvB,CAAC;IACF,qCAAqC;IACrC,SAAS,CAAC,EAAE;QACV,SAAS,EAAE,CAAC,SAAS,EAAE,MAAM,KAAK,OAAO,CAAC;KAC3C,CAAC;IACF,6CAA6C;IAC7C,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CAClC;AAED;;;GAGG;AACH,MAAM,WAAW,aAAa;IAC5B,yBAAyB;IACzB,SAAS,EAAE,MAAM,CAAC;IAClB,yCAAyC;IACzC,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,wCAAwC;IACxC,cAAc,EAAE,MAAM,MAAM,GAAG,IAAI,CAAC;IACpC,qCAAqC;IACrC,aAAa,EAAE,CAAC,UAAU,EAAE,MAAM,KAAK,OAAO,CAAC;IAC/C,0CAA0C;IAC1C,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,2BAA2B;IAC3B,UAAU,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACtC;AAED;;;GAGG;AACH,MAAM,WAAW,WAAW;IAC1B,+BAA+B;IAC/B,EAAE,EAAE,MAAM,CAAC;IACX,mBAAmB;IACnB,IAAI,EAAE,MAAM,CAAC;IACb,8BAA8B;IAC9B,OAAO,EAAE,MAAM,CAAC;IAEhB,yCAAyC;IACzC,QAAQ,EAAE,kBAAkB,EAAE,CAAC;IAC/B,oCAAoC;IACpC,MAAM,CAAC,EAAE,gBAAgB,EAAE,CAAC;IAC5B,yDAAyD;IACzD,UAAU,EAAE,MAAM,CAAC,MAAM,EAAE,aAAa,CAAC,iBAAiB,CAAC,CAAC,CAAC;IAE7D;;;OAGG;IACH,mBAAmB,EAAE,CAAC,WAAW,EAAE,WAAW,KAAK,aAAa,CAAC;IAEjE;;OAEG;IACH,eAAe,EAAE,CAAC,UAAU,EAAE,MAAM,EAAE,WAAW,EAAE,WAAW,KAAK,OAAO,CAAC;IAE3E,+DAA+D;IAC/D,YAAY,EAAE,MAAM,CAAC;IACrB,sDAAsD;IACtD,UAAU,CAAC,EAAE,CAAC,WAAW,EAAE,WAAW,KAAK,IAAI,CAAC;IAChD,wDAAwD;IACxD,YAAY,CAAC,EAAE,MAAM,IAAI,CAAC;CAC3B"}
|
|
@@ -8034,7 +8034,7 @@ function PN({
|
|
|
8034
8034
|
}
|
|
8035
8035
|
const Ot = (e) => Cp(async () => {
|
|
8036
8036
|
const r = (await e()).default;
|
|
8037
|
-
return { default: ({
|
|
8037
|
+
return { default: ({ pluginContext: i }) => {
|
|
8038
8038
|
const s = {
|
|
8039
8039
|
serverUrl: i.serverUrl
|
|
8040
8040
|
// authManager will be created by the shell from context
|
|
@@ -8062,14 +8062,14 @@ const Ot = (e) => Cp(async () => {
|
|
|
8062
8062
|
],
|
|
8063
8063
|
groups: [
|
|
8064
8064
|
{ id: "Store", label: "Store", order: 1 },
|
|
8065
|
-
{ id: "Configuration", label: "Configuration", order: 2,
|
|
8065
|
+
{ id: "Configuration", label: "Configuration", order: 2, defaultCollapsed: !0 }
|
|
8066
8066
|
],
|
|
8067
8067
|
components: {
|
|
8068
|
-
products: Ot(() => import("./sections-
|
|
8068
|
+
products: Ot(() => import("./sections-TiollkCu.mjs").then((e) => ({ default: e.ProductsSection }))),
|
|
8069
8069
|
subscriptions: Ot(() => Promise.resolve().then(() => uf).then((e) => ({ default: e.SubscriptionsSection }))),
|
|
8070
|
-
transactions: Ot(() => import("./sections-
|
|
8071
|
-
coupons: Ot(() => import("./sections-
|
|
8072
|
-
refunds: Ot(() => import("./sections-
|
|
8070
|
+
transactions: Ot(() => import("./sections-TiollkCu.mjs").then((e) => ({ default: e.TransactionsSection }))),
|
|
8071
|
+
coupons: Ot(() => import("./sections-TiollkCu.mjs").then((e) => ({ default: e.CouponsSection }))),
|
|
8072
|
+
refunds: Ot(() => import("./sections-TiollkCu.mjs").then((e) => ({ default: e.RefundsSection }))),
|
|
8073
8073
|
storefront: Ot(() => Promise.resolve().then(() => hf).then((e) => ({ default: e.StorefrontSection }))),
|
|
8074
8074
|
"ai-settings": Ot(() => Promise.resolve().then(() => bf).then((e) => ({ default: e.AISettingsSection }))),
|
|
8075
8075
|
faqs: Ot(() => Promise.resolve().then(() => kf).then((e) => ({ default: e.FAQSection }))),
|
|
@@ -50,7 +50,7 @@ Guidelines:
|
|
|
50
50
|
- Use sensory language when appropriate
|
|
51
51
|
- Keep descriptions scannable with short paragraphs
|
|
52
52
|
- Avoid superlatives and unverifiable claims
|
|
53
|
-
- Include relevant keywords naturally for SEO`}],Wp=[{id:"gemini",label:"Google Gemini API",placeholder:"AIza..."},{id:"openai",label:"OpenAI API",placeholder:"sk-..."}],Ci={apiKeys:[{provider:"gemini",isConfigured:!1},{provider:"openai",isConfigured:!1}],taskAssignments:Oo.map(e=>({task:e.task,label:e.label,description:e.description,assignedModel:"not_set",systemPrompt:e.defaultPrompt}))};function cl({serverUrl:e,apiKey:t,authManager:r}){const[s,o]=w.useState("api-keys"),[a,i]=w.useState(Ci),[c,l]=w.useState(!0),[d,m]=w.useState(!1),[u,f]=w.useState(null),[h,x]=w.useState(!1),p=w.useRef(null),[y,j]=w.useState({gemini:"",openai:""}),[b,v]=w.useState({gemini:!1,openai:!1});w.useEffect(()=>{async function k(){try{let A;if(r?.isAuthenticated())A=await r.fetchWithAuth("/admin/config/ai");else{const P={"Content-Type":"application/json"};t&&(P["X-API-Key"]=t);const D=await fetch(`${e}/admin/config/ai`,{headers:P});if(!D.ok)throw new Error(`Failed to fetch: ${D.status}`);A=await D.json()}A.settings&&i(A.settings)}catch{i(Ci)}finally{l(!1)}}k()},[e,t,r]);const _=w.useCallback(async k=>{const A=y[k];if(A.trim()){m(!0),f(null);try{const P={provider:k,apiKey:A};if(r?.isAuthenticated())await r.fetchWithAuth("/admin/config/ai/api-key",{method:"PUT",body:JSON.stringify(P)});else{const D={"Content-Type":"application/json"};t&&(D["X-API-Key"]=t);const z=await fetch(`${e}/admin/config/ai/api-key`,{method:"PUT",headers:D,body:JSON.stringify(P)});if(!z.ok)throw new Error(`Failed to save: ${z.status}`)}i(D=>({...D,apiKeys:D.apiKeys.map(z=>z.provider===k?{...z,isConfigured:!0,maskedKey:`${A.slice(0,4)}...${A.slice(-4)}`,updatedAt:new Date().toISOString()}:z)})),j(D=>({...D,[k]:""})),x(!0),p.current&&clearTimeout(p.current),p.current=setTimeout(()=>x(!1),3e3)}catch(P){f(P instanceof Error?P.message:"Failed to save API key")}finally{m(!1)}}},[y,e,t,r]),C=w.useCallback(async k=>{if(confirm(`Are you sure you want to delete the ${k==="gemini"?"Google Gemini":"OpenAI"} API key?`)){m(!0),f(null);try{if(r?.isAuthenticated())await r.fetchWithAuth(`/admin/config/ai/api-key/${k}`,{method:"DELETE"});else{const A={"Content-Type":"application/json"};t&&(A["X-API-Key"]=t);const P=await fetch(`${e}/admin/config/ai/api-key/${k}`,{method:"DELETE",headers:A});if(!P.ok)throw new Error(`Failed to delete: ${P.status}`)}i(A=>({...A,apiKeys:A.apiKeys.map(P=>P.provider===k?{provider:k,isConfigured:!1}:P)}))}catch(A){f(A instanceof Error?A.message:"Failed to delete API key")}finally{m(!1)}}},[e,t,r]),E=w.useCallback(async(k,A)=>{m(!0),f(null);try{const P={task:k,model:A};if(r?.isAuthenticated())await r.fetchWithAuth("/admin/config/ai/assignment",{method:"PUT",body:JSON.stringify(P)});else{const D={"Content-Type":"application/json"};t&&(D["X-API-Key"]=t);const z=await fetch(`${e}/admin/config/ai/assignment`,{method:"PUT",headers:D,body:JSON.stringify(P)});if(!z.ok)throw new Error(`Failed to save: ${z.status}`)}i(D=>({...D,taskAssignments:D.taskAssignments.map(z=>z.task===k?{...z,assignedModel:A}:z)})),x(!0),p.current&&clearTimeout(p.current),p.current=setTimeout(()=>x(!1),3e3)}catch(P){f(P instanceof Error?P.message:"Failed to save assignment")}finally{m(!1)}},[e,t,r]),S=w.useCallback(k=>{if(k==="not_set")return!0;const A=ao.find(D=>D.id===k);return A?.provider?a.apiKeys.find(D=>D.provider===A.provider)?.isConfigured??!1:!0},[a.apiKeys]),N=w.useMemo(()=>ao.map(k=>{const A=S(k.id);return{value:k.id,label:A?k.label:`${k.label} (API key required)`,disabled:!A}}),[S]),U=w.useCallback(async(k,A)=>{m(!0),f(null);try{const P={task:k,systemPrompt:A};if(r?.isAuthenticated())await r.fetchWithAuth("/admin/config/ai/prompt",{method:"PUT",body:JSON.stringify(P)});else{const D={"Content-Type":"application/json"};t&&(D["X-API-Key"]=t);const z=await fetch(`${e}/admin/config/ai/prompt`,{method:"PUT",headers:D,body:JSON.stringify(P)});if(!z.ok)throw new Error(`Failed to save: ${z.status}`)}i(D=>({...D,taskAssignments:D.taskAssignments.map(z=>z.task===k?{...z,systemPrompt:A}:z)})),x(!0),p.current&&clearTimeout(p.current),p.current=setTimeout(()=>x(!1),3e3)}catch(P){f(P instanceof Error?P.message:"Failed to save prompt")}finally{m(!1)}},[e,t,r]);return w.useEffect(()=>()=>{p.current&&clearTimeout(p.current)},[]),c?n.jsx("div",{className:"cedros-admin__section",children:n.jsxs("div",{className:"cedros-admin__loading",children:[G.loading," Loading AI settings..."]})}):n.jsxs("div",{className:"cedros-admin__ai-settings",children:[n.jsxs("div",{className:"cedros-admin__page-header",children:[n.jsx("h2",{className:"cedros-admin__page-title",children:"Store AI"}),n.jsx("p",{className:"cedros-admin__page-description",children:"Configure AI providers, model assignments, and system prompts."})]}),n.jsxs("div",{className:"cedros-admin__tabs cedros-admin__tabs--line",children:[n.jsx("button",{type:"button",className:`cedros-admin__tab ${s==="api-keys"?"cedros-admin__tab--active":""}`,onClick:()=>o("api-keys"),children:"API Keys"}),n.jsx("button",{type:"button",className:`cedros-admin__tab ${s==="assignments"?"cedros-admin__tab--active":""}`,onClick:()=>o("assignments"),children:"Model Assignments"}),n.jsx("button",{type:"button",className:`cedros-admin__tab ${s==="prompts"?"cedros-admin__tab--active":""}`,onClick:()=>o("prompts"),children:"Prompts"})]}),u&&n.jsx("div",{className:"cedros-admin__error-banner",style:{marginTop:"1rem"},children:u}),h&&n.jsxs("div",{className:"cedros-admin__success-banner",style:{marginTop:"1rem"},children:[G.check," Settings saved successfully"]}),s==="api-keys"&&n.jsxs("div",{className:"cedros-admin__section",style:{marginTop:"1rem"},children:[n.jsx("div",{className:"cedros-admin__section-header",children:n.jsx("h3",{className:"cedros-admin__section-title",children:"API Keys"})}),n.jsx("p",{style:{marginBottom:"1.5rem",opacity:.7,fontSize:14},children:"Configure API keys for AI providers. Keys are stored securely and never exposed."}),n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"1.5rem"},children:Wp.map(k=>{const A=a.apiKeys.find(D=>D.provider===k.id),P=A?.isConfigured??!1;return n.jsxs("div",{className:"cedros-admin__api-key-card",style:{padding:"1rem",border:"1px solid var(--cedros-admin-border)",borderRadius:8},children:[n.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"0.75rem"},children:[n.jsxs("div",{children:[n.jsx("div",{style:{fontWeight:600},children:k.label}),P&&A?.maskedKey&&n.jsxs("div",{style:{fontSize:12,opacity:.6,marginTop:2},children:["Current key: ",A.maskedKey,A.updatedAt&&n.jsxs("span",{children:[" (updated ",new Date(A.updatedAt).toLocaleDateString(),")"]})]})]}),n.jsx("span",{className:`cedros-admin__badge ${P?"cedros-admin__badge--success":"cedros-admin__badge--muted"}`,children:P?"Configured":"Not Set"})]}),n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"0.75rem"},children:n.jsxs("div",{style:{display:"flex",gap:"0.5rem",alignItems:"center"},children:[n.jsx("input",{type:b[k.id]?"text":"password",className:"cedros-admin__input",placeholder:P?"Enter new key to replace":k.placeholder,value:y[k.id],onChange:D=>j(z=>({...z,[k.id]:D.target.value})),onBlur:()=>{y[k.id].trim()&&_(k.id)},style:{flex:1}}),n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost",onClick:()=>v(D=>({...D,[k.id]:!D[k.id]})),title:b[k.id]?"Hide key":"Show key",style:{padding:"0.5rem"},children:b[k.id]?G.eyeOff:G.eye}),P&&n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost cedros-admin__button--danger",onClick:()=>C(k.id),disabled:d,title:"Remove API key",style:{padding:"0.5rem"},children:G.trash})]})})]},k.id)})})]}),s==="assignments"&&n.jsxs("div",{className:"cedros-admin__section",style:{marginTop:"1rem"},children:[n.jsx("div",{className:"cedros-admin__section-header",children:n.jsx("h3",{className:"cedros-admin__section-title",children:"Model Assignments"})}),n.jsx("p",{style:{marginBottom:"1.5rem",opacity:.7,fontSize:14},children:"Assign AI models to specific tasks. Models require their provider's API key to be configured."}),n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"1rem"},children:a.taskAssignments.map(k=>{const A=Oo.find(D=>D.task===k.task),P=ao.find(D=>D.id===k.assignedModel);return n.jsxs("div",{style:{padding:"1rem",border:"1px solid var(--cedros-admin-border)",borderRadius:8},children:[n.jsxs("div",{style:{marginBottom:"0.75rem"},children:[n.jsx("div",{style:{fontWeight:600},children:A?.label??k.task}),n.jsx("div",{style:{fontSize:13,opacity:.7,marginTop:2},children:A?.description})]}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[n.jsx(lt,{value:k.assignedModel,onChange:D=>E(k.task,D),options:N,label:"",disabled:d,style:{flex:1,maxWidth:280}}),P&&P.provider&&n.jsx("span",{className:`cedros-admin__badge ${S(P.id)?"cedros-admin__badge--success":"cedros-admin__badge--warning"}`,children:S(P.id)?"Ready":"Missing API Key"})]})]},k.task)})})]}),s==="prompts"&&n.jsxs("div",{className:"cedros-admin__section",style:{marginTop:"1rem"},children:[n.jsx("div",{className:"cedros-admin__section-header",children:n.jsx("h3",{className:"cedros-admin__section-title",children:"System Prompts"})}),n.jsx("p",{style:{marginBottom:"1.5rem",opacity:.7,fontSize:14},children:"Configure the default system prompts for each AI task. These prompts guide the AI's behavior and responses."}),n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"1.5rem"},children:a.taskAssignments.map(k=>{const A=Oo.find(P=>P.task===k.task);return n.jsx(Vp,{task:k.task,label:A?.label??k.task,description:A?.description??"",initialPrompt:k.systemPrompt??"",onSave:U},k.task)})})]})]})}function Vp({task:e,label:t,description:r,initialPrompt:s,onSave:o}){const[a,i]=w.useState(s),[c,l]=w.useState("idle"),d=w.useRef(null),m=w.useRef(null),u=w.useRef(!0);return w.useEffect(()=>{if(u.current){u.current=!1;return}return d.current&&clearTimeout(d.current),m.current&&clearTimeout(m.current),l("pending"),d.current=setTimeout(async()=>{l("saving");try{await o(e,a),l("saved"),m.current=setTimeout(()=>l("idle"),2e3)}catch{l("error")}},1500),()=>{d.current&&clearTimeout(d.current)}},[a,e,o]),w.useEffect(()=>()=>{d.current&&clearTimeout(d.current),m.current&&clearTimeout(m.current)},[]),n.jsxs("div",{style:{padding:"1rem",border:"1px solid var(--cedros-admin-border)",borderRadius:8},children:[n.jsxs("div",{style:{marginBottom:"0.75rem",display:"flex",justifyContent:"space-between",alignItems:"flex-start"},children:[n.jsxs("div",{children:[n.jsx("div",{style:{fontWeight:600},children:t}),n.jsx("div",{style:{fontSize:13,opacity:.7,marginTop:2},children:r})]}),n.jsx(Hp,{status:c})]}),n.jsx("textarea",{className:"cedros-admin__input",value:a,onChange:f=>i(f.target.value),placeholder:"Enter system prompt...",rows:4,style:{width:"100%",resize:"vertical",fontFamily:"inherit",minHeight:100}})]})}function Hp({status:e}){return e==="idle"?null:n.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:"0.375rem",fontSize:"0.75rem",color:e==="error"?"var(--cedros-admin-error, #ef4444)":"var(--cedros-admin-text-muted, #64748b)"},children:[e==="pending"&&n.jsx("span",{style:{opacity:.7},children:"Unsaved"}),e==="saving"&&n.jsxs(n.Fragment,{children:[G.loading,n.jsx("span",{children:"Saving..."})]}),e==="saved"&&n.jsxs(n.Fragment,{children:[G.check,n.jsx("span",{style:{color:"var(--cedros-admin-success, #22c55e)"},children:"Saved"})]}),e==="error"&&n.jsx("span",{children:"Failed"})]})}const qp=Object.freeze(Object.defineProperty({__proto__:null,AISettingsSection:cl},Symbol.toStringTag,{value:"Module"}));function Dn({href:e,children:t}){return n.jsx("a",{href:e,target:"_blank",rel:"noopener noreferrer",style:{color:"inherit",textDecoration:"underline"},children:t})}const Ni=[{id:"stripe",label:"Stripe",category:"stripe",description:n.jsxs(n.Fragment,{children:["Configure your Stripe integration for card payments. Get your API keys from the"," ",n.jsx(Dn,{href:"https://dashboard.stripe.com/apikeys",children:"Stripe Dashboard"}),"."]})},{id:"crypto",label:"Crypto",category:"x402",description:n.jsxs(n.Fragment,{children:["Configure Solana wallet and token settings for crypto payments. Get a fast RPC endpoint from"," ",n.jsx(Dn,{href:"https://www.helius.dev",children:"Helius"})," or"," ",n.jsx(Dn,{href:"https://www.quicknode.com/chains/sol",children:"QuickNode"}),". Set up a payment address using"," ",n.jsx(Dn,{href:"https://phantom.app",children:"Phantom"})," or"," ",n.jsx(Dn,{href:"https://solflare.com",children:"Solflare"})," wallet."]})},{id:"credits",label:"Credits",category:"cedros_login",description:n.jsxs(n.Fragment,{children:["Configure Cedros Login integration for credits payments. See the"," ",n.jsx(Dn,{href:"https://docs.cedros.dev/credits",children:"Credits API documentation"}),"."]})}];function ll({serverUrl:e,apiKey:t,authManager:r}){const[s,o]=w.useState("stripe"),a=Ni.find(i=>i.id===s);return n.jsxs("div",{className:"cedros-admin__payment-settings",children:[n.jsxs("div",{className:"cedros-admin__page-header",children:[n.jsx("h2",{className:"cedros-admin__page-title",children:"Payment Options"}),n.jsx("p",{className:"cedros-admin__page-description",children:"Configure payment methods including Stripe, crypto, and credits."})]}),n.jsx("div",{className:"cedros-admin__tabs cedros-admin__tabs--line",children:Ni.map(i=>n.jsx("button",{type:"button",className:`cedros-admin__tab ${s===i.id?"cedros-admin__tab--active":""}`,onClick:()=>o(i.id),children:i.label},i.id))}),n.jsx("div",{style:{marginTop:"1rem"},children:n.jsx(ol,{serverUrl:e,apiKey:t,authManager:r,category:a.category,title:`${a.label} Settings`,description:a.description,showEnabledToggle:!0},a.category)})]})}const Zp=Object.freeze(Object.defineProperty({__proto__:null,PaymentSettingsSection:ll},Symbol.toStringTag,{value:"Module"})),io={email_enabled:!1,smtp_host:"",smtp_port:587,smtp_username:"",smtp_password:"",from_email:"",from_name:"",webhook_enabled:!1,webhook_url:"",webhook_secret:"",webhook_timeout:30};function dl({serverUrl:e,apiKey:t,authManager:r}){const[s,o]=w.useState("messages"),[a,i]=w.useState(io),[c,l]=w.useState(!0),[d,m]=w.useState(!0),[u,f]=w.useState(new Set),h=w.useCallback(async()=>{try{let b;const v="/admin/config/messaging";if(r?.isAuthenticated())b=await r.fetchWithAuth(v);else{const _={"Content-Type":"application/json"};t&&(_["X-API-Key"]=t);const C=await fetch(`${e}${v}`,{headers:_});if(!C.ok)throw new Error(`Failed to fetch: ${C.status}`);b=await C.json()}i({...io,...b.config})}catch{i(io)}finally{l(!1),setTimeout(()=>m(!1),100)}},[e,t,r]);w.useEffect(()=>{h()},[h]);const x=w.useCallback(async b=>{const v="/admin/config/messaging",_={...b};u.has("smtp_password")||delete _.smtp_password,u.has("webhook_secret")||delete _.webhook_secret;const C=JSON.stringify({config:_});try{if(r?.isAuthenticated())await r.fetchWithAuth(v,{method:"PUT",body:C});else{const E={"Content-Type":"application/json"};t&&(E["X-API-Key"]=t);const S=await fetch(`${e}${v}`,{method:"PUT",headers:E,body:C});if(!S.ok)throw new Error(`Failed to save: ${S.status}`)}}catch{}},[e,t,r,u]),{status:p,error:y}=ia({data:a,onSave:x,debounceMs:1500,enabled:!d}),j=(b,v)=>{(b==="smtp_password"||b==="webhook_secret")&&f(_=>new Set(_).add(b)),i(_=>({..._,[b]:v}))};return c?n.jsxs("div",{className:"cedros-admin__messaging-settings",children:[n.jsxs("div",{className:"cedros-admin__page-header",children:[n.jsx("h2",{className:"cedros-admin__page-title",children:"Store Messages"}),n.jsx("p",{className:"cedros-admin__page-description",children:"Configure email delivery and webhook notifications."})]}),n.jsxs("div",{className:"cedros-admin__loading",style:{marginTop:"1rem"},children:[G.loading," Loading message settings..."]})]}):n.jsxs("div",{className:"cedros-admin__messaging-settings",children:[n.jsxs("div",{className:"cedros-admin__page-header",children:[n.jsx("h2",{className:"cedros-admin__page-title",children:"Store Messages"}),n.jsx("p",{className:"cedros-admin__page-description",children:"Configure email delivery and webhook notifications."})]}),n.jsxs("div",{className:"cedros-admin__tabs cedros-admin__tabs--line",children:[n.jsx("button",{type:"button",className:`cedros-admin__tab ${s==="messages"?"cedros-admin__tab--active":""}`,onClick:()=>o("messages"),children:"Messages"}),n.jsx("button",{type:"button",className:`cedros-admin__tab ${s==="email"?"cedros-admin__tab--active":""}`,onClick:()=>o("email"),children:"Email"}),n.jsx("button",{type:"button",className:`cedros-admin__tab ${s==="webhooks"?"cedros-admin__tab--active":""}`,onClick:()=>o("webhooks"),children:"Webhooks"}),n.jsx("div",{style:{flex:1}}),n.jsx(Gp,{status:p,error:y})]}),n.jsxs("div",{className:"cedros-admin__tab-content",style:{marginTop:"1rem"},children:[s==="messages"&&n.jsxs("div",{className:"cedros-admin__section",children:[n.jsx("p",{style:{marginBottom:"1.5rem",fontSize:"0.875rem",opacity:.7},children:"Enable or disable notification types. Configure the delivery settings in the Email or Webhooks tab."}),n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"1rem"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:"1rem",padding:"1rem",border:"1px solid var(--cedros-admin-border, #e5e5e5)",borderRadius:"0.5rem"},children:[n.jsx(Ai,{checked:a.email_enabled,onChange:()=>j("email_enabled",!a.email_enabled)}),n.jsxs("div",{style:{flex:1},children:[n.jsx("div",{style:{fontWeight:500},children:"Email Confirmation"}),n.jsx("p",{style:{margin:"0.25rem 0 0",fontSize:"0.8125rem",opacity:.6},children:"Send order confirmation emails to customers after successful purchase."}),n.jsx("p",{style:{margin:"0.5rem 0 0",fontSize:"0.75rem",opacity:.5},children:"Requires Email configuration"})]})]}),n.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:"1rem",padding:"1rem",border:"1px solid var(--cedros-admin-border, #e5e5e5)",borderRadius:"0.5rem"},children:[n.jsx(Ai,{checked:a.webhook_enabled,onChange:()=>j("webhook_enabled",!a.webhook_enabled)}),n.jsxs("div",{style:{flex:1},children:[n.jsx("div",{style:{fontWeight:500},children:"Admin Purchase Notification"}),n.jsx("p",{style:{margin:"0.25rem 0 0",fontSize:"0.8125rem",opacity:.6},children:"Send webhook notifications to your server when a purchase is completed."}),n.jsx("p",{style:{margin:"0.5rem 0 0",fontSize:"0.75rem",opacity:.5},children:"Requires Webhook configuration"})]})]})]})]}),s==="email"&&n.jsxs("div",{className:"cedros-admin__section",children:[n.jsx("p",{style:{marginBottom:"1.5rem",fontSize:"0.875rem",opacity:.7},children:"Configure your email provider for sending customer notifications."}),!a.email_enabled&&n.jsx("div",{style:{padding:"1rem",marginBottom:"1.5rem",background:"var(--cedros-admin-bg-accent, #fef3c7)",borderRadius:"0.5rem",border:"1px solid var(--cedros-admin-warning, #f59e0b)",fontSize:"0.875rem"},children:"Email notifications are disabled. Enable them in the Messages tab."}),n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"1rem",opacity:a.email_enabled?1:.5},children:[n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"SMTP Host"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:a.smtp_host,onChange:b=>j("smtp_host",b.target.value),placeholder:"smtp.example.com",disabled:!a.email_enabled})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"SMTP Port"}),n.jsx("input",{type:"number",className:"cedros-admin__input",value:a.smtp_port,onChange:b=>j("smtp_port",parseInt(b.target.value)||587),placeholder:"587",disabled:!a.email_enabled,style:{maxWidth:120}})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"SMTP Username"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:a.smtp_username,onChange:b=>j("smtp_username",b.target.value),placeholder:"username or API key",disabled:!a.email_enabled})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"SMTP Password"}),n.jsx("input",{type:"password",className:"cedros-admin__input",value:u.has("smtp_password")?a.smtp_password:"",onChange:b=>j("smtp_password",b.target.value),placeholder:a.smtp_password?"••••••••":"Enter password",disabled:!a.email_enabled})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"From Email"}),n.jsx("input",{type:"email",className:"cedros-admin__input",value:a.from_email,onChange:b=>j("from_email",b.target.value),placeholder:"orders@yourstore.com",disabled:!a.email_enabled})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"From Name"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:a.from_name,onChange:b=>j("from_name",b.target.value),placeholder:"Your Store",disabled:!a.email_enabled})]})]})]}),s==="webhooks"&&n.jsxs("div",{className:"cedros-admin__section",children:[n.jsx("p",{style:{marginBottom:"1.5rem",fontSize:"0.875rem",opacity:.7},children:"Configure webhook endpoint for receiving purchase notifications."}),!a.webhook_enabled&&n.jsx("div",{style:{padding:"1rem",marginBottom:"1.5rem",background:"var(--cedros-admin-bg-accent, #fef3c7)",borderRadius:"0.5rem",border:"1px solid var(--cedros-admin-warning, #f59e0b)",fontSize:"0.875rem"},children:"Webhook notifications are disabled. Enable them in the Messages tab."}),n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"1rem",opacity:a.webhook_enabled?1:.5},children:[n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Webhook URL"}),n.jsx("input",{type:"url",className:"cedros-admin__input",value:a.webhook_url,onChange:b=>j("webhook_url",b.target.value),placeholder:"https://api.yoursite.com/webhooks/orders",disabled:!a.webhook_enabled})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Webhook Secret"}),n.jsx("input",{type:"password",className:"cedros-admin__input",value:u.has("webhook_secret")?a.webhook_secret:"",onChange:b=>j("webhook_secret",b.target.value),placeholder:a.webhook_secret?"••••••••":"Enter secret for HMAC-SHA256",disabled:!a.webhook_enabled}),n.jsx("p",{style:{margin:"0.25rem 0 0",fontSize:"0.75rem",opacity:.6},children:"Used for HMAC-SHA256 signature verification"})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Timeout (seconds)"}),n.jsx("input",{type:"number",className:"cedros-admin__input",value:a.webhook_timeout,onChange:b=>j("webhook_timeout",parseInt(b.target.value)||30),placeholder:"30",disabled:!a.webhook_enabled,style:{maxWidth:120}})]})]})]})]})]})}function Gp({status:e,error:t}){return e==="idle"?null:n.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:"0.375rem",fontSize:"0.8125rem",color:e==="error"?"var(--cedros-admin-error, #ef4444)":"var(--cedros-admin-text-muted, #64748b)"},children:[e==="pending"&&n.jsx("span",{style:{opacity:.7},children:"Unsaved changes"}),e==="saving"&&n.jsxs(n.Fragment,{children:[G.loading,n.jsx("span",{children:"Saving..."})]}),e==="saved"&&n.jsxs(n.Fragment,{children:[G.check,n.jsx("span",{style:{color:"var(--cedros-admin-success, #22c55e)"},children:"Saved"})]}),e==="error"&&n.jsxs("span",{children:["Save failed",t?`: ${t}`:""]})]})}function Ai({checked:e,onChange:t,disabled:r=!1}){return n.jsx("button",{type:"button",role:"switch","aria-checked":e,disabled:r,onClick:t,style:{position:"relative",width:44,height:24,borderRadius:12,border:"none",backgroundColor:e?"var(--cedros-admin-primary, #171717)":"var(--cedros-admin-border, #d4d4d4)",cursor:r?"not-allowed":"pointer",transition:"background-color 0.2s",flexShrink:0,opacity:r?.5:1},children:n.jsx("span",{style:{position:"absolute",top:2,left:e?22:2,width:20,height:20,borderRadius:"50%",backgroundColor:"white",boxShadow:"0 1px 3px rgba(0,0,0,0.2)",transition:"left 0.2s"}})})}const Qp=Object.freeze(Object.defineProperty({__proto__:null,MessagingSection:dl},Symbol.toStringTag,{value:"Module"}));function Mo(e){return!e||typeof e!="string"?[]:e.split(",").map(t=>t.trim()).filter(Boolean)}function ul({serverUrl:e,apiKey:t,pageSize:r=20,authManager:s}){const[o,a]=w.useState([]),[i,c]=w.useState(!0),[l,d]=w.useState(!1),[m,u]=w.useState(null),[f,h]=w.useState(!1),[x,p]=w.useState(""),[y,j]=w.useState("all"),[b,v]=w.useState(null),[_,C]=w.useState({question:"",answer:"",keywordsCsv:"",active:!0,useInChat:!0,displayOnPage:!0}),E=w.useCallback(async()=>{c(!0);try{let M;const R=`/admin/faqs?limit=${r}`;if(s?.isAuthenticated())M=await s.fetchWithAuth(R);else{const W={"Content-Type":"application/json"};t&&(W["X-API-Key"]=t);const T=await fetch(`${e}${R}`,{headers:W});if(!T.ok)throw new Error(`Failed to fetch FAQs: ${T.status}`);M=await T.json()}a(M.faqs||[])}catch{a([{id:"faq_1",question:"What is your return policy?",answer:"We accept returns within 30 days of purchase. Items must be unused and in original packaging.",keywords:["returns","refund","policy"],active:!0,useInChat:!0,displayOnPage:!0,createdAt:"2026-01-15T10:00:00Z"},{id:"faq_2",question:"How long does shipping take?",answer:"Standard shipping takes 5-7 business days. Express shipping is available for 2-3 day delivery.",keywords:["shipping","delivery","time"],active:!0,useInChat:!0,displayOnPage:!0,createdAt:"2026-01-16T10:00:00Z"},{id:"faq_3",question:"Do you ship internationally?",answer:"Yes, we ship to most countries. International shipping typically takes 10-14 business days.",keywords:["international","shipping","global"],active:!1,useInChat:!0,displayOnPage:!1,createdAt:"2026-01-17T10:00:00Z"}])}finally{c(!1)}},[e,t,r,s]);w.useEffect(()=>{E()},[E]);const S=async M=>{if(M.preventDefault(),!(!_.question.trim()||!_.answer.trim())){h(!0);try{const R=_.keywordsCsv.split(",").map(T=>T.trim().toLowerCase()).filter(Boolean),W={question:_.question.trim(),answer:_.answer.trim(),keywords:R,active:_.active,useInChat:_.useInChat,displayOnPage:_.displayOnPage};if(m){const T=`/admin/faqs/${m.id}`;if(s?.isAuthenticated())await s.fetchWithAuth(T,{method:"PUT",body:JSON.stringify(W)});else{const V={"Content-Type":"application/json"};t&&(V["X-API-Key"]=t);const ee=await fetch(`${e}${T}`,{method:"PUT",headers:V,body:JSON.stringify(W)});if(!ee.ok)throw new Error(`Failed to update FAQ: ${ee.status}`)}}else if(s?.isAuthenticated())await s.fetchWithAuth("/admin/faqs",{method:"POST",body:JSON.stringify(W)});else{const T={"Content-Type":"application/json"};t&&(T["X-API-Key"]=t);const V=await fetch(`${e}/admin/faqs`,{method:"POST",headers:T,body:JSON.stringify(W)});if(!V.ok)throw new Error(`Failed to create FAQ: ${V.status}`)}k(),E()}catch{a(m?R=>R.map(W=>W.id===m.id?{...W,question:_.question.trim(),answer:_.answer.trim(),keywords:Mo(_.keywordsCsv).map(T=>T.toLowerCase()),active:_.active,useInChat:_.useInChat,displayOnPage:_.displayOnPage,updatedAt:new Date().toISOString()}:W):R=>[...R,{id:`faq_${Date.now()}`,question:_.question.trim(),answer:_.answer.trim(),keywords:Mo(_.keywordsCsv).map(W=>W.toLowerCase()),active:_.active,useInChat:_.useInChat,displayOnPage:_.displayOnPage,createdAt:new Date().toISOString()}]),k()}finally{h(!1)}}},N=async M=>{try{const R=`/admin/faqs/${M}`;if(s?.isAuthenticated())await s.fetchWithAuth(R,{method:"DELETE"});else{const W={"Content-Type":"application/json"};t&&(W["X-API-Key"]=t);const T=await fetch(`${e}${R}`,{method:"DELETE",headers:W});if(!T.ok)throw new Error(`Failed to delete FAQ: ${T.status}`)}E()}catch{a(R=>R.filter(W=>W.id!==M))}v(null)},U=async M=>{try{const R=`/admin/faqs/${M.id}`,W={...M,active:!M.active};if(s?.isAuthenticated())await s.fetchWithAuth(R,{method:"PUT",body:JSON.stringify(W)});else{const T={"Content-Type":"application/json"};t&&(T["X-API-Key"]=t);const V=await fetch(`${e}${R}`,{method:"PUT",headers:T,body:JSON.stringify(W)});if(!V.ok)throw new Error(`Failed to update FAQ: ${V.status}`)}E()}catch{a(R=>R.map(W=>W.id===M.id?{...W,active:!W.active}:W))}},k=()=>{C({question:"",answer:"",keywordsCsv:"",active:!0,useInChat:!0,displayOnPage:!0}),u(null),d(!1)},A=M=>{C({question:M.question,answer:M.answer,keywordsCsv:M.keywords.join(", "),active:M.active,useInChat:M.useInChat??!0,displayOnPage:M.displayOnPage??!0}),u(M),d(!0)},P=o.length,D=o.filter(M=>M.active).length,z=o.filter(M=>M.active&&M.useInChat).length,L=o.filter(M=>M.active&&M.displayOnPage).length,O=w.useMemo(()=>o.filter(M=>{if(y==="active"&&!M.active||y==="inactive"&&M.active)return!1;if(x){const R=x.toLowerCase();return M.question.toLowerCase().includes(R)||M.answer.toLowerCase().includes(R)||M.keywords.some(W=>W.includes(R))}return!0}),[o,y,x]);return n.jsxs("div",{className:"cedros-admin__faqs",children:[n.jsx(Gn,{stats:[{label:"Total FAQs",value:P},{label:"Active",value:D,variant:"success"},{label:"In Chat",value:z},{label:"On Page",value:L}]}),n.jsxs("div",{className:"cedros-admin__section",children:[n.jsxs("div",{className:"cedros-admin__section-header",children:[n.jsxs("div",{className:"cedros-admin__section-header-left",children:[n.jsx("h3",{className:"cedros-admin__section-title",children:"Knowledge Base"}),n.jsx("p",{className:"cedros-admin__section-subtitle",children:"Manage FAQs for the AI chat assistant and public FAQ page."})]}),n.jsx("div",{className:"cedros-admin__section-header-right",children:n.jsxs("button",{className:"cedros-admin__btn cedros-admin__btn--primary",onClick:()=>{k(),d(!0)},children:[G.plus," Add FAQ"]})})]}),n.jsxs("div",{className:"cedros-admin__filters",style:{display:"flex",gap:"1rem",marginBottom:"1rem"},children:[n.jsx("input",{type:"text",placeholder:"Search FAQs...",value:x,onChange:M=>p(M.target.value),className:"cedros-admin__input",style:{flex:1,maxWidth:300}}),n.jsxs("select",{value:y,onChange:M=>j(M.target.value),className:"cedros-admin__select",children:[n.jsx("option",{value:"all",children:"All Status"}),n.jsx("option",{value:"active",children:"Active Only"}),n.jsx("option",{value:"inactive",children:"Inactive Only"})]})]}),l&&n.jsx("div",{className:"cedros-admin__form-container",style:{marginBottom:"1.5rem"},children:n.jsxs("form",{onSubmit:S,className:"cedros-admin__form",children:[n.jsxs("div",{className:"cedros-admin__form-header",children:[n.jsx("h4",{children:m?"Edit FAQ":"Add New FAQ"}),n.jsx("button",{type:"button",className:"cedros-admin__btn--icon",onClick:k,children:G.close})]}),n.jsxs("div",{className:"cedros-admin__form-group",children:[n.jsx("label",{className:"cedros-admin__label",children:"Question *"}),n.jsx("input",{type:"text",value:_.question,onChange:M=>C(R=>({...R,question:M.target.value})),className:"cedros-admin__input",placeholder:"What is your return policy?",required:!0})]}),n.jsxs("div",{className:"cedros-admin__form-group",children:[n.jsx("label",{className:"cedros-admin__label",children:"Answer *"}),n.jsx("textarea",{value:_.answer,onChange:M=>C(R=>({...R,answer:M.target.value})),className:"cedros-admin__textarea",placeholder:"We accept returns within 30 days...",rows:4,required:!0}),n.jsx("span",{className:"cedros-admin__hint",children:"Supports markdown formatting."})]}),n.jsxs("div",{className:"cedros-admin__form-group",children:[n.jsx("label",{className:"cedros-admin__label",children:"Keywords"}),n.jsx("input",{type:"text",value:_.keywordsCsv,onChange:M=>C(R=>({...R,keywordsCsv:M.target.value})),className:"cedros-admin__input",placeholder:"returns, refund, policy"}),n.jsx("span",{className:"cedros-admin__hint",children:"Comma-separated keywords to help AI find this FAQ."})]}),n.jsxs("div",{className:"cedros-admin__form-group",children:[n.jsxs("label",{className:"cedros-admin__checkbox-label",children:[n.jsx("input",{type:"checkbox",checked:_.active,onChange:M=>C(R=>({...R,active:M.target.checked}))}),n.jsx("span",{children:"Active"})]}),n.jsx("span",{className:"cedros-admin__hint",children:"Inactive FAQs won't appear anywhere."})]}),n.jsxs("div",{className:"cedros-admin__form-group",children:[n.jsx("label",{className:"cedros-admin__label",children:"Visibility"}),n.jsxs("div",{className:"cedros-admin__checkbox-group",children:[n.jsxs("label",{className:"cedros-admin__checkbox-label",children:[n.jsx("input",{type:"checkbox",checked:_.useInChat,onChange:M=>C(R=>({...R,useInChat:M.target.checked}))}),n.jsx("span",{children:"Use in AI Chat"})]}),n.jsxs("label",{className:"cedros-admin__checkbox-label",children:[n.jsx("input",{type:"checkbox",checked:_.displayOnPage,onChange:M=>C(R=>({...R,displayOnPage:M.target.checked}))}),n.jsx("span",{children:"Display on FAQ Page"})]})]}),n.jsx("span",{className:"cedros-admin__hint",children:"Choose where this FAQ should appear."})]}),n.jsxs("div",{className:"cedros-admin__form-actions",children:[n.jsx("button",{type:"button",className:"cedros-admin__btn",onClick:k,children:"Cancel"}),n.jsx("button",{type:"submit",className:"cedros-admin__btn cedros-admin__btn--primary",disabled:f||!_.question.trim()||!_.answer.trim(),children:f?G.loading:m?"Update FAQ":"Create FAQ"})]})]})}),i?n.jsxs("div",{className:"cedros-admin__loading",children:[G.loading,n.jsx("span",{children:"Loading FAQs..."})]}):O.length===0?n.jsx("div",{className:"cedros-admin__empty",children:n.jsx("p",{children:x||y!=="all"?"No FAQs match your filters.":"No FAQs yet. Add one to get started."})}):n.jsx("div",{className:"cedros-admin__faq-list",children:O.map(M=>n.jsxs("div",{className:`cedros-admin__faq-item ${M.active?"":"cedros-admin__faq-item--inactive"}`,children:[n.jsxs("div",{className:"cedros-admin__faq-content",children:[n.jsxs("div",{className:"cedros-admin__faq-question",children:[n.jsx("span",{className:`cedros-admin__status-dot ${M.active?"cedros-admin__status-dot--active":"cedros-admin__status-dot--inactive"}`}),M.question]}),n.jsx("div",{className:"cedros-admin__faq-answer",children:M.answer}),n.jsxs("div",{className:"cedros-admin__faq-meta",children:[M.keywords.length>0&&n.jsx("div",{className:"cedros-admin__faq-keywords",children:M.keywords.map(R=>n.jsx("span",{className:"cedros-admin__tag",children:R},R))}),n.jsxs("div",{className:"cedros-admin__faq-visibility",children:[M.useInChat&&n.jsxs("span",{className:"cedros-admin__badge cedros-admin__badge--chat",title:"Used in AI Chat",children:[G.chat," Chat"]}),M.displayOnPage&&n.jsxs("span",{className:"cedros-admin__badge cedros-admin__badge--page",title:"Displayed on FAQ Page",children:[G.globe," Page"]})]})]})]}),n.jsxs("div",{className:"cedros-admin__faq-actions",children:[n.jsx("button",{className:"cedros-admin__btn--icon",onClick:()=>U(M),title:M.active?"Deactivate":"Activate",children:M.active?G.eyeOff:G.eye}),n.jsx("button",{className:"cedros-admin__btn--icon",onClick:()=>A(M),title:"Edit",children:G.edit}),n.jsx("button",{className:"cedros-admin__btn--icon cedros-admin__btn--danger",onClick:()=>v(M.id),title:"Delete",children:G.trash})]}),b===M.id&&n.jsx("div",{className:"cedros-admin__confirm-overlay",children:n.jsxs("div",{className:"cedros-admin__confirm-dialog",children:[n.jsx("p",{children:"Delete this FAQ?"}),n.jsxs("div",{className:"cedros-admin__confirm-actions",children:[n.jsx("button",{className:"cedros-admin__btn",onClick:()=>v(null),children:"Cancel"}),n.jsx("button",{className:"cedros-admin__btn cedros-admin__btn--danger",onClick:()=>N(M.id),children:"Delete"})]})]})})]},M.id))})]})]})}const Yp=Object.freeze(Object.defineProperty({__proto__:null,FAQSection:ul},Symbol.toStringTag,{value:"Module"}));class Kp{serverUrl;walletSigner=null;jwtToken=null;isAdmin=!1;constructor(t){this.serverUrl=t}getAuthMethod(){return this.walletSigner?.publicKey&&this.walletSigner.signMessage?"wallet":this.jwtToken&&this.isAdmin?"cedros-login":"none"}isAuthenticated(){return this.getAuthMethod()!=="none"}setWalletSigner(t){this.walletSigner=t,oe.getLogger().debug("[AdminAuthManager] Wallet signer updated:",!!t?.publicKey)}setCedrosLoginAuth(t,r){this.jwtToken=t,this.isAdmin=r,oe.getLogger().debug("[AdminAuthManager] Cedros-login auth updated:",{hasToken:!!t,isAdmin:r})}async createAuthHeaders(t){const r=this.getAuthMethod();if(r==="wallet")return this.createWalletAuthHeaders(t);if(r==="cedros-login")return this.createJwtAuthHeaders();throw new Error("No admin authentication configured. Connect a wallet or sign in as admin.")}async createWalletAuthHeaders(t){if(!this.walletSigner?.publicKey||!this.walletSigner.signMessage)throw new Error("Wallet not connected or does not support message signing");const r=await this.fetchNonce(t),s=new TextEncoder().encode(r.nonce_id),o=await this.walletSigner.signMessage(s),a=oe.bs58.encode(this.walletSigner.publicKey.toBytes()),i=oe.bs58.encode(o);return{"X-Signer":a,"X-Message":r.nonce_id,"X-Signature":i}}createJwtAuthHeaders(){if(!this.jwtToken)throw new Error("No JWT token available");return{Authorization:`Bearer ${this.jwtToken}`}}async fetchNonce(t){const r=`${this.serverUrl}/paywall/v1/nonce`;oe.getLogger().debug("[AdminAuthManager] Fetching nonce for purpose:",t);const s=await oe.fetchWithTimeout(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({purpose:t})});if(!s.ok){const o=await s.text();throw new Error(`Failed to fetch nonce: ${s.status} ${o}`)}return await s.json()}async fetchWithAuth(t,r={}){if(this.getAuthMethod()==="none")throw new Error("No admin authentication configured");const o=this.getPurposeFromPath(t,r.method||"GET"),a=await this.createAuthHeaders(o),i={"Content-Type":"application/json",...r.headers||{},...a},c=await oe.fetchWithTimeout(`${this.serverUrl}${t}`,{...r,headers:i});if(!c.ok){const l=await c.text();throw new Error(`Admin API error ${c.status}: ${l}`)}return await c.json()}getPurposeFromPath(t,r){const o={"/admin/stats":{GET:"admin_stats"},"/admin/products":{GET:"admin_products_list",POST:"admin_products_create"},"/admin/transactions":{GET:"admin_transactions_list"},"/admin/coupons":{GET:"admin_coupons_list",POST:"admin_coupons_create"},"/admin/refunds":{GET:"admin_refunds_list"},"/admin/config":{GET:"admin_config_list"}}[t];if(o?.[r])return o[r];if(t.startsWith("/admin/products/")){if(r==="PUT")return"admin_products_update";if(r==="DELETE")return"admin_products_delete"}if(t.startsWith("/admin/coupons/")){if(r==="PUT")return"admin_coupons_update";if(r==="DELETE")return"admin_coupons_delete"}if(t.startsWith("/admin/refunds/")&&t.includes("/process"))return"admin_refunds_process";if(t.startsWith("/admin/config/")){if(r==="GET")return"admin_config_get";if(r==="PUT")return"admin_config_update";if(r==="PATCH")return"admin_config_patch"}return`admin_${r.toLowerCase()}`}}function Jp({serverUrl:e,cedrosLoginToken:t,isAdmin:r=!1}){const s=Hn.useWallet(),o=w.useMemo(()=>new Kp(e),[e]);w.useEffect(()=>{s.publicKey&&s.signMessage?o.setWalletSigner({publicKey:s.publicKey,signMessage:s.signMessage}):o.setWalletSigner(null)},[o,s.publicKey,s.signMessage]),w.useEffect(()=>{o.setCedrosLoginAuth(t??null,r)},[o,t,r]);const a=o.getAuthMethod(),i=o.isAuthenticated(),c=!!(s.publicKey&&s.signMessage),l=!!(t&&r),d=w.useMemo(()=>{if(!s.publicKey)return null;const u=s.publicKey.toBase58();return`${u.slice(0,4)}...${u.slice(-4)}`},[s.publicKey]),m=w.useCallback((u,f)=>o.fetchWithAuth(u,f),[o]);return{authMethod:a,isAuthenticated:i,walletConnected:c,walletAddress:d,cedrosLoginAvailable:l,authManager:o,fetchWithAuth:m}}const ml=[{label:"Menu",sections:[{id:"transactions",label:"Transactions",icon:G.transactions},{id:"products",label:"Products",icon:G.products},{id:"subscriptions",label:"Subscriptions",icon:G.calendarRepeat},{id:"coupons",label:"Coupons",icon:G.coupons},{id:"refunds",label:"Refunds",icon:G.refunds}]},{label:"Configuration",collapsible:!0,sections:[{id:"storefront",label:"Storefront",icon:G.storefront},{id:"ai-settings",label:"Store AI",icon:G.brain},{id:"faqs",label:"Knowledge Base",icon:G.faq},{id:"payment-settings",label:"Payment Options",icon:G.creditCard},{id:"messaging",label:"Store Messages",icon:G.mail},{id:"settings",label:"Store Server",icon:G.server}]}],Xp=ml.flatMap(e=>e.sections);function ef(){const[e,t]=w.useState(()=>typeof window>"u"?"light":window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light");return w.useEffect(()=>{const r=window.matchMedia("(prefers-color-scheme: dark)"),s=o=>t(o.matches?"dark":"light");return r.addEventListener("change",s),()=>r.removeEventListener("change",s)},[]),e}function tf(e,t,r){return e!=="system"?e:t||r}function nf({serverUrl:e,apiKey:t,title:r="Cedros Pay",sections:s=["transactions","products","subscriptions","coupons","refunds","storefront","ai-settings","faqs","payment-settings","messaging","settings"],defaultSection:o="transactions",refreshInterval:a=3e4,pageSize:i=20,onSectionChange:c,className:l="",cedrosLoginToken:d,isAdmin:m=!1,theme:u="system"}){const[f,h]=w.useState(o),[x,p]=w.useState(!0),[y,j]=w.useState(new Set),b=w.useCallback(A=>{j(P=>{const D=new Set(P);return D.has(A)?D.delete(A):D.add(A),D})},[]),v=oe.useCedrosThemeOptional(),_=ef(),E=tf(u,v?.mode??null,_)==="dark"?"cedros-admin--dark":"",{authManager:S}=Jp({serverUrl:e,cedrosLoginToken:d,isAdmin:m}),N=w.useCallback(A=>{h(A),c?.(A)},[c]),k=Xp.filter(A=>s.includes(A.id)).find(A=>A.id===f);return w.useEffect(()=>{const A=setTimeout(()=>p(!1),500);return()=>clearTimeout(A)},[]),x?n.jsxs("div",{className:`cedros-admin cedros-admin--loading ${E} ${l}`,children:[G.loading,n.jsx("span",{className:"cedros-admin__loading-text",children:"Loading dashboard..."})]}):n.jsxs("div",{className:`cedros-admin ${E} ${l}`,children:[n.jsxs("aside",{className:"cedros-admin__sidebar",children:[n.jsx("div",{className:"cedros-admin__sidebar-header",children:n.jsxs("div",{className:"cedros-admin__logo",children:[G.wallet,n.jsx("span",{className:"cedros-admin__logo-text",children:r})]})}),n.jsx("nav",{className:"cedros-admin__nav",children:ml.map(A=>{const P=A.sections.filter(z=>s.includes(z.id));if(P.length===0)return null;const D=A.collapsible&&y.has(A.label);return n.jsxs("div",{className:"cedros-admin__nav-group",children:[A.collapsible?n.jsxs("button",{type:"button",className:"cedros-admin__nav-label cedros-admin__nav-label--collapsible",onClick:()=>b(A.label),"aria-expanded":!D,children:[A.label,n.jsx("span",{className:`cedros-admin__nav-label-icon ${D?"":"cedros-admin__nav-label-icon--expanded"}`,children:G.chevronRight})]}):n.jsx("span",{className:"cedros-admin__nav-label",children:A.label}),!D&&P.map(z=>n.jsxs("button",{type:"button",className:`cedros-admin__nav-item ${f===z.id?"cedros-admin__nav-item--active":""}`,onClick:()=>N(z.id),"aria-current":f===z.id?"page":void 0,children:[n.jsx("span",{className:"cedros-admin__nav-icon",children:z.icon}),n.jsx("span",{className:"cedros-admin__nav-text",children:z.label})]},z.id))]},A.label)})})]}),n.jsxs("main",{className:"cedros-admin__main",children:[n.jsx("header",{className:"cedros-admin__header",children:n.jsxs("div",{className:"cedros-admin__breadcrumb",children:[n.jsx("span",{className:"cedros-admin__breadcrumb-root",children:r}),n.jsx("span",{className:"cedros-admin__breadcrumb-sep",children:G.chevronRight}),n.jsx("span",{className:"cedros-admin__breadcrumb-current",children:k?.label})]})}),n.jsxs("div",{className:"cedros-admin__content",children:[f==="products"&&n.jsx(el,{serverUrl:e,apiKey:t,pageSize:i,authManager:S}),f==="subscriptions"&&n.jsx(al,{serverUrl:e,apiKey:t,authManager:S}),f==="transactions"&&n.jsx(tl,{serverUrl:e,apiKey:t,pageSize:i,authManager:S}),f==="coupons"&&n.jsx(nl,{serverUrl:e,apiKey:t,pageSize:i,authManager:S}),f==="refunds"&&n.jsx(rl,{serverUrl:e,apiKey:t,pageSize:i,authManager:S}),f==="storefront"&&n.jsx(il,{serverUrl:e,apiKey:t,authManager:S}),f==="ai-settings"&&n.jsx(cl,{serverUrl:e,apiKey:t,authManager:S}),f==="faqs"&&n.jsx(ul,{serverUrl:e,apiKey:t,pageSize:i,authManager:S}),f==="payment-settings"&&n.jsx(ll,{serverUrl:e,apiKey:t,authManager:S}),f==="messaging"&&n.jsx(dl,{serverUrl:e,apiKey:t,authManager:S}),f==="settings"&&n.jsx(ca,{serverUrl:e,apiKey:t,authManager:S})]})]})]})}const Nt=e=>w.lazy(async()=>{const s=(await e()).default;return{default:({context:a})=>{const i={serverUrl:a.serverUrl};return n.jsx(s,{...i})}}}),rf={id:"cedros-pay",name:"Cedros Pay",version:"1.0.0",sections:[{id:"transactions",label:"Transactions",icon:G.transactions,group:"Store",order:0},{id:"products",label:"Products",icon:G.products,group:"Store",order:1},{id:"subscriptions",label:"Subscriptions",icon:G.subscriptions,group:"Store",order:2},{id:"coupons",label:"Coupons",icon:G.coupons,group:"Store",order:3},{id:"refunds",label:"Refunds",icon:G.refunds,group:"Store",order:4},{id:"storefront",label:"Storefront",icon:G.storefront,group:"Configuration",order:10},{id:"ai-settings",label:"Store AI",icon:G.ai,group:"Configuration",order:11},{id:"faqs",label:"Knowledge Base",icon:G.faq,group:"Configuration",order:12},{id:"payment-settings",label:"Payment Options",icon:G.wallet,group:"Configuration",order:13},{id:"messaging",label:"Store Messages",icon:G.notifications,group:"Configuration",order:14},{id:"settings",label:"Store Server",icon:G.settings,group:"Configuration",order:15}],groups:[{id:"Store",label:"Store",order:1},{id:"Configuration",label:"Configuration",order:2,collapsible:!0}],components:{products:Nt(()=>Promise.resolve().then(()=>require("./sections-6IcZ6JeN.js")).then(e=>({default:e.ProductsSection}))),subscriptions:Nt(()=>Promise.resolve().then(()=>$p).then(e=>({default:e.SubscriptionsSection}))),transactions:Nt(()=>Promise.resolve().then(()=>require("./sections-6IcZ6JeN.js")).then(e=>({default:e.TransactionsSection}))),coupons:Nt(()=>Promise.resolve().then(()=>require("./sections-6IcZ6JeN.js")).then(e=>({default:e.CouponsSection}))),refunds:Nt(()=>Promise.resolve().then(()=>require("./sections-6IcZ6JeN.js")).then(e=>({default:e.RefundsSection}))),storefront:Nt(()=>Promise.resolve().then(()=>Up).then(e=>({default:e.StorefrontSection}))),"ai-settings":Nt(()=>Promise.resolve().then(()=>qp).then(e=>({default:e.AISettingsSection}))),faqs:Nt(()=>Promise.resolve().then(()=>Yp).then(e=>({default:e.FAQSection}))),"payment-settings":Nt(()=>Promise.resolve().then(()=>Zp).then(e=>({default:e.PaymentSettingsSection}))),messaging:Nt(()=>Promise.resolve().then(()=>Qp).then(e=>({default:e.MessagingSection}))),settings:Nt(()=>Promise.resolve().then(()=>Mp).then(e=>({default:e.SettingsSection})))},createPluginContext(e){const t=e.cedrosPay,r=e.cedrosLogin;return{serverUrl:t?.serverUrl||r?.serverUrl||"",userId:r?.user?.id,getAccessToken:()=>r?.getAccessToken?.()||t?.jwtToken||null,hasPermission:o=>this.checkPermission(o,e),orgId:e.org?.orgId,pluginData:{walletAddress:t?.walletAddress}}},checkPermission(e,t){return t.org?.permissions?t.org.permissions.includes(e):!!(t.cedrosLogin?.user||t.cedrosPay?.jwtToken||t.cedrosPay?.walletAddress)},cssNamespace:"cedros-admin"};function pl(){const{subscriptionManager:e}=oe.useCedrosContext(),[t,r]=w.useState({status:"idle",error:null,sessionId:null,subscriptionStatus:null,expiresAt:null}),s=w.useCallback(async c=>{r(d=>({...d,status:"loading",error:null}));const l=await e.processSubscription(c);return r(d=>({...d,status:l.success?"success":"error",error:l.success?null:l.error||"Subscription failed",sessionId:l.success&&l.transactionId||null})),l},[e]),o=w.useCallback(async c=>{r(l=>({...l,status:"checking",error:null}));try{const l=await e.checkSubscriptionStatus(c);return r(d=>({...d,status:l.active?"success":"idle",subscriptionStatus:l.status,expiresAt:l.expiresAt||l.currentPeriodEnd||null})),l}catch(l){const d=l instanceof Error?l.message:"Failed to check subscription status";throw r(m=>({...m,status:"error",error:d})),l}},[e]),a=w.useCallback(async(c,l,d)=>{r(m=>({...m,status:"loading",error:null}));try{const m=await e.requestSubscriptionQuote(c,l,d);return r(u=>({...u,status:"idle"})),m}catch(m){const u=m instanceof Error?m.message:"Failed to get subscription quote";throw r(f=>({...f,status:"error",error:u})),m}},[e]),i=w.useCallback(()=>{r({status:"idle",error:null,sessionId:null,subscriptionStatus:null,expiresAt:null})},[]);return{...t,processSubscription:s,checkStatus:o,requestQuote:a,reset:i}}function sf({resource:e,interval:t,intervalDays:r,trialDays:s,successUrl:o,cancelUrl:a,metadata:i,customerEmail:c,couponCode:l,label:d,disabled:m=!1,onAttempt:u,onSuccess:f,onError:h,className:x=""}){const{status:p,error:y,sessionId:j,processSubscription:b}=pl(),v=oe.useCedrosTheme(),{t:_,translations:C}=fe.useTranslation(),E=d||_("ui.subscribe"),S=v.unstyled?x:`${v.className} cedros-theme__stripe-button ${x}`.trim(),N=y&&typeof y!="string"?y?.code??null:null,k=y?typeof y=="string"?y:(O=>{if(!O||!C)return"";const M=C.errors[O];return M?M.action?`${M.message} ${M.action}`:M.message:""})(N):null,A=w.useCallback(async()=>{oe.getLogger().debug("[SubscribeButton] executeSubscription:",{resource:e,interval:t,intervalDays:r,trialDays:s,couponCode:l}),fe.emitPaymentStart("stripe",e),u&&u("stripe"),fe.emitPaymentProcessing("stripe",e);const O=await b({resource:e,interval:t,intervalDays:r,trialDays:s,customerEmail:c,metadata:i,couponCode:l,successUrl:o,cancelUrl:a});O.success&&O.transactionId?(fe.emitPaymentSuccess("stripe",O.transactionId,e),f&&f(O.transactionId)):!O.success&&O.error&&(fe.emitPaymentError("stripe",O.error,e),h&&h(O.error))},[e,t,r,s,c,i,l,o,a,b,u,f,h]),P=w.useMemo(()=>`subscribe-${e}-${t}`,[e,t]),D=w.useMemo(()=>fe.createDedupedClickHandler(P,A),[P,A]),z=p==="loading",L=m||z;return n.jsxs("div",{className:S,style:v.unstyled?{}:v.style,children:[n.jsx("button",{onClick:D,disabled:L,className:v.unstyled?x:"cedros-theme__button cedros-theme__stripe",type:"button",children:z?_("ui.processing"):E}),k&&n.jsx("div",{className:v.unstyled?"":"cedros-theme__error",children:k}),j&&n.jsx("div",{className:v.unstyled?"":"cedros-theme__success",children:_("ui.redirecting_to_checkout")})]})}function fl(){const{subscriptionManager:e,x402Manager:t,walletManager:r}=oe.useCedrosContext(),{publicKey:s,signTransaction:o}=Hn.useWallet(),[a,i]=w.useState({status:"idle",error:null,sessionId:null,subscriptionStatus:null,expiresAt:null}),[c,l]=w.useState(null),d=w.useCallback(()=>{if(!s){const x="Wallet not connected";return i(p=>({...p,status:"error",error:x})),{valid:!1,error:x}}if(!o){const x="Wallet does not support signing";return i(p=>({...p,status:"error",error:x})),{valid:!1,error:x}}return{valid:!0}},[s,o]),m=w.useCallback(async x=>{if(!s)return i(p=>({...p,status:"error",error:"Wallet not connected"})),null;i(p=>({...p,status:"checking",error:null}));try{const p=await e.checkSubscriptionStatus({resource:x,userId:s.toString()});return i(y=>({...y,status:p.active?"success":"idle",subscriptionStatus:p.status,expiresAt:p.expiresAt||p.currentPeriodEnd||null})),p}catch(p){const y=oe.formatError(p,"Failed to check subscription status");return i(j=>({...j,status:"error",error:y})),null}},[s,e]),u=w.useCallback(async(x,p,y)=>{i(j=>({...j,status:"loading",error:null}));try{const j=await e.requestSubscriptionQuote(x,p,y);return l(j),i(b=>({...b,status:"idle"})),j}catch(j){const b=oe.formatError(j,"Failed to get subscription quote");return i(v=>({...v,status:"error",error:b})),null}},[e]),f=w.useCallback(async(x,p,y)=>{const j=d();if(!j.valid)return{success:!1,error:j.error};i(b=>({...b,status:"loading",error:null}));try{const b=await e.requestSubscriptionQuote(x,p,y);l(b);const v=b.requirement;if(!t.validateRequirement(v))throw new Error("Invalid subscription quote received from server");const _=!!v.extra?.feePayer;let C;if(_){const{transaction:E,blockhash:S}=await t.buildGaslessTransaction({resourceId:x,userWallet:s.toString(),feePayer:v.extra.feePayer,couponCode:y?.couponCode}),N=r.deserializeTransaction(E),U=await r.partiallySignTransaction({transaction:N,signTransaction:o,blockhash:S});C=await t.submitGaslessTransaction({resource:x,partialTx:U,couponCode:y?.couponCode,resourceType:"regular",requirement:v})}else{const E=await r.buildTransaction({requirement:v,payerPublicKey:s}),S=await r.signTransaction({transaction:E,signTransaction:o}),N=r.buildPaymentPayload({requirement:v,signedTx:S,payerPublicKey:s});C=await t.submitPayment({resource:x,payload:N,couponCode:y?.couponCode,resourceType:"regular"})}if(C.success){const E=await e.checkSubscriptionStatus({resource:x,userId:s.toString()});i({status:"success",error:null,sessionId:C.transactionId||null,subscriptionStatus:E.status,expiresAt:E.expiresAt||E.currentPeriodEnd||null})}else i(E=>({...E,status:"error",error:C.error||"Subscription payment failed"}));return C}catch(b){const v=oe.formatError(b,"Subscription payment failed");return i(_=>({..._,status:"error",error:v})),{success:!1,error:v}}},[d,e,t,r,s,o]),h=w.useCallback(()=>{i({status:"idle",error:null,sessionId:null,subscriptionStatus:null,expiresAt:null}),l(null)},[]);return{...a,quote:c,checkStatus:m,requestQuote:u,processPayment:f,reset:h}}function of({resource:e,interval:t,intervalDays:r,couponCode:s,label:o,disabled:a=!1,onAttempt:i,onSuccess:c,onError:l,className:d="",testPageUrl:m,hideMessages:u=!1,autoCheckStatus:f=!0}){const{connected:h,connecting:x,connect:p,disconnect:y,select:j,wallets:b,wallet:v,publicKey:_}=Hn.useWallet(),{status:C,error:E,subscriptionStatus:S,expiresAt:N,checkStatus:U,processPayment:k}=fl(),A=oe.useCedrosTheme(),{solanaError:P}=oe.useCedrosContext(),{t:D,translations:z}=fe.useTranslation(),L=o||D("ui.subscribe_with_crypto"),O=w.useRef(k),M=w.useRef(U);w.useEffect(()=>{O.current=k,M.current=U},[k,U]);const R=E&&typeof E!="string"?E?.code??null:null,W=P&&typeof P!="string"?P?.code??null:null,T=de=>{if(!de||!z)return"";const ke=z.errors[de];return ke?ke.action?`${ke.message} ${ke.action}`:ke.message:""},V=E?typeof E=="string"?E:T(R):null,ee=P?typeof P=="string"?P:T(W):null,B=w.useMemo(()=>b.map(de=>`${de.adapter.name}-${de.readyState}`).join(","),[b]),Y=w.useMemo(()=>b.filter(({readyState:de})=>de===wi.WalletReadyState.Installed||de===wi.WalletReadyState.Loadable),[B]);w.useEffect(()=>{f&&h&&_&&(oe.getLogger().debug("[CryptoSubscribeButton] Auto-checking subscription status"),M.current(e))},[f,h,_,e]),w.useEffect(()=>{C==="success"&&S==="active"&&(fe.emitPaymentSuccess("crypto","subscription-active",e),c&&c("subscription-active"))},[C,S,e,c]),w.useEffect(()=>{C==="error"&&E&&(fe.emitPaymentError("crypto",E,e),l&&l(E))},[C,E,e,l]);const J=typeof window<"u"&&window.top!==window.self,[ge,F]=w.useState(!1),[K,me]=w.useState(!1),[q,te]=w.useState(!1),ce=P;w.useEffect(()=>{let de=!1;return de||(async()=>{if(K&&v&&!h&&!x){oe.getLogger().debug("[CryptoSubscribeButton] Wallet detected, attempting auto-connect:",v.adapter.name),me(!1),fe.emitWalletConnect(v.adapter.name);try{await p(),de||oe.getLogger().debug("[CryptoSubscribeButton] Auto-connect successful")}catch($){if(!de){oe.getLogger().error("[CryptoSubscribeButton] Auto-connect failed:",$);const X=$ instanceof Error?$.message:"Failed to connect wallet";fe.emitWalletError(X,v.adapter.name),te(!1)}}}})(),()=>{de=!0}},[v,K,h,x,p]),w.useEffect(()=>{h&&q&&_&&v&&(fe.emitWalletConnected(v.adapter.name,_.toString()),oe.getLogger().debug("[CryptoSubscribeButton] Processing pending subscription payment"),te(!1),F(!1),fe.emitPaymentProcessing("crypto",e),O.current(e,t,{couponCode:s,intervalDays:r}))},[h,q,_,v,e,t,s,r]);const pe=w.useCallback(async()=>{if(oe.getLogger().debug("[CryptoSubscribeButton] executeSubscriptionFlow called",{connected:h,wallet:v?.adapter.name,resource:e,interval:t}),fe.emitPaymentStart("crypto",e),i&&i("crypto"),ce){oe.getLogger().error("[CryptoSubscribeButton] Solana dependencies missing:",ce),fe.emitPaymentError("crypto",ce,e),l&&l(ce);return}if(J){const de=m||window.location.href;try{if(new URL(de,window.location.origin).origin!==window.location.origin)throw oe.getLogger().error("[CryptoSubscribeButton] Blocked attempt to open external URL:",de),new Error("Cannot open external URLs from embedded context");window.open(de,"_blank","noopener,noreferrer")}catch(ke){throw oe.getLogger().error("[CryptoSubscribeButton] URL validation failed:",ke),ke}return}if(h)fe.emitPaymentProcessing("crypto",e),await k(e,t,{couponCode:s,intervalDays:r});else{te(!0);try{if(v)oe.getLogger().debug("[CryptoSubscribeButton] Wallet already selected, connecting:",v.adapter.name),fe.emitWalletConnect(v.adapter.name),await p();else{if(oe.getLogger().debug("[CryptoSubscribeButton] No wallet selected, showing selector"),Y.length===0){te(!1);const de="No wallets available";throw fe.emitWalletError(de),new Error(de)}F(!0)}}catch(de){te(!1);const ke=de instanceof Error?de.message:"Failed to connect wallet";oe.getLogger().error("[CryptoSubscribeButton] Connection error:",ke),fe.emitWalletError(ke,v?.adapter.name)}}},[h,v,e,t,s,r,J,m,Y,p,k,ce,i,l]),Oe=w.useMemo(()=>`crypto-subscribe-${e}-${t}`,[e,t]),Ge=w.useMemo(()=>fe.createDedupedClickHandler(Oe,pe,{cooldownMs:200,deduplicationWindowMs:0}),[Oe,pe]),Qe=C==="loading"||C==="checking",$e=S==="active"||S==="trialing",Ye=a||Qe||x||!!ce||$e;let Ne=L;if(Qe)Ne=D("ui.processing");else if($e&&N){const de=new Date(N).toLocaleDateString();Ne=`${D("ui.subscribed_until")} ${de}`}else $e&&(Ne=D("ui.subscribed"));const st=w.useCallback(async()=>{try{me(!1),h&&await y(),j(null),F(!0)}catch(de){oe.getLogger().error("Failed to change wallet:",de)}},[h,y,j]),Ae=w.useCallback(de=>{oe.getLogger().debug("[CryptoSubscribeButton] Wallet clicked:",de),F(!1),j(de),me(!0)},[j]),Fe=w.useCallback(async()=>{try{if(await y(),te(!1),typeof window<"u"&&window.localStorage)try{window.localStorage.removeItem("walletName")}catch(de){de instanceof Error&&de.name==="QuotaExceededError"?oe.getLogger().warn("localStorage quota exceeded when removing wallet preference"):oe.getLogger().error("Failed to clear wallet preference from localStorage:",de)}}catch(de){oe.getLogger().error("Failed to disconnect wallet:",de)}},[y]);return n.jsxs("div",{className:A.unstyled?d:`${A.className} cedros-theme__crypto-button ${d||""}`,style:A.unstyled?{}:A.style,children:[n.jsx("button",{onClick:Ge,disabled:Ye,className:A.unstyled?d:"cedros-theme__button cedros-theme__crypto",type:"button",children:Ne}),ge&&!u&&n.jsx("div",{className:"cedros-modal-overlay",style:{position:"fixed",top:0,left:0,right:0,bottom:0,backgroundColor:A.tokens.modalOverlay,display:"flex",alignItems:"center",justifyContent:"center",zIndex:9999,padding:"1rem"},onClick:()=>F(!1),children:n.jsxs("div",{className:"cedros-modal-content",style:{backgroundColor:A.tokens.modalBackground,borderRadius:"12px",padding:"2rem",maxWidth:"400px",width:"100%",boxShadow:"0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04)",border:`1px solid ${A.tokens.modalBorder}`},onClick:de=>de.stopPropagation(),children:[n.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"1.5rem"},children:[n.jsx("h3",{style:{margin:0,fontSize:"1.25rem",fontWeight:600,color:A.tokens.surfaceText},children:D("wallet.select_wallet")}),n.jsx("button",{onClick:()=>F(!1),style:fe.getModalCloseButtonStyles(A.tokens.surfaceText),"aria-label":"Close modal",type:"button",children:"×"})]}),n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"0.75rem"},children:Y.map(de=>n.jsxs("button",{onClick:()=>Ae(de.adapter.name),style:{width:"100%",padding:"1rem",backgroundColor:A.tokens.surfaceBackground,border:`1px solid ${A.tokens.surfaceBorder}`,borderRadius:"0.5rem",cursor:"pointer",fontSize:"1rem",textAlign:"left",color:A.tokens.surfaceText,display:"flex",alignItems:"center",gap:"1rem",transition:"all 0.2s ease"},onMouseEnter:ke=>{ke.currentTarget.style.backgroundColor=A.tokens.modalBackground,ke.currentTarget.style.borderColor=A.tokens.surfaceText,ke.currentTarget.style.transform="translateY(-2px)"},onMouseLeave:ke=>{ke.currentTarget.style.backgroundColor=A.tokens.surfaceBackground,ke.currentTarget.style.borderColor=A.tokens.surfaceBorder,ke.currentTarget.style.transform="translateY(0)"},type:"button",children:[n.jsx(hp.WalletIcon,{wallet:de,style:{width:"24px",height:"24px"}}),n.jsx("span",{style:{fontWeight:500},children:de.adapter.name})]},de.adapter.name))})]})}),h&&!u&&!ge&&n.jsxs("div",{style:{display:"flex",justifyContent:"space-between",marginTop:"0.5rem",fontSize:"0.75rem",color:A.tokens.surfaceText,opacity:.7},children:[n.jsx("button",{onClick:st,style:{background:"none",border:"none",padding:0,color:"inherit",textDecoration:"none",cursor:"pointer",fontSize:"inherit"},type:"button",children:D("wallet.change")}),n.jsx("button",{onClick:Fe,style:{background:"none",border:"none",padding:0,color:"inherit",textDecoration:"none",cursor:"pointer",fontSize:"inherit"},type:"button",children:D("ui.disconnect")})]}),!u&&ee&&n.jsx("div",{className:A.unstyled?"":"cedros-theme__error",children:ee}),!u&&V&&n.jsx("div",{className:A.unstyled?"":"cedros-theme__error",children:V}),!u&&$e&&n.jsx("div",{className:A.unstyled?"":"cedros-theme__success",children:D("ui.subscription_active")})]})}function hl(){const{subscriptionManager:e,creditsManager:t}=oe.useCedrosContext(),[r,s]=w.useState({status:"idle",error:null,sessionId:null,subscriptionStatus:null,expiresAt:null,creditsRequirement:null}),o=w.useCallback(async(l,d)=>{s(m=>({...m,status:"checking",error:null}));try{const m=await e.checkSubscriptionStatus({resource:l,userId:d});return s(u=>({...u,status:m.active?"success":"idle",subscriptionStatus:m.status,expiresAt:m.expiresAt||m.currentPeriodEnd||null})),m}catch(m){const u=oe.formatError(m,"Failed to check subscription status");return s(f=>({...f,status:"error",error:u})),null}},[e]),a=w.useCallback(async(l,d,m)=>{s(u=>({...u,status:"loading",error:null}));try{const u=await t.requestQuote(l,m?.couponCode);return s(f=>({...f,status:"idle",creditsRequirement:u})),u}catch(u){const f=oe.formatError(u,"Failed to get subscription quote");return s(h=>({...h,status:"error",error:f})),null}},[t]),i=w.useCallback(async(l,d,m,u)=>{if(!m){const f="Authentication required for credits payment";return s(h=>({...h,status:"error",error:f})),{success:!1,error:f}}s(f=>({...f,status:"loading",error:null}));try{const f=await t.processPayment(l,m,u?.couponCode,{interval:d,...u?.intervalDays&&{intervalDays:String(u.intervalDays)}});return f.success?s({status:"success",error:null,sessionId:f.transactionId||null,subscriptionStatus:"active",expiresAt:null,creditsRequirement:null}):s(h=>({...h,status:"error",error:f.error||"Credits subscription payment failed"})),f}catch(f){const h=oe.formatError(f,"Credits subscription payment failed");return s(x=>({...x,status:"error",error:h})),{success:!1,error:h}}},[t]),c=w.useCallback(()=>{s({status:"idle",error:null,sessionId:null,subscriptionStatus:null,expiresAt:null,creditsRequirement:null})},[]);return{...r,checkStatus:o,requestQuote:a,processPayment:i,reset:c}}function af({resource:e,interval:t,intervalDays:r,authToken:s,userId:o,couponCode:a,label:i,disabled:c=!1,onAttempt:l,onSuccess:d,onError:m,className:u="",hideMessages:f=!1,autoCheckStatus:h=!1}){const{status:x,error:p,subscriptionStatus:y,expiresAt:j,checkStatus:b,processPayment:v}=hl(),_=oe.useCedrosTheme(),{t:C,translations:E}=fe.useTranslation(),S=w.useRef(b);w.useEffect(()=>{S.current=b},[b]),w.useEffect(()=>{h&&o&&(oe.getLogger().debug("[CreditsSubscribeButton] Auto-checking subscription status",{resource:e,userId:o}),S.current(e,o))},[h,o,e]);const N=i||C("ui.subscribe_with_credits")||"Subscribe with Credits",U=p&&typeof p!="string"?p?.code??null:null,A=p?typeof p=="string"?p:(T=>{if(!T||!E)return"";const V=E.errors[T];return V?V.action?`${V.message} ${V.action}`:V.message:""})(U):null,P=w.useCallback(async()=>{if(oe.getLogger().debug("[CreditsSubscribeButton] executeSubscriptionFlow",{resource:e,interval:t,intervalDays:r,hasAuthToken:!!s}),fe.emitPaymentStart("credits",e),l&&l("credits"),!s){const V="Authentication required: please log in to subscribe with credits";oe.getLogger().error("[CreditsSubscribeButton]",V),fe.emitPaymentError("credits",V,e),m&&m(V);return}fe.emitPaymentProcessing("credits",e);const T=await v(e,t,s,{couponCode:a,intervalDays:r});T.success&&T.transactionId?(fe.emitPaymentSuccess("credits",T.transactionId,e),d&&d(T.transactionId)):!T.success&&T.error&&(fe.emitPaymentError("credits",T.error,e),m&&m(T.error))},[e,t,r,s,a,v,l,d,m]),D=w.useMemo(()=>`credits-subscribe-${e}-${t}`,[e,t]),z=w.useMemo(()=>fe.createDedupedClickHandler(D,P,{cooldownMs:200,deduplicationWindowMs:0}),[D,P]),L=x==="loading"||x==="checking",O=y==="active"||y==="trialing",M=c||L||O;let R=N;if(L)R=C("ui.processing");else if(O&&j){const T=new Date(j).toLocaleDateString();R=`${C("ui.subscribed_until")} ${T}`}else O&&(R=C("ui.subscribed"));const W=_.unstyled?u:`${_.className} cedros-theme__credits-button ${u}`.trim();return n.jsxs("div",{className:W,style:_.unstyled?{}:_.style,children:[n.jsx("button",{onClick:z,disabled:M,className:_.unstyled?u:"cedros-theme__button cedros-theme__credits",type:"button",children:R}),!f&&A&&n.jsx("div",{className:_.unstyled?"":"cedros-theme__error",children:A}),!f&&O&&n.jsx("div",{className:_.unstyled?"":"cedros-theme__success",children:C("ui.subscription_active")})]})}function gl(){const{subscriptionChangeManager:e}=oe.useCedrosContext(),[t,r]=w.useState({status:"idle",error:null,subscription:null,changePreview:null,userId:null}),s=w.useRef(t);s.current=t;const o=w.useCallback(async(u,f)=>{r(h=>({...h,status:"loading",error:null}));try{const h=await e.getDetails(u,f);return r(x=>({...x,status:"success",subscription:h,userId:f})),h}catch(h){const x=h instanceof Error?h.message:"Failed to load subscription";return r(p=>({...p,status:"error",error:x})),null}},[e]),a=w.useCallback(async(u,f,h,x)=>{r(p=>({...p,status:"loading",error:null}));try{const p={currentResource:u,newResource:f,userId:h,newInterval:x},y=await e.previewChange(p);return r(j=>({...j,status:"idle",changePreview:y})),y}catch(p){const y=p instanceof Error?p.message:"Failed to preview change";return r(j=>({...j,status:"error",error:y})),null}},[e]),i=w.useCallback(async u=>{const{subscription:f,userId:h}=s.current;if(!f||!h)return r(x=>({...x,status:"error",error:"No subscription loaded"})),null;r(x=>({...x,status:"loading",error:null}));try{const x={currentResource:f.resource,newResource:u.newResource,userId:h,newInterval:u.newInterval,prorationBehavior:u.prorationBehavior,immediate:u.immediate},p=await e.changeSubscription(x);return p.success?r(y=>({...y,status:"success",subscription:y.subscription?{...y.subscription,resource:p.newResource,interval:p.newInterval,status:p.status}:null,changePreview:null})):r(y=>({...y,status:"error",error:p.error||"Failed to change subscription"})),p}catch(x){const p=x instanceof Error?x.message:"Failed to change subscription";return r(y=>({...y,status:"error",error:p})),null}},[e]),c=w.useCallback(async u=>{const{subscription:f,userId:h}=s.current;if(!f||!h)return r(x=>({...x,status:"error",error:"No subscription loaded"})),null;r(x=>({...x,status:"loading",error:null}));try{const x={resource:f.resource,userId:h,immediate:u},p=await e.cancel(x);if(p.success){const y=u?"canceled":f.status;r(j=>({...j,status:"success",subscription:j.subscription?{...j.subscription,status:y,cancelAtPeriodEnd:!u}:null}))}else r(y=>({...y,status:"error",error:p.error||"Failed to cancel subscription"}));return p}catch(x){const p=x instanceof Error?x.message:"Failed to cancel subscription";return r(y=>({...y,status:"error",error:p})),null}},[e]),l=w.useCallback(async(u,f)=>{r(h=>({...h,status:"loading",error:null}));try{const h=await e.getBillingPortalUrl({userId:u,returnUrl:f});return window.location.href=h.url,h}catch(h){const x=h instanceof Error?h.message:"Failed to open billing portal";return r(p=>({...p,status:"error",error:x})),null}},[e]),d=w.useCallback(()=>{r(u=>({...u,changePreview:null}))},[]),m=w.useCallback(()=>{r({status:"idle",error:null,subscription:null,changePreview:null,userId:null})},[]);return{...t,loadSubscription:o,previewChange:a,changeSubscription:i,cancelSubscription:c,openBillingPortal:l,clearPreview:d,reset:m}}const cf={bg:"#fff",bgMuted:"#f9fafb",bgHighlight:"#eff6ff",text:"#111827",textMuted:"#6b7280",textFaint:"#9ca3af",border:"#e5e7eb",borderLight:"#f3f4f6",primary:"#3b82f6",error:"#ef4444",errorBg:"#fef2f2",errorBorder:"#fecaca",warningBg:"#fef3c7",warningBorder:"#fcd34d",warningText:"#92400e",buttonBg:"#f3f4f6",buttonBorder:"#d1d5db",buttonText:"#374151"},lf={bg:"#1e293b",bgMuted:"#334155",bgHighlight:"rgba(59, 130, 246, 0.15)",text:"#f1f5f9",textMuted:"#94a3b8",textFaint:"#64748b",border:"#475569",borderLight:"#334155",primary:"#3b82f6",error:"#ef4444",errorBg:"rgba(239, 68, 68, 0.15)",errorBorder:"rgba(239, 68, 68, 0.3)",warningBg:"rgba(245, 158, 11, 0.15)",warningBorder:"rgba(245, 158, 11, 0.3)",warningText:"#fbbf24",buttonBg:"#334155",buttonBorder:"#475569",buttonText:"#e2e8f0"};function df(e){const t=e?lf:cf;return{container:{padding:"24px",backgroundColor:t.bg,borderRadius:"8px",border:`1px solid ${t.border}`,fontFamily:"system-ui, -apple-system, sans-serif",color:t.text},error:{padding:"12px 16px",backgroundColor:t.errorBg,border:`1px solid ${t.errorBorder}`,borderRadius:"6px",color:t.error,marginBottom:"16px"},loading:{padding:"24px",textAlign:"center",color:t.textMuted},details:{marginBottom:"24px"},title:{margin:"0 0 16px 0",fontSize:"18px",fontWeight:600,color:t.text},detailRow:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"8px 0",borderBottom:`1px solid ${t.borderLight}`},label:{color:t.textMuted,fontSize:"14px"},value:{color:t.text,fontSize:"14px",fontWeight:500},statusBadge:{padding:"4px 8px",borderRadius:"4px",color:"#fff",fontSize:"12px",fontWeight:500,textTransform:"capitalize"},cancelNotice:{marginTop:"12px",padding:"8px 12px",backgroundColor:t.warningBg,border:`1px solid ${t.warningBorder}`,borderRadius:"6px",color:t.warningText,fontSize:"13px"},prorationPreview:{padding:"16px",backgroundColor:t.bgMuted,borderRadius:"8px",marginBottom:"24px"},previewTitle:{margin:"0 0 12px 0",fontSize:"16px",fontWeight:600,color:t.text},previewDetails:{marginBottom:"16px"},previewRow:{display:"flex",justifyContent:"space-between",padding:"6px 0",fontSize:"14px",color:t.textMuted},previewTotal:{borderTop:`1px solid ${t.border}`,marginTop:"8px",paddingTop:"12px",fontWeight:600,color:t.text},previewActions:{display:"flex",gap:"12px",justifyContent:"flex-end"},cancelButton:{padding:"8px 16px",backgroundColor:t.bg,border:`1px solid ${t.buttonBorder}`,borderRadius:"6px",color:t.buttonText,cursor:"pointer",fontSize:"14px"},confirmButton:{padding:"8px 16px",backgroundColor:t.primary,border:"none",borderRadius:"6px",color:"#fff",cursor:"pointer",fontSize:"14px",fontWeight:500},plansSection:{marginBottom:"24px"},plansTitle:{margin:"0 0 12px 0",fontSize:"16px",fontWeight:600,color:t.text},plansList:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(200px, 1fr))",gap:"16px"},planCard:{padding:"16px",backgroundColor:t.bg,border:`1px solid ${t.border}`,borderRadius:"8px",textAlign:"center"},currentPlan:{borderColor:t.primary,backgroundColor:t.bgHighlight},planName:{fontSize:"16px",fontWeight:600,color:t.text,marginBottom:"4px"},planPrice:{fontSize:"14px",color:t.textMuted,marginBottom:"8px"},planDescription:{fontSize:"12px",color:t.textFaint,marginBottom:"12px"},currentBadge:{display:"inline-block",padding:"4px 8px",backgroundColor:t.primary,color:"#fff",borderRadius:"4px",fontSize:"12px",fontWeight:500},changePlanButton:{padding:"8px 16px",backgroundColor:t.buttonBg,border:`1px solid ${t.buttonBorder}`,borderRadius:"6px",color:t.buttonText,cursor:"pointer",fontSize:"14px",width:"100%"},actions:{display:"flex",gap:"12px",justifyContent:"flex-end",paddingTop:"16px",borderTop:`1px solid ${t.border}`},portalButton:{padding:"10px 20px",backgroundColor:t.primary,border:"none",borderRadius:"6px",color:"#fff",cursor:"pointer",fontSize:"14px",fontWeight:500},cancelSubscriptionButton:{padding:"10px 20px",backgroundColor:t.bg,border:`1px solid ${t.error}`,borderRadius:"6px",color:t.error,cursor:"pointer",fontSize:"14px"}}}function vn(e,t){return new Intl.NumberFormat("en-US",{style:"currency",currency:t.toUpperCase()}).format(e/100)}function xl(e){return new Date(e).toLocaleDateString("en-US",{year:"numeric",month:"long",day:"numeric"})}function uf(e){switch(e){case"active":return"#22c55e";case"trialing":return"#3b82f6";case"past_due":return"#f59e0b";case"canceled":case"expired":return"#ef4444";default:return"#6b7280"}}function mf({preview:e,onConfirm:t,onCancel:r,isLoading:s,styles:o}){const a=e.immediateAmount<0;return n.jsxs("div",{className:"cedros-proration-preview",style:o.prorationPreview,children:[n.jsx("h4",{style:o.previewTitle,children:"Change Preview"}),n.jsxs("div",{style:o.previewDetails,children:[n.jsxs("div",{style:o.previewRow,children:[n.jsx("span",{children:"Current plan:"}),n.jsxs("span",{children:[vn(e.currentPlanPrice,e.currency),"/period"]})]}),n.jsxs("div",{style:o.previewRow,children:[n.jsx("span",{children:"New plan:"}),n.jsxs("span",{children:[vn(e.newPlanPrice,e.currency),"/period"]})]}),n.jsxs("div",{style:o.previewRow,children:[n.jsx("span",{children:"Days remaining:"}),n.jsxs("span",{children:[e.daysRemaining," days"]})]}),e.prorationDetails&&n.jsxs(n.Fragment,{children:[n.jsxs("div",{style:o.previewRow,children:[n.jsx("span",{children:"Unused credit:"}),n.jsxs("span",{children:["-",vn(e.prorationDetails.unusedCredit,e.currency)]})]}),n.jsxs("div",{style:o.previewRow,children:[n.jsx("span",{children:"New plan cost:"}),n.jsx("span",{children:vn(e.prorationDetails.newPlanCost,e.currency)})]})]}),n.jsxs("div",{style:{...o.previewRow,...o.previewTotal},children:[n.jsx("span",{children:a?"Credit to account:":"Amount due now:"}),n.jsx("span",{style:{color:a?"#22c55e":"#ef4444"},children:vn(Math.abs(e.immediateAmount),e.currency)})]}),n.jsxs("div",{style:o.previewRow,children:[n.jsx("span",{children:"Effective date:"}),n.jsx("span",{children:xl(e.effectiveDate)})]})]}),n.jsxs("div",{style:o.previewActions,children:[n.jsx("button",{onClick:r,style:o.cancelButton,disabled:s,children:"Cancel"}),n.jsx("button",{onClick:t,style:o.confirmButton,disabled:s,children:s?"Processing...":"Confirm Change"})]})]})}function pf({resource:e,userId:t,availablePlans:r=[],onSubscriptionChanged:s,onSubscriptionCanceled:o,billingPortalReturnUrl:a,showBillingPortal:i=!1,className:c,style:l}){const{mode:d}=oe.useCedrosTheme(),m=w.useMemo(()=>df(d==="dark"),[d]),{subscription:u,changePreview:f,status:h,error:x,loadSubscription:p,previewChange:y,changeSubscription:j,cancelSubscription:b,openBillingPortal:v,clearPreview:_}=gl();w.useEffect(()=>{p(e,t)},[e,t,p]);const C=w.useCallback(async(k,A)=>{await y(e,k,t,A)},[e,t,y]),E=w.useCallback(async()=>{if(!f)return;const k=r.find(P=>P.price===f.newPlanPrice&&P.currency===f.currency);(await j({newResource:k?.resource||e,newInterval:k?.interval,immediate:!0}))?.success&&k&&s?.(k.resource,k.interval)},[f,r,e,j,s]),S=w.useCallback(async k=>{(await b(k))?.success&&o?.()},[b,o]),N=w.useCallback(()=>{v(t,a)},[t,a,v]),U=h==="loading";return n.jsxs("div",{className:`cedros-subscription-panel ${c||""}`,style:{...m.container,...l},children:[x&&n.jsx("div",{className:"cedros-subscription-error",style:m.error,children:x}),U&&!u&&n.jsx("div",{className:"cedros-subscription-loading",style:m.loading,children:"Loading subscription..."}),u&&n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:"cedros-subscription-details",style:m.details,children:[n.jsx("h3",{style:m.title,children:"Current Subscription"}),n.jsxs("div",{style:m.detailRow,children:[n.jsx("span",{style:m.label,children:"Plan:"}),n.jsx("span",{style:m.value,children:u.resource})]}),n.jsxs("div",{style:m.detailRow,children:[n.jsx("span",{style:m.label,children:"Status:"}),n.jsx("span",{style:{...m.statusBadge,backgroundColor:uf(u.status)},children:u.status})]}),n.jsxs("div",{style:m.detailRow,children:[n.jsx("span",{style:m.label,children:"Price:"}),n.jsxs("span",{style:m.value,children:[vn(u.pricePerPeriod,u.currency),"/",u.interval]})]}),n.jsxs("div",{style:m.detailRow,children:[n.jsx("span",{style:m.label,children:"Current period ends:"}),n.jsx("span",{style:m.value,children:xl(u.currentPeriodEnd)})]}),u.cancelAtPeriodEnd&&n.jsx("div",{style:m.cancelNotice,children:"Subscription will cancel at end of current period"})]}),f&&n.jsx(mf,{preview:f,onConfirm:E,onCancel:_,isLoading:U,styles:m}),r.length>0&&!f&&n.jsxs("div",{className:"cedros-available-plans",style:m.plansSection,children:[n.jsx("h4",{style:m.plansTitle,children:"Available Plans"}),n.jsx("div",{style:m.plansList,children:r.map(k=>{const A=k.resource===u.resource;return n.jsxs("div",{style:{...m.planCard,...A?m.currentPlan:{}},children:[n.jsx("div",{style:m.planName,children:k.name}),n.jsxs("div",{style:m.planPrice,children:[vn(k.price,k.currency),"/",k.interval]}),k.description&&n.jsx("div",{style:m.planDescription,children:k.description}),A?n.jsx("span",{style:m.currentBadge,children:"Current Plan"}):n.jsx("button",{onClick:()=>C(k.resource,k.interval),style:m.changePlanButton,disabled:U,children:k.price>u.pricePerPeriod?"Upgrade":"Downgrade"})]},k.resource)})})]}),n.jsxs("div",{className:"cedros-subscription-actions",style:m.actions,children:[i&&u.paymentMethod==="stripe"&&n.jsx("button",{onClick:N,style:m.portalButton,disabled:U,children:"Manage Billing"}),u.status==="active"&&!u.cancelAtPeriodEnd&&n.jsx("button",{onClick:()=>S(!1),style:m.cancelSubscriptionButton,disabled:U,children:"Cancel Subscription"})]})]})]})}function ff(){const{x402Manager:e,walletManager:t}=oe.useCedrosContext(),{publicKey:r,signTransaction:s}=Hn.useWallet(),[o,a]=w.useState({status:"idle",error:null,transactionId:null}),[i,c]=w.useState(null),[l,d]=w.useState(null),m=w.useCallback(async x=>{try{a(y=>({...y,status:"loading"}));const p=await e.requestQuote({resource:x});if(!e.validateRequirement(p))throw new Error("Invalid refund requirement received from server");return c(p),a(y=>({...y,status:"idle"})),p}catch(p){const y=oe.formatError(p,"Failed to fetch refund requirement");throw a({status:"error",error:y,transactionId:null}),p}},[e]),u=w.useCallback(async(x,p)=>{if(!r||!s)throw new Error("Wallet not connected");try{a({status:"loading",error:null,transactionId:null});const y=await e.requestQuote({resource:x,couponCode:p});if(!e.validateRequirement(y))throw new Error("Invalid refund requirement received");c(y);const j=await t.buildTransaction({requirement:y,payerPublicKey:r}),b=await t.signTransaction({transaction:j,signTransaction:s}),v=t.buildPaymentPayload({requirement:y,signedTx:b,payerPublicKey:r}),_=await e.submitPayment({resource:x,payload:v,couponCode:p,metadata:void 0,resourceType:"refund"});return _.settlement&&d(_.settlement),a({status:"success",error:null,transactionId:_.transactionId||b.signature}),_}catch(y){const j=oe.formatError(y,"Refund payment failed");throw a({status:"error",error:j,transactionId:null}),y}},[r,s,e,t]),f=w.useCallback(async x=>{if(!r||!s)throw new Error("Wallet not connected");try{a({status:"loading",error:null,transactionId:null});const p=await e.requestQuote({resource:x});if(!e.validateRequirement(p))throw new Error("Invalid refund requirement received");c(p);const{transaction:y}=await e.buildGaslessTransaction({resourceId:x,userWallet:r.toString(),feePayer:p.extra.feePayer}),j=t.deserializeTransaction(y),b=await t.partiallySignTransaction({transaction:j,signTransaction:s}),v=await e.submitGaslessTransaction({resource:x,partialTx:b,couponCode:void 0,metadata:void 0,resourceType:"refund",requirement:p});return v.settlement&&d(v.settlement),a({status:"success",error:null,transactionId:v.transactionId||"gasless-refund-tx"}),v}catch(p){const y=oe.formatError(p,"Gasless refund payment failed");throw a({status:"error",error:y,transactionId:null}),p}},[r,s,e,t]),h=w.useCallback(()=>{a({status:"idle",error:null,transactionId:null}),c(null),d(null)},[]);return{state:o,requirement:i,settlement:l,fetchRefundQuote:m,processRefund:u,processGaslessRefund:f,reset:h}}function hf(){if(typeof window>"u")return{passed:!0,severity:"info",message:"HTTPS check skipped (SSR environment)"};const e=window.location.protocol==="https:",t=window.location.hostname==="localhost"||window.location.hostname==="127.0.0.1";return e||t?{passed:!0,severity:"info",message:"HTTPS enforced"}:{passed:!1,severity:"error",message:"Page not served over HTTPS",recommendation:"Enable HTTPS for all payment pages. Stripe.js requires HTTPS in production."}}function gf(){return typeof document>"u"?{passed:!0,severity:"info",message:"CSP check skipped (SSR environment)"}:document.querySelector('meta[http-equiv="Content-Security-Policy"]')?{passed:!0,severity:"info",message:"Content Security Policy detected"}:{passed:!1,severity:"warning",message:"No Content Security Policy detected",recommendation:"Configure CSP headers to protect against XSS and CDN compromise. Use generateCSP() helper from @cedros/pay-react."}}function xf(){return process.env.NODE_ENV==="development"||typeof window<"u"&&window.location.hostname==="localhost"?{passed:!0,severity:"info",message:"Running in development mode (some security checks relaxed)"}:{passed:!0,severity:"info",message:"Running in production mode"}}function yf(){return{passed:!0,severity:"info",message:"Stripe.js loaded via @stripe/stripe-js package (CSP recommended, not SRI)",recommendation:"Ensure CSP script-src includes https://js.stripe.com"}}function bf(){return typeof window>"u"?{passed:!0,severity:"info",message:"Mixed content check skipped (SSR environment)"}:window.location.protocol==="https:"?{passed:!0,severity:"info",message:"Mixed content protection active (HTTPS page)"}:{passed:!0,severity:"info",message:"Mixed content check skipped (HTTP page)"}}function vf(){const e=[hf(),gf(),xf(),yf(),bf()],t=e.some(a=>a.severity==="error"&&!a.passed),r=e.some(a=>a.severity==="warning"&&!a.passed);let s,o;return t?(s="vulnerable",o="Security issues detected. Review errors and apply recommendations."):r?(s="warnings",o="Minor security warnings detected. Consider applying recommendations."):(s="secure",o="All security checks passed."),{checks:e,overallStatus:s,summary:o}}function wf(e){process.env.NODE_ENV!=="production"&&(console.group("🔒 Cedros Pay Security Report"),console.log(`Status: ${e.overallStatus.toUpperCase()}`),console.log(`Summary: ${e.summary}`),console.log(""),e.checks.forEach(t=>{const r=t.passed?"✅":t.severity==="error"?"❌":"⚠️";console.log(`${r} ${t.message}`),t.recommendation&&console.log(` → ${t.recommendation}`)}),console.groupEnd())}const _f={CSP:"Use generateCSP() from @cedros/pay-react to generate Content Security Policy headers",HTTPS:"Always serve payment pages over HTTPS in production",PACKAGE_UPDATES:"Keep @stripe/stripe-js and @cedros/pay-react updated for security patches",AUDIT:"Run npm audit regularly to check for known vulnerabilities",MONITORING:"Monitor Stripe security advisories and apply updates promptly",NO_SRI:"Do NOT use SRI hashes for Stripe.js - use CSP instead"},la=w.createContext(null);function De(){const e=w.useContext(la);if(!e)throw new Error("useCedrosShop must be used within CedrosShopProvider");return e}function da(){return w.useContext(la)}function jf({config:e,children:t}){return n.jsx(la.Provider,{value:{config:e},children:t})}function At(e){return new Promise(t=>setTimeout(t,e))}const yl=[{id:"cat_all",slug:"all",name:"All Products",description:"Everything in the catalog."},{id:"cat_apparel",slug:"apparel",name:"Apparel",description:"Soft goods and daily wear."},{id:"cat_accessories",slug:"accessories",name:"Accessories",description:"Carry, attach, decorate."}],ts=[{id:"p_tee",slug:"cedros-tee",title:"Cedros Tee",description:"A heavyweight tee with a clean silhouette.",images:[{url:"https://picsum.photos/seed/cedros-tee/900/900",alt:"Cedros Tee"},{url:"https://picsum.photos/seed/cedros-tee-2/900/900",alt:"Cedros Tee detail"}],price:38,currency:"USD",tags:["new","cotton"],categoryIds:["cat_apparel"],compareAtPrice:48,inventoryStatus:"in_stock",variants:[{id:"v_tee_s",title:"Small / Black",options:{Size:"S",Color:"Black"}},{id:"v_tee_m",title:"Medium / Black",options:{Size:"M",Color:"Black"}},{id:"v_tee_l",title:"Large / Black",options:{Size:"L",Color:"Black"}}],shippingProfile:"physical"},{id:"p_crewneck",slug:"cedros-crewneck",title:"Cedros Crewneck",description:"Midweight fleece with a relaxed fit and embroidered mark.",images:[{url:"https://picsum.photos/seed/cedros-crewneck/900/900",alt:"Cedros Crewneck"}],price:64,currency:"USD",tags:["fleece","core"],categoryIds:["cat_apparel"],inventoryStatus:"in_stock",compareAtPrice:78,variants:[{id:"v_crew_s",title:"Small / Heather",options:{Size:"S",Color:"Heather"}},{id:"v_crew_m",title:"Medium / Heather",options:{Size:"M",Color:"Heather"}},{id:"v_crew_l",title:"Large / Heather",options:{Size:"L",Color:"Heather"}}],shippingProfile:"physical"},{id:"p_hoodie",slug:"cedros-hoodie",title:"Cedros Hoodie",description:"Pullover hoodie with soft interior and structured hood.",images:[{url:"https://picsum.photos/seed/cedros-hoodie/900/900",alt:"Cedros Hoodie"},{url:"https://picsum.photos/seed/cedros-hoodie-2/900/900",alt:"Cedros Hoodie detail"}],price:74,currency:"USD",tags:["fleece","new"],categoryIds:["cat_apparel"],inventoryStatus:"low",variants:[{id:"v_hoodie_s",title:"Small / Black",options:{Size:"S",Color:"Black"}},{id:"v_hoodie_m",title:"Medium / Black",options:{Size:"M",Color:"Black"}},{id:"v_hoodie_l",title:"Large / Black",options:{Size:"L",Color:"Black"}}],shippingProfile:"physical"},{id:"p_cap",slug:"cedros-cap",title:"Cedros Cap",description:"Unstructured cap with adjustable strap and curved brim.",images:[{url:"https://picsum.photos/seed/cedros-cap/900/900",alt:"Cedros Cap"}],price:28,currency:"USD",tags:["core"],categoryIds:["cat_apparel"],inventoryStatus:"in_stock",shippingProfile:"physical"},{id:"p_socks",slug:"cedros-socks",title:"Cedros Socks",description:"Rib-knit socks designed for everyday comfort.",images:[{url:"https://picsum.photos/seed/cedros-socks/900/900",alt:"Cedros Socks"}],price:14,currency:"USD",tags:["cotton"],categoryIds:["cat_apparel"],inventoryStatus:"in_stock",shippingProfile:"physical"},{id:"p_tote",slug:"cedros-tote",title:"Cedros Tote",description:"Heavy canvas tote with reinforced handles.",images:[{url:"https://picsum.photos/seed/cedros-tote/900/900",alt:"Cedros Tote"}],price:32,currency:"USD",tags:["gift","canvas"],categoryIds:["cat_accessories"],inventoryStatus:"in_stock",shippingProfile:"physical"},{id:"p_stickers",slug:"cedros-sticker-pack",title:"Sticker Pack",description:"Five durable vinyl stickers for laptops and water bottles.",images:[{url:"https://picsum.photos/seed/cedros-stickers/900/900",alt:"Sticker Pack"}],price:8,currency:"USD",tags:["gift"],categoryIds:["cat_accessories"],inventoryStatus:"in_stock",shippingProfile:"physical"},{id:"p_keychain",slug:"cedros-keychain",title:"Enamel Keychain",description:"Polished enamel keychain with a subtle mark.",images:[{url:"https://picsum.photos/seed/cedros-keychain/900/900",alt:"Enamel Keychain"}],price:12,currency:"USD",tags:["gift"],categoryIds:["cat_accessories"],inventoryStatus:"low",shippingProfile:"physical"},{id:"p_lanyard",slug:"cedros-lanyard",title:"Woven Lanyard",description:"Soft woven lanyard with swivel clasp.",images:[{url:"https://picsum.photos/seed/cedros-lanyard/900/900",alt:"Woven Lanyard"}],price:10,currency:"USD",tags:["core"],categoryIds:["cat_accessories"],inventoryStatus:"in_stock",shippingProfile:"physical"},{id:"p_notebook",slug:"cedros-notebook",title:"Dot Grid Notebook",description:"Lay-flat notebook for sketches, notes, and plans.",images:[{url:"https://picsum.photos/seed/cedros-notebook/900/900",alt:"Dot Grid Notebook"}],price:18,currency:"USD",tags:["gift"],categoryIds:["cat_accessories"],inventoryStatus:"in_stock",shippingProfile:"physical"},{id:"p_waterbottle",slug:"cedros-water-bottle",title:"Insulated Bottle",description:"Vacuum-insulated bottle that keeps drinks cold for hours.",images:[{url:"https://picsum.photos/seed/cedros-bottle/900/900",alt:"Insulated Bottle"}],price:36,currency:"USD",tags:["gift","new"],categoryIds:["cat_accessories"],inventoryStatus:"backorder",shippingProfile:"physical"},{id:"p_posters",slug:"cedros-poster-set",title:"Poster Set",description:"Two prints on thick matte stock.",images:[{url:"https://picsum.photos/seed/cedros-posters/900/900",alt:"Poster Set"}],price:24,currency:"USD",tags:["gift","limited"],categoryIds:["cat_accessories"],inventoryStatus:"out_of_stock",shippingProfile:"physical"},{id:"p_pins",slug:"cedros-pin-set",title:"Pin Set",description:"Two enamel pins with rubber backings.",images:[{url:"https://picsum.photos/seed/cedros-pins/900/900",alt:"Pin Set"}],price:16,currency:"USD",tags:["gift"],categoryIds:["cat_accessories"],inventoryStatus:"in_stock",shippingProfile:"physical"},{id:"p_brandbook",slug:"cedros-brand-book",title:"Brand Book (PDF)",description:"A compact brand book: typography, color, layout, and voice.",images:[{url:"https://picsum.photos/seed/cedros-brandbook/900/900",alt:"Brand Book cover"}],price:19,currency:"USD",tags:["digital"],categoryIds:["cat_accessories"],inventoryStatus:"in_stock",shippingProfile:"digital",checkoutRequirements:{email:"optional",name:"none",phone:"none",shippingAddress:!1,billingAddress:!1},fulfillment:{type:"digital_download",notes:"This is a digital product and will be downloadable from your account after purchase."}},{id:"p_wallpaper",slug:"cedros-wallpaper-pack",title:"Wallpaper Pack",description:"A set of desktop + mobile wallpapers in multiple colorways.",images:[{url:"https://picsum.photos/seed/cedros-wallpaper/900/900",alt:"Wallpaper Pack"}],price:6,currency:"USD",tags:["digital","new"],categoryIds:["cat_accessories"],inventoryStatus:"in_stock",shippingProfile:"digital"},{id:"p_longsleeve",slug:"cedros-long-sleeve",title:"Long Sleeve Tee",description:"Soft long sleeve tee with rib cuff and relaxed drape.",images:[{url:"https://picsum.photos/seed/cedros-longsleeve/900/900",alt:"Long Sleeve Tee"}],price:44,currency:"USD",tags:["cotton"],categoryIds:["cat_apparel"],inventoryStatus:"in_stock",shippingProfile:"physical"},{id:"p_shorts",slug:"cedros-shorts",title:"Everyday Shorts",description:"Lightweight shorts with a comfortable waistband.",images:[{url:"https://picsum.photos/seed/cedros-shorts/900/900",alt:"Everyday Shorts"}],price:40,currency:"USD",tags:["new"],categoryIds:["cat_apparel"],inventoryStatus:"in_stock",shippingProfile:"physical"},{id:"p_beanie",slug:"cedros-beanie",title:"Rib Beanie",description:"Warm rib beanie with a clean folded cuff.",images:[{url:"https://picsum.photos/seed/cedros-beanie/900/900",alt:"Rib Beanie"}],price:20,currency:"USD",tags:["core"],categoryIds:["cat_apparel"],inventoryStatus:"low",shippingProfile:"physical"},{id:"p_jacket",slug:"cedros-coach-jacket",title:"Coach Jacket",description:"Lightweight jacket with snap front and subtle sheen.",images:[{url:"https://picsum.photos/seed/cedros-jacket/900/900",alt:"Coach Jacket"}],price:96,currency:"USD",tags:["limited"],categoryIds:["cat_apparel"],inventoryStatus:"backorder",shippingProfile:"physical"},{id:"p_mug",slug:"cedros-mug",title:"Cedros Mug",description:"Stoneware mug with a satin glaze.",images:[{url:"https://picsum.photos/seed/cedros-mug/900/900",alt:"Cedros Mug"}],price:22,currency:"USD",tags:["gift"],categoryIds:["cat_accessories"],inventoryStatus:"low",shippingProfile:"physical"},{id:"p_guide",slug:"cedros-field-guide",title:"Field Guide (Digital)",description:"A short digital guide to shipping delightful checkout flows.",images:[{url:"https://picsum.photos/seed/cedros-guide/900/900",alt:"Field Guide cover"}],price:12,currency:"USD",tags:["digital"],categoryIds:["cat_accessories"],inventoryStatus:"in_stock",shippingProfile:"digital"}];let co=[];const Rr={};function Sf(e,t){let r=e;if(t.category&&t.category!=="all"){const l=yl.find(d=>d.slug===t.category||d.id===t.category);l&&(r=r.filter(d=>d.categoryIds.includes(l.id)))}if(t.search){const l=t.search.toLowerCase();r=r.filter(d=>d.title.toLowerCase().includes(l)||d.description.toLowerCase().includes(l))}const s=t.filters??{},o=s.tags;if(Array.isArray(o)&&o.length>0){const l=new Set(o.map(String));r=r.filter(d=>d.tags?.some(m=>l.has(m)))}const a=typeof s.priceMin=="number"?s.priceMin:void 0,i=typeof s.priceMax=="number"?s.priceMax:void 0;return typeof a=="number"&&(r=r.filter(l=>l.price>=a)),typeof i=="number"&&(r=r.filter(l=>l.price<=i)),(typeof s.inStock=="boolean"?s.inStock:void 0)===!0&&(r=r.filter(l=>l.inventoryStatus!=="out_of_stock")),r}function kf(e,t){if(!t||t==="featured")return e;const r=[...e];return t==="price_asc"&&r.sort((s,o)=>s.price-o.price),t==="price_desc"&&r.sort((s,o)=>o.price-s.price),r}function Cf(e,t,r){const s=(t-1)*r;return{items:e.slice(s,s+r),page:t,pageSize:r,total:e.length,hasNextPage:s+r<e.length}}function Nf(e){const t=new Date().toISOString(),r=e.cart.map(o=>{const a=ts.find(i=>i.id===o.resource||i.slug===o.resource)??ts[0];return{title:a.title,qty:o.quantity,unitPrice:a.price,currency:e.options.currency,imageUrl:a.images[0]?.url}}),s=r.reduce((o,a)=>o+a.qty*a.unitPrice,0);return{id:`ord_${Math.random().toString(16).slice(2)}`,createdAt:t,status:"paid",total:s,currency:e.options.currency,items:r,receiptUrl:e.options.successUrl}}function Af(){return{async listProducts(e){await At(150);const t=e.page??1,r=e.pageSize??24,s=Sf(ts,e),o=kf(s,e.sort);return Cf(o,t,r)},async getProductBySlug(e){return await At(100),ts.find(t=>t.slug===e)??null},async listCategories(){return await At(80),yl},async getOrderHistory(){return await At(120),co},async getCart({customerId:e}){return await At(80),Rr[e]??{items:[]}},async mergeCart({customerId:e,cart:t}){await At(120);const r=Rr[e]??{items:[]},s=new Map,o=i=>{const c=`${i.productId}::${i.variantId??""}`,l=s.get(c);l?s.set(c,{...l,qty:l.qty+i.qty}):s.set(c,i)};for(const i of r.items)o(i);for(const i of t.items)o(i);const a={items:Array.from(s.values()),promoCode:t.promoCode??r.promoCode};return Rr[e]=a,a},async updateCart({customerId:e,cart:t}){await At(60),Rr[e]=t},async createCheckoutSession(e){await At(250);const t=Nf(e);if(co=[t,...co].slice(0,25),e.options.successUrl){const r=new URL(e.options.successUrl,"http://localhost");return r.searchParams.set("demoOrderId",t.id),{kind:"redirect",url:r.toString().replace("http://localhost","")}}return{kind:"custom",data:{orderId:t.id}}},async listSubscriptionTiers(){return await At(80),[{id:"tier_starter",title:"Starter",description:"For small shops getting started.",priceMonthly:19,priceAnnual:190,currency:"USD",features:["Basic analytics","Email support","1 storefront"]},{id:"tier_growth",title:"Growth",description:"For teams iterating fast.",priceMonthly:49,priceAnnual:490,currency:"USD",features:["Advanced analytics","Priority support","3 storefronts"],isPopular:!0},{id:"tier_enterprise",title:"Enterprise",description:"For high volume and custom needs.",priceMonthly:199,priceAnnual:1990,currency:"USD",features:["SLA","Dedicated success","Unlimited storefronts"]}]},async getSubscriptionStatus(){return await At(80),{isActive:!1}},async createSubscriptionCheckoutSession(e){return await At(200),e.successUrl?{kind:"redirect",url:e.successUrl}:{kind:"custom",data:e}}}}function bl(e){return e.replace(/[_-]+/g," ").trim().replace(/\b\w/g,t=>t.toUpperCase())}function Pf(e){return e?e.toUpperCase():"USD"}function Tf(e){if(e&&(e==="in_stock"||e==="low"||e==="out_of_stock"||e==="backorder"))return e}function Ef(e){if(e&&(e==="physical"||e==="digital"))return e}function If(e){const t=[];if(Array.isArray(e))for(const r of e)typeof r=="string"&&t.push(r);else if(typeof e=="string"){const r=e.trim();if(r.startsWith("["))try{const s=JSON.parse(r);if(Array.isArray(s))for(const o of s)typeof o=="string"&&t.push(o);else t.push(e)}catch{t.push(e)}else t.push(e)}return t.flatMap(r=>r.split(",")).map(r=>r.trim().toUpperCase()).filter(Boolean)}function Or(e){const t=Pf(e.fiatCurrency),r=e.images&&e.images.length?e.images:e.imageUrl?[{url:e.imageUrl,alt:e.title}]:[],s=e.effectiveFiatAmountCents??e.fiatAmountCents??0,o=e.compareAtAmountCents,a=e.metadata?.shippingCountries??e.metadata?.shipping_countries,i=If(a);return{id:e.id,slug:e.slug??e.id,title:e.title??bl(e.id),description:e.description??"",images:r,price:s/100,currency:t,tags:e.tags??[],categoryIds:e.categoryIds??[],inventoryStatus:Tf(e.inventoryStatus),inventoryQuantity:typeof e.inventoryQuantity=="number"?e.inventoryQuantity:void 0,compareAtPrice:typeof o=="number"?o/100:void 0,shippingProfile:Ef(e.shippingProfile),checkoutRequirements:e.checkoutRequirements,fulfillment:e.fulfillment,attributes:i.length?{shippingCountries:i.join(",")}:void 0}}function lo(e){if(Array.isArray(e))return{products:e};const t=e.products??e.items??[],r=e.total??e.count;return{products:t,total:r}}async function Xt(e,t,r){const s={};r&&(s["X-API-Key"]=r);const o=await fetch(`${e}${t}`,{headers:s});if(!o.ok){const a=await o.text().catch(()=>""),i=new Error(`Request failed (${o.status}): ${a}`);throw i.status=o.status,i}return o.json()}function Rf(e){return{listProducts:async l=>{const d=l.page??1,m=l.pageSize??24,u=m,f=(d-1)*m,h=new URLSearchParams;h.set("limit",String(u)),h.set("offset",String(f)),l.search&&h.set("search",l.search),l.category&&h.set("category",l.category),l.sort&&h.set("sort",l.sort),l.filters?.inStock&&h.set("in_stock","true"),l.filters?.minPrice!=null&&h.set("min_price",String(l.filters.minPrice)),l.filters?.maxPrice!=null&&h.set("max_price",String(l.filters.maxPrice));const x=l.filters?.tags,p=Array.isArray(x)?x:typeof x=="string"?[x]:[];p.length&&h.set("tags",p.join(","));const y=await Xt(e.serverUrl,`/paywall/v1/products?${h.toString()}`,e.apiKey),{products:j,total:b}=lo(y);return{items:j.map(Or),page:d,pageSize:m,total:b,hasNextPage:typeof b=="number"?f+u<b:j.length===u}},getProductBySlug:async l=>{try{const d=await Xt(e.serverUrl,`/paywall/v1/products/by-slug/${encodeURIComponent(l)}`,e.apiKey);return Or(d)}catch(d){const m=d?.status;if(m!==404&&m!==405)throw d;try{const u=await Xt(e.serverUrl,`/paywall/v1/products/${encodeURIComponent(l)}`,e.apiKey);return Or(u)}catch(u){const f=u?.status;if(f!==404&&f!==405)throw u;const h=await Xt(e.serverUrl,"/paywall/v1/products?limit=200&offset=0",e.apiKey),{products:x}=lo(h),p=x.find(y=>y.slug===l||y.id===l);return p?Or(p):null}}},listCategories:async()=>{const l=await Xt(e.serverUrl,"/paywall/v1/products?limit=500&offset=0",e.apiKey),{products:d}=lo(l),m=new Set;for(const u of d)for(const f of u.categoryIds??[])m.add(f);return Array.from(m).map(u=>({id:u,slug:u,name:bl(u)}))},getOrderHistory:async()=>[],createCheckoutSession:async l=>{throw new Error("createCheckoutSession is not implemented for paywall adapter")},getStorefrontSettings:async()=>{try{return(await Xt(e.serverUrl,"/admin/config/storefront",e.apiKey)).config??null}catch{return null}},getPaymentMethodsConfig:async()=>{try{const[l,d,m]=await Promise.allSettled([Xt(e.serverUrl,"/admin/config/stripe",e.apiKey),Xt(e.serverUrl,"/admin/config/x402",e.apiKey),Xt(e.serverUrl,"/admin/config/cedros_login",e.apiKey)]),u=l.status==="fulfilled"?!!l.value?.config?.enabled:!1,f=d.status==="fulfilled"?!!d.value?.config?.enabled:!1,h=m.status==="fulfilled"?!!m.value?.config?.enabled:!1;return{card:u,crypto:f,credits:h}}catch{return null}},getAIRelatedProducts:async l=>{const d={"Content-Type":"application/json"};e.apiKey&&(d["X-API-Key"]=e.apiKey);const m=await fetch(`${e.serverUrl}/admin/ai/related-products`,{method:"POST",headers:d,body:JSON.stringify(l)});if(!m.ok){const u=await m.text().catch(()=>"");throw new Error(`AI related products request failed (${m.status}): ${u}`)}return m.json()}}}function Of(e){throw new Error(`Unhandled cart action: ${JSON.stringify(e)}`)}function yn(e){return`${e.productId}::${e.variantId??""}`}const Mf={items:[]};function Df(e,t){switch(t.type){case"cart/hydrate":return t.state;case"cart/add":{const r=Math.max(1,Math.floor(t.qty??1)),s=yn(t.item);return e.items.find(a=>yn(a)===s)?{...e,items:e.items.map(a=>yn(a)===s?{...a,qty:a.qty+r}:a)}:{...e,items:[...e.items,{...t.item,qty:r}]}}case"cart/remove":{const r=`${t.productId}::${t.variantId??""}`;return{...e,items:e.items.filter(s=>yn(s)!==r)}}case"cart/setQty":{const r=Math.max(0,Math.floor(t.qty)),s=`${t.productId}::${t.variantId??""}`;return r===0?{...e,items:e.items.filter(o=>yn(o)!==s)}:{...e,items:e.items.map(o=>yn(o)===s?{...o,qty:r}:o)}}case"cart/clear":return{items:[],promoCode:void 0};case"cart/setPromoCode":return{...e,promoCode:t.promoCode||void 0};case"cart/updateHold":{const r=`${t.productId}::${t.variantId??""}`;return{...e,items:e.items.map(s=>yn(s)===r?{...s,holdId:t.holdId,holdExpiresAt:t.holdExpiresAt}:s)}}default:return Of(t)}}function Lf(e){return e.reduce((t,r)=>t+r.qty,0)}function $f(e){return e.reduce((t,r)=>t+r.qty*r.unitPrice,0)}function Pi(){try{return typeof window>"u"?null:window.localStorage}catch{return null}}function zf(e,t){try{const r=e.getItem(t);return r?JSON.parse(r):null}catch{return null}}function Ff(e,t,r){try{e.setItem(t,JSON.stringify(r))}catch{}}const vl=w.createContext(null);function Mt(){const e=w.useContext(vl);if(!e)throw new Error("useCart must be used within CartProvider");return e}function Bf({children:e}){const{config:t}=De(),r=t.cart?.storageKey??"cedros_shop_cart_v1",s=t.customer?.id,o=t.customer?.isSignedIn??!!s,a=t.cart?.syncDebounceMs??800,i=!!t.adapter.getCartInventoryStatus,[c,l]=w.useReducer(Df,Mf),[d,m]=w.useState(!1),u=w.useRef(!1),f=w.useRef(null);w.useEffect(()=>{const y=Pi();if(!y)return;const j=zf(y,r);j&&Array.isArray(j.items)&&l({type:"cart/hydrate",state:j}),m(!0)},[r]),w.useEffect(()=>{const y=Pi();y&&Ff(y,r,c)},[c,r]),w.useEffect(()=>{d&&(!o||!s||!t.adapter.mergeCart&&!t.adapter.getCart||u.current||(u.current=!0,(async()=>{try{const y=t.adapter.mergeCart?await t.adapter.mergeCart({customerId:s,cart:c}):await t.adapter.getCart({customerId:s});y&&Array.isArray(y.items)&&(l({type:"cart/hydrate",state:y}),f.current=JSON.stringify(y))}catch{}})()))},[t.adapter,s,d,o,c]),w.useEffect(()=>{if(!d||!o||!s||!t.adapter.updateCart||!u.current||typeof window>"u")return;const y=JSON.stringify(c);if(f.current===y)return;const j=window.setTimeout(()=>{t.adapter.updateCart({customerId:s,cart:c}).then(()=>{f.current=y}).catch(()=>{})},a);return()=>window.clearTimeout(j)},[t.adapter,s,d,o,c,a]);const h=w.useCallback((y,j)=>{const b=c.items.find(v=>v.productId===y&&v.variantId===j);if(b)return{holdId:b.holdId,expiresAt:b.holdExpiresAt}},[c.items]),x=w.useCallback((y,j,b)=>{l({type:"cart/updateHold",productId:y,variantId:j,holdExpiresAt:b})},[]),p=w.useMemo(()=>{const y=Lf(c.items),j=$f(c.items);return{items:c.items,promoCode:c.promoCode,count:y,subtotal:j,addItem:(b,v)=>l({type:"cart/add",item:b,qty:v}),removeItem:(b,v)=>l({type:"cart/remove",productId:b,variantId:v}),setQty:(b,v,_)=>l({type:"cart/setQty",productId:b,variantId:v,qty:_}),clear:()=>l({type:"cart/clear"}),setPromoCode:b=>l({type:"cart/setPromoCode",promoCode:b}),holdsSupported:i,getItemHold:h,updateItemHold:x}},[c.items,c.promoCode,i,h,x]);return n.jsx(vl.Provider,{value:p,children:e})}function Z(e,t,r){function s(c,l){if(c._zod||Object.defineProperty(c,"_zod",{value:{def:l,constr:i,traits:new Set},enumerable:!1}),c._zod.traits.has(e))return;c._zod.traits.add(e),t(c,l);const d=i.prototype,m=Object.keys(d);for(let u=0;u<m.length;u++){const f=m[u];f in c||(c[f]=d[f].bind(c))}}const o=r?.Parent??Object;class a extends o{}Object.defineProperty(a,"name",{value:e});function i(c){var l;const d=r?.Parent?new a:this;s(d,c),(l=d._zod).deferred??(l.deferred=[]);for(const m of d._zod.deferred)m();return d}return Object.defineProperty(i,"init",{value:s}),Object.defineProperty(i,Symbol.hasInstance,{value:c=>r?.Parent&&c instanceof r.Parent?!0:c?._zod?.traits?.has(e)}),Object.defineProperty(i,"name",{value:e}),i}class Un extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class wl extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}}const _l={};function _n(e){return _l}function jl(e){const t=Object.values(e).filter(s=>typeof s=="number");return Object.entries(e).filter(([s,o])=>t.indexOf(+s)===-1).map(([s,o])=>o)}function Do(e,t){return typeof t=="bigint"?t.toString():t}function ua(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function ma(e){return e==null}function pa(e){const t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function Uf(e,t){const r=(e.toString().split(".")[1]||"").length,s=t.toString();let o=(s.split(".")[1]||"").length;if(o===0&&/\d?e-\d?/.test(s)){const l=s.match(/\d?e-(\d?)/);l?.[1]&&(o=Number.parseInt(l[1]))}const a=r>o?r:o,i=Number.parseInt(e.toFixed(a).replace(".","")),c=Number.parseInt(t.toFixed(a).replace(".",""));return i%c/10**a}const Ti=Symbol("evaluating");function Ce(e,t,r){let s;Object.defineProperty(e,t,{get(){if(s!==Ti)return s===void 0&&(s=Ti,s=r()),s},set(o){Object.defineProperty(e,t,{value:o})},configurable:!0})}function An(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function un(...e){const t={};for(const r of e){const s=Object.getOwnPropertyDescriptors(r);Object.assign(t,s)}return Object.defineProperties({},t)}function Ei(e){return JSON.stringify(e)}function Wf(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}const Sl="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function ns(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const Vf=ua(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function yr(e){if(ns(e)===!1)return!1;const t=e.constructor;if(t===void 0||typeof t!="function")return!0;const r=t.prototype;return!(ns(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function kl(e){return yr(e)?{...e}:Array.isArray(e)?[...e]:e}const Hf=new Set(["string","number","symbol"]);function bs(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function mn(e,t,r){const s=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(s._zod.parent=e),s}function ue(e){const t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function qf(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const Zf={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function Gf(e,t){const r=e._zod.def,s=r.checks;if(s&&s.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");const a=un(e._zod.def,{get shape(){const i={};for(const c in t){if(!(c in r.shape))throw new Error(`Unrecognized key: "${c}"`);t[c]&&(i[c]=r.shape[c])}return An(this,"shape",i),i},checks:[]});return mn(e,a)}function Qf(e,t){const r=e._zod.def,s=r.checks;if(s&&s.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");const a=un(e._zod.def,{get shape(){const i={...e._zod.def.shape};for(const c in t){if(!(c in r.shape))throw new Error(`Unrecognized key: "${c}"`);t[c]&&delete i[c]}return An(this,"shape",i),i},checks:[]});return mn(e,a)}function Yf(e,t){if(!yr(t))throw new Error("Invalid input to extend: expected a plain object");const r=e._zod.def.checks;if(r&&r.length>0){const a=e._zod.def.shape;for(const i in t)if(Object.getOwnPropertyDescriptor(a,i)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}const o=un(e._zod.def,{get shape(){const a={...e._zod.def.shape,...t};return An(this,"shape",a),a}});return mn(e,o)}function Kf(e,t){if(!yr(t))throw new Error("Invalid input to safeExtend: expected a plain object");const r=un(e._zod.def,{get shape(){const s={...e._zod.def.shape,...t};return An(this,"shape",s),s}});return mn(e,r)}function Jf(e,t){const r=un(e._zod.def,{get shape(){const s={...e._zod.def.shape,...t._zod.def.shape};return An(this,"shape",s),s},get catchall(){return t._zod.def.catchall},checks:[]});return mn(e,r)}function Xf(e,t,r){const o=t._zod.def.checks;if(o&&o.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");const i=un(t._zod.def,{get shape(){const c=t._zod.def.shape,l={...c};if(r)for(const d in r){if(!(d in c))throw new Error(`Unrecognized key: "${d}"`);r[d]&&(l[d]=e?new e({type:"optional",innerType:c[d]}):c[d])}else for(const d in c)l[d]=e?new e({type:"optional",innerType:c[d]}):c[d];return An(this,"shape",l),l},checks:[]});return mn(t,i)}function eh(e,t,r){const s=un(t._zod.def,{get shape(){const o=t._zod.def.shape,a={...o};if(r)for(const i in r){if(!(i in a))throw new Error(`Unrecognized key: "${i}"`);r[i]&&(a[i]=new e({type:"nonoptional",innerType:o[i]}))}else for(const i in o)a[i]=new e({type:"nonoptional",innerType:o[i]});return An(this,"shape",a),a}});return mn(t,s)}function Bn(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function Cl(e,t){return t.map(r=>{var s;return(s=r).path??(s.path=[]),r.path.unshift(e),r})}function Mr(e){return typeof e=="string"?e:e?.message}function jn(e,t,r){const s={...e,path:e.path??[]};if(!e.message){const o=Mr(e.inst?._zod.def?.error?.(e))??Mr(t?.error?.(e))??Mr(r.customError?.(e))??Mr(r.localeError?.(e))??"Invalid input";s.message=o}return delete s.inst,delete s.continue,t?.reportInput||delete s.input,s}function fa(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function br(...e){const[t,r,s]=e;return typeof t=="string"?{message:t,code:"custom",input:r,inst:s}:{...t}}const Nl=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,Do,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Al=Z("$ZodError",Nl),Pl=Z("$ZodError",Nl,{Parent:Error});function th(e,t=r=>r.message){const r={},s=[];for(const o of e.issues)o.path.length>0?(r[o.path[0]]=r[o.path[0]]||[],r[o.path[0]].push(t(o))):s.push(t(o));return{formErrors:s,fieldErrors:r}}function nh(e,t=r=>r.message){const r={_errors:[]},s=o=>{for(const a of o.issues)if(a.code==="invalid_union"&&a.errors.length)a.errors.map(i=>s({issues:i}));else if(a.code==="invalid_key")s({issues:a.issues});else if(a.code==="invalid_element")s({issues:a.issues});else if(a.path.length===0)r._errors.push(t(a));else{let i=r,c=0;for(;c<a.path.length;){const l=a.path[c];c===a.path.length-1?(i[l]=i[l]||{_errors:[]},i[l]._errors.push(t(a))):i[l]=i[l]||{_errors:[]},i=i[l],c++}}};return s(e),r}const ha=e=>(t,r,s,o)=>{const a=s?Object.assign(s,{async:!1}):{async:!1},i=t._zod.run({value:r,issues:[]},a);if(i instanceof Promise)throw new Un;if(i.issues.length){const c=new(o?.Err??e)(i.issues.map(l=>jn(l,a,_n())));throw Sl(c,o?.callee),c}return i.value},ga=e=>async(t,r,s,o)=>{const a=s?Object.assign(s,{async:!0}):{async:!0};let i=t._zod.run({value:r,issues:[]},a);if(i instanceof Promise&&(i=await i),i.issues.length){const c=new(o?.Err??e)(i.issues.map(l=>jn(l,a,_n())));throw Sl(c,o?.callee),c}return i.value},vs=e=>(t,r,s)=>{const o=s?{...s,async:!1}:{async:!1},a=t._zod.run({value:r,issues:[]},o);if(a instanceof Promise)throw new Un;return a.issues.length?{success:!1,error:new(e??Al)(a.issues.map(i=>jn(i,o,_n())))}:{success:!0,data:a.value}},rh=vs(Pl),ws=e=>async(t,r,s)=>{const o=s?Object.assign(s,{async:!0}):{async:!0};let a=t._zod.run({value:r,issues:[]},o);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new e(a.issues.map(i=>jn(i,o,_n())))}:{success:!0,data:a.value}},sh=ws(Pl),oh=e=>(t,r,s)=>{const o=s?Object.assign(s,{direction:"backward"}):{direction:"backward"};return ha(e)(t,r,o)},ah=e=>(t,r,s)=>ha(e)(t,r,s),ih=e=>async(t,r,s)=>{const o=s?Object.assign(s,{direction:"backward"}):{direction:"backward"};return ga(e)(t,r,o)},ch=e=>async(t,r,s)=>ga(e)(t,r,s),lh=e=>(t,r,s)=>{const o=s?Object.assign(s,{direction:"backward"}):{direction:"backward"};return vs(e)(t,r,o)},dh=e=>(t,r,s)=>vs(e)(t,r,s),uh=e=>async(t,r,s)=>{const o=s?Object.assign(s,{direction:"backward"}):{direction:"backward"};return ws(e)(t,r,o)},mh=e=>async(t,r,s)=>ws(e)(t,r,s),ph=/^[cC][^\s-]{8,}$/,fh=/^[0-9a-z]+$/,hh=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,gh=/^[0-9a-vA-V]{20}$/,xh=/^[A-Za-z0-9]{27}$/,yh=/^[a-zA-Z0-9_-]{21}$/,bh=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,vh=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,Ii=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,wh=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,_h="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function jh(){return new RegExp(_h,"u")}const Sh=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,kh=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,Ch=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,Nh=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Ah=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Tl=/^[A-Za-z0-9_-]*$/,Ph=/^\+[1-9]\d{6,14}$/,El="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",Th=new RegExp(`^${El}$`);function Il(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function Eh(e){return new RegExp(`^${Il(e)}$`)}function Ih(e){const t=Il({precision:e.precision}),r=["Z"];e.local&&r.push(""),e.offset&&r.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const s=`${t}(?:${r.join("|")})`;return new RegExp(`^${El}T(?:${s})$`)}const Rh=e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},Oh=/^-?\d+$/,Mh=/^-?\d+(?:\.\d+)?$/,Dh=/^[^A-Z]*$/,Lh=/^[^a-z]*$/,gt=Z("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),Rl={number:"number",bigint:"bigint",object:"date"},Ol=Z("$ZodCheckLessThan",(e,t)=>{gt.init(e,t);const r=Rl[typeof t.value];e._zod.onattach.push(s=>{const o=s._zod.bag,a=(t.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<a&&(t.inclusive?o.maximum=t.value:o.exclusiveMaximum=t.value)}),e._zod.check=s=>{(t.inclusive?s.value<=t.value:s.value<t.value)||s.issues.push({origin:r,code:"too_big",maximum:typeof t.value=="object"?t.value.getTime():t.value,input:s.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Ml=Z("$ZodCheckGreaterThan",(e,t)=>{gt.init(e,t);const r=Rl[typeof t.value];e._zod.onattach.push(s=>{const o=s._zod.bag,a=(t.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>a&&(t.inclusive?o.minimum=t.value:o.exclusiveMinimum=t.value)}),e._zod.check=s=>{(t.inclusive?s.value>=t.value:s.value>t.value)||s.issues.push({origin:r,code:"too_small",minimum:typeof t.value=="object"?t.value.getTime():t.value,input:s.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),$h=Z("$ZodCheckMultipleOf",(e,t)=>{gt.init(e,t),e._zod.onattach.push(r=>{var s;(s=r._zod.bag).multipleOf??(s.multipleOf=t.value)}),e._zod.check=r=>{if(typeof r.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%t.value===BigInt(0):Uf(r.value,t.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),zh=Z("$ZodCheckNumberFormat",(e,t)=>{gt.init(e,t),t.format=t.format||"float64";const r=t.format?.includes("int"),s=r?"int":"number",[o,a]=Zf[t.format];e._zod.onattach.push(i=>{const c=i._zod.bag;c.format=t.format,c.minimum=o,c.maximum=a,r&&(c.pattern=Oh)}),e._zod.check=i=>{const c=i.value;if(r){if(!Number.isInteger(c)){i.issues.push({expected:s,format:t.format,code:"invalid_type",continue:!1,input:c,inst:e});return}if(!Number.isSafeInteger(c)){c>0?i.issues.push({input:c,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:s,inclusive:!0,continue:!t.abort}):i.issues.push({input:c,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:s,inclusive:!0,continue:!t.abort});return}}c<o&&i.issues.push({origin:"number",input:c,code:"too_small",minimum:o,inclusive:!0,inst:e,continue:!t.abort}),c>a&&i.issues.push({origin:"number",input:c,code:"too_big",maximum:a,inclusive:!0,inst:e,continue:!t.abort})}}),Fh=Z("$ZodCheckMaxLength",(e,t)=>{var r;gt.init(e,t),(r=e._zod.def).when??(r.when=s=>{const o=s.value;return!ma(o)&&o.length!==void 0}),e._zod.onattach.push(s=>{const o=s._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<o&&(s._zod.bag.maximum=t.maximum)}),e._zod.check=s=>{const o=s.value;if(o.length<=t.maximum)return;const i=fa(o);s.issues.push({origin:i,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),Bh=Z("$ZodCheckMinLength",(e,t)=>{var r;gt.init(e,t),(r=e._zod.def).when??(r.when=s=>{const o=s.value;return!ma(o)&&o.length!==void 0}),e._zod.onattach.push(s=>{const o=s._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>o&&(s._zod.bag.minimum=t.minimum)}),e._zod.check=s=>{const o=s.value;if(o.length>=t.minimum)return;const i=fa(o);s.issues.push({origin:i,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),Uh=Z("$ZodCheckLengthEquals",(e,t)=>{var r;gt.init(e,t),(r=e._zod.def).when??(r.when=s=>{const o=s.value;return!ma(o)&&o.length!==void 0}),e._zod.onattach.push(s=>{const o=s._zod.bag;o.minimum=t.length,o.maximum=t.length,o.length=t.length}),e._zod.check=s=>{const o=s.value,a=o.length;if(a===t.length)return;const i=fa(o),c=a>t.length;s.issues.push({origin:i,...c?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:s.value,inst:e,continue:!t.abort})}}),_s=Z("$ZodCheckStringFormat",(e,t)=>{var r,s;gt.init(e,t),e._zod.onattach.push(o=>{const a=o._zod.bag;a.format=t.format,t.pattern&&(a.patterns??(a.patterns=new Set),a.patterns.add(t.pattern))}),t.pattern?(r=e._zod).check??(r.check=o=>{t.pattern.lastIndex=0,!t.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:t.format,input:o.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(s=e._zod).check??(s.check=()=>{})}),Wh=Z("$ZodCheckRegex",(e,t)=>{_s.init(e,t),e._zod.check=r=>{t.pattern.lastIndex=0,!t.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Vh=Z("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Dh),_s.init(e,t)}),Hh=Z("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=Lh),_s.init(e,t)}),qh=Z("$ZodCheckIncludes",(e,t)=>{gt.init(e,t);const r=bs(t.includes),s=new RegExp(typeof t.position=="number"?`^.{${t.position}}${r}`:r);t.pattern=s,e._zod.onattach.push(o=>{const a=o._zod.bag;a.patterns??(a.patterns=new Set),a.patterns.add(s)}),e._zod.check=o=>{o.value.includes(t.includes,t.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:o.value,inst:e,continue:!t.abort})}}),Zh=Z("$ZodCheckStartsWith",(e,t)=>{gt.init(e,t);const r=new RegExp(`^${bs(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.onattach.push(s=>{const o=s._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),e._zod.check=s=>{s.value.startsWith(t.prefix)||s.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:s.value,inst:e,continue:!t.abort})}}),Gh=Z("$ZodCheckEndsWith",(e,t)=>{gt.init(e,t);const r=new RegExp(`.*${bs(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.onattach.push(s=>{const o=s._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),e._zod.check=s=>{s.value.endsWith(t.suffix)||s.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:s.value,inst:e,continue:!t.abort})}}),Qh=Z("$ZodCheckOverwrite",(e,t)=>{gt.init(e,t),e._zod.check=r=>{r.value=t.tx(r.value)}});class Yh{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}const s=t.split(`
|
|
53
|
+
- Include relevant keywords naturally for SEO`}],Wp=[{id:"gemini",label:"Google Gemini API",placeholder:"AIza..."},{id:"openai",label:"OpenAI API",placeholder:"sk-..."}],Ci={apiKeys:[{provider:"gemini",isConfigured:!1},{provider:"openai",isConfigured:!1}],taskAssignments:Oo.map(e=>({task:e.task,label:e.label,description:e.description,assignedModel:"not_set",systemPrompt:e.defaultPrompt}))};function cl({serverUrl:e,apiKey:t,authManager:r}){const[s,o]=w.useState("api-keys"),[a,i]=w.useState(Ci),[c,l]=w.useState(!0),[d,m]=w.useState(!1),[u,f]=w.useState(null),[h,x]=w.useState(!1),p=w.useRef(null),[y,j]=w.useState({gemini:"",openai:""}),[b,v]=w.useState({gemini:!1,openai:!1});w.useEffect(()=>{async function k(){try{let A;if(r?.isAuthenticated())A=await r.fetchWithAuth("/admin/config/ai");else{const P={"Content-Type":"application/json"};t&&(P["X-API-Key"]=t);const D=await fetch(`${e}/admin/config/ai`,{headers:P});if(!D.ok)throw new Error(`Failed to fetch: ${D.status}`);A=await D.json()}A.settings&&i(A.settings)}catch{i(Ci)}finally{l(!1)}}k()},[e,t,r]);const _=w.useCallback(async k=>{const A=y[k];if(A.trim()){m(!0),f(null);try{const P={provider:k,apiKey:A};if(r?.isAuthenticated())await r.fetchWithAuth("/admin/config/ai/api-key",{method:"PUT",body:JSON.stringify(P)});else{const D={"Content-Type":"application/json"};t&&(D["X-API-Key"]=t);const z=await fetch(`${e}/admin/config/ai/api-key`,{method:"PUT",headers:D,body:JSON.stringify(P)});if(!z.ok)throw new Error(`Failed to save: ${z.status}`)}i(D=>({...D,apiKeys:D.apiKeys.map(z=>z.provider===k?{...z,isConfigured:!0,maskedKey:`${A.slice(0,4)}...${A.slice(-4)}`,updatedAt:new Date().toISOString()}:z)})),j(D=>({...D,[k]:""})),x(!0),p.current&&clearTimeout(p.current),p.current=setTimeout(()=>x(!1),3e3)}catch(P){f(P instanceof Error?P.message:"Failed to save API key")}finally{m(!1)}}},[y,e,t,r]),C=w.useCallback(async k=>{if(confirm(`Are you sure you want to delete the ${k==="gemini"?"Google Gemini":"OpenAI"} API key?`)){m(!0),f(null);try{if(r?.isAuthenticated())await r.fetchWithAuth(`/admin/config/ai/api-key/${k}`,{method:"DELETE"});else{const A={"Content-Type":"application/json"};t&&(A["X-API-Key"]=t);const P=await fetch(`${e}/admin/config/ai/api-key/${k}`,{method:"DELETE",headers:A});if(!P.ok)throw new Error(`Failed to delete: ${P.status}`)}i(A=>({...A,apiKeys:A.apiKeys.map(P=>P.provider===k?{provider:k,isConfigured:!1}:P)}))}catch(A){f(A instanceof Error?A.message:"Failed to delete API key")}finally{m(!1)}}},[e,t,r]),E=w.useCallback(async(k,A)=>{m(!0),f(null);try{const P={task:k,model:A};if(r?.isAuthenticated())await r.fetchWithAuth("/admin/config/ai/assignment",{method:"PUT",body:JSON.stringify(P)});else{const D={"Content-Type":"application/json"};t&&(D["X-API-Key"]=t);const z=await fetch(`${e}/admin/config/ai/assignment`,{method:"PUT",headers:D,body:JSON.stringify(P)});if(!z.ok)throw new Error(`Failed to save: ${z.status}`)}i(D=>({...D,taskAssignments:D.taskAssignments.map(z=>z.task===k?{...z,assignedModel:A}:z)})),x(!0),p.current&&clearTimeout(p.current),p.current=setTimeout(()=>x(!1),3e3)}catch(P){f(P instanceof Error?P.message:"Failed to save assignment")}finally{m(!1)}},[e,t,r]),S=w.useCallback(k=>{if(k==="not_set")return!0;const A=ao.find(D=>D.id===k);return A?.provider?a.apiKeys.find(D=>D.provider===A.provider)?.isConfigured??!1:!0},[a.apiKeys]),N=w.useMemo(()=>ao.map(k=>{const A=S(k.id);return{value:k.id,label:A?k.label:`${k.label} (API key required)`,disabled:!A}}),[S]),U=w.useCallback(async(k,A)=>{m(!0),f(null);try{const P={task:k,systemPrompt:A};if(r?.isAuthenticated())await r.fetchWithAuth("/admin/config/ai/prompt",{method:"PUT",body:JSON.stringify(P)});else{const D={"Content-Type":"application/json"};t&&(D["X-API-Key"]=t);const z=await fetch(`${e}/admin/config/ai/prompt`,{method:"PUT",headers:D,body:JSON.stringify(P)});if(!z.ok)throw new Error(`Failed to save: ${z.status}`)}i(D=>({...D,taskAssignments:D.taskAssignments.map(z=>z.task===k?{...z,systemPrompt:A}:z)})),x(!0),p.current&&clearTimeout(p.current),p.current=setTimeout(()=>x(!1),3e3)}catch(P){f(P instanceof Error?P.message:"Failed to save prompt")}finally{m(!1)}},[e,t,r]);return w.useEffect(()=>()=>{p.current&&clearTimeout(p.current)},[]),c?n.jsx("div",{className:"cedros-admin__section",children:n.jsxs("div",{className:"cedros-admin__loading",children:[G.loading," Loading AI settings..."]})}):n.jsxs("div",{className:"cedros-admin__ai-settings",children:[n.jsxs("div",{className:"cedros-admin__page-header",children:[n.jsx("h2",{className:"cedros-admin__page-title",children:"Store AI"}),n.jsx("p",{className:"cedros-admin__page-description",children:"Configure AI providers, model assignments, and system prompts."})]}),n.jsxs("div",{className:"cedros-admin__tabs cedros-admin__tabs--line",children:[n.jsx("button",{type:"button",className:`cedros-admin__tab ${s==="api-keys"?"cedros-admin__tab--active":""}`,onClick:()=>o("api-keys"),children:"API Keys"}),n.jsx("button",{type:"button",className:`cedros-admin__tab ${s==="assignments"?"cedros-admin__tab--active":""}`,onClick:()=>o("assignments"),children:"Model Assignments"}),n.jsx("button",{type:"button",className:`cedros-admin__tab ${s==="prompts"?"cedros-admin__tab--active":""}`,onClick:()=>o("prompts"),children:"Prompts"})]}),u&&n.jsx("div",{className:"cedros-admin__error-banner",style:{marginTop:"1rem"},children:u}),h&&n.jsxs("div",{className:"cedros-admin__success-banner",style:{marginTop:"1rem"},children:[G.check," Settings saved successfully"]}),s==="api-keys"&&n.jsxs("div",{className:"cedros-admin__section",style:{marginTop:"1rem"},children:[n.jsx("div",{className:"cedros-admin__section-header",children:n.jsx("h3",{className:"cedros-admin__section-title",children:"API Keys"})}),n.jsx("p",{style:{marginBottom:"1.5rem",opacity:.7,fontSize:14},children:"Configure API keys for AI providers. Keys are stored securely and never exposed."}),n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"1.5rem"},children:Wp.map(k=>{const A=a.apiKeys.find(D=>D.provider===k.id),P=A?.isConfigured??!1;return n.jsxs("div",{className:"cedros-admin__api-key-card",style:{padding:"1rem",border:"1px solid var(--cedros-admin-border)",borderRadius:8},children:[n.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"0.75rem"},children:[n.jsxs("div",{children:[n.jsx("div",{style:{fontWeight:600},children:k.label}),P&&A?.maskedKey&&n.jsxs("div",{style:{fontSize:12,opacity:.6,marginTop:2},children:["Current key: ",A.maskedKey,A.updatedAt&&n.jsxs("span",{children:[" (updated ",new Date(A.updatedAt).toLocaleDateString(),")"]})]})]}),n.jsx("span",{className:`cedros-admin__badge ${P?"cedros-admin__badge--success":"cedros-admin__badge--muted"}`,children:P?"Configured":"Not Set"})]}),n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"0.75rem"},children:n.jsxs("div",{style:{display:"flex",gap:"0.5rem",alignItems:"center"},children:[n.jsx("input",{type:b[k.id]?"text":"password",className:"cedros-admin__input",placeholder:P?"Enter new key to replace":k.placeholder,value:y[k.id],onChange:D=>j(z=>({...z,[k.id]:D.target.value})),onBlur:()=>{y[k.id].trim()&&_(k.id)},style:{flex:1}}),n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost",onClick:()=>v(D=>({...D,[k.id]:!D[k.id]})),title:b[k.id]?"Hide key":"Show key",style:{padding:"0.5rem"},children:b[k.id]?G.eyeOff:G.eye}),P&&n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost cedros-admin__button--danger",onClick:()=>C(k.id),disabled:d,title:"Remove API key",style:{padding:"0.5rem"},children:G.trash})]})})]},k.id)})})]}),s==="assignments"&&n.jsxs("div",{className:"cedros-admin__section",style:{marginTop:"1rem"},children:[n.jsx("div",{className:"cedros-admin__section-header",children:n.jsx("h3",{className:"cedros-admin__section-title",children:"Model Assignments"})}),n.jsx("p",{style:{marginBottom:"1.5rem",opacity:.7,fontSize:14},children:"Assign AI models to specific tasks. Models require their provider's API key to be configured."}),n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"1rem"},children:a.taskAssignments.map(k=>{const A=Oo.find(D=>D.task===k.task),P=ao.find(D=>D.id===k.assignedModel);return n.jsxs("div",{style:{padding:"1rem",border:"1px solid var(--cedros-admin-border)",borderRadius:8},children:[n.jsxs("div",{style:{marginBottom:"0.75rem"},children:[n.jsx("div",{style:{fontWeight:600},children:A?.label??k.task}),n.jsx("div",{style:{fontSize:13,opacity:.7,marginTop:2},children:A?.description})]}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[n.jsx(lt,{value:k.assignedModel,onChange:D=>E(k.task,D),options:N,label:"",disabled:d,style:{flex:1,maxWidth:280}}),P&&P.provider&&n.jsx("span",{className:`cedros-admin__badge ${S(P.id)?"cedros-admin__badge--success":"cedros-admin__badge--warning"}`,children:S(P.id)?"Ready":"Missing API Key"})]})]},k.task)})})]}),s==="prompts"&&n.jsxs("div",{className:"cedros-admin__section",style:{marginTop:"1rem"},children:[n.jsx("div",{className:"cedros-admin__section-header",children:n.jsx("h3",{className:"cedros-admin__section-title",children:"System Prompts"})}),n.jsx("p",{style:{marginBottom:"1.5rem",opacity:.7,fontSize:14},children:"Configure the default system prompts for each AI task. These prompts guide the AI's behavior and responses."}),n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"1.5rem"},children:a.taskAssignments.map(k=>{const A=Oo.find(P=>P.task===k.task);return n.jsx(Vp,{task:k.task,label:A?.label??k.task,description:A?.description??"",initialPrompt:k.systemPrompt??"",onSave:U},k.task)})})]})]})}function Vp({task:e,label:t,description:r,initialPrompt:s,onSave:o}){const[a,i]=w.useState(s),[c,l]=w.useState("idle"),d=w.useRef(null),m=w.useRef(null),u=w.useRef(!0);return w.useEffect(()=>{if(u.current){u.current=!1;return}return d.current&&clearTimeout(d.current),m.current&&clearTimeout(m.current),l("pending"),d.current=setTimeout(async()=>{l("saving");try{await o(e,a),l("saved"),m.current=setTimeout(()=>l("idle"),2e3)}catch{l("error")}},1500),()=>{d.current&&clearTimeout(d.current)}},[a,e,o]),w.useEffect(()=>()=>{d.current&&clearTimeout(d.current),m.current&&clearTimeout(m.current)},[]),n.jsxs("div",{style:{padding:"1rem",border:"1px solid var(--cedros-admin-border)",borderRadius:8},children:[n.jsxs("div",{style:{marginBottom:"0.75rem",display:"flex",justifyContent:"space-between",alignItems:"flex-start"},children:[n.jsxs("div",{children:[n.jsx("div",{style:{fontWeight:600},children:t}),n.jsx("div",{style:{fontSize:13,opacity:.7,marginTop:2},children:r})]}),n.jsx(Hp,{status:c})]}),n.jsx("textarea",{className:"cedros-admin__input",value:a,onChange:f=>i(f.target.value),placeholder:"Enter system prompt...",rows:4,style:{width:"100%",resize:"vertical",fontFamily:"inherit",minHeight:100}})]})}function Hp({status:e}){return e==="idle"?null:n.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:"0.375rem",fontSize:"0.75rem",color:e==="error"?"var(--cedros-admin-error, #ef4444)":"var(--cedros-admin-text-muted, #64748b)"},children:[e==="pending"&&n.jsx("span",{style:{opacity:.7},children:"Unsaved"}),e==="saving"&&n.jsxs(n.Fragment,{children:[G.loading,n.jsx("span",{children:"Saving..."})]}),e==="saved"&&n.jsxs(n.Fragment,{children:[G.check,n.jsx("span",{style:{color:"var(--cedros-admin-success, #22c55e)"},children:"Saved"})]}),e==="error"&&n.jsx("span",{children:"Failed"})]})}const qp=Object.freeze(Object.defineProperty({__proto__:null,AISettingsSection:cl},Symbol.toStringTag,{value:"Module"}));function Dn({href:e,children:t}){return n.jsx("a",{href:e,target:"_blank",rel:"noopener noreferrer",style:{color:"inherit",textDecoration:"underline"},children:t})}const Ni=[{id:"stripe",label:"Stripe",category:"stripe",description:n.jsxs(n.Fragment,{children:["Configure your Stripe integration for card payments. Get your API keys from the"," ",n.jsx(Dn,{href:"https://dashboard.stripe.com/apikeys",children:"Stripe Dashboard"}),"."]})},{id:"crypto",label:"Crypto",category:"x402",description:n.jsxs(n.Fragment,{children:["Configure Solana wallet and token settings for crypto payments. Get a fast RPC endpoint from"," ",n.jsx(Dn,{href:"https://www.helius.dev",children:"Helius"})," or"," ",n.jsx(Dn,{href:"https://www.quicknode.com/chains/sol",children:"QuickNode"}),". Set up a payment address using"," ",n.jsx(Dn,{href:"https://phantom.app",children:"Phantom"})," or"," ",n.jsx(Dn,{href:"https://solflare.com",children:"Solflare"})," wallet."]})},{id:"credits",label:"Credits",category:"cedros_login",description:n.jsxs(n.Fragment,{children:["Configure Cedros Login integration for credits payments. See the"," ",n.jsx(Dn,{href:"https://docs.cedros.dev/credits",children:"Credits API documentation"}),"."]})}];function ll({serverUrl:e,apiKey:t,authManager:r}){const[s,o]=w.useState("stripe"),a=Ni.find(i=>i.id===s);return n.jsxs("div",{className:"cedros-admin__payment-settings",children:[n.jsxs("div",{className:"cedros-admin__page-header",children:[n.jsx("h2",{className:"cedros-admin__page-title",children:"Payment Options"}),n.jsx("p",{className:"cedros-admin__page-description",children:"Configure payment methods including Stripe, crypto, and credits."})]}),n.jsx("div",{className:"cedros-admin__tabs cedros-admin__tabs--line",children:Ni.map(i=>n.jsx("button",{type:"button",className:`cedros-admin__tab ${s===i.id?"cedros-admin__tab--active":""}`,onClick:()=>o(i.id),children:i.label},i.id))}),n.jsx("div",{style:{marginTop:"1rem"},children:n.jsx(ol,{serverUrl:e,apiKey:t,authManager:r,category:a.category,title:`${a.label} Settings`,description:a.description,showEnabledToggle:!0},a.category)})]})}const Zp=Object.freeze(Object.defineProperty({__proto__:null,PaymentSettingsSection:ll},Symbol.toStringTag,{value:"Module"})),io={email_enabled:!1,smtp_host:"",smtp_port:587,smtp_username:"",smtp_password:"",from_email:"",from_name:"",webhook_enabled:!1,webhook_url:"",webhook_secret:"",webhook_timeout:30};function dl({serverUrl:e,apiKey:t,authManager:r}){const[s,o]=w.useState("messages"),[a,i]=w.useState(io),[c,l]=w.useState(!0),[d,m]=w.useState(!0),[u,f]=w.useState(new Set),h=w.useCallback(async()=>{try{let b;const v="/admin/config/messaging";if(r?.isAuthenticated())b=await r.fetchWithAuth(v);else{const _={"Content-Type":"application/json"};t&&(_["X-API-Key"]=t);const C=await fetch(`${e}${v}`,{headers:_});if(!C.ok)throw new Error(`Failed to fetch: ${C.status}`);b=await C.json()}i({...io,...b.config})}catch{i(io)}finally{l(!1),setTimeout(()=>m(!1),100)}},[e,t,r]);w.useEffect(()=>{h()},[h]);const x=w.useCallback(async b=>{const v="/admin/config/messaging",_={...b};u.has("smtp_password")||delete _.smtp_password,u.has("webhook_secret")||delete _.webhook_secret;const C=JSON.stringify({config:_});try{if(r?.isAuthenticated())await r.fetchWithAuth(v,{method:"PUT",body:C});else{const E={"Content-Type":"application/json"};t&&(E["X-API-Key"]=t);const S=await fetch(`${e}${v}`,{method:"PUT",headers:E,body:C});if(!S.ok)throw new Error(`Failed to save: ${S.status}`)}}catch{}},[e,t,r,u]),{status:p,error:y}=ia({data:a,onSave:x,debounceMs:1500,enabled:!d}),j=(b,v)=>{(b==="smtp_password"||b==="webhook_secret")&&f(_=>new Set(_).add(b)),i(_=>({..._,[b]:v}))};return c?n.jsxs("div",{className:"cedros-admin__messaging-settings",children:[n.jsxs("div",{className:"cedros-admin__page-header",children:[n.jsx("h2",{className:"cedros-admin__page-title",children:"Store Messages"}),n.jsx("p",{className:"cedros-admin__page-description",children:"Configure email delivery and webhook notifications."})]}),n.jsxs("div",{className:"cedros-admin__loading",style:{marginTop:"1rem"},children:[G.loading," Loading message settings..."]})]}):n.jsxs("div",{className:"cedros-admin__messaging-settings",children:[n.jsxs("div",{className:"cedros-admin__page-header",children:[n.jsx("h2",{className:"cedros-admin__page-title",children:"Store Messages"}),n.jsx("p",{className:"cedros-admin__page-description",children:"Configure email delivery and webhook notifications."})]}),n.jsxs("div",{className:"cedros-admin__tabs cedros-admin__tabs--line",children:[n.jsx("button",{type:"button",className:`cedros-admin__tab ${s==="messages"?"cedros-admin__tab--active":""}`,onClick:()=>o("messages"),children:"Messages"}),n.jsx("button",{type:"button",className:`cedros-admin__tab ${s==="email"?"cedros-admin__tab--active":""}`,onClick:()=>o("email"),children:"Email"}),n.jsx("button",{type:"button",className:`cedros-admin__tab ${s==="webhooks"?"cedros-admin__tab--active":""}`,onClick:()=>o("webhooks"),children:"Webhooks"}),n.jsx("div",{style:{flex:1}}),n.jsx(Gp,{status:p,error:y})]}),n.jsxs("div",{className:"cedros-admin__tab-content",style:{marginTop:"1rem"},children:[s==="messages"&&n.jsxs("div",{className:"cedros-admin__section",children:[n.jsx("p",{style:{marginBottom:"1.5rem",fontSize:"0.875rem",opacity:.7},children:"Enable or disable notification types. Configure the delivery settings in the Email or Webhooks tab."}),n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"1rem"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:"1rem",padding:"1rem",border:"1px solid var(--cedros-admin-border, #e5e5e5)",borderRadius:"0.5rem"},children:[n.jsx(Ai,{checked:a.email_enabled,onChange:()=>j("email_enabled",!a.email_enabled)}),n.jsxs("div",{style:{flex:1},children:[n.jsx("div",{style:{fontWeight:500},children:"Email Confirmation"}),n.jsx("p",{style:{margin:"0.25rem 0 0",fontSize:"0.8125rem",opacity:.6},children:"Send order confirmation emails to customers after successful purchase."}),n.jsx("p",{style:{margin:"0.5rem 0 0",fontSize:"0.75rem",opacity:.5},children:"Requires Email configuration"})]})]}),n.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:"1rem",padding:"1rem",border:"1px solid var(--cedros-admin-border, #e5e5e5)",borderRadius:"0.5rem"},children:[n.jsx(Ai,{checked:a.webhook_enabled,onChange:()=>j("webhook_enabled",!a.webhook_enabled)}),n.jsxs("div",{style:{flex:1},children:[n.jsx("div",{style:{fontWeight:500},children:"Admin Purchase Notification"}),n.jsx("p",{style:{margin:"0.25rem 0 0",fontSize:"0.8125rem",opacity:.6},children:"Send webhook notifications to your server when a purchase is completed."}),n.jsx("p",{style:{margin:"0.5rem 0 0",fontSize:"0.75rem",opacity:.5},children:"Requires Webhook configuration"})]})]})]})]}),s==="email"&&n.jsxs("div",{className:"cedros-admin__section",children:[n.jsx("p",{style:{marginBottom:"1.5rem",fontSize:"0.875rem",opacity:.7},children:"Configure your email provider for sending customer notifications."}),!a.email_enabled&&n.jsx("div",{style:{padding:"1rem",marginBottom:"1.5rem",background:"var(--cedros-admin-bg-accent, #fef3c7)",borderRadius:"0.5rem",border:"1px solid var(--cedros-admin-warning, #f59e0b)",fontSize:"0.875rem"},children:"Email notifications are disabled. Enable them in the Messages tab."}),n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"1rem",opacity:a.email_enabled?1:.5},children:[n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"SMTP Host"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:a.smtp_host,onChange:b=>j("smtp_host",b.target.value),placeholder:"smtp.example.com",disabled:!a.email_enabled})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"SMTP Port"}),n.jsx("input",{type:"number",className:"cedros-admin__input",value:a.smtp_port,onChange:b=>j("smtp_port",parseInt(b.target.value)||587),placeholder:"587",disabled:!a.email_enabled,style:{maxWidth:120}})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"SMTP Username"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:a.smtp_username,onChange:b=>j("smtp_username",b.target.value),placeholder:"username or API key",disabled:!a.email_enabled})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"SMTP Password"}),n.jsx("input",{type:"password",className:"cedros-admin__input",value:u.has("smtp_password")?a.smtp_password:"",onChange:b=>j("smtp_password",b.target.value),placeholder:a.smtp_password?"••••••••":"Enter password",disabled:!a.email_enabled})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"From Email"}),n.jsx("input",{type:"email",className:"cedros-admin__input",value:a.from_email,onChange:b=>j("from_email",b.target.value),placeholder:"orders@yourstore.com",disabled:!a.email_enabled})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"From Name"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:a.from_name,onChange:b=>j("from_name",b.target.value),placeholder:"Your Store",disabled:!a.email_enabled})]})]})]}),s==="webhooks"&&n.jsxs("div",{className:"cedros-admin__section",children:[n.jsx("p",{style:{marginBottom:"1.5rem",fontSize:"0.875rem",opacity:.7},children:"Configure webhook endpoint for receiving purchase notifications."}),!a.webhook_enabled&&n.jsx("div",{style:{padding:"1rem",marginBottom:"1.5rem",background:"var(--cedros-admin-bg-accent, #fef3c7)",borderRadius:"0.5rem",border:"1px solid var(--cedros-admin-warning, #f59e0b)",fontSize:"0.875rem"},children:"Webhook notifications are disabled. Enable them in the Messages tab."}),n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"1rem",opacity:a.webhook_enabled?1:.5},children:[n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Webhook URL"}),n.jsx("input",{type:"url",className:"cedros-admin__input",value:a.webhook_url,onChange:b=>j("webhook_url",b.target.value),placeholder:"https://api.yoursite.com/webhooks/orders",disabled:!a.webhook_enabled})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Webhook Secret"}),n.jsx("input",{type:"password",className:"cedros-admin__input",value:u.has("webhook_secret")?a.webhook_secret:"",onChange:b=>j("webhook_secret",b.target.value),placeholder:a.webhook_secret?"••••••••":"Enter secret for HMAC-SHA256",disabled:!a.webhook_enabled}),n.jsx("p",{style:{margin:"0.25rem 0 0",fontSize:"0.75rem",opacity:.6},children:"Used for HMAC-SHA256 signature verification"})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Timeout (seconds)"}),n.jsx("input",{type:"number",className:"cedros-admin__input",value:a.webhook_timeout,onChange:b=>j("webhook_timeout",parseInt(b.target.value)||30),placeholder:"30",disabled:!a.webhook_enabled,style:{maxWidth:120}})]})]})]})]})]})}function Gp({status:e,error:t}){return e==="idle"?null:n.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:"0.375rem",fontSize:"0.8125rem",color:e==="error"?"var(--cedros-admin-error, #ef4444)":"var(--cedros-admin-text-muted, #64748b)"},children:[e==="pending"&&n.jsx("span",{style:{opacity:.7},children:"Unsaved changes"}),e==="saving"&&n.jsxs(n.Fragment,{children:[G.loading,n.jsx("span",{children:"Saving..."})]}),e==="saved"&&n.jsxs(n.Fragment,{children:[G.check,n.jsx("span",{style:{color:"var(--cedros-admin-success, #22c55e)"},children:"Saved"})]}),e==="error"&&n.jsxs("span",{children:["Save failed",t?`: ${t}`:""]})]})}function Ai({checked:e,onChange:t,disabled:r=!1}){return n.jsx("button",{type:"button",role:"switch","aria-checked":e,disabled:r,onClick:t,style:{position:"relative",width:44,height:24,borderRadius:12,border:"none",backgroundColor:e?"var(--cedros-admin-primary, #171717)":"var(--cedros-admin-border, #d4d4d4)",cursor:r?"not-allowed":"pointer",transition:"background-color 0.2s",flexShrink:0,opacity:r?.5:1},children:n.jsx("span",{style:{position:"absolute",top:2,left:e?22:2,width:20,height:20,borderRadius:"50%",backgroundColor:"white",boxShadow:"0 1px 3px rgba(0,0,0,0.2)",transition:"left 0.2s"}})})}const Qp=Object.freeze(Object.defineProperty({__proto__:null,MessagingSection:dl},Symbol.toStringTag,{value:"Module"}));function Mo(e){return!e||typeof e!="string"?[]:e.split(",").map(t=>t.trim()).filter(Boolean)}function ul({serverUrl:e,apiKey:t,pageSize:r=20,authManager:s}){const[o,a]=w.useState([]),[i,c]=w.useState(!0),[l,d]=w.useState(!1),[m,u]=w.useState(null),[f,h]=w.useState(!1),[x,p]=w.useState(""),[y,j]=w.useState("all"),[b,v]=w.useState(null),[_,C]=w.useState({question:"",answer:"",keywordsCsv:"",active:!0,useInChat:!0,displayOnPage:!0}),E=w.useCallback(async()=>{c(!0);try{let M;const R=`/admin/faqs?limit=${r}`;if(s?.isAuthenticated())M=await s.fetchWithAuth(R);else{const W={"Content-Type":"application/json"};t&&(W["X-API-Key"]=t);const T=await fetch(`${e}${R}`,{headers:W});if(!T.ok)throw new Error(`Failed to fetch FAQs: ${T.status}`);M=await T.json()}a(M.faqs||[])}catch{a([{id:"faq_1",question:"What is your return policy?",answer:"We accept returns within 30 days of purchase. Items must be unused and in original packaging.",keywords:["returns","refund","policy"],active:!0,useInChat:!0,displayOnPage:!0,createdAt:"2026-01-15T10:00:00Z"},{id:"faq_2",question:"How long does shipping take?",answer:"Standard shipping takes 5-7 business days. Express shipping is available for 2-3 day delivery.",keywords:["shipping","delivery","time"],active:!0,useInChat:!0,displayOnPage:!0,createdAt:"2026-01-16T10:00:00Z"},{id:"faq_3",question:"Do you ship internationally?",answer:"Yes, we ship to most countries. International shipping typically takes 10-14 business days.",keywords:["international","shipping","global"],active:!1,useInChat:!0,displayOnPage:!1,createdAt:"2026-01-17T10:00:00Z"}])}finally{c(!1)}},[e,t,r,s]);w.useEffect(()=>{E()},[E]);const S=async M=>{if(M.preventDefault(),!(!_.question.trim()||!_.answer.trim())){h(!0);try{const R=_.keywordsCsv.split(",").map(T=>T.trim().toLowerCase()).filter(Boolean),W={question:_.question.trim(),answer:_.answer.trim(),keywords:R,active:_.active,useInChat:_.useInChat,displayOnPage:_.displayOnPage};if(m){const T=`/admin/faqs/${m.id}`;if(s?.isAuthenticated())await s.fetchWithAuth(T,{method:"PUT",body:JSON.stringify(W)});else{const V={"Content-Type":"application/json"};t&&(V["X-API-Key"]=t);const ee=await fetch(`${e}${T}`,{method:"PUT",headers:V,body:JSON.stringify(W)});if(!ee.ok)throw new Error(`Failed to update FAQ: ${ee.status}`)}}else if(s?.isAuthenticated())await s.fetchWithAuth("/admin/faqs",{method:"POST",body:JSON.stringify(W)});else{const T={"Content-Type":"application/json"};t&&(T["X-API-Key"]=t);const V=await fetch(`${e}/admin/faqs`,{method:"POST",headers:T,body:JSON.stringify(W)});if(!V.ok)throw new Error(`Failed to create FAQ: ${V.status}`)}k(),E()}catch{a(m?R=>R.map(W=>W.id===m.id?{...W,question:_.question.trim(),answer:_.answer.trim(),keywords:Mo(_.keywordsCsv).map(T=>T.toLowerCase()),active:_.active,useInChat:_.useInChat,displayOnPage:_.displayOnPage,updatedAt:new Date().toISOString()}:W):R=>[...R,{id:`faq_${Date.now()}`,question:_.question.trim(),answer:_.answer.trim(),keywords:Mo(_.keywordsCsv).map(W=>W.toLowerCase()),active:_.active,useInChat:_.useInChat,displayOnPage:_.displayOnPage,createdAt:new Date().toISOString()}]),k()}finally{h(!1)}}},N=async M=>{try{const R=`/admin/faqs/${M}`;if(s?.isAuthenticated())await s.fetchWithAuth(R,{method:"DELETE"});else{const W={"Content-Type":"application/json"};t&&(W["X-API-Key"]=t);const T=await fetch(`${e}${R}`,{method:"DELETE",headers:W});if(!T.ok)throw new Error(`Failed to delete FAQ: ${T.status}`)}E()}catch{a(R=>R.filter(W=>W.id!==M))}v(null)},U=async M=>{try{const R=`/admin/faqs/${M.id}`,W={...M,active:!M.active};if(s?.isAuthenticated())await s.fetchWithAuth(R,{method:"PUT",body:JSON.stringify(W)});else{const T={"Content-Type":"application/json"};t&&(T["X-API-Key"]=t);const V=await fetch(`${e}${R}`,{method:"PUT",headers:T,body:JSON.stringify(W)});if(!V.ok)throw new Error(`Failed to update FAQ: ${V.status}`)}E()}catch{a(R=>R.map(W=>W.id===M.id?{...W,active:!W.active}:W))}},k=()=>{C({question:"",answer:"",keywordsCsv:"",active:!0,useInChat:!0,displayOnPage:!0}),u(null),d(!1)},A=M=>{C({question:M.question,answer:M.answer,keywordsCsv:M.keywords.join(", "),active:M.active,useInChat:M.useInChat??!0,displayOnPage:M.displayOnPage??!0}),u(M),d(!0)},P=o.length,D=o.filter(M=>M.active).length,z=o.filter(M=>M.active&&M.useInChat).length,L=o.filter(M=>M.active&&M.displayOnPage).length,O=w.useMemo(()=>o.filter(M=>{if(y==="active"&&!M.active||y==="inactive"&&M.active)return!1;if(x){const R=x.toLowerCase();return M.question.toLowerCase().includes(R)||M.answer.toLowerCase().includes(R)||M.keywords.some(W=>W.includes(R))}return!0}),[o,y,x]);return n.jsxs("div",{className:"cedros-admin__faqs",children:[n.jsx(Gn,{stats:[{label:"Total FAQs",value:P},{label:"Active",value:D,variant:"success"},{label:"In Chat",value:z},{label:"On Page",value:L}]}),n.jsxs("div",{className:"cedros-admin__section",children:[n.jsxs("div",{className:"cedros-admin__section-header",children:[n.jsxs("div",{className:"cedros-admin__section-header-left",children:[n.jsx("h3",{className:"cedros-admin__section-title",children:"Knowledge Base"}),n.jsx("p",{className:"cedros-admin__section-subtitle",children:"Manage FAQs for the AI chat assistant and public FAQ page."})]}),n.jsx("div",{className:"cedros-admin__section-header-right",children:n.jsxs("button",{className:"cedros-admin__btn cedros-admin__btn--primary",onClick:()=>{k(),d(!0)},children:[G.plus," Add FAQ"]})})]}),n.jsxs("div",{className:"cedros-admin__filters",style:{display:"flex",gap:"1rem",marginBottom:"1rem"},children:[n.jsx("input",{type:"text",placeholder:"Search FAQs...",value:x,onChange:M=>p(M.target.value),className:"cedros-admin__input",style:{flex:1,maxWidth:300}}),n.jsxs("select",{value:y,onChange:M=>j(M.target.value),className:"cedros-admin__select",children:[n.jsx("option",{value:"all",children:"All Status"}),n.jsx("option",{value:"active",children:"Active Only"}),n.jsx("option",{value:"inactive",children:"Inactive Only"})]})]}),l&&n.jsx("div",{className:"cedros-admin__form-container",style:{marginBottom:"1.5rem"},children:n.jsxs("form",{onSubmit:S,className:"cedros-admin__form",children:[n.jsxs("div",{className:"cedros-admin__form-header",children:[n.jsx("h4",{children:m?"Edit FAQ":"Add New FAQ"}),n.jsx("button",{type:"button",className:"cedros-admin__btn--icon",onClick:k,children:G.close})]}),n.jsxs("div",{className:"cedros-admin__form-group",children:[n.jsx("label",{className:"cedros-admin__label",children:"Question *"}),n.jsx("input",{type:"text",value:_.question,onChange:M=>C(R=>({...R,question:M.target.value})),className:"cedros-admin__input",placeholder:"What is your return policy?",required:!0})]}),n.jsxs("div",{className:"cedros-admin__form-group",children:[n.jsx("label",{className:"cedros-admin__label",children:"Answer *"}),n.jsx("textarea",{value:_.answer,onChange:M=>C(R=>({...R,answer:M.target.value})),className:"cedros-admin__textarea",placeholder:"We accept returns within 30 days...",rows:4,required:!0}),n.jsx("span",{className:"cedros-admin__hint",children:"Supports markdown formatting."})]}),n.jsxs("div",{className:"cedros-admin__form-group",children:[n.jsx("label",{className:"cedros-admin__label",children:"Keywords"}),n.jsx("input",{type:"text",value:_.keywordsCsv,onChange:M=>C(R=>({...R,keywordsCsv:M.target.value})),className:"cedros-admin__input",placeholder:"returns, refund, policy"}),n.jsx("span",{className:"cedros-admin__hint",children:"Comma-separated keywords to help AI find this FAQ."})]}),n.jsxs("div",{className:"cedros-admin__form-group",children:[n.jsxs("label",{className:"cedros-admin__checkbox-label",children:[n.jsx("input",{type:"checkbox",checked:_.active,onChange:M=>C(R=>({...R,active:M.target.checked}))}),n.jsx("span",{children:"Active"})]}),n.jsx("span",{className:"cedros-admin__hint",children:"Inactive FAQs won't appear anywhere."})]}),n.jsxs("div",{className:"cedros-admin__form-group",children:[n.jsx("label",{className:"cedros-admin__label",children:"Visibility"}),n.jsxs("div",{className:"cedros-admin__checkbox-group",children:[n.jsxs("label",{className:"cedros-admin__checkbox-label",children:[n.jsx("input",{type:"checkbox",checked:_.useInChat,onChange:M=>C(R=>({...R,useInChat:M.target.checked}))}),n.jsx("span",{children:"Use in AI Chat"})]}),n.jsxs("label",{className:"cedros-admin__checkbox-label",children:[n.jsx("input",{type:"checkbox",checked:_.displayOnPage,onChange:M=>C(R=>({...R,displayOnPage:M.target.checked}))}),n.jsx("span",{children:"Display on FAQ Page"})]})]}),n.jsx("span",{className:"cedros-admin__hint",children:"Choose where this FAQ should appear."})]}),n.jsxs("div",{className:"cedros-admin__form-actions",children:[n.jsx("button",{type:"button",className:"cedros-admin__btn",onClick:k,children:"Cancel"}),n.jsx("button",{type:"submit",className:"cedros-admin__btn cedros-admin__btn--primary",disabled:f||!_.question.trim()||!_.answer.trim(),children:f?G.loading:m?"Update FAQ":"Create FAQ"})]})]})}),i?n.jsxs("div",{className:"cedros-admin__loading",children:[G.loading,n.jsx("span",{children:"Loading FAQs..."})]}):O.length===0?n.jsx("div",{className:"cedros-admin__empty",children:n.jsx("p",{children:x||y!=="all"?"No FAQs match your filters.":"No FAQs yet. Add one to get started."})}):n.jsx("div",{className:"cedros-admin__faq-list",children:O.map(M=>n.jsxs("div",{className:`cedros-admin__faq-item ${M.active?"":"cedros-admin__faq-item--inactive"}`,children:[n.jsxs("div",{className:"cedros-admin__faq-content",children:[n.jsxs("div",{className:"cedros-admin__faq-question",children:[n.jsx("span",{className:`cedros-admin__status-dot ${M.active?"cedros-admin__status-dot--active":"cedros-admin__status-dot--inactive"}`}),M.question]}),n.jsx("div",{className:"cedros-admin__faq-answer",children:M.answer}),n.jsxs("div",{className:"cedros-admin__faq-meta",children:[M.keywords.length>0&&n.jsx("div",{className:"cedros-admin__faq-keywords",children:M.keywords.map(R=>n.jsx("span",{className:"cedros-admin__tag",children:R},R))}),n.jsxs("div",{className:"cedros-admin__faq-visibility",children:[M.useInChat&&n.jsxs("span",{className:"cedros-admin__badge cedros-admin__badge--chat",title:"Used in AI Chat",children:[G.chat," Chat"]}),M.displayOnPage&&n.jsxs("span",{className:"cedros-admin__badge cedros-admin__badge--page",title:"Displayed on FAQ Page",children:[G.globe," Page"]})]})]})]}),n.jsxs("div",{className:"cedros-admin__faq-actions",children:[n.jsx("button",{className:"cedros-admin__btn--icon",onClick:()=>U(M),title:M.active?"Deactivate":"Activate",children:M.active?G.eyeOff:G.eye}),n.jsx("button",{className:"cedros-admin__btn--icon",onClick:()=>A(M),title:"Edit",children:G.edit}),n.jsx("button",{className:"cedros-admin__btn--icon cedros-admin__btn--danger",onClick:()=>v(M.id),title:"Delete",children:G.trash})]}),b===M.id&&n.jsx("div",{className:"cedros-admin__confirm-overlay",children:n.jsxs("div",{className:"cedros-admin__confirm-dialog",children:[n.jsx("p",{children:"Delete this FAQ?"}),n.jsxs("div",{className:"cedros-admin__confirm-actions",children:[n.jsx("button",{className:"cedros-admin__btn",onClick:()=>v(null),children:"Cancel"}),n.jsx("button",{className:"cedros-admin__btn cedros-admin__btn--danger",onClick:()=>N(M.id),children:"Delete"})]})]})})]},M.id))})]})]})}const Yp=Object.freeze(Object.defineProperty({__proto__:null,FAQSection:ul},Symbol.toStringTag,{value:"Module"}));class Kp{serverUrl;walletSigner=null;jwtToken=null;isAdmin=!1;constructor(t){this.serverUrl=t}getAuthMethod(){return this.walletSigner?.publicKey&&this.walletSigner.signMessage?"wallet":this.jwtToken&&this.isAdmin?"cedros-login":"none"}isAuthenticated(){return this.getAuthMethod()!=="none"}setWalletSigner(t){this.walletSigner=t,oe.getLogger().debug("[AdminAuthManager] Wallet signer updated:",!!t?.publicKey)}setCedrosLoginAuth(t,r){this.jwtToken=t,this.isAdmin=r,oe.getLogger().debug("[AdminAuthManager] Cedros-login auth updated:",{hasToken:!!t,isAdmin:r})}async createAuthHeaders(t){const r=this.getAuthMethod();if(r==="wallet")return this.createWalletAuthHeaders(t);if(r==="cedros-login")return this.createJwtAuthHeaders();throw new Error("No admin authentication configured. Connect a wallet or sign in as admin.")}async createWalletAuthHeaders(t){if(!this.walletSigner?.publicKey||!this.walletSigner.signMessage)throw new Error("Wallet not connected or does not support message signing");const r=await this.fetchNonce(t),s=new TextEncoder().encode(r.nonce_id),o=await this.walletSigner.signMessage(s),a=oe.bs58.encode(this.walletSigner.publicKey.toBytes()),i=oe.bs58.encode(o);return{"X-Signer":a,"X-Message":r.nonce_id,"X-Signature":i}}createJwtAuthHeaders(){if(!this.jwtToken)throw new Error("No JWT token available");return{Authorization:`Bearer ${this.jwtToken}`}}async fetchNonce(t){const r=`${this.serverUrl}/paywall/v1/nonce`;oe.getLogger().debug("[AdminAuthManager] Fetching nonce for purpose:",t);const s=await oe.fetchWithTimeout(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({purpose:t})});if(!s.ok){const o=await s.text();throw new Error(`Failed to fetch nonce: ${s.status} ${o}`)}return await s.json()}async fetchWithAuth(t,r={}){if(this.getAuthMethod()==="none")throw new Error("No admin authentication configured");const o=this.getPurposeFromPath(t,r.method||"GET"),a=await this.createAuthHeaders(o),i={"Content-Type":"application/json",...r.headers||{},...a},c=await oe.fetchWithTimeout(`${this.serverUrl}${t}`,{...r,headers:i});if(!c.ok){const l=await c.text();throw new Error(`Admin API error ${c.status}: ${l}`)}return await c.json()}getPurposeFromPath(t,r){const o={"/admin/stats":{GET:"admin_stats"},"/admin/products":{GET:"admin_products_list",POST:"admin_products_create"},"/admin/transactions":{GET:"admin_transactions_list"},"/admin/coupons":{GET:"admin_coupons_list",POST:"admin_coupons_create"},"/admin/refunds":{GET:"admin_refunds_list"},"/admin/config":{GET:"admin_config_list"}}[t];if(o?.[r])return o[r];if(t.startsWith("/admin/products/")){if(r==="PUT")return"admin_products_update";if(r==="DELETE")return"admin_products_delete"}if(t.startsWith("/admin/coupons/")){if(r==="PUT")return"admin_coupons_update";if(r==="DELETE")return"admin_coupons_delete"}if(t.startsWith("/admin/refunds/")&&t.includes("/process"))return"admin_refunds_process";if(t.startsWith("/admin/config/")){if(r==="GET")return"admin_config_get";if(r==="PUT")return"admin_config_update";if(r==="PATCH")return"admin_config_patch"}return`admin_${r.toLowerCase()}`}}function Jp({serverUrl:e,cedrosLoginToken:t,isAdmin:r=!1}){const s=Hn.useWallet(),o=w.useMemo(()=>new Kp(e),[e]);w.useEffect(()=>{s.publicKey&&s.signMessage?o.setWalletSigner({publicKey:s.publicKey,signMessage:s.signMessage}):o.setWalletSigner(null)},[o,s.publicKey,s.signMessage]),w.useEffect(()=>{o.setCedrosLoginAuth(t??null,r)},[o,t,r]);const a=o.getAuthMethod(),i=o.isAuthenticated(),c=!!(s.publicKey&&s.signMessage),l=!!(t&&r),d=w.useMemo(()=>{if(!s.publicKey)return null;const u=s.publicKey.toBase58();return`${u.slice(0,4)}...${u.slice(-4)}`},[s.publicKey]),m=w.useCallback((u,f)=>o.fetchWithAuth(u,f),[o]);return{authMethod:a,isAuthenticated:i,walletConnected:c,walletAddress:d,cedrosLoginAvailable:l,authManager:o,fetchWithAuth:m}}const ml=[{label:"Menu",sections:[{id:"transactions",label:"Transactions",icon:G.transactions},{id:"products",label:"Products",icon:G.products},{id:"subscriptions",label:"Subscriptions",icon:G.calendarRepeat},{id:"coupons",label:"Coupons",icon:G.coupons},{id:"refunds",label:"Refunds",icon:G.refunds}]},{label:"Configuration",collapsible:!0,sections:[{id:"storefront",label:"Storefront",icon:G.storefront},{id:"ai-settings",label:"Store AI",icon:G.brain},{id:"faqs",label:"Knowledge Base",icon:G.faq},{id:"payment-settings",label:"Payment Options",icon:G.creditCard},{id:"messaging",label:"Store Messages",icon:G.mail},{id:"settings",label:"Store Server",icon:G.server}]}],Xp=ml.flatMap(e=>e.sections);function ef(){const[e,t]=w.useState(()=>typeof window>"u"?"light":window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light");return w.useEffect(()=>{const r=window.matchMedia("(prefers-color-scheme: dark)"),s=o=>t(o.matches?"dark":"light");return r.addEventListener("change",s),()=>r.removeEventListener("change",s)},[]),e}function tf(e,t,r){return e!=="system"?e:t||r}function nf({serverUrl:e,apiKey:t,title:r="Cedros Pay",sections:s=["transactions","products","subscriptions","coupons","refunds","storefront","ai-settings","faqs","payment-settings","messaging","settings"],defaultSection:o="transactions",refreshInterval:a=3e4,pageSize:i=20,onSectionChange:c,className:l="",cedrosLoginToken:d,isAdmin:m=!1,theme:u="system"}){const[f,h]=w.useState(o),[x,p]=w.useState(!0),[y,j]=w.useState(new Set),b=w.useCallback(A=>{j(P=>{const D=new Set(P);return D.has(A)?D.delete(A):D.add(A),D})},[]),v=oe.useCedrosThemeOptional(),_=ef(),E=tf(u,v?.mode??null,_)==="dark"?"cedros-admin--dark":"",{authManager:S}=Jp({serverUrl:e,cedrosLoginToken:d,isAdmin:m}),N=w.useCallback(A=>{h(A),c?.(A)},[c]),k=Xp.filter(A=>s.includes(A.id)).find(A=>A.id===f);return w.useEffect(()=>{const A=setTimeout(()=>p(!1),500);return()=>clearTimeout(A)},[]),x?n.jsxs("div",{className:`cedros-admin cedros-admin--loading ${E} ${l}`,children:[G.loading,n.jsx("span",{className:"cedros-admin__loading-text",children:"Loading dashboard..."})]}):n.jsxs("div",{className:`cedros-admin ${E} ${l}`,children:[n.jsxs("aside",{className:"cedros-admin__sidebar",children:[n.jsx("div",{className:"cedros-admin__sidebar-header",children:n.jsxs("div",{className:"cedros-admin__logo",children:[G.wallet,n.jsx("span",{className:"cedros-admin__logo-text",children:r})]})}),n.jsx("nav",{className:"cedros-admin__nav",children:ml.map(A=>{const P=A.sections.filter(z=>s.includes(z.id));if(P.length===0)return null;const D=A.collapsible&&y.has(A.label);return n.jsxs("div",{className:"cedros-admin__nav-group",children:[A.collapsible?n.jsxs("button",{type:"button",className:"cedros-admin__nav-label cedros-admin__nav-label--collapsible",onClick:()=>b(A.label),"aria-expanded":!D,children:[A.label,n.jsx("span",{className:`cedros-admin__nav-label-icon ${D?"":"cedros-admin__nav-label-icon--expanded"}`,children:G.chevronRight})]}):n.jsx("span",{className:"cedros-admin__nav-label",children:A.label}),!D&&P.map(z=>n.jsxs("button",{type:"button",className:`cedros-admin__nav-item ${f===z.id?"cedros-admin__nav-item--active":""}`,onClick:()=>N(z.id),"aria-current":f===z.id?"page":void 0,children:[n.jsx("span",{className:"cedros-admin__nav-icon",children:z.icon}),n.jsx("span",{className:"cedros-admin__nav-text",children:z.label})]},z.id))]},A.label)})})]}),n.jsxs("main",{className:"cedros-admin__main",children:[n.jsx("header",{className:"cedros-admin__header",children:n.jsxs("div",{className:"cedros-admin__breadcrumb",children:[n.jsx("span",{className:"cedros-admin__breadcrumb-root",children:r}),n.jsx("span",{className:"cedros-admin__breadcrumb-sep",children:G.chevronRight}),n.jsx("span",{className:"cedros-admin__breadcrumb-current",children:k?.label})]})}),n.jsxs("div",{className:"cedros-admin__content",children:[f==="products"&&n.jsx(el,{serverUrl:e,apiKey:t,pageSize:i,authManager:S}),f==="subscriptions"&&n.jsx(al,{serverUrl:e,apiKey:t,authManager:S}),f==="transactions"&&n.jsx(tl,{serverUrl:e,apiKey:t,pageSize:i,authManager:S}),f==="coupons"&&n.jsx(nl,{serverUrl:e,apiKey:t,pageSize:i,authManager:S}),f==="refunds"&&n.jsx(rl,{serverUrl:e,apiKey:t,pageSize:i,authManager:S}),f==="storefront"&&n.jsx(il,{serverUrl:e,apiKey:t,authManager:S}),f==="ai-settings"&&n.jsx(cl,{serverUrl:e,apiKey:t,authManager:S}),f==="faqs"&&n.jsx(ul,{serverUrl:e,apiKey:t,pageSize:i,authManager:S}),f==="payment-settings"&&n.jsx(ll,{serverUrl:e,apiKey:t,authManager:S}),f==="messaging"&&n.jsx(dl,{serverUrl:e,apiKey:t,authManager:S}),f==="settings"&&n.jsx(ca,{serverUrl:e,apiKey:t,authManager:S})]})]})]})}const Nt=e=>w.lazy(async()=>{const s=(await e()).default;return{default:({pluginContext:a})=>{const i={serverUrl:a.serverUrl};return n.jsx(s,{...i})}}}),rf={id:"cedros-pay",name:"Cedros Pay",version:"1.0.0",sections:[{id:"transactions",label:"Transactions",icon:G.transactions,group:"Store",order:0},{id:"products",label:"Products",icon:G.products,group:"Store",order:1},{id:"subscriptions",label:"Subscriptions",icon:G.subscriptions,group:"Store",order:2},{id:"coupons",label:"Coupons",icon:G.coupons,group:"Store",order:3},{id:"refunds",label:"Refunds",icon:G.refunds,group:"Store",order:4},{id:"storefront",label:"Storefront",icon:G.storefront,group:"Configuration",order:10},{id:"ai-settings",label:"Store AI",icon:G.ai,group:"Configuration",order:11},{id:"faqs",label:"Knowledge Base",icon:G.faq,group:"Configuration",order:12},{id:"payment-settings",label:"Payment Options",icon:G.wallet,group:"Configuration",order:13},{id:"messaging",label:"Store Messages",icon:G.notifications,group:"Configuration",order:14},{id:"settings",label:"Store Server",icon:G.settings,group:"Configuration",order:15}],groups:[{id:"Store",label:"Store",order:1},{id:"Configuration",label:"Configuration",order:2,defaultCollapsed:!0}],components:{products:Nt(()=>Promise.resolve().then(()=>require("./sections-D7gSCYck.js")).then(e=>({default:e.ProductsSection}))),subscriptions:Nt(()=>Promise.resolve().then(()=>$p).then(e=>({default:e.SubscriptionsSection}))),transactions:Nt(()=>Promise.resolve().then(()=>require("./sections-D7gSCYck.js")).then(e=>({default:e.TransactionsSection}))),coupons:Nt(()=>Promise.resolve().then(()=>require("./sections-D7gSCYck.js")).then(e=>({default:e.CouponsSection}))),refunds:Nt(()=>Promise.resolve().then(()=>require("./sections-D7gSCYck.js")).then(e=>({default:e.RefundsSection}))),storefront:Nt(()=>Promise.resolve().then(()=>Up).then(e=>({default:e.StorefrontSection}))),"ai-settings":Nt(()=>Promise.resolve().then(()=>qp).then(e=>({default:e.AISettingsSection}))),faqs:Nt(()=>Promise.resolve().then(()=>Yp).then(e=>({default:e.FAQSection}))),"payment-settings":Nt(()=>Promise.resolve().then(()=>Zp).then(e=>({default:e.PaymentSettingsSection}))),messaging:Nt(()=>Promise.resolve().then(()=>Qp).then(e=>({default:e.MessagingSection}))),settings:Nt(()=>Promise.resolve().then(()=>Mp).then(e=>({default:e.SettingsSection})))},createPluginContext(e){const t=e.cedrosPay,r=e.cedrosLogin;return{serverUrl:t?.serverUrl||r?.serverUrl||"",userId:r?.user?.id,getAccessToken:()=>r?.getAccessToken?.()||t?.jwtToken||null,hasPermission:o=>this.checkPermission(o,e),orgId:e.org?.orgId,pluginData:{walletAddress:t?.walletAddress}}},checkPermission(e,t){return t.org?.permissions?t.org.permissions.includes(e):!!(t.cedrosLogin?.user||t.cedrosPay?.jwtToken||t.cedrosPay?.walletAddress)},cssNamespace:"cedros-admin"};function pl(){const{subscriptionManager:e}=oe.useCedrosContext(),[t,r]=w.useState({status:"idle",error:null,sessionId:null,subscriptionStatus:null,expiresAt:null}),s=w.useCallback(async c=>{r(d=>({...d,status:"loading",error:null}));const l=await e.processSubscription(c);return r(d=>({...d,status:l.success?"success":"error",error:l.success?null:l.error||"Subscription failed",sessionId:l.success&&l.transactionId||null})),l},[e]),o=w.useCallback(async c=>{r(l=>({...l,status:"checking",error:null}));try{const l=await e.checkSubscriptionStatus(c);return r(d=>({...d,status:l.active?"success":"idle",subscriptionStatus:l.status,expiresAt:l.expiresAt||l.currentPeriodEnd||null})),l}catch(l){const d=l instanceof Error?l.message:"Failed to check subscription status";throw r(m=>({...m,status:"error",error:d})),l}},[e]),a=w.useCallback(async(c,l,d)=>{r(m=>({...m,status:"loading",error:null}));try{const m=await e.requestSubscriptionQuote(c,l,d);return r(u=>({...u,status:"idle"})),m}catch(m){const u=m instanceof Error?m.message:"Failed to get subscription quote";throw r(f=>({...f,status:"error",error:u})),m}},[e]),i=w.useCallback(()=>{r({status:"idle",error:null,sessionId:null,subscriptionStatus:null,expiresAt:null})},[]);return{...t,processSubscription:s,checkStatus:o,requestQuote:a,reset:i}}function sf({resource:e,interval:t,intervalDays:r,trialDays:s,successUrl:o,cancelUrl:a,metadata:i,customerEmail:c,couponCode:l,label:d,disabled:m=!1,onAttempt:u,onSuccess:f,onError:h,className:x=""}){const{status:p,error:y,sessionId:j,processSubscription:b}=pl(),v=oe.useCedrosTheme(),{t:_,translations:C}=fe.useTranslation(),E=d||_("ui.subscribe"),S=v.unstyled?x:`${v.className} cedros-theme__stripe-button ${x}`.trim(),N=y&&typeof y!="string"?y?.code??null:null,k=y?typeof y=="string"?y:(O=>{if(!O||!C)return"";const M=C.errors[O];return M?M.action?`${M.message} ${M.action}`:M.message:""})(N):null,A=w.useCallback(async()=>{oe.getLogger().debug("[SubscribeButton] executeSubscription:",{resource:e,interval:t,intervalDays:r,trialDays:s,couponCode:l}),fe.emitPaymentStart("stripe",e),u&&u("stripe"),fe.emitPaymentProcessing("stripe",e);const O=await b({resource:e,interval:t,intervalDays:r,trialDays:s,customerEmail:c,metadata:i,couponCode:l,successUrl:o,cancelUrl:a});O.success&&O.transactionId?(fe.emitPaymentSuccess("stripe",O.transactionId,e),f&&f(O.transactionId)):!O.success&&O.error&&(fe.emitPaymentError("stripe",O.error,e),h&&h(O.error))},[e,t,r,s,c,i,l,o,a,b,u,f,h]),P=w.useMemo(()=>`subscribe-${e}-${t}`,[e,t]),D=w.useMemo(()=>fe.createDedupedClickHandler(P,A),[P,A]),z=p==="loading",L=m||z;return n.jsxs("div",{className:S,style:v.unstyled?{}:v.style,children:[n.jsx("button",{onClick:D,disabled:L,className:v.unstyled?x:"cedros-theme__button cedros-theme__stripe",type:"button",children:z?_("ui.processing"):E}),k&&n.jsx("div",{className:v.unstyled?"":"cedros-theme__error",children:k}),j&&n.jsx("div",{className:v.unstyled?"":"cedros-theme__success",children:_("ui.redirecting_to_checkout")})]})}function fl(){const{subscriptionManager:e,x402Manager:t,walletManager:r}=oe.useCedrosContext(),{publicKey:s,signTransaction:o}=Hn.useWallet(),[a,i]=w.useState({status:"idle",error:null,sessionId:null,subscriptionStatus:null,expiresAt:null}),[c,l]=w.useState(null),d=w.useCallback(()=>{if(!s){const x="Wallet not connected";return i(p=>({...p,status:"error",error:x})),{valid:!1,error:x}}if(!o){const x="Wallet does not support signing";return i(p=>({...p,status:"error",error:x})),{valid:!1,error:x}}return{valid:!0}},[s,o]),m=w.useCallback(async x=>{if(!s)return i(p=>({...p,status:"error",error:"Wallet not connected"})),null;i(p=>({...p,status:"checking",error:null}));try{const p=await e.checkSubscriptionStatus({resource:x,userId:s.toString()});return i(y=>({...y,status:p.active?"success":"idle",subscriptionStatus:p.status,expiresAt:p.expiresAt||p.currentPeriodEnd||null})),p}catch(p){const y=oe.formatError(p,"Failed to check subscription status");return i(j=>({...j,status:"error",error:y})),null}},[s,e]),u=w.useCallback(async(x,p,y)=>{i(j=>({...j,status:"loading",error:null}));try{const j=await e.requestSubscriptionQuote(x,p,y);return l(j),i(b=>({...b,status:"idle"})),j}catch(j){const b=oe.formatError(j,"Failed to get subscription quote");return i(v=>({...v,status:"error",error:b})),null}},[e]),f=w.useCallback(async(x,p,y)=>{const j=d();if(!j.valid)return{success:!1,error:j.error};i(b=>({...b,status:"loading",error:null}));try{const b=await e.requestSubscriptionQuote(x,p,y);l(b);const v=b.requirement;if(!t.validateRequirement(v))throw new Error("Invalid subscription quote received from server");const _=!!v.extra?.feePayer;let C;if(_){const{transaction:E,blockhash:S}=await t.buildGaslessTransaction({resourceId:x,userWallet:s.toString(),feePayer:v.extra.feePayer,couponCode:y?.couponCode}),N=r.deserializeTransaction(E),U=await r.partiallySignTransaction({transaction:N,signTransaction:o,blockhash:S});C=await t.submitGaslessTransaction({resource:x,partialTx:U,couponCode:y?.couponCode,resourceType:"regular",requirement:v})}else{const E=await r.buildTransaction({requirement:v,payerPublicKey:s}),S=await r.signTransaction({transaction:E,signTransaction:o}),N=r.buildPaymentPayload({requirement:v,signedTx:S,payerPublicKey:s});C=await t.submitPayment({resource:x,payload:N,couponCode:y?.couponCode,resourceType:"regular"})}if(C.success){const E=await e.checkSubscriptionStatus({resource:x,userId:s.toString()});i({status:"success",error:null,sessionId:C.transactionId||null,subscriptionStatus:E.status,expiresAt:E.expiresAt||E.currentPeriodEnd||null})}else i(E=>({...E,status:"error",error:C.error||"Subscription payment failed"}));return C}catch(b){const v=oe.formatError(b,"Subscription payment failed");return i(_=>({..._,status:"error",error:v})),{success:!1,error:v}}},[d,e,t,r,s,o]),h=w.useCallback(()=>{i({status:"idle",error:null,sessionId:null,subscriptionStatus:null,expiresAt:null}),l(null)},[]);return{...a,quote:c,checkStatus:m,requestQuote:u,processPayment:f,reset:h}}function of({resource:e,interval:t,intervalDays:r,couponCode:s,label:o,disabled:a=!1,onAttempt:i,onSuccess:c,onError:l,className:d="",testPageUrl:m,hideMessages:u=!1,autoCheckStatus:f=!0}){const{connected:h,connecting:x,connect:p,disconnect:y,select:j,wallets:b,wallet:v,publicKey:_}=Hn.useWallet(),{status:C,error:E,subscriptionStatus:S,expiresAt:N,checkStatus:U,processPayment:k}=fl(),A=oe.useCedrosTheme(),{solanaError:P}=oe.useCedrosContext(),{t:D,translations:z}=fe.useTranslation(),L=o||D("ui.subscribe_with_crypto"),O=w.useRef(k),M=w.useRef(U);w.useEffect(()=>{O.current=k,M.current=U},[k,U]);const R=E&&typeof E!="string"?E?.code??null:null,W=P&&typeof P!="string"?P?.code??null:null,T=de=>{if(!de||!z)return"";const ke=z.errors[de];return ke?ke.action?`${ke.message} ${ke.action}`:ke.message:""},V=E?typeof E=="string"?E:T(R):null,ee=P?typeof P=="string"?P:T(W):null,B=w.useMemo(()=>b.map(de=>`${de.adapter.name}-${de.readyState}`).join(","),[b]),Y=w.useMemo(()=>b.filter(({readyState:de})=>de===wi.WalletReadyState.Installed||de===wi.WalletReadyState.Loadable),[B]);w.useEffect(()=>{f&&h&&_&&(oe.getLogger().debug("[CryptoSubscribeButton] Auto-checking subscription status"),M.current(e))},[f,h,_,e]),w.useEffect(()=>{C==="success"&&S==="active"&&(fe.emitPaymentSuccess("crypto","subscription-active",e),c&&c("subscription-active"))},[C,S,e,c]),w.useEffect(()=>{C==="error"&&E&&(fe.emitPaymentError("crypto",E,e),l&&l(E))},[C,E,e,l]);const J=typeof window<"u"&&window.top!==window.self,[ge,F]=w.useState(!1),[K,me]=w.useState(!1),[q,te]=w.useState(!1),ce=P;w.useEffect(()=>{let de=!1;return de||(async()=>{if(K&&v&&!h&&!x){oe.getLogger().debug("[CryptoSubscribeButton] Wallet detected, attempting auto-connect:",v.adapter.name),me(!1),fe.emitWalletConnect(v.adapter.name);try{await p(),de||oe.getLogger().debug("[CryptoSubscribeButton] Auto-connect successful")}catch($){if(!de){oe.getLogger().error("[CryptoSubscribeButton] Auto-connect failed:",$);const X=$ instanceof Error?$.message:"Failed to connect wallet";fe.emitWalletError(X,v.adapter.name),te(!1)}}}})(),()=>{de=!0}},[v,K,h,x,p]),w.useEffect(()=>{h&&q&&_&&v&&(fe.emitWalletConnected(v.adapter.name,_.toString()),oe.getLogger().debug("[CryptoSubscribeButton] Processing pending subscription payment"),te(!1),F(!1),fe.emitPaymentProcessing("crypto",e),O.current(e,t,{couponCode:s,intervalDays:r}))},[h,q,_,v,e,t,s,r]);const pe=w.useCallback(async()=>{if(oe.getLogger().debug("[CryptoSubscribeButton] executeSubscriptionFlow called",{connected:h,wallet:v?.adapter.name,resource:e,interval:t}),fe.emitPaymentStart("crypto",e),i&&i("crypto"),ce){oe.getLogger().error("[CryptoSubscribeButton] Solana dependencies missing:",ce),fe.emitPaymentError("crypto",ce,e),l&&l(ce);return}if(J){const de=m||window.location.href;try{if(new URL(de,window.location.origin).origin!==window.location.origin)throw oe.getLogger().error("[CryptoSubscribeButton] Blocked attempt to open external URL:",de),new Error("Cannot open external URLs from embedded context");window.open(de,"_blank","noopener,noreferrer")}catch(ke){throw oe.getLogger().error("[CryptoSubscribeButton] URL validation failed:",ke),ke}return}if(h)fe.emitPaymentProcessing("crypto",e),await k(e,t,{couponCode:s,intervalDays:r});else{te(!0);try{if(v)oe.getLogger().debug("[CryptoSubscribeButton] Wallet already selected, connecting:",v.adapter.name),fe.emitWalletConnect(v.adapter.name),await p();else{if(oe.getLogger().debug("[CryptoSubscribeButton] No wallet selected, showing selector"),Y.length===0){te(!1);const de="No wallets available";throw fe.emitWalletError(de),new Error(de)}F(!0)}}catch(de){te(!1);const ke=de instanceof Error?de.message:"Failed to connect wallet";oe.getLogger().error("[CryptoSubscribeButton] Connection error:",ke),fe.emitWalletError(ke,v?.adapter.name)}}},[h,v,e,t,s,r,J,m,Y,p,k,ce,i,l]),Oe=w.useMemo(()=>`crypto-subscribe-${e}-${t}`,[e,t]),Ge=w.useMemo(()=>fe.createDedupedClickHandler(Oe,pe,{cooldownMs:200,deduplicationWindowMs:0}),[Oe,pe]),Qe=C==="loading"||C==="checking",$e=S==="active"||S==="trialing",Ye=a||Qe||x||!!ce||$e;let Ne=L;if(Qe)Ne=D("ui.processing");else if($e&&N){const de=new Date(N).toLocaleDateString();Ne=`${D("ui.subscribed_until")} ${de}`}else $e&&(Ne=D("ui.subscribed"));const st=w.useCallback(async()=>{try{me(!1),h&&await y(),j(null),F(!0)}catch(de){oe.getLogger().error("Failed to change wallet:",de)}},[h,y,j]),Ae=w.useCallback(de=>{oe.getLogger().debug("[CryptoSubscribeButton] Wallet clicked:",de),F(!1),j(de),me(!0)},[j]),Fe=w.useCallback(async()=>{try{if(await y(),te(!1),typeof window<"u"&&window.localStorage)try{window.localStorage.removeItem("walletName")}catch(de){de instanceof Error&&de.name==="QuotaExceededError"?oe.getLogger().warn("localStorage quota exceeded when removing wallet preference"):oe.getLogger().error("Failed to clear wallet preference from localStorage:",de)}}catch(de){oe.getLogger().error("Failed to disconnect wallet:",de)}},[y]);return n.jsxs("div",{className:A.unstyled?d:`${A.className} cedros-theme__crypto-button ${d||""}`,style:A.unstyled?{}:A.style,children:[n.jsx("button",{onClick:Ge,disabled:Ye,className:A.unstyled?d:"cedros-theme__button cedros-theme__crypto",type:"button",children:Ne}),ge&&!u&&n.jsx("div",{className:"cedros-modal-overlay",style:{position:"fixed",top:0,left:0,right:0,bottom:0,backgroundColor:A.tokens.modalOverlay,display:"flex",alignItems:"center",justifyContent:"center",zIndex:9999,padding:"1rem"},onClick:()=>F(!1),children:n.jsxs("div",{className:"cedros-modal-content",style:{backgroundColor:A.tokens.modalBackground,borderRadius:"12px",padding:"2rem",maxWidth:"400px",width:"100%",boxShadow:"0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04)",border:`1px solid ${A.tokens.modalBorder}`},onClick:de=>de.stopPropagation(),children:[n.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"1.5rem"},children:[n.jsx("h3",{style:{margin:0,fontSize:"1.25rem",fontWeight:600,color:A.tokens.surfaceText},children:D("wallet.select_wallet")}),n.jsx("button",{onClick:()=>F(!1),style:fe.getModalCloseButtonStyles(A.tokens.surfaceText),"aria-label":"Close modal",type:"button",children:"×"})]}),n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"0.75rem"},children:Y.map(de=>n.jsxs("button",{onClick:()=>Ae(de.adapter.name),style:{width:"100%",padding:"1rem",backgroundColor:A.tokens.surfaceBackground,border:`1px solid ${A.tokens.surfaceBorder}`,borderRadius:"0.5rem",cursor:"pointer",fontSize:"1rem",textAlign:"left",color:A.tokens.surfaceText,display:"flex",alignItems:"center",gap:"1rem",transition:"all 0.2s ease"},onMouseEnter:ke=>{ke.currentTarget.style.backgroundColor=A.tokens.modalBackground,ke.currentTarget.style.borderColor=A.tokens.surfaceText,ke.currentTarget.style.transform="translateY(-2px)"},onMouseLeave:ke=>{ke.currentTarget.style.backgroundColor=A.tokens.surfaceBackground,ke.currentTarget.style.borderColor=A.tokens.surfaceBorder,ke.currentTarget.style.transform="translateY(0)"},type:"button",children:[n.jsx(hp.WalletIcon,{wallet:de,style:{width:"24px",height:"24px"}}),n.jsx("span",{style:{fontWeight:500},children:de.adapter.name})]},de.adapter.name))})]})}),h&&!u&&!ge&&n.jsxs("div",{style:{display:"flex",justifyContent:"space-between",marginTop:"0.5rem",fontSize:"0.75rem",color:A.tokens.surfaceText,opacity:.7},children:[n.jsx("button",{onClick:st,style:{background:"none",border:"none",padding:0,color:"inherit",textDecoration:"none",cursor:"pointer",fontSize:"inherit"},type:"button",children:D("wallet.change")}),n.jsx("button",{onClick:Fe,style:{background:"none",border:"none",padding:0,color:"inherit",textDecoration:"none",cursor:"pointer",fontSize:"inherit"},type:"button",children:D("ui.disconnect")})]}),!u&&ee&&n.jsx("div",{className:A.unstyled?"":"cedros-theme__error",children:ee}),!u&&V&&n.jsx("div",{className:A.unstyled?"":"cedros-theme__error",children:V}),!u&&$e&&n.jsx("div",{className:A.unstyled?"":"cedros-theme__success",children:D("ui.subscription_active")})]})}function hl(){const{subscriptionManager:e,creditsManager:t}=oe.useCedrosContext(),[r,s]=w.useState({status:"idle",error:null,sessionId:null,subscriptionStatus:null,expiresAt:null,creditsRequirement:null}),o=w.useCallback(async(l,d)=>{s(m=>({...m,status:"checking",error:null}));try{const m=await e.checkSubscriptionStatus({resource:l,userId:d});return s(u=>({...u,status:m.active?"success":"idle",subscriptionStatus:m.status,expiresAt:m.expiresAt||m.currentPeriodEnd||null})),m}catch(m){const u=oe.formatError(m,"Failed to check subscription status");return s(f=>({...f,status:"error",error:u})),null}},[e]),a=w.useCallback(async(l,d,m)=>{s(u=>({...u,status:"loading",error:null}));try{const u=await t.requestQuote(l,m?.couponCode);return s(f=>({...f,status:"idle",creditsRequirement:u})),u}catch(u){const f=oe.formatError(u,"Failed to get subscription quote");return s(h=>({...h,status:"error",error:f})),null}},[t]),i=w.useCallback(async(l,d,m,u)=>{if(!m){const f="Authentication required for credits payment";return s(h=>({...h,status:"error",error:f})),{success:!1,error:f}}s(f=>({...f,status:"loading",error:null}));try{const f=await t.processPayment(l,m,u?.couponCode,{interval:d,...u?.intervalDays&&{intervalDays:String(u.intervalDays)}});return f.success?s({status:"success",error:null,sessionId:f.transactionId||null,subscriptionStatus:"active",expiresAt:null,creditsRequirement:null}):s(h=>({...h,status:"error",error:f.error||"Credits subscription payment failed"})),f}catch(f){const h=oe.formatError(f,"Credits subscription payment failed");return s(x=>({...x,status:"error",error:h})),{success:!1,error:h}}},[t]),c=w.useCallback(()=>{s({status:"idle",error:null,sessionId:null,subscriptionStatus:null,expiresAt:null,creditsRequirement:null})},[]);return{...r,checkStatus:o,requestQuote:a,processPayment:i,reset:c}}function af({resource:e,interval:t,intervalDays:r,authToken:s,userId:o,couponCode:a,label:i,disabled:c=!1,onAttempt:l,onSuccess:d,onError:m,className:u="",hideMessages:f=!1,autoCheckStatus:h=!1}){const{status:x,error:p,subscriptionStatus:y,expiresAt:j,checkStatus:b,processPayment:v}=hl(),_=oe.useCedrosTheme(),{t:C,translations:E}=fe.useTranslation(),S=w.useRef(b);w.useEffect(()=>{S.current=b},[b]),w.useEffect(()=>{h&&o&&(oe.getLogger().debug("[CreditsSubscribeButton] Auto-checking subscription status",{resource:e,userId:o}),S.current(e,o))},[h,o,e]);const N=i||C("ui.subscribe_with_credits")||"Subscribe with Credits",U=p&&typeof p!="string"?p?.code??null:null,A=p?typeof p=="string"?p:(T=>{if(!T||!E)return"";const V=E.errors[T];return V?V.action?`${V.message} ${V.action}`:V.message:""})(U):null,P=w.useCallback(async()=>{if(oe.getLogger().debug("[CreditsSubscribeButton] executeSubscriptionFlow",{resource:e,interval:t,intervalDays:r,hasAuthToken:!!s}),fe.emitPaymentStart("credits",e),l&&l("credits"),!s){const V="Authentication required: please log in to subscribe with credits";oe.getLogger().error("[CreditsSubscribeButton]",V),fe.emitPaymentError("credits",V,e),m&&m(V);return}fe.emitPaymentProcessing("credits",e);const T=await v(e,t,s,{couponCode:a,intervalDays:r});T.success&&T.transactionId?(fe.emitPaymentSuccess("credits",T.transactionId,e),d&&d(T.transactionId)):!T.success&&T.error&&(fe.emitPaymentError("credits",T.error,e),m&&m(T.error))},[e,t,r,s,a,v,l,d,m]),D=w.useMemo(()=>`credits-subscribe-${e}-${t}`,[e,t]),z=w.useMemo(()=>fe.createDedupedClickHandler(D,P,{cooldownMs:200,deduplicationWindowMs:0}),[D,P]),L=x==="loading"||x==="checking",O=y==="active"||y==="trialing",M=c||L||O;let R=N;if(L)R=C("ui.processing");else if(O&&j){const T=new Date(j).toLocaleDateString();R=`${C("ui.subscribed_until")} ${T}`}else O&&(R=C("ui.subscribed"));const W=_.unstyled?u:`${_.className} cedros-theme__credits-button ${u}`.trim();return n.jsxs("div",{className:W,style:_.unstyled?{}:_.style,children:[n.jsx("button",{onClick:z,disabled:M,className:_.unstyled?u:"cedros-theme__button cedros-theme__credits",type:"button",children:R}),!f&&A&&n.jsx("div",{className:_.unstyled?"":"cedros-theme__error",children:A}),!f&&O&&n.jsx("div",{className:_.unstyled?"":"cedros-theme__success",children:C("ui.subscription_active")})]})}function gl(){const{subscriptionChangeManager:e}=oe.useCedrosContext(),[t,r]=w.useState({status:"idle",error:null,subscription:null,changePreview:null,userId:null}),s=w.useRef(t);s.current=t;const o=w.useCallback(async(u,f)=>{r(h=>({...h,status:"loading",error:null}));try{const h=await e.getDetails(u,f);return r(x=>({...x,status:"success",subscription:h,userId:f})),h}catch(h){const x=h instanceof Error?h.message:"Failed to load subscription";return r(p=>({...p,status:"error",error:x})),null}},[e]),a=w.useCallback(async(u,f,h,x)=>{r(p=>({...p,status:"loading",error:null}));try{const p={currentResource:u,newResource:f,userId:h,newInterval:x},y=await e.previewChange(p);return r(j=>({...j,status:"idle",changePreview:y})),y}catch(p){const y=p instanceof Error?p.message:"Failed to preview change";return r(j=>({...j,status:"error",error:y})),null}},[e]),i=w.useCallback(async u=>{const{subscription:f,userId:h}=s.current;if(!f||!h)return r(x=>({...x,status:"error",error:"No subscription loaded"})),null;r(x=>({...x,status:"loading",error:null}));try{const x={currentResource:f.resource,newResource:u.newResource,userId:h,newInterval:u.newInterval,prorationBehavior:u.prorationBehavior,immediate:u.immediate},p=await e.changeSubscription(x);return p.success?r(y=>({...y,status:"success",subscription:y.subscription?{...y.subscription,resource:p.newResource,interval:p.newInterval,status:p.status}:null,changePreview:null})):r(y=>({...y,status:"error",error:p.error||"Failed to change subscription"})),p}catch(x){const p=x instanceof Error?x.message:"Failed to change subscription";return r(y=>({...y,status:"error",error:p})),null}},[e]),c=w.useCallback(async u=>{const{subscription:f,userId:h}=s.current;if(!f||!h)return r(x=>({...x,status:"error",error:"No subscription loaded"})),null;r(x=>({...x,status:"loading",error:null}));try{const x={resource:f.resource,userId:h,immediate:u},p=await e.cancel(x);if(p.success){const y=u?"canceled":f.status;r(j=>({...j,status:"success",subscription:j.subscription?{...j.subscription,status:y,cancelAtPeriodEnd:!u}:null}))}else r(y=>({...y,status:"error",error:p.error||"Failed to cancel subscription"}));return p}catch(x){const p=x instanceof Error?x.message:"Failed to cancel subscription";return r(y=>({...y,status:"error",error:p})),null}},[e]),l=w.useCallback(async(u,f)=>{r(h=>({...h,status:"loading",error:null}));try{const h=await e.getBillingPortalUrl({userId:u,returnUrl:f});return window.location.href=h.url,h}catch(h){const x=h instanceof Error?h.message:"Failed to open billing portal";return r(p=>({...p,status:"error",error:x})),null}},[e]),d=w.useCallback(()=>{r(u=>({...u,changePreview:null}))},[]),m=w.useCallback(()=>{r({status:"idle",error:null,subscription:null,changePreview:null,userId:null})},[]);return{...t,loadSubscription:o,previewChange:a,changeSubscription:i,cancelSubscription:c,openBillingPortal:l,clearPreview:d,reset:m}}const cf={bg:"#fff",bgMuted:"#f9fafb",bgHighlight:"#eff6ff",text:"#111827",textMuted:"#6b7280",textFaint:"#9ca3af",border:"#e5e7eb",borderLight:"#f3f4f6",primary:"#3b82f6",error:"#ef4444",errorBg:"#fef2f2",errorBorder:"#fecaca",warningBg:"#fef3c7",warningBorder:"#fcd34d",warningText:"#92400e",buttonBg:"#f3f4f6",buttonBorder:"#d1d5db",buttonText:"#374151"},lf={bg:"#1e293b",bgMuted:"#334155",bgHighlight:"rgba(59, 130, 246, 0.15)",text:"#f1f5f9",textMuted:"#94a3b8",textFaint:"#64748b",border:"#475569",borderLight:"#334155",primary:"#3b82f6",error:"#ef4444",errorBg:"rgba(239, 68, 68, 0.15)",errorBorder:"rgba(239, 68, 68, 0.3)",warningBg:"rgba(245, 158, 11, 0.15)",warningBorder:"rgba(245, 158, 11, 0.3)",warningText:"#fbbf24",buttonBg:"#334155",buttonBorder:"#475569",buttonText:"#e2e8f0"};function df(e){const t=e?lf:cf;return{container:{padding:"24px",backgroundColor:t.bg,borderRadius:"8px",border:`1px solid ${t.border}`,fontFamily:"system-ui, -apple-system, sans-serif",color:t.text},error:{padding:"12px 16px",backgroundColor:t.errorBg,border:`1px solid ${t.errorBorder}`,borderRadius:"6px",color:t.error,marginBottom:"16px"},loading:{padding:"24px",textAlign:"center",color:t.textMuted},details:{marginBottom:"24px"},title:{margin:"0 0 16px 0",fontSize:"18px",fontWeight:600,color:t.text},detailRow:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"8px 0",borderBottom:`1px solid ${t.borderLight}`},label:{color:t.textMuted,fontSize:"14px"},value:{color:t.text,fontSize:"14px",fontWeight:500},statusBadge:{padding:"4px 8px",borderRadius:"4px",color:"#fff",fontSize:"12px",fontWeight:500,textTransform:"capitalize"},cancelNotice:{marginTop:"12px",padding:"8px 12px",backgroundColor:t.warningBg,border:`1px solid ${t.warningBorder}`,borderRadius:"6px",color:t.warningText,fontSize:"13px"},prorationPreview:{padding:"16px",backgroundColor:t.bgMuted,borderRadius:"8px",marginBottom:"24px"},previewTitle:{margin:"0 0 12px 0",fontSize:"16px",fontWeight:600,color:t.text},previewDetails:{marginBottom:"16px"},previewRow:{display:"flex",justifyContent:"space-between",padding:"6px 0",fontSize:"14px",color:t.textMuted},previewTotal:{borderTop:`1px solid ${t.border}`,marginTop:"8px",paddingTop:"12px",fontWeight:600,color:t.text},previewActions:{display:"flex",gap:"12px",justifyContent:"flex-end"},cancelButton:{padding:"8px 16px",backgroundColor:t.bg,border:`1px solid ${t.buttonBorder}`,borderRadius:"6px",color:t.buttonText,cursor:"pointer",fontSize:"14px"},confirmButton:{padding:"8px 16px",backgroundColor:t.primary,border:"none",borderRadius:"6px",color:"#fff",cursor:"pointer",fontSize:"14px",fontWeight:500},plansSection:{marginBottom:"24px"},plansTitle:{margin:"0 0 12px 0",fontSize:"16px",fontWeight:600,color:t.text},plansList:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(200px, 1fr))",gap:"16px"},planCard:{padding:"16px",backgroundColor:t.bg,border:`1px solid ${t.border}`,borderRadius:"8px",textAlign:"center"},currentPlan:{borderColor:t.primary,backgroundColor:t.bgHighlight},planName:{fontSize:"16px",fontWeight:600,color:t.text,marginBottom:"4px"},planPrice:{fontSize:"14px",color:t.textMuted,marginBottom:"8px"},planDescription:{fontSize:"12px",color:t.textFaint,marginBottom:"12px"},currentBadge:{display:"inline-block",padding:"4px 8px",backgroundColor:t.primary,color:"#fff",borderRadius:"4px",fontSize:"12px",fontWeight:500},changePlanButton:{padding:"8px 16px",backgroundColor:t.buttonBg,border:`1px solid ${t.buttonBorder}`,borderRadius:"6px",color:t.buttonText,cursor:"pointer",fontSize:"14px",width:"100%"},actions:{display:"flex",gap:"12px",justifyContent:"flex-end",paddingTop:"16px",borderTop:`1px solid ${t.border}`},portalButton:{padding:"10px 20px",backgroundColor:t.primary,border:"none",borderRadius:"6px",color:"#fff",cursor:"pointer",fontSize:"14px",fontWeight:500},cancelSubscriptionButton:{padding:"10px 20px",backgroundColor:t.bg,border:`1px solid ${t.error}`,borderRadius:"6px",color:t.error,cursor:"pointer",fontSize:"14px"}}}function vn(e,t){return new Intl.NumberFormat("en-US",{style:"currency",currency:t.toUpperCase()}).format(e/100)}function xl(e){return new Date(e).toLocaleDateString("en-US",{year:"numeric",month:"long",day:"numeric"})}function uf(e){switch(e){case"active":return"#22c55e";case"trialing":return"#3b82f6";case"past_due":return"#f59e0b";case"canceled":case"expired":return"#ef4444";default:return"#6b7280"}}function mf({preview:e,onConfirm:t,onCancel:r,isLoading:s,styles:o}){const a=e.immediateAmount<0;return n.jsxs("div",{className:"cedros-proration-preview",style:o.prorationPreview,children:[n.jsx("h4",{style:o.previewTitle,children:"Change Preview"}),n.jsxs("div",{style:o.previewDetails,children:[n.jsxs("div",{style:o.previewRow,children:[n.jsx("span",{children:"Current plan:"}),n.jsxs("span",{children:[vn(e.currentPlanPrice,e.currency),"/period"]})]}),n.jsxs("div",{style:o.previewRow,children:[n.jsx("span",{children:"New plan:"}),n.jsxs("span",{children:[vn(e.newPlanPrice,e.currency),"/period"]})]}),n.jsxs("div",{style:o.previewRow,children:[n.jsx("span",{children:"Days remaining:"}),n.jsxs("span",{children:[e.daysRemaining," days"]})]}),e.prorationDetails&&n.jsxs(n.Fragment,{children:[n.jsxs("div",{style:o.previewRow,children:[n.jsx("span",{children:"Unused credit:"}),n.jsxs("span",{children:["-",vn(e.prorationDetails.unusedCredit,e.currency)]})]}),n.jsxs("div",{style:o.previewRow,children:[n.jsx("span",{children:"New plan cost:"}),n.jsx("span",{children:vn(e.prorationDetails.newPlanCost,e.currency)})]})]}),n.jsxs("div",{style:{...o.previewRow,...o.previewTotal},children:[n.jsx("span",{children:a?"Credit to account:":"Amount due now:"}),n.jsx("span",{style:{color:a?"#22c55e":"#ef4444"},children:vn(Math.abs(e.immediateAmount),e.currency)})]}),n.jsxs("div",{style:o.previewRow,children:[n.jsx("span",{children:"Effective date:"}),n.jsx("span",{children:xl(e.effectiveDate)})]})]}),n.jsxs("div",{style:o.previewActions,children:[n.jsx("button",{onClick:r,style:o.cancelButton,disabled:s,children:"Cancel"}),n.jsx("button",{onClick:t,style:o.confirmButton,disabled:s,children:s?"Processing...":"Confirm Change"})]})]})}function pf({resource:e,userId:t,availablePlans:r=[],onSubscriptionChanged:s,onSubscriptionCanceled:o,billingPortalReturnUrl:a,showBillingPortal:i=!1,className:c,style:l}){const{mode:d}=oe.useCedrosTheme(),m=w.useMemo(()=>df(d==="dark"),[d]),{subscription:u,changePreview:f,status:h,error:x,loadSubscription:p,previewChange:y,changeSubscription:j,cancelSubscription:b,openBillingPortal:v,clearPreview:_}=gl();w.useEffect(()=>{p(e,t)},[e,t,p]);const C=w.useCallback(async(k,A)=>{await y(e,k,t,A)},[e,t,y]),E=w.useCallback(async()=>{if(!f)return;const k=r.find(P=>P.price===f.newPlanPrice&&P.currency===f.currency);(await j({newResource:k?.resource||e,newInterval:k?.interval,immediate:!0}))?.success&&k&&s?.(k.resource,k.interval)},[f,r,e,j,s]),S=w.useCallback(async k=>{(await b(k))?.success&&o?.()},[b,o]),N=w.useCallback(()=>{v(t,a)},[t,a,v]),U=h==="loading";return n.jsxs("div",{className:`cedros-subscription-panel ${c||""}`,style:{...m.container,...l},children:[x&&n.jsx("div",{className:"cedros-subscription-error",style:m.error,children:x}),U&&!u&&n.jsx("div",{className:"cedros-subscription-loading",style:m.loading,children:"Loading subscription..."}),u&&n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:"cedros-subscription-details",style:m.details,children:[n.jsx("h3",{style:m.title,children:"Current Subscription"}),n.jsxs("div",{style:m.detailRow,children:[n.jsx("span",{style:m.label,children:"Plan:"}),n.jsx("span",{style:m.value,children:u.resource})]}),n.jsxs("div",{style:m.detailRow,children:[n.jsx("span",{style:m.label,children:"Status:"}),n.jsx("span",{style:{...m.statusBadge,backgroundColor:uf(u.status)},children:u.status})]}),n.jsxs("div",{style:m.detailRow,children:[n.jsx("span",{style:m.label,children:"Price:"}),n.jsxs("span",{style:m.value,children:[vn(u.pricePerPeriod,u.currency),"/",u.interval]})]}),n.jsxs("div",{style:m.detailRow,children:[n.jsx("span",{style:m.label,children:"Current period ends:"}),n.jsx("span",{style:m.value,children:xl(u.currentPeriodEnd)})]}),u.cancelAtPeriodEnd&&n.jsx("div",{style:m.cancelNotice,children:"Subscription will cancel at end of current period"})]}),f&&n.jsx(mf,{preview:f,onConfirm:E,onCancel:_,isLoading:U,styles:m}),r.length>0&&!f&&n.jsxs("div",{className:"cedros-available-plans",style:m.plansSection,children:[n.jsx("h4",{style:m.plansTitle,children:"Available Plans"}),n.jsx("div",{style:m.plansList,children:r.map(k=>{const A=k.resource===u.resource;return n.jsxs("div",{style:{...m.planCard,...A?m.currentPlan:{}},children:[n.jsx("div",{style:m.planName,children:k.name}),n.jsxs("div",{style:m.planPrice,children:[vn(k.price,k.currency),"/",k.interval]}),k.description&&n.jsx("div",{style:m.planDescription,children:k.description}),A?n.jsx("span",{style:m.currentBadge,children:"Current Plan"}):n.jsx("button",{onClick:()=>C(k.resource,k.interval),style:m.changePlanButton,disabled:U,children:k.price>u.pricePerPeriod?"Upgrade":"Downgrade"})]},k.resource)})})]}),n.jsxs("div",{className:"cedros-subscription-actions",style:m.actions,children:[i&&u.paymentMethod==="stripe"&&n.jsx("button",{onClick:N,style:m.portalButton,disabled:U,children:"Manage Billing"}),u.status==="active"&&!u.cancelAtPeriodEnd&&n.jsx("button",{onClick:()=>S(!1),style:m.cancelSubscriptionButton,disabled:U,children:"Cancel Subscription"})]})]})]})}function ff(){const{x402Manager:e,walletManager:t}=oe.useCedrosContext(),{publicKey:r,signTransaction:s}=Hn.useWallet(),[o,a]=w.useState({status:"idle",error:null,transactionId:null}),[i,c]=w.useState(null),[l,d]=w.useState(null),m=w.useCallback(async x=>{try{a(y=>({...y,status:"loading"}));const p=await e.requestQuote({resource:x});if(!e.validateRequirement(p))throw new Error("Invalid refund requirement received from server");return c(p),a(y=>({...y,status:"idle"})),p}catch(p){const y=oe.formatError(p,"Failed to fetch refund requirement");throw a({status:"error",error:y,transactionId:null}),p}},[e]),u=w.useCallback(async(x,p)=>{if(!r||!s)throw new Error("Wallet not connected");try{a({status:"loading",error:null,transactionId:null});const y=await e.requestQuote({resource:x,couponCode:p});if(!e.validateRequirement(y))throw new Error("Invalid refund requirement received");c(y);const j=await t.buildTransaction({requirement:y,payerPublicKey:r}),b=await t.signTransaction({transaction:j,signTransaction:s}),v=t.buildPaymentPayload({requirement:y,signedTx:b,payerPublicKey:r}),_=await e.submitPayment({resource:x,payload:v,couponCode:p,metadata:void 0,resourceType:"refund"});return _.settlement&&d(_.settlement),a({status:"success",error:null,transactionId:_.transactionId||b.signature}),_}catch(y){const j=oe.formatError(y,"Refund payment failed");throw a({status:"error",error:j,transactionId:null}),y}},[r,s,e,t]),f=w.useCallback(async x=>{if(!r||!s)throw new Error("Wallet not connected");try{a({status:"loading",error:null,transactionId:null});const p=await e.requestQuote({resource:x});if(!e.validateRequirement(p))throw new Error("Invalid refund requirement received");c(p);const{transaction:y}=await e.buildGaslessTransaction({resourceId:x,userWallet:r.toString(),feePayer:p.extra.feePayer}),j=t.deserializeTransaction(y),b=await t.partiallySignTransaction({transaction:j,signTransaction:s}),v=await e.submitGaslessTransaction({resource:x,partialTx:b,couponCode:void 0,metadata:void 0,resourceType:"refund",requirement:p});return v.settlement&&d(v.settlement),a({status:"success",error:null,transactionId:v.transactionId||"gasless-refund-tx"}),v}catch(p){const y=oe.formatError(p,"Gasless refund payment failed");throw a({status:"error",error:y,transactionId:null}),p}},[r,s,e,t]),h=w.useCallback(()=>{a({status:"idle",error:null,transactionId:null}),c(null),d(null)},[]);return{state:o,requirement:i,settlement:l,fetchRefundQuote:m,processRefund:u,processGaslessRefund:f,reset:h}}function hf(){if(typeof window>"u")return{passed:!0,severity:"info",message:"HTTPS check skipped (SSR environment)"};const e=window.location.protocol==="https:",t=window.location.hostname==="localhost"||window.location.hostname==="127.0.0.1";return e||t?{passed:!0,severity:"info",message:"HTTPS enforced"}:{passed:!1,severity:"error",message:"Page not served over HTTPS",recommendation:"Enable HTTPS for all payment pages. Stripe.js requires HTTPS in production."}}function gf(){return typeof document>"u"?{passed:!0,severity:"info",message:"CSP check skipped (SSR environment)"}:document.querySelector('meta[http-equiv="Content-Security-Policy"]')?{passed:!0,severity:"info",message:"Content Security Policy detected"}:{passed:!1,severity:"warning",message:"No Content Security Policy detected",recommendation:"Configure CSP headers to protect against XSS and CDN compromise. Use generateCSP() helper from @cedros/pay-react."}}function xf(){return process.env.NODE_ENV==="development"||typeof window<"u"&&window.location.hostname==="localhost"?{passed:!0,severity:"info",message:"Running in development mode (some security checks relaxed)"}:{passed:!0,severity:"info",message:"Running in production mode"}}function yf(){return{passed:!0,severity:"info",message:"Stripe.js loaded via @stripe/stripe-js package (CSP recommended, not SRI)",recommendation:"Ensure CSP script-src includes https://js.stripe.com"}}function bf(){return typeof window>"u"?{passed:!0,severity:"info",message:"Mixed content check skipped (SSR environment)"}:window.location.protocol==="https:"?{passed:!0,severity:"info",message:"Mixed content protection active (HTTPS page)"}:{passed:!0,severity:"info",message:"Mixed content check skipped (HTTP page)"}}function vf(){const e=[hf(),gf(),xf(),yf(),bf()],t=e.some(a=>a.severity==="error"&&!a.passed),r=e.some(a=>a.severity==="warning"&&!a.passed);let s,o;return t?(s="vulnerable",o="Security issues detected. Review errors and apply recommendations."):r?(s="warnings",o="Minor security warnings detected. Consider applying recommendations."):(s="secure",o="All security checks passed."),{checks:e,overallStatus:s,summary:o}}function wf(e){process.env.NODE_ENV!=="production"&&(console.group("🔒 Cedros Pay Security Report"),console.log(`Status: ${e.overallStatus.toUpperCase()}`),console.log(`Summary: ${e.summary}`),console.log(""),e.checks.forEach(t=>{const r=t.passed?"✅":t.severity==="error"?"❌":"⚠️";console.log(`${r} ${t.message}`),t.recommendation&&console.log(` → ${t.recommendation}`)}),console.groupEnd())}const _f={CSP:"Use generateCSP() from @cedros/pay-react to generate Content Security Policy headers",HTTPS:"Always serve payment pages over HTTPS in production",PACKAGE_UPDATES:"Keep @stripe/stripe-js and @cedros/pay-react updated for security patches",AUDIT:"Run npm audit regularly to check for known vulnerabilities",MONITORING:"Monitor Stripe security advisories and apply updates promptly",NO_SRI:"Do NOT use SRI hashes for Stripe.js - use CSP instead"},la=w.createContext(null);function De(){const e=w.useContext(la);if(!e)throw new Error("useCedrosShop must be used within CedrosShopProvider");return e}function da(){return w.useContext(la)}function jf({config:e,children:t}){return n.jsx(la.Provider,{value:{config:e},children:t})}function At(e){return new Promise(t=>setTimeout(t,e))}const yl=[{id:"cat_all",slug:"all",name:"All Products",description:"Everything in the catalog."},{id:"cat_apparel",slug:"apparel",name:"Apparel",description:"Soft goods and daily wear."},{id:"cat_accessories",slug:"accessories",name:"Accessories",description:"Carry, attach, decorate."}],ts=[{id:"p_tee",slug:"cedros-tee",title:"Cedros Tee",description:"A heavyweight tee with a clean silhouette.",images:[{url:"https://picsum.photos/seed/cedros-tee/900/900",alt:"Cedros Tee"},{url:"https://picsum.photos/seed/cedros-tee-2/900/900",alt:"Cedros Tee detail"}],price:38,currency:"USD",tags:["new","cotton"],categoryIds:["cat_apparel"],compareAtPrice:48,inventoryStatus:"in_stock",variants:[{id:"v_tee_s",title:"Small / Black",options:{Size:"S",Color:"Black"}},{id:"v_tee_m",title:"Medium / Black",options:{Size:"M",Color:"Black"}},{id:"v_tee_l",title:"Large / Black",options:{Size:"L",Color:"Black"}}],shippingProfile:"physical"},{id:"p_crewneck",slug:"cedros-crewneck",title:"Cedros Crewneck",description:"Midweight fleece with a relaxed fit and embroidered mark.",images:[{url:"https://picsum.photos/seed/cedros-crewneck/900/900",alt:"Cedros Crewneck"}],price:64,currency:"USD",tags:["fleece","core"],categoryIds:["cat_apparel"],inventoryStatus:"in_stock",compareAtPrice:78,variants:[{id:"v_crew_s",title:"Small / Heather",options:{Size:"S",Color:"Heather"}},{id:"v_crew_m",title:"Medium / Heather",options:{Size:"M",Color:"Heather"}},{id:"v_crew_l",title:"Large / Heather",options:{Size:"L",Color:"Heather"}}],shippingProfile:"physical"},{id:"p_hoodie",slug:"cedros-hoodie",title:"Cedros Hoodie",description:"Pullover hoodie with soft interior and structured hood.",images:[{url:"https://picsum.photos/seed/cedros-hoodie/900/900",alt:"Cedros Hoodie"},{url:"https://picsum.photos/seed/cedros-hoodie-2/900/900",alt:"Cedros Hoodie detail"}],price:74,currency:"USD",tags:["fleece","new"],categoryIds:["cat_apparel"],inventoryStatus:"low",variants:[{id:"v_hoodie_s",title:"Small / Black",options:{Size:"S",Color:"Black"}},{id:"v_hoodie_m",title:"Medium / Black",options:{Size:"M",Color:"Black"}},{id:"v_hoodie_l",title:"Large / Black",options:{Size:"L",Color:"Black"}}],shippingProfile:"physical"},{id:"p_cap",slug:"cedros-cap",title:"Cedros Cap",description:"Unstructured cap with adjustable strap and curved brim.",images:[{url:"https://picsum.photos/seed/cedros-cap/900/900",alt:"Cedros Cap"}],price:28,currency:"USD",tags:["core"],categoryIds:["cat_apparel"],inventoryStatus:"in_stock",shippingProfile:"physical"},{id:"p_socks",slug:"cedros-socks",title:"Cedros Socks",description:"Rib-knit socks designed for everyday comfort.",images:[{url:"https://picsum.photos/seed/cedros-socks/900/900",alt:"Cedros Socks"}],price:14,currency:"USD",tags:["cotton"],categoryIds:["cat_apparel"],inventoryStatus:"in_stock",shippingProfile:"physical"},{id:"p_tote",slug:"cedros-tote",title:"Cedros Tote",description:"Heavy canvas tote with reinforced handles.",images:[{url:"https://picsum.photos/seed/cedros-tote/900/900",alt:"Cedros Tote"}],price:32,currency:"USD",tags:["gift","canvas"],categoryIds:["cat_accessories"],inventoryStatus:"in_stock",shippingProfile:"physical"},{id:"p_stickers",slug:"cedros-sticker-pack",title:"Sticker Pack",description:"Five durable vinyl stickers for laptops and water bottles.",images:[{url:"https://picsum.photos/seed/cedros-stickers/900/900",alt:"Sticker Pack"}],price:8,currency:"USD",tags:["gift"],categoryIds:["cat_accessories"],inventoryStatus:"in_stock",shippingProfile:"physical"},{id:"p_keychain",slug:"cedros-keychain",title:"Enamel Keychain",description:"Polished enamel keychain with a subtle mark.",images:[{url:"https://picsum.photos/seed/cedros-keychain/900/900",alt:"Enamel Keychain"}],price:12,currency:"USD",tags:["gift"],categoryIds:["cat_accessories"],inventoryStatus:"low",shippingProfile:"physical"},{id:"p_lanyard",slug:"cedros-lanyard",title:"Woven Lanyard",description:"Soft woven lanyard with swivel clasp.",images:[{url:"https://picsum.photos/seed/cedros-lanyard/900/900",alt:"Woven Lanyard"}],price:10,currency:"USD",tags:["core"],categoryIds:["cat_accessories"],inventoryStatus:"in_stock",shippingProfile:"physical"},{id:"p_notebook",slug:"cedros-notebook",title:"Dot Grid Notebook",description:"Lay-flat notebook for sketches, notes, and plans.",images:[{url:"https://picsum.photos/seed/cedros-notebook/900/900",alt:"Dot Grid Notebook"}],price:18,currency:"USD",tags:["gift"],categoryIds:["cat_accessories"],inventoryStatus:"in_stock",shippingProfile:"physical"},{id:"p_waterbottle",slug:"cedros-water-bottle",title:"Insulated Bottle",description:"Vacuum-insulated bottle that keeps drinks cold for hours.",images:[{url:"https://picsum.photos/seed/cedros-bottle/900/900",alt:"Insulated Bottle"}],price:36,currency:"USD",tags:["gift","new"],categoryIds:["cat_accessories"],inventoryStatus:"backorder",shippingProfile:"physical"},{id:"p_posters",slug:"cedros-poster-set",title:"Poster Set",description:"Two prints on thick matte stock.",images:[{url:"https://picsum.photos/seed/cedros-posters/900/900",alt:"Poster Set"}],price:24,currency:"USD",tags:["gift","limited"],categoryIds:["cat_accessories"],inventoryStatus:"out_of_stock",shippingProfile:"physical"},{id:"p_pins",slug:"cedros-pin-set",title:"Pin Set",description:"Two enamel pins with rubber backings.",images:[{url:"https://picsum.photos/seed/cedros-pins/900/900",alt:"Pin Set"}],price:16,currency:"USD",tags:["gift"],categoryIds:["cat_accessories"],inventoryStatus:"in_stock",shippingProfile:"physical"},{id:"p_brandbook",slug:"cedros-brand-book",title:"Brand Book (PDF)",description:"A compact brand book: typography, color, layout, and voice.",images:[{url:"https://picsum.photos/seed/cedros-brandbook/900/900",alt:"Brand Book cover"}],price:19,currency:"USD",tags:["digital"],categoryIds:["cat_accessories"],inventoryStatus:"in_stock",shippingProfile:"digital",checkoutRequirements:{email:"optional",name:"none",phone:"none",shippingAddress:!1,billingAddress:!1},fulfillment:{type:"digital_download",notes:"This is a digital product and will be downloadable from your account after purchase."}},{id:"p_wallpaper",slug:"cedros-wallpaper-pack",title:"Wallpaper Pack",description:"A set of desktop + mobile wallpapers in multiple colorways.",images:[{url:"https://picsum.photos/seed/cedros-wallpaper/900/900",alt:"Wallpaper Pack"}],price:6,currency:"USD",tags:["digital","new"],categoryIds:["cat_accessories"],inventoryStatus:"in_stock",shippingProfile:"digital"},{id:"p_longsleeve",slug:"cedros-long-sleeve",title:"Long Sleeve Tee",description:"Soft long sleeve tee with rib cuff and relaxed drape.",images:[{url:"https://picsum.photos/seed/cedros-longsleeve/900/900",alt:"Long Sleeve Tee"}],price:44,currency:"USD",tags:["cotton"],categoryIds:["cat_apparel"],inventoryStatus:"in_stock",shippingProfile:"physical"},{id:"p_shorts",slug:"cedros-shorts",title:"Everyday Shorts",description:"Lightweight shorts with a comfortable waistband.",images:[{url:"https://picsum.photos/seed/cedros-shorts/900/900",alt:"Everyday Shorts"}],price:40,currency:"USD",tags:["new"],categoryIds:["cat_apparel"],inventoryStatus:"in_stock",shippingProfile:"physical"},{id:"p_beanie",slug:"cedros-beanie",title:"Rib Beanie",description:"Warm rib beanie with a clean folded cuff.",images:[{url:"https://picsum.photos/seed/cedros-beanie/900/900",alt:"Rib Beanie"}],price:20,currency:"USD",tags:["core"],categoryIds:["cat_apparel"],inventoryStatus:"low",shippingProfile:"physical"},{id:"p_jacket",slug:"cedros-coach-jacket",title:"Coach Jacket",description:"Lightweight jacket with snap front and subtle sheen.",images:[{url:"https://picsum.photos/seed/cedros-jacket/900/900",alt:"Coach Jacket"}],price:96,currency:"USD",tags:["limited"],categoryIds:["cat_apparel"],inventoryStatus:"backorder",shippingProfile:"physical"},{id:"p_mug",slug:"cedros-mug",title:"Cedros Mug",description:"Stoneware mug with a satin glaze.",images:[{url:"https://picsum.photos/seed/cedros-mug/900/900",alt:"Cedros Mug"}],price:22,currency:"USD",tags:["gift"],categoryIds:["cat_accessories"],inventoryStatus:"low",shippingProfile:"physical"},{id:"p_guide",slug:"cedros-field-guide",title:"Field Guide (Digital)",description:"A short digital guide to shipping delightful checkout flows.",images:[{url:"https://picsum.photos/seed/cedros-guide/900/900",alt:"Field Guide cover"}],price:12,currency:"USD",tags:["digital"],categoryIds:["cat_accessories"],inventoryStatus:"in_stock",shippingProfile:"digital"}];let co=[];const Rr={};function Sf(e,t){let r=e;if(t.category&&t.category!=="all"){const l=yl.find(d=>d.slug===t.category||d.id===t.category);l&&(r=r.filter(d=>d.categoryIds.includes(l.id)))}if(t.search){const l=t.search.toLowerCase();r=r.filter(d=>d.title.toLowerCase().includes(l)||d.description.toLowerCase().includes(l))}const s=t.filters??{},o=s.tags;if(Array.isArray(o)&&o.length>0){const l=new Set(o.map(String));r=r.filter(d=>d.tags?.some(m=>l.has(m)))}const a=typeof s.priceMin=="number"?s.priceMin:void 0,i=typeof s.priceMax=="number"?s.priceMax:void 0;return typeof a=="number"&&(r=r.filter(l=>l.price>=a)),typeof i=="number"&&(r=r.filter(l=>l.price<=i)),(typeof s.inStock=="boolean"?s.inStock:void 0)===!0&&(r=r.filter(l=>l.inventoryStatus!=="out_of_stock")),r}function kf(e,t){if(!t||t==="featured")return e;const r=[...e];return t==="price_asc"&&r.sort((s,o)=>s.price-o.price),t==="price_desc"&&r.sort((s,o)=>o.price-s.price),r}function Cf(e,t,r){const s=(t-1)*r;return{items:e.slice(s,s+r),page:t,pageSize:r,total:e.length,hasNextPage:s+r<e.length}}function Nf(e){const t=new Date().toISOString(),r=e.cart.map(o=>{const a=ts.find(i=>i.id===o.resource||i.slug===o.resource)??ts[0];return{title:a.title,qty:o.quantity,unitPrice:a.price,currency:e.options.currency,imageUrl:a.images[0]?.url}}),s=r.reduce((o,a)=>o+a.qty*a.unitPrice,0);return{id:`ord_${Math.random().toString(16).slice(2)}`,createdAt:t,status:"paid",total:s,currency:e.options.currency,items:r,receiptUrl:e.options.successUrl}}function Af(){return{async listProducts(e){await At(150);const t=e.page??1,r=e.pageSize??24,s=Sf(ts,e),o=kf(s,e.sort);return Cf(o,t,r)},async getProductBySlug(e){return await At(100),ts.find(t=>t.slug===e)??null},async listCategories(){return await At(80),yl},async getOrderHistory(){return await At(120),co},async getCart({customerId:e}){return await At(80),Rr[e]??{items:[]}},async mergeCart({customerId:e,cart:t}){await At(120);const r=Rr[e]??{items:[]},s=new Map,o=i=>{const c=`${i.productId}::${i.variantId??""}`,l=s.get(c);l?s.set(c,{...l,qty:l.qty+i.qty}):s.set(c,i)};for(const i of r.items)o(i);for(const i of t.items)o(i);const a={items:Array.from(s.values()),promoCode:t.promoCode??r.promoCode};return Rr[e]=a,a},async updateCart({customerId:e,cart:t}){await At(60),Rr[e]=t},async createCheckoutSession(e){await At(250);const t=Nf(e);if(co=[t,...co].slice(0,25),e.options.successUrl){const r=new URL(e.options.successUrl,"http://localhost");return r.searchParams.set("demoOrderId",t.id),{kind:"redirect",url:r.toString().replace("http://localhost","")}}return{kind:"custom",data:{orderId:t.id}}},async listSubscriptionTiers(){return await At(80),[{id:"tier_starter",title:"Starter",description:"For small shops getting started.",priceMonthly:19,priceAnnual:190,currency:"USD",features:["Basic analytics","Email support","1 storefront"]},{id:"tier_growth",title:"Growth",description:"For teams iterating fast.",priceMonthly:49,priceAnnual:490,currency:"USD",features:["Advanced analytics","Priority support","3 storefronts"],isPopular:!0},{id:"tier_enterprise",title:"Enterprise",description:"For high volume and custom needs.",priceMonthly:199,priceAnnual:1990,currency:"USD",features:["SLA","Dedicated success","Unlimited storefronts"]}]},async getSubscriptionStatus(){return await At(80),{isActive:!1}},async createSubscriptionCheckoutSession(e){return await At(200),e.successUrl?{kind:"redirect",url:e.successUrl}:{kind:"custom",data:e}}}}function bl(e){return e.replace(/[_-]+/g," ").trim().replace(/\b\w/g,t=>t.toUpperCase())}function Pf(e){return e?e.toUpperCase():"USD"}function Tf(e){if(e&&(e==="in_stock"||e==="low"||e==="out_of_stock"||e==="backorder"))return e}function Ef(e){if(e&&(e==="physical"||e==="digital"))return e}function If(e){const t=[];if(Array.isArray(e))for(const r of e)typeof r=="string"&&t.push(r);else if(typeof e=="string"){const r=e.trim();if(r.startsWith("["))try{const s=JSON.parse(r);if(Array.isArray(s))for(const o of s)typeof o=="string"&&t.push(o);else t.push(e)}catch{t.push(e)}else t.push(e)}return t.flatMap(r=>r.split(",")).map(r=>r.trim().toUpperCase()).filter(Boolean)}function Or(e){const t=Pf(e.fiatCurrency),r=e.images&&e.images.length?e.images:e.imageUrl?[{url:e.imageUrl,alt:e.title}]:[],s=e.effectiveFiatAmountCents??e.fiatAmountCents??0,o=e.compareAtAmountCents,a=e.metadata?.shippingCountries??e.metadata?.shipping_countries,i=If(a);return{id:e.id,slug:e.slug??e.id,title:e.title??bl(e.id),description:e.description??"",images:r,price:s/100,currency:t,tags:e.tags??[],categoryIds:e.categoryIds??[],inventoryStatus:Tf(e.inventoryStatus),inventoryQuantity:typeof e.inventoryQuantity=="number"?e.inventoryQuantity:void 0,compareAtPrice:typeof o=="number"?o/100:void 0,shippingProfile:Ef(e.shippingProfile),checkoutRequirements:e.checkoutRequirements,fulfillment:e.fulfillment,attributes:i.length?{shippingCountries:i.join(",")}:void 0}}function lo(e){if(Array.isArray(e))return{products:e};const t=e.products??e.items??[],r=e.total??e.count;return{products:t,total:r}}async function Xt(e,t,r){const s={};r&&(s["X-API-Key"]=r);const o=await fetch(`${e}${t}`,{headers:s});if(!o.ok){const a=await o.text().catch(()=>""),i=new Error(`Request failed (${o.status}): ${a}`);throw i.status=o.status,i}return o.json()}function Rf(e){return{listProducts:async l=>{const d=l.page??1,m=l.pageSize??24,u=m,f=(d-1)*m,h=new URLSearchParams;h.set("limit",String(u)),h.set("offset",String(f)),l.search&&h.set("search",l.search),l.category&&h.set("category",l.category),l.sort&&h.set("sort",l.sort),l.filters?.inStock&&h.set("in_stock","true"),l.filters?.minPrice!=null&&h.set("min_price",String(l.filters.minPrice)),l.filters?.maxPrice!=null&&h.set("max_price",String(l.filters.maxPrice));const x=l.filters?.tags,p=Array.isArray(x)?x:typeof x=="string"?[x]:[];p.length&&h.set("tags",p.join(","));const y=await Xt(e.serverUrl,`/paywall/v1/products?${h.toString()}`,e.apiKey),{products:j,total:b}=lo(y);return{items:j.map(Or),page:d,pageSize:m,total:b,hasNextPage:typeof b=="number"?f+u<b:j.length===u}},getProductBySlug:async l=>{try{const d=await Xt(e.serverUrl,`/paywall/v1/products/by-slug/${encodeURIComponent(l)}`,e.apiKey);return Or(d)}catch(d){const m=d?.status;if(m!==404&&m!==405)throw d;try{const u=await Xt(e.serverUrl,`/paywall/v1/products/${encodeURIComponent(l)}`,e.apiKey);return Or(u)}catch(u){const f=u?.status;if(f!==404&&f!==405)throw u;const h=await Xt(e.serverUrl,"/paywall/v1/products?limit=200&offset=0",e.apiKey),{products:x}=lo(h),p=x.find(y=>y.slug===l||y.id===l);return p?Or(p):null}}},listCategories:async()=>{const l=await Xt(e.serverUrl,"/paywall/v1/products?limit=500&offset=0",e.apiKey),{products:d}=lo(l),m=new Set;for(const u of d)for(const f of u.categoryIds??[])m.add(f);return Array.from(m).map(u=>({id:u,slug:u,name:bl(u)}))},getOrderHistory:async()=>[],createCheckoutSession:async l=>{throw new Error("createCheckoutSession is not implemented for paywall adapter")},getStorefrontSettings:async()=>{try{return(await Xt(e.serverUrl,"/admin/config/storefront",e.apiKey)).config??null}catch{return null}},getPaymentMethodsConfig:async()=>{try{const[l,d,m]=await Promise.allSettled([Xt(e.serverUrl,"/admin/config/stripe",e.apiKey),Xt(e.serverUrl,"/admin/config/x402",e.apiKey),Xt(e.serverUrl,"/admin/config/cedros_login",e.apiKey)]),u=l.status==="fulfilled"?!!l.value?.config?.enabled:!1,f=d.status==="fulfilled"?!!d.value?.config?.enabled:!1,h=m.status==="fulfilled"?!!m.value?.config?.enabled:!1;return{card:u,crypto:f,credits:h}}catch{return null}},getAIRelatedProducts:async l=>{const d={"Content-Type":"application/json"};e.apiKey&&(d["X-API-Key"]=e.apiKey);const m=await fetch(`${e.serverUrl}/admin/ai/related-products`,{method:"POST",headers:d,body:JSON.stringify(l)});if(!m.ok){const u=await m.text().catch(()=>"");throw new Error(`AI related products request failed (${m.status}): ${u}`)}return m.json()}}}function Of(e){throw new Error(`Unhandled cart action: ${JSON.stringify(e)}`)}function yn(e){return`${e.productId}::${e.variantId??""}`}const Mf={items:[]};function Df(e,t){switch(t.type){case"cart/hydrate":return t.state;case"cart/add":{const r=Math.max(1,Math.floor(t.qty??1)),s=yn(t.item);return e.items.find(a=>yn(a)===s)?{...e,items:e.items.map(a=>yn(a)===s?{...a,qty:a.qty+r}:a)}:{...e,items:[...e.items,{...t.item,qty:r}]}}case"cart/remove":{const r=`${t.productId}::${t.variantId??""}`;return{...e,items:e.items.filter(s=>yn(s)!==r)}}case"cart/setQty":{const r=Math.max(0,Math.floor(t.qty)),s=`${t.productId}::${t.variantId??""}`;return r===0?{...e,items:e.items.filter(o=>yn(o)!==s)}:{...e,items:e.items.map(o=>yn(o)===s?{...o,qty:r}:o)}}case"cart/clear":return{items:[],promoCode:void 0};case"cart/setPromoCode":return{...e,promoCode:t.promoCode||void 0};case"cart/updateHold":{const r=`${t.productId}::${t.variantId??""}`;return{...e,items:e.items.map(s=>yn(s)===r?{...s,holdId:t.holdId,holdExpiresAt:t.holdExpiresAt}:s)}}default:return Of(t)}}function Lf(e){return e.reduce((t,r)=>t+r.qty,0)}function $f(e){return e.reduce((t,r)=>t+r.qty*r.unitPrice,0)}function Pi(){try{return typeof window>"u"?null:window.localStorage}catch{return null}}function zf(e,t){try{const r=e.getItem(t);return r?JSON.parse(r):null}catch{return null}}function Ff(e,t,r){try{e.setItem(t,JSON.stringify(r))}catch{}}const vl=w.createContext(null);function Mt(){const e=w.useContext(vl);if(!e)throw new Error("useCart must be used within CartProvider");return e}function Bf({children:e}){const{config:t}=De(),r=t.cart?.storageKey??"cedros_shop_cart_v1",s=t.customer?.id,o=t.customer?.isSignedIn??!!s,a=t.cart?.syncDebounceMs??800,i=!!t.adapter.getCartInventoryStatus,[c,l]=w.useReducer(Df,Mf),[d,m]=w.useState(!1),u=w.useRef(!1),f=w.useRef(null);w.useEffect(()=>{const y=Pi();if(!y)return;const j=zf(y,r);j&&Array.isArray(j.items)&&l({type:"cart/hydrate",state:j}),m(!0)},[r]),w.useEffect(()=>{const y=Pi();y&&Ff(y,r,c)},[c,r]),w.useEffect(()=>{d&&(!o||!s||!t.adapter.mergeCart&&!t.adapter.getCart||u.current||(u.current=!0,(async()=>{try{const y=t.adapter.mergeCart?await t.adapter.mergeCart({customerId:s,cart:c}):await t.adapter.getCart({customerId:s});y&&Array.isArray(y.items)&&(l({type:"cart/hydrate",state:y}),f.current=JSON.stringify(y))}catch{}})()))},[t.adapter,s,d,o,c]),w.useEffect(()=>{if(!d||!o||!s||!t.adapter.updateCart||!u.current||typeof window>"u")return;const y=JSON.stringify(c);if(f.current===y)return;const j=window.setTimeout(()=>{t.adapter.updateCart({customerId:s,cart:c}).then(()=>{f.current=y}).catch(()=>{})},a);return()=>window.clearTimeout(j)},[t.adapter,s,d,o,c,a]);const h=w.useCallback((y,j)=>{const b=c.items.find(v=>v.productId===y&&v.variantId===j);if(b)return{holdId:b.holdId,expiresAt:b.holdExpiresAt}},[c.items]),x=w.useCallback((y,j,b)=>{l({type:"cart/updateHold",productId:y,variantId:j,holdExpiresAt:b})},[]),p=w.useMemo(()=>{const y=Lf(c.items),j=$f(c.items);return{items:c.items,promoCode:c.promoCode,count:y,subtotal:j,addItem:(b,v)=>l({type:"cart/add",item:b,qty:v}),removeItem:(b,v)=>l({type:"cart/remove",productId:b,variantId:v}),setQty:(b,v,_)=>l({type:"cart/setQty",productId:b,variantId:v,qty:_}),clear:()=>l({type:"cart/clear"}),setPromoCode:b=>l({type:"cart/setPromoCode",promoCode:b}),holdsSupported:i,getItemHold:h,updateItemHold:x}},[c.items,c.promoCode,i,h,x]);return n.jsx(vl.Provider,{value:p,children:e})}function Z(e,t,r){function s(c,l){if(c._zod||Object.defineProperty(c,"_zod",{value:{def:l,constr:i,traits:new Set},enumerable:!1}),c._zod.traits.has(e))return;c._zod.traits.add(e),t(c,l);const d=i.prototype,m=Object.keys(d);for(let u=0;u<m.length;u++){const f=m[u];f in c||(c[f]=d[f].bind(c))}}const o=r?.Parent??Object;class a extends o{}Object.defineProperty(a,"name",{value:e});function i(c){var l;const d=r?.Parent?new a:this;s(d,c),(l=d._zod).deferred??(l.deferred=[]);for(const m of d._zod.deferred)m();return d}return Object.defineProperty(i,"init",{value:s}),Object.defineProperty(i,Symbol.hasInstance,{value:c=>r?.Parent&&c instanceof r.Parent?!0:c?._zod?.traits?.has(e)}),Object.defineProperty(i,"name",{value:e}),i}class Un extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class wl extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}}const _l={};function _n(e){return _l}function jl(e){const t=Object.values(e).filter(s=>typeof s=="number");return Object.entries(e).filter(([s,o])=>t.indexOf(+s)===-1).map(([s,o])=>o)}function Do(e,t){return typeof t=="bigint"?t.toString():t}function ua(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function ma(e){return e==null}function pa(e){const t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function Uf(e,t){const r=(e.toString().split(".")[1]||"").length,s=t.toString();let o=(s.split(".")[1]||"").length;if(o===0&&/\d?e-\d?/.test(s)){const l=s.match(/\d?e-(\d?)/);l?.[1]&&(o=Number.parseInt(l[1]))}const a=r>o?r:o,i=Number.parseInt(e.toFixed(a).replace(".","")),c=Number.parseInt(t.toFixed(a).replace(".",""));return i%c/10**a}const Ti=Symbol("evaluating");function Ce(e,t,r){let s;Object.defineProperty(e,t,{get(){if(s!==Ti)return s===void 0&&(s=Ti,s=r()),s},set(o){Object.defineProperty(e,t,{value:o})},configurable:!0})}function An(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function un(...e){const t={};for(const r of e){const s=Object.getOwnPropertyDescriptors(r);Object.assign(t,s)}return Object.defineProperties({},t)}function Ei(e){return JSON.stringify(e)}function Wf(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}const Sl="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function ns(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const Vf=ua(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function yr(e){if(ns(e)===!1)return!1;const t=e.constructor;if(t===void 0||typeof t!="function")return!0;const r=t.prototype;return!(ns(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function kl(e){return yr(e)?{...e}:Array.isArray(e)?[...e]:e}const Hf=new Set(["string","number","symbol"]);function bs(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function mn(e,t,r){const s=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(s._zod.parent=e),s}function ue(e){const t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function qf(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const Zf={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function Gf(e,t){const r=e._zod.def,s=r.checks;if(s&&s.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");const a=un(e._zod.def,{get shape(){const i={};for(const c in t){if(!(c in r.shape))throw new Error(`Unrecognized key: "${c}"`);t[c]&&(i[c]=r.shape[c])}return An(this,"shape",i),i},checks:[]});return mn(e,a)}function Qf(e,t){const r=e._zod.def,s=r.checks;if(s&&s.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");const a=un(e._zod.def,{get shape(){const i={...e._zod.def.shape};for(const c in t){if(!(c in r.shape))throw new Error(`Unrecognized key: "${c}"`);t[c]&&delete i[c]}return An(this,"shape",i),i},checks:[]});return mn(e,a)}function Yf(e,t){if(!yr(t))throw new Error("Invalid input to extend: expected a plain object");const r=e._zod.def.checks;if(r&&r.length>0){const a=e._zod.def.shape;for(const i in t)if(Object.getOwnPropertyDescriptor(a,i)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}const o=un(e._zod.def,{get shape(){const a={...e._zod.def.shape,...t};return An(this,"shape",a),a}});return mn(e,o)}function Kf(e,t){if(!yr(t))throw new Error("Invalid input to safeExtend: expected a plain object");const r=un(e._zod.def,{get shape(){const s={...e._zod.def.shape,...t};return An(this,"shape",s),s}});return mn(e,r)}function Jf(e,t){const r=un(e._zod.def,{get shape(){const s={...e._zod.def.shape,...t._zod.def.shape};return An(this,"shape",s),s},get catchall(){return t._zod.def.catchall},checks:[]});return mn(e,r)}function Xf(e,t,r){const o=t._zod.def.checks;if(o&&o.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");const i=un(t._zod.def,{get shape(){const c=t._zod.def.shape,l={...c};if(r)for(const d in r){if(!(d in c))throw new Error(`Unrecognized key: "${d}"`);r[d]&&(l[d]=e?new e({type:"optional",innerType:c[d]}):c[d])}else for(const d in c)l[d]=e?new e({type:"optional",innerType:c[d]}):c[d];return An(this,"shape",l),l},checks:[]});return mn(t,i)}function eh(e,t,r){const s=un(t._zod.def,{get shape(){const o=t._zod.def.shape,a={...o};if(r)for(const i in r){if(!(i in a))throw new Error(`Unrecognized key: "${i}"`);r[i]&&(a[i]=new e({type:"nonoptional",innerType:o[i]}))}else for(const i in o)a[i]=new e({type:"nonoptional",innerType:o[i]});return An(this,"shape",a),a}});return mn(t,s)}function Bn(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function Cl(e,t){return t.map(r=>{var s;return(s=r).path??(s.path=[]),r.path.unshift(e),r})}function Mr(e){return typeof e=="string"?e:e?.message}function jn(e,t,r){const s={...e,path:e.path??[]};if(!e.message){const o=Mr(e.inst?._zod.def?.error?.(e))??Mr(t?.error?.(e))??Mr(r.customError?.(e))??Mr(r.localeError?.(e))??"Invalid input";s.message=o}return delete s.inst,delete s.continue,t?.reportInput||delete s.input,s}function fa(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function br(...e){const[t,r,s]=e;return typeof t=="string"?{message:t,code:"custom",input:r,inst:s}:{...t}}const Nl=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,Do,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Al=Z("$ZodError",Nl),Pl=Z("$ZodError",Nl,{Parent:Error});function th(e,t=r=>r.message){const r={},s=[];for(const o of e.issues)o.path.length>0?(r[o.path[0]]=r[o.path[0]]||[],r[o.path[0]].push(t(o))):s.push(t(o));return{formErrors:s,fieldErrors:r}}function nh(e,t=r=>r.message){const r={_errors:[]},s=o=>{for(const a of o.issues)if(a.code==="invalid_union"&&a.errors.length)a.errors.map(i=>s({issues:i}));else if(a.code==="invalid_key")s({issues:a.issues});else if(a.code==="invalid_element")s({issues:a.issues});else if(a.path.length===0)r._errors.push(t(a));else{let i=r,c=0;for(;c<a.path.length;){const l=a.path[c];c===a.path.length-1?(i[l]=i[l]||{_errors:[]},i[l]._errors.push(t(a))):i[l]=i[l]||{_errors:[]},i=i[l],c++}}};return s(e),r}const ha=e=>(t,r,s,o)=>{const a=s?Object.assign(s,{async:!1}):{async:!1},i=t._zod.run({value:r,issues:[]},a);if(i instanceof Promise)throw new Un;if(i.issues.length){const c=new(o?.Err??e)(i.issues.map(l=>jn(l,a,_n())));throw Sl(c,o?.callee),c}return i.value},ga=e=>async(t,r,s,o)=>{const a=s?Object.assign(s,{async:!0}):{async:!0};let i=t._zod.run({value:r,issues:[]},a);if(i instanceof Promise&&(i=await i),i.issues.length){const c=new(o?.Err??e)(i.issues.map(l=>jn(l,a,_n())));throw Sl(c,o?.callee),c}return i.value},vs=e=>(t,r,s)=>{const o=s?{...s,async:!1}:{async:!1},a=t._zod.run({value:r,issues:[]},o);if(a instanceof Promise)throw new Un;return a.issues.length?{success:!1,error:new(e??Al)(a.issues.map(i=>jn(i,o,_n())))}:{success:!0,data:a.value}},rh=vs(Pl),ws=e=>async(t,r,s)=>{const o=s?Object.assign(s,{async:!0}):{async:!0};let a=t._zod.run({value:r,issues:[]},o);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new e(a.issues.map(i=>jn(i,o,_n())))}:{success:!0,data:a.value}},sh=ws(Pl),oh=e=>(t,r,s)=>{const o=s?Object.assign(s,{direction:"backward"}):{direction:"backward"};return ha(e)(t,r,o)},ah=e=>(t,r,s)=>ha(e)(t,r,s),ih=e=>async(t,r,s)=>{const o=s?Object.assign(s,{direction:"backward"}):{direction:"backward"};return ga(e)(t,r,o)},ch=e=>async(t,r,s)=>ga(e)(t,r,s),lh=e=>(t,r,s)=>{const o=s?Object.assign(s,{direction:"backward"}):{direction:"backward"};return vs(e)(t,r,o)},dh=e=>(t,r,s)=>vs(e)(t,r,s),uh=e=>async(t,r,s)=>{const o=s?Object.assign(s,{direction:"backward"}):{direction:"backward"};return ws(e)(t,r,o)},mh=e=>async(t,r,s)=>ws(e)(t,r,s),ph=/^[cC][^\s-]{8,}$/,fh=/^[0-9a-z]+$/,hh=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,gh=/^[0-9a-vA-V]{20}$/,xh=/^[A-Za-z0-9]{27}$/,yh=/^[a-zA-Z0-9_-]{21}$/,bh=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,vh=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,Ii=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,wh=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,_h="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function jh(){return new RegExp(_h,"u")}const Sh=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,kh=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,Ch=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,Nh=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Ah=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Tl=/^[A-Za-z0-9_-]*$/,Ph=/^\+[1-9]\d{6,14}$/,El="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",Th=new RegExp(`^${El}$`);function Il(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function Eh(e){return new RegExp(`^${Il(e)}$`)}function Ih(e){const t=Il({precision:e.precision}),r=["Z"];e.local&&r.push(""),e.offset&&r.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const s=`${t}(?:${r.join("|")})`;return new RegExp(`^${El}T(?:${s})$`)}const Rh=e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},Oh=/^-?\d+$/,Mh=/^-?\d+(?:\.\d+)?$/,Dh=/^[^A-Z]*$/,Lh=/^[^a-z]*$/,gt=Z("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),Rl={number:"number",bigint:"bigint",object:"date"},Ol=Z("$ZodCheckLessThan",(e,t)=>{gt.init(e,t);const r=Rl[typeof t.value];e._zod.onattach.push(s=>{const o=s._zod.bag,a=(t.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<a&&(t.inclusive?o.maximum=t.value:o.exclusiveMaximum=t.value)}),e._zod.check=s=>{(t.inclusive?s.value<=t.value:s.value<t.value)||s.issues.push({origin:r,code:"too_big",maximum:typeof t.value=="object"?t.value.getTime():t.value,input:s.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Ml=Z("$ZodCheckGreaterThan",(e,t)=>{gt.init(e,t);const r=Rl[typeof t.value];e._zod.onattach.push(s=>{const o=s._zod.bag,a=(t.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>a&&(t.inclusive?o.minimum=t.value:o.exclusiveMinimum=t.value)}),e._zod.check=s=>{(t.inclusive?s.value>=t.value:s.value>t.value)||s.issues.push({origin:r,code:"too_small",minimum:typeof t.value=="object"?t.value.getTime():t.value,input:s.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),$h=Z("$ZodCheckMultipleOf",(e,t)=>{gt.init(e,t),e._zod.onattach.push(r=>{var s;(s=r._zod.bag).multipleOf??(s.multipleOf=t.value)}),e._zod.check=r=>{if(typeof r.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%t.value===BigInt(0):Uf(r.value,t.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),zh=Z("$ZodCheckNumberFormat",(e,t)=>{gt.init(e,t),t.format=t.format||"float64";const r=t.format?.includes("int"),s=r?"int":"number",[o,a]=Zf[t.format];e._zod.onattach.push(i=>{const c=i._zod.bag;c.format=t.format,c.minimum=o,c.maximum=a,r&&(c.pattern=Oh)}),e._zod.check=i=>{const c=i.value;if(r){if(!Number.isInteger(c)){i.issues.push({expected:s,format:t.format,code:"invalid_type",continue:!1,input:c,inst:e});return}if(!Number.isSafeInteger(c)){c>0?i.issues.push({input:c,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:s,inclusive:!0,continue:!t.abort}):i.issues.push({input:c,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:s,inclusive:!0,continue:!t.abort});return}}c<o&&i.issues.push({origin:"number",input:c,code:"too_small",minimum:o,inclusive:!0,inst:e,continue:!t.abort}),c>a&&i.issues.push({origin:"number",input:c,code:"too_big",maximum:a,inclusive:!0,inst:e,continue:!t.abort})}}),Fh=Z("$ZodCheckMaxLength",(e,t)=>{var r;gt.init(e,t),(r=e._zod.def).when??(r.when=s=>{const o=s.value;return!ma(o)&&o.length!==void 0}),e._zod.onattach.push(s=>{const o=s._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<o&&(s._zod.bag.maximum=t.maximum)}),e._zod.check=s=>{const o=s.value;if(o.length<=t.maximum)return;const i=fa(o);s.issues.push({origin:i,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),Bh=Z("$ZodCheckMinLength",(e,t)=>{var r;gt.init(e,t),(r=e._zod.def).when??(r.when=s=>{const o=s.value;return!ma(o)&&o.length!==void 0}),e._zod.onattach.push(s=>{const o=s._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>o&&(s._zod.bag.minimum=t.minimum)}),e._zod.check=s=>{const o=s.value;if(o.length>=t.minimum)return;const i=fa(o);s.issues.push({origin:i,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),Uh=Z("$ZodCheckLengthEquals",(e,t)=>{var r;gt.init(e,t),(r=e._zod.def).when??(r.when=s=>{const o=s.value;return!ma(o)&&o.length!==void 0}),e._zod.onattach.push(s=>{const o=s._zod.bag;o.minimum=t.length,o.maximum=t.length,o.length=t.length}),e._zod.check=s=>{const o=s.value,a=o.length;if(a===t.length)return;const i=fa(o),c=a>t.length;s.issues.push({origin:i,...c?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:s.value,inst:e,continue:!t.abort})}}),_s=Z("$ZodCheckStringFormat",(e,t)=>{var r,s;gt.init(e,t),e._zod.onattach.push(o=>{const a=o._zod.bag;a.format=t.format,t.pattern&&(a.patterns??(a.patterns=new Set),a.patterns.add(t.pattern))}),t.pattern?(r=e._zod).check??(r.check=o=>{t.pattern.lastIndex=0,!t.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:t.format,input:o.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(s=e._zod).check??(s.check=()=>{})}),Wh=Z("$ZodCheckRegex",(e,t)=>{_s.init(e,t),e._zod.check=r=>{t.pattern.lastIndex=0,!t.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Vh=Z("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Dh),_s.init(e,t)}),Hh=Z("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=Lh),_s.init(e,t)}),qh=Z("$ZodCheckIncludes",(e,t)=>{gt.init(e,t);const r=bs(t.includes),s=new RegExp(typeof t.position=="number"?`^.{${t.position}}${r}`:r);t.pattern=s,e._zod.onattach.push(o=>{const a=o._zod.bag;a.patterns??(a.patterns=new Set),a.patterns.add(s)}),e._zod.check=o=>{o.value.includes(t.includes,t.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:o.value,inst:e,continue:!t.abort})}}),Zh=Z("$ZodCheckStartsWith",(e,t)=>{gt.init(e,t);const r=new RegExp(`^${bs(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.onattach.push(s=>{const o=s._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),e._zod.check=s=>{s.value.startsWith(t.prefix)||s.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:s.value,inst:e,continue:!t.abort})}}),Gh=Z("$ZodCheckEndsWith",(e,t)=>{gt.init(e,t);const r=new RegExp(`.*${bs(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.onattach.push(s=>{const o=s._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),e._zod.check=s=>{s.value.endsWith(t.suffix)||s.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:s.value,inst:e,continue:!t.abort})}}),Qh=Z("$ZodCheckOverwrite",(e,t)=>{gt.init(e,t),e._zod.check=r=>{r.value=t.tx(r.value)}});class Yh{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}const s=t.split(`
|
|
54
54
|
`).filter(i=>i),o=Math.min(...s.map(i=>i.length-i.trimStart().length)),a=s.map(i=>i.slice(o)).map(i=>" ".repeat(this.indent*2)+i);for(const i of a)this.content.push(i)}compile(){const t=Function,r=this?.args,o=[...(this?.content??[""]).map(a=>` ${a}`)];return new t(...r,o.join(`
|
|
55
55
|
`))}}const Kh={major:4,minor:3,patch:6},qe=Z("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Kh;const s=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&s.unshift(e);for(const o of s)for(const a of o._zod.onattach)a(e);if(s.length===0)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const o=(i,c,l)=>{let d=Bn(i),m;for(const u of c){if(u._zod.def.when){if(!u._zod.def.when(i))continue}else if(d)continue;const f=i.issues.length,h=u._zod.check(i);if(h instanceof Promise&&l?.async===!1)throw new Un;if(m||h instanceof Promise)m=(m??Promise.resolve()).then(async()=>{await h,i.issues.length!==f&&(d||(d=Bn(i,f)))});else{if(i.issues.length===f)continue;d||(d=Bn(i,f))}}return m?m.then(()=>i):i},a=(i,c,l)=>{if(Bn(i))return i.aborted=!0,i;const d=o(c,s,l);if(d instanceof Promise){if(l.async===!1)throw new Un;return d.then(m=>e._zod.parse(m,l))}return e._zod.parse(d,l)};e._zod.run=(i,c)=>{if(c.skipChecks)return e._zod.parse(i,c);if(c.direction==="backward"){const d=e._zod.parse({value:i.value,issues:[]},{...c,skipChecks:!0});return d instanceof Promise?d.then(m=>a(m,i,c)):a(d,i,c)}const l=e._zod.parse(i,c);if(l instanceof Promise){if(c.async===!1)throw new Un;return l.then(d=>o(d,s,c))}return o(l,s,c)}}Ce(e,"~standard",()=>({validate:o=>{try{const a=rh(e,o);return a.success?{value:a.data}:{issues:a.error?.issues}}catch{return sh(e,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}))}),xa=Z("$ZodString",(e,t)=>{qe.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??Rh(e._zod.bag),e._zod.parse=(r,s)=>{if(t.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),Re=Z("$ZodStringFormat",(e,t)=>{_s.init(e,t),xa.init(e,t)}),Jh=Z("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=vh),Re.init(e,t)}),Xh=Z("$ZodUUID",(e,t)=>{if(t.version){const s={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(s===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=Ii(s))}else t.pattern??(t.pattern=Ii());Re.init(e,t)}),eg=Z("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=wh),Re.init(e,t)}),tg=Z("$ZodURL",(e,t)=>{Re.init(e,t),e._zod.check=r=>{try{const s=r.value.trim(),o=new URL(s);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(o.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:r.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:r.value,inst:e,continue:!t.abort})),t.normalize?r.value=o.href:r.value=s;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),ng=Z("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=jh()),Re.init(e,t)}),rg=Z("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=yh),Re.init(e,t)}),sg=Z("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=ph),Re.init(e,t)}),og=Z("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=fh),Re.init(e,t)}),ag=Z("$ZodULID",(e,t)=>{t.pattern??(t.pattern=hh),Re.init(e,t)}),ig=Z("$ZodXID",(e,t)=>{t.pattern??(t.pattern=gh),Re.init(e,t)}),cg=Z("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=xh),Re.init(e,t)}),lg=Z("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=Ih(t)),Re.init(e,t)}),dg=Z("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=Th),Re.init(e,t)}),ug=Z("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=Eh(t)),Re.init(e,t)}),mg=Z("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=bh),Re.init(e,t)}),pg=Z("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=Sh),Re.init(e,t),e._zod.bag.format="ipv4"}),fg=Z("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=kh),Re.init(e,t),e._zod.bag.format="ipv6",e._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:e,continue:!t.abort})}}}),hg=Z("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=Ch),Re.init(e,t)}),gg=Z("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=Nh),Re.init(e,t),e._zod.check=r=>{const s=r.value.split("/");try{if(s.length!==2)throw new Error;const[o,a]=s;if(!a)throw new Error;const i=Number(a);if(`${i}`!==a)throw new Error;if(i<0||i>128)throw new Error;new URL(`http://[${o}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:e,continue:!t.abort})}}});function Dl(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}const xg=Z("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=Ah),Re.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=r=>{Dl(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});function yg(e){if(!Tl.test(e))return!1;const t=e.replace(/[-_]/g,s=>s==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return Dl(r)}const bg=Z("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=Tl),Re.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=r=>{yg(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),vg=Z("$ZodE164",(e,t)=>{t.pattern??(t.pattern=Ph),Re.init(e,t)});function wg(e,t=null){try{const r=e.split(".");if(r.length!==3)return!1;const[s]=r;if(!s)return!1;const o=JSON.parse(atob(s));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||t&&(!("alg"in o)||o.alg!==t))}catch{return!1}}const _g=Z("$ZodJWT",(e,t)=>{Re.init(e,t),e._zod.check=r=>{wg(r.value,t.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}}),Ll=Z("$ZodNumber",(e,t)=>{qe.init(e,t),e._zod.pattern=e._zod.bag.pattern??Mh,e._zod.parse=(r,s)=>{if(t.coerce)try{r.value=Number(r.value)}catch{}const o=r.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return r;const a=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:o,inst:e,...a?{received:a}:{}}),r}}),jg=Z("$ZodNumberFormat",(e,t)=>{zh.init(e,t),Ll.init(e,t)}),Sg=Z("$ZodUnknown",(e,t)=>{qe.init(e,t),e._zod.parse=r=>r}),kg=Z("$ZodNever",(e,t)=>{qe.init(e,t),e._zod.parse=(r,s)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:e}),r)});function Ri(e,t,r){e.issues.length&&t.issues.push(...Cl(r,e.issues)),t.value[r]=e.value}const Cg=Z("$ZodArray",(e,t)=>{qe.init(e,t),e._zod.parse=(r,s)=>{const o=r.value;if(!Array.isArray(o))return r.issues.push({expected:"array",code:"invalid_type",input:o,inst:e}),r;r.value=Array(o.length);const a=[];for(let i=0;i<o.length;i++){const c=o[i],l=t.element._zod.run({value:c,issues:[]},s);l instanceof Promise?a.push(l.then(d=>Ri(d,r,i))):Ri(l,r,i)}return a.length?Promise.all(a).then(()=>r):r}});function rs(e,t,r,s,o){if(e.issues.length){if(o&&!(r in s))return;t.issues.push(...Cl(r,e.issues))}e.value===void 0?r in s&&(t.value[r]=void 0):t.value[r]=e.value}function $l(e){const t=Object.keys(e.shape);for(const s of t)if(!e.shape?.[s]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${s}": expected a Zod schema`);const r=qf(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(r)}}function zl(e,t,r,s,o,a){const i=[],c=o.keySet,l=o.catchall._zod,d=l.def.type,m=l.optout==="optional";for(const u in t){if(c.has(u))continue;if(d==="never"){i.push(u);continue}const f=l.run({value:t[u],issues:[]},s);f instanceof Promise?e.push(f.then(h=>rs(h,r,u,t,m))):rs(f,r,u,t,m)}return i.length&&r.issues.push({code:"unrecognized_keys",keys:i,input:t,inst:a}),e.length?Promise.all(e).then(()=>r):r}const Ng=Z("$ZodObject",(e,t)=>{if(qe.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){const c=t.shape;Object.defineProperty(t,"shape",{get:()=>{const l={...c};return Object.defineProperty(t,"shape",{value:l}),l}})}const s=ua(()=>$l(t));Ce(e._zod,"propValues",()=>{const c=t.shape,l={};for(const d in c){const m=c[d]._zod;if(m.values){l[d]??(l[d]=new Set);for(const u of m.values)l[d].add(u)}}return l});const o=ns,a=t.catchall;let i;e._zod.parse=(c,l)=>{i??(i=s.value);const d=c.value;if(!o(d))return c.issues.push({expected:"object",code:"invalid_type",input:d,inst:e}),c;c.value={};const m=[],u=i.shape;for(const f of i.keys){const h=u[f],x=h._zod.optout==="optional",p=h._zod.run({value:d[f],issues:[]},l);p instanceof Promise?m.push(p.then(y=>rs(y,c,f,d,x))):rs(p,c,f,d,x)}return a?zl(m,d,c,l,s.value,e):m.length?Promise.all(m).then(()=>c):c}}),Ag=Z("$ZodObjectJIT",(e,t)=>{Ng.init(e,t);const r=e._zod.parse,s=ua(()=>$l(t)),o=f=>{const h=new Yh(["shape","payload","ctx"]),x=s.value,p=v=>{const _=Ei(v);return`shape[${_}]._zod.run({ value: input[${_}], issues: [] }, ctx)`};h.write("const input = payload.value;");const y=Object.create(null);let j=0;for(const v of x.keys)y[v]=`key_${j++}`;h.write("const newResult = {};");for(const v of x.keys){const _=y[v],C=Ei(v),S=f[v]?._zod?.optout==="optional";h.write(`const ${_} = ${p(v)};`),S?h.write(`
|
|
56
56
|
if (${_}.issues.length) {
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("./index-
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("./index-CWbWPgXt.js");require("react/jsx-runtime");require("react");const r=require("./CedrosContext-efFL4kQz.js");require("@solana/web3.js");require("@solana/wallet-adapter-react");const e=require("./styles-C4-_hbgr.js");exports.CSP_PRESETS=t.CSP_PRESETS;exports.CedrosPay=t.CedrosPay;exports.CedrosPayAdminDashboard=t.CedrosPayAdminDashboard;exports.CreditsSubscribeButton=t.CreditsSubscribeButton;exports.CryptoSubscribeButton=t.CryptoSubscribeButton;exports.PurchaseButton=t.PurchaseButton;exports.RPC_PROVIDERS=t.RPC_PROVIDERS;exports.SECURITY_RECOMMENDATIONS=t.SECURITY_RECOMMENDATIONS;exports.SubscribeButton=t.SubscribeButton;exports.SubscriptionManagementPanel=t.SubscriptionManagementPanel;exports.cedrosPayPlugin=t.cedrosPayPlugin;exports.ecommerce=t.index;exports.formatCSP=t.formatCSP;exports.generateCSP=t.generateCSP;exports.generateCSPDirectives=t.generateCSPDirectives;exports.logSecurityReport=t.logSecurityReport;exports.useCreditsSubscription=t.useCreditsSubscription;exports.useCryptoSubscription=t.useCryptoSubscription;exports.useRefundVerification=t.useRefundVerification;exports.useSubscription=t.useSubscription;exports.useSubscriptionManagement=t.useSubscriptionManagement;exports.validateSecurity=t.validateSecurity;exports.CIRCUIT_BREAKER_PRESETS=r.CIRCUIT_BREAKER_PRESETS;exports.CedrosProvider=r.CedrosProvider;exports.CircuitBreakerOpenError=r.CircuitBreakerOpenError;exports.CircuitState=r.CircuitState;exports.LogLevel=r.LogLevel;exports.Logger=r.Logger;exports.RATE_LIMITER_PRESETS=r.RATE_LIMITER_PRESETS;exports.RETRY_PRESETS=r.RETRY_PRESETS;exports.WalletPool=r.WalletPool;exports.createCircuitBreaker=r.createCircuitBreaker;exports.createLogger=r.createLogger;exports.createRateLimiter=r.createRateLimiter;exports.createWalletPool=r.createWalletPool;exports.getLogger=r.getLogger;exports.retryWithBackoff=r.retryWithBackoff;exports.useCedrosContext=r.useCedrosContext;exports.useCedrosTheme=r.useCedrosTheme;exports.validateConfig=r.validateConfig;exports.CEDROS_EVENTS=e.CEDROS_EVENTS;exports.CreditsButton=e.CreditsButton;exports.CryptoButton=e.CryptoButton;exports.ERROR_CATEGORIES=e.ERROR_CATEGORIES;exports.PaymentMethodBadge=e.PaymentMethodBadge;exports.PaymentModal=e.PaymentModal;exports.ProductPrice=e.ProductPrice;exports.StripeButton=e.StripeButton;exports.calculateDiscountPercentage=e.calculateDiscountPercentage;exports.createTranslator=e.createTranslator;exports.detectLocale=e.detectLocale;exports.emitPaymentError=e.emitPaymentError;exports.emitPaymentProcessing=e.emitPaymentProcessing;exports.emitPaymentStart=e.emitPaymentStart;exports.emitPaymentSuccess=e.emitPaymentSuccess;exports.emitWalletConnect=e.emitWalletConnect;exports.emitWalletConnected=e.emitWalletConnected;exports.emitWalletError=e.emitWalletError;exports.formatCouponCodes=e.formatCouponCodes;exports.getAvailableLocales=e.getAvailableLocales;exports.getLocalizedError=e.getLocalizedError;exports.getUserErrorMessage=e.getUserErrorMessage;exports.isRetryableError=e.isRetryableError;exports.loadLocale=e.loadLocale;exports.parseCouponCodes=e.parseCouponCodes;exports.stackCheckoutCoupons=e.stackCheckoutCoupons;exports.useCreditsPayment=e.useCreditsPayment;exports.useLocalizedError=e.useLocalizedError;exports.usePaymentMode=e.usePaymentMode;exports.useStripeCheckout=e.useStripeCheckout;exports.useTranslation=e.useTranslation;exports.useX402Payment=e.useX402Payment;
|
package/dist/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { q as i, a as n, b as c, g as u, f as C, d as l, p as m, s as S, e as P, h as d, c as E, t as p, o as R, m as g, n as y, r as b, k as T, j as B, u as L, i as f, l as _, v as h } from "./index-
|
|
1
|
+
import { q as i, a as n, b as c, g as u, f as C, d as l, p as m, s as S, e as P, h as d, c as E, t as p, o as R, m as g, n as y, r as b, k as T, j as B, u as L, i as f, l as _, v as h } from "./index-CUoeIbXT.mjs";
|
|
2
2
|
import "react/jsx-runtime";
|
|
3
3
|
import "react";
|
|
4
4
|
import { n as v, C as M, m as I, l as A, L as D, b as O, R as W, o as x, W as z, k as N, d as U, c as V, p as j, g as G, r as Y, u as q, a as F, v as K } from "./CedrosContext-DUT3cLZg.mjs";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});require("react/jsx-runtime");require("react");const e=require("./index-
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});require("react/jsx-runtime");require("react");const e=require("./index-CWbWPgXt.js");exports.CouponsSection=e.CouponsSection;exports.ProductsSection=e.ProductsSection;exports.RefundsSection=e.RefundsSection;exports.SettingsSection=e.SettingsSection;exports.TransactionsSection=e.TransactionsSection;
|