const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/AnalyticsDashboard-B_WKlADe.js","assets/vendor-query-BSpUEUJE.js","assets/vendor-react-CWq2BoMo.js","assets/card-Dd3vXi0j.js","assets/index-DVdSf46I.js","assets/vendor-pdf-OPq5ZiHo.js","assets/vendor-ui-extra-CW6ezZiQ.js","assets/vendor-ui-core-BWFXPlYg.js","assets/vendor-charts-bmwX1u6y.js","assets/index-CFOwLxe1.css","assets/currencyConfig-Ch2cK6at.js","assets/date-picker-mgFhUy-U.js","assets/calendar-BjYdwRhe.js","assets/vendor-date-BDZqQjIb.js","assets/usePhpSellerId-C6BnBLkv.js","assets/chart-column-DZxbdZNH.js","assets/filter-CrT8avJX.js","assets/alert-cV8dsncc.js","assets/vendor-barcode-DhT-N8Id.js","assets/ExecutiveDashboard-CX2xhCpd.js","assets/award-axXXLRc1.js","assets/ShiftManagement-25WIPYWd.js","assets/ShiftReport-yqYKdCeT.js","assets/chart-pie-oUDzrogX.js","assets/CashDrawerMovements-CS-g03RT.js","assets/EmployeeManagement-9UtVvY9l.js","assets/useEmployees-eEh0-2eZ.js","assets/permissionDefaults-DhL9EK1T.js","assets/mail-D3z08Jo4.js","assets/EmployeePerformance-B7C3sIht.js","assets/AuditLog-BXpf9x1X.js","assets/LoyaltyProgram-BO1F64_F.js","assets/PromotionsManagement-BBLo4qRm.js","assets/checkbox-be7Y7u6l.js","assets/CustomerAnalyticsReport-BAM5vZQg.js","assets/ABCAnalysisReport-BpL_eVGY.js","assets/SalesForecastReport-Ew-TzkrD.js","assets/activity-DGpODQxJ.js","assets/ProductPerformanceReport-DsoViFYp.js","assets/analyticsHelpers-Dhiy7f7s.js","assets/ExpenseManagement-BSOtSAIi.js","assets/useExpenses-B9sCTuAP.js","assets/vendor-forms-Bkp1rCGP.js","assets/form-B68-jcLg.js","assets/ExpenseCategoriesManager-y5iMrB00.js","assets/folder-open-YbsM9hGS.js","assets/ExpenseReport-DshfdAS1.js","assets/progress-DbdJg_K5.js","assets/collapsible-D-qvISpe.js","assets/StocktakeSessionsList-CTDuNBng.js","assets/dropdown-menu-_tO9X-Op.js","assets/StocktakeStepIndicator-D7EjZMX_.js","assets/useVarianceReasons-C1qsjLC9.js","assets/ellipsis-vertical-MEzxSsKu.js","assets/VarianceReasonsManager-Dlu2kZGI.js","assets/StocktakeReport-Cxkc5PcG.js","assets/file-down-CoG2-WQC.js","assets/SupplierManagement-CH79Q6bY.js","assets/usePhpSuppliers-dMSWU_Bv.js","assets/PurchaseOrderList-D5dKnRq1.js","assets/SupplierPayments-w43Rrauu.js","assets/SupplierReport-DY1AAreQ.js","assets/OfflineSyncReport-BI2deLJe.js","assets/hard-drive-C3hNEnQL.js","assets/RegenerateQRCodes-CsvsSvtr.js","assets/FixDuplicateQRCodes-BMjrOnad.js","assets/BulkResendInvoices-BXQSwXEP.js","assets/DuplicateCleanup-D3-m0Svs.js"])))=>i.map(i=>d[i]);
import{_ as Ve}from"./vendor-pdf-OPq5ZiHo.js";import{j as e,u as dn,b as vr,c as $t}from"./vendor-query-BSpUEUJE.js";import{r as v,R as su,g as Ln,d as Li,b as cs,c as we,a as ls,u as Di,h as ou}from"./vendor-react-CWq2BoMo.js";import{S as zt,D as gt,a as bt,U as Rt,P as ht,b as To,C as $i,c as Tt,d as At,e as kn,f as un,g as au,B as Ae,h as As,i as Ur,R as xs,F as It,T as Fi,j as Ui,k as Vr,l as Gr,m as vt,n as _t,o as wt,p as jt,q as Je,r as Dn,s as mn,t as Zr,u as Ao,v as Io,w as Oo,x as ar,y as rt,z as Ro,A as Qe,E as en,G as ho,H as iu,I as gs,J as mr,K as cu,L as Po,M as Mo,N as lu,O as zi,Q as Is,V as Lo,W as Qs,X as ds,Y as bn,Z as du,_ as bs,$ as Bi,a0 as xr,a1 as qi,a2 as ns,a3 as uu,a4 as Vi,a5 as Os,a6 as mu,a7 as hu}from"./currencyConfig-Ch2cK6at.js";import{c as te,a as Z,B as V,u as tr,b as lt,I as Te,T as xe,A as W,g as oe,d as Gi,U as Bt,J as Ge,e as Mt,f as nt,h as $n,L as ct,X as at,E as fo,D as Rs,R as _r,S as Sr,i as fu,j as Zt,k as Do,l as Tn,m as $o,n as po,o as Hi,p as Wi,q as Xi,r as pu,P as Ji,s as xu}from"./index-DVdSf46I.js";import{f as ir,q as Ki,r as Yi,O as Fo,s as Uo,P as Lt,c as Fn,u as Mr,b as cr,d as Ps,h as gu,t as Qi,p as bu,g as Zi,v as yu,I as vu,w as _u,n as ec,j as wu,k as ju,i as Nu,l as Cu,F as Eu,D as Su,x as ku,m as Tu,S as Au,y as Iu,T as tc,z as rc,B as Ou}from"./vendor-ui-core-BWFXPlYg.js";import{P as kt,C as fe,a as De,b as $e,c as kr,d as ve,Z as zo,W as tn,e as nc,f as Tr,S as Ru,g as Bo}from"./card-Dd3vXi0j.js";import{P as ae}from"./vendor-charts-bmwX1u6y.js";import{u as Pu,a as Mu,b as sc,c as Lu,d as Du}from"./vendor-ui-extra-CW6ezZiQ.js";import{A as qo,M as $u,a as Ta,b as Aa,c as Ia,I as Vo}from"./alert-cV8dsncc.js";import{J as Fu}from"./vendor-barcode-DhT-N8Id.js";/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Uu=te("Apple",[["path",{d:"M12 20.94c1.5 0 2.75 1.06 4 1.06 3 0 6-8 6-12.22A4.91 4.91 0 0 0 17 5c-2.22 0-4 1.44-5 2-1-.56-2.78-2-5-2a4.9 4.9 0 0 0-5 4.78C2 14 5 22 8 22c1.25 0 2.5-1.06 4-1.06Z",key:"3s7exb"}],["path",{d:"M10 2c1 .5 2 2 2 5",key:"fcco2y"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const zu=te("Archive",[["rect",{width:"20",height:"5",x:"2",y:"3",rx:"1",key:"1wp1u1"}],["path",{d:"M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8",key:"1s80jp"}],["path",{d:"M10 12h4",key:"a56b0p"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Bu=te("ArrowDown",[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const qu=te("Baby",[["path",{d:"M9 12h.01",key:"157uk2"}],["path",{d:"M15 12h.01",key:"1k8ypt"}],["path",{d:"M10 16c.5.3 1.2.5 2 .5s1.5-.2 2-.5",key:"1u7htd"}],["path",{d:"M19 6.3a9 9 0 0 1 1.8 3.9 2 2 0 0 1 0 3.6 9 9 0 0 1-17.6 0 2 2 0 0 1 0-3.6A9 9 0 0 1 12 3c2 0 3.5 1.1 3.5 2.5s-.9 2.5-2 2.5c-.8 0-1.5-.4-1.5-1",key:"5yv0yz"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Vu=te("Banknote",[["rect",{width:"20",height:"12",x:"2",y:"6",rx:"2",key:"9lu3g6"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}],["path",{d:"M6 12h.01M18 12h.01",key:"113zkx"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const En=te("Barcode",[["path",{d:"M3 5v14",key:"1nt18q"}],["path",{d:"M8 5v14",key:"1ybrkv"}],["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"M17 5v14",key:"ycjyhj"}],["path",{d:"M21 5v14",key:"nzette"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Gu=te("Battery",[["rect",{width:"16",height:"10",x:"2",y:"7",rx:"2",ry:"2",key:"1w10f2"}],["line",{x1:"22",x2:"22",y1:"11",y2:"13",key:"4dh1rd"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Hu=te("BedDouble",[["path",{d:"M2 20v-8a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v8",key:"1k78r4"}],["path",{d:"M4 10V6a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v4",key:"fb3tl2"}],["path",{d:"M12 4v6",key:"1dcgq2"}],["path",{d:"M2 18h20",key:"ajqnye"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Wu=te("Beef",[["circle",{cx:"12.5",cy:"8.5",r:"2.5",key:"9738u8"}],["path",{d:"M12.5 2a6.5 6.5 0 0 0-6.22 4.6c-1.1 3.13-.78 3.9-3.18 6.08A3 3 0 0 0 5 18c4 0 8.4-1.8 11.4-4.3A6.5 6.5 0 0 0 12.5 2Z",key:"o0f6za"}],["path",{d:"m18.5 6 2.19 4.5a6.48 6.48 0 0 1 .31 2 6.49 6.49 0 0 1-2.6 5.2C15.4 20.2 11 22 7 22a3 3 0 0 1-2.68-1.66L2.4 16.5",key:"k7p6i0"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const us=te("Bell",[["path",{d:"M6 8a6 6 0 0 1 12 0c0 7 3 9 3 9H3s3-2 3-9",key:"1qo2s2"}],["path",{d:"M10.3 21a1.94 1.94 0 0 0 3.4 0",key:"qgo35s"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Xu=te("Bike",[["circle",{cx:"18.5",cy:"17.5",r:"3.5",key:"15x4ox"}],["circle",{cx:"5.5",cy:"17.5",r:"3.5",key:"1noe27"}],["circle",{cx:"15",cy:"5",r:"1",key:"19l28e"}],["path",{d:"M12 17.5V14l-3-3 4-3 2 3h2",key:"1npguv"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Ju=te("Book",[["path",{d:"M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H19a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1H6.5a1 1 0 0 1 0-5H20",key:"k3hazp"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Ku=te("Briefcase",[["path",{d:"M16 20V4a2 2 0 0 0-2-2h-4a2 2 0 0 0-2 2v16",key:"jecpp"}],["rect",{width:"20",height:"14",x:"2",y:"6",rx:"2",key:"i6l2r4"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Yu=te("Cake",[["path",{d:"M20 21v-8a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v8",key:"1w3rig"}],["path",{d:"M4 16s.5-1 2-1 2.5 2 4 2 2.5-2 4-2 2.5 2 4 2 2-1 2-1",key:"n2jgmb"}],["path",{d:"M2 21h20",key:"1nyx9w"}],["path",{d:"M7 8v3",key:"1qtyvj"}],["path",{d:"M12 8v3",key:"hwp4zt"}],["path",{d:"M17 8v3",key:"1i6e5u"}],["path",{d:"M7 4h.01",key:"1bh4kh"}],["path",{d:"M12 4h.01",key:"1ujb9j"}],["path",{d:"M17 4h.01",key:"1upcoc"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const oc=te("Calendar",[["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M16 2v4",key:"4m81vk"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2",key:"1hopcy"}],["path",{d:"M3 10h18",key:"8toen8"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Qu=te("Camera",[["path",{d:"M14.5 4h-5L7 7H4a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-3l-2.5-3z",key:"1tc9qg"}],["circle",{cx:"12",cy:"13",r:"3",key:"1vg3eu"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Zu=te("Candy",[["path",{d:"m9.5 7.5-2 2a4.95 4.95 0 1 0 7 7l2-2a4.95 4.95 0 1 0-7-7Z",key:"ue6khb"}],["path",{d:"M14 6.5v10",key:"5xnk7c"}],["path",{d:"M10 7.5v10",key:"1uew51"}],["path",{d:"m16 7 1-5 1.37.68A3 3 0 0 0 19.7 3H21v1.3c0 .46.1.92.32 1.33L22 7l-5 1",key:"b9cp6k"}],["path",{d:"m8 17-1 5-1.37-.68A3 3 0 0 0 4.3 21H3v-1.3a3 3 0 0 0-.32-1.33L2 17l5-1",key:"5lney8"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const em=te("Car",[["path",{d:"M19 17h2c.6 0 1-.4 1-1v-3c0-.9-.7-1.7-1.5-1.9C18.7 10.6 16 10 16 10s-1.3-1.4-2.2-2.3c-.5-.4-1.1-.7-1.8-.7H5c-.6 0-1.1.4-1.4.9l-1.4 2.9A3.7 3.7 0 0 0 2 12v4c0 .6.4 1 1 1h2",key:"5owen"}],["circle",{cx:"7",cy:"17",r:"2",key:"u2ysq9"}],["path",{d:"M9 17h6",key:"r8uit2"}],["circle",{cx:"17",cy:"17",r:"2",key:"axvx0g"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const tm=te("Carrot",[["path",{d:"M2.27 21.7s9.87-3.5 12.73-6.36a4.5 4.5 0 0 0-6.36-6.37C5.77 11.84 2.27 21.7 2.27 21.7zM8.64 14l-2.05-2.04M15.34 15l-2.46-2.46",key:"rfqxbe"}],["path",{d:"M22 9s-1.33-2-3.5-2C16.86 7 15 9 15 9s1.33 2 3.5 2S22 9 22 9z",key:"6b25w4"}],["path",{d:"M15 2s-2 1.33-2 3.5S15 9 15 9s2-1.84 2-3.5C17 3.33 15 2 15 2z",key:"fn65lo"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const rm=te("Cat",[["path",{d:"M12 5c.67 0 1.35.09 2 .26 1.78-2 5.03-2.84 6.42-2.26 1.4.58-.42 7-.42 7 .57 1.07 1 2.24 1 3.44C21 17.9 16.97 21 12 21s-9-3-9-7.56c0-1.25.5-2.4 1-3.44 0 0-1.89-6.42-.5-7 1.39-.58 4.72.23 6.5 2.23A9.04 9.04 0 0 1 12 5Z",key:"x6xyqk"}],["path",{d:"M8 14v.5",key:"1nzgdb"}],["path",{d:"M16 14v.5",key:"1lajdz"}],["path",{d:"M11.25 16.25h1.5L12 17l-.75-.75Z",key:"12kq1m"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const nm=te("Cherry",[["path",{d:"M2 17a5 5 0 0 0 10 0c0-2.76-2.5-5-5-3-2.5-2-5 .24-5 3Z",key:"cvxqlc"}],["path",{d:"M12 17a5 5 0 0 0 10 0c0-2.76-2.5-5-5-3-2.5-2-5 .24-5 3Z",key:"1ostrc"}],["path",{d:"M7 14c3.22-2.91 4.29-8.75 5-12 1.66 2.38 4.94 9 5 12",key:"hqx58h"}],["path",{d:"M22 9c-4.29 0-7.14-2.33-10-7 5.71 0 10 4.67 10 7Z",key:"eykp1o"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Ms=te("ChevronLeft",[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Go=te("ChevronRight",[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const sm=te("ChevronsUpDown",[["path",{d:"m7 15 5 5 5-5",key:"1hf1tw"}],["path",{d:"m7 9 5-5 5 5",key:"sgt6xg"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const om=te("Cigarette",[["path",{d:"M17 12H3a1 1 0 0 0-1 1v2a1 1 0 0 0 1 1h14",key:"1mb5g1"}],["path",{d:"M18 8c0-2.5-2-2.5-2-5",key:"1il607"}],["path",{d:"M21 16a1 1 0 0 0 1-1v-2a1 1 0 0 0-1-1",key:"1yl5r7"}],["path",{d:"M22 8c0-2.5-2-2.5-2-5",key:"1gah44"}],["path",{d:"M7 12v4",key:"jqww69"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Oa=te("CircleHelp",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3",key:"1u773s"}],["path",{d:"M12 17h.01",key:"p32p05"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Ra=te("CircleUser",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"10",r:"3",key:"ilqhr7"}],["path",{d:"M7 20.662V19a2 2 0 0 1 2-2h6a2 2 0 0 1 2 2v1.662",key:"154egf"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const am=te("Circle",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Pa=te("Cloud",[["path",{d:"M17.5 19H9a7 7 0 1 1 6.71-9h1.79a4.5 4.5 0 1 1 0 9Z",key:"p7xjir"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const im=te("Coffee",[["path",{d:"M10 2v2",key:"7u0qdc"}],["path",{d:"M14 2v2",key:"6buw04"}],["path",{d:"M16 8a1 1 0 0 1 1 1v8a4 4 0 0 1-4 4H7a4 4 0 0 1-4-4V9a1 1 0 0 1 1-1h14a4 4 0 1 1 0 8h-1",key:"pwadti"}],["path",{d:"M6 2v2",key:"colzsn"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const cm=te("Command",[["path",{d:"M15 6v12a3 3 0 1 0 3-3H6a3 3 0 1 0 3 3V6a3 3 0 1 0-3 3h12a3 3 0 1 0-3-3",key:"11bfej"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const lm=te("Cookie",[["path",{d:"M12 2a10 10 0 1 0 10 10 4 4 0 0 1-5-5 4 4 0 0 1-5-5",key:"laymnq"}],["path",{d:"M8.5 8.5v.01",key:"ue8clq"}],["path",{d:"M16 15.5v.01",key:"14dtrp"}],["path",{d:"M12 12v.01",key:"u5ubse"}],["path",{d:"M11 17v.01",key:"1hyl5a"}],["path",{d:"M7 14v.01",key:"uct60s"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Un=te("CreditCard",[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2",key:"ynyp8z"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10",key:"1b3vmo"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const dm=te("Delete",[["path",{d:"M10 5a2 2 0 0 0-1.344.519l-6.328 5.74a1 1 0 0 0 0 1.481l6.328 5.741A2 2 0 0 0 10 19h10a2 2 0 0 0 2-2V7a2 2 0 0 0-2-2z",key:"1yo7s0"}],["path",{d:"m12 9 6 6",key:"anjzzh"}],["path",{d:"m18 9-6 6",key:"1fp51s"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const um=te("Dog",[["path",{d:"M11.25 16.25h1.5L12 17z",key:"w7jh35"}],["path",{d:"M16 14v.5",key:"1lajdz"}],["path",{d:"M4.42 11.247A13.152 13.152 0 0 0 4 14.556C4 18.728 7.582 21 12 21s8-2.272 8-6.444a11.702 11.702 0 0 0-.493-3.309",key:"u7s9ue"}],["path",{d:"M8 14v.5",key:"1nzgdb"}],["path",{d:"M8.5 8.5c-.384 1.05-1.083 2.028-2.344 2.5-1.931.722-3.576-.297-3.656-1-.113-.994 1.177-6.53 4-7 1.923-.321 3.651.845 3.651 2.235A7.497 7.497 0 0 1 14 5.277c0-1.39 1.844-2.598 3.767-2.277 2.823.47 4.113 6.006 4 7-.08.703-1.725 1.722-3.656 1-1.261-.472-1.855-1.45-2.239-2.5",key:"v8hric"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const gr=te("DollarSign",[["line",{x1:"12",x2:"12",y1:"2",y2:"22",key:"7eqyqh"}],["path",{d:"M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6",key:"1b0p4s"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const mm=te("Droplet",[["path",{d:"M12 22a7 7 0 0 0 7-7c0-2-1-3.9-3-5.5s-3.5-4-4-6.5c-.5 2.5-2 4.9-4 6.5C6 11.1 5 13 5 15a7 7 0 0 0 7 7z",key:"c7niix"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const hm=te("Dumbbell",[["path",{d:"M14.4 14.4 9.6 9.6",key:"ic80wn"}],["path",{d:"M18.657 21.485a2 2 0 1 1-2.829-2.828l-1.767 1.768a2 2 0 1 1-2.829-2.829l6.364-6.364a2 2 0 1 1 2.829 2.829l-1.768 1.767a2 2 0 1 1 2.828 2.829z",key:"nnl7wr"}],["path",{d:"m21.5 21.5-1.4-1.4",key:"1f1ice"}],["path",{d:"M3.9 3.9 2.5 2.5",key:"1evmna"}],["path",{d:"M6.404 12.768a2 2 0 1 1-2.829-2.829l1.768-1.767a2 2 0 1 1-2.828-2.829l2.828-2.828a2 2 0 1 1 2.829 2.828l1.767-1.768a2 2 0 1 1 2.829 2.829z",key:"yhosts"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const fm=te("Egg",[["path",{d:"M12 22c6.23-.05 7.87-5.57 7.5-10-.36-4.34-3.95-9.96-7.5-10-3.55.04-7.14 5.66-7.5 10-.37 4.43 1.27 9.95 7.5 10z",key:"1c39pg"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const pm=te("Fish",[["path",{d:"M6.5 12c.94-3.46 4.94-6 8.5-6 3.56 0 6.06 2.54 7 6-.94 3.47-3.44 6-7 6s-7.56-2.53-8.5-6Z",key:"15baut"}],["path",{d:"M18 12v.5",key:"18hhni"}],["path",{d:"M16 17.93a9.77 9.77 0 0 1 0-11.86",key:"16dt7o"}],["path",{d:"M7 10.67C7 8 5.58 5.97 2.73 5.5c-1 1.5-1 5 .23 6.5-1.24 1.5-1.24 5-.23 6.5C5.58 18.03 7 16 7 13.33",key:"l9di03"}],["path",{d:"M10.46 7.26C10.2 5.88 9.17 4.24 8 3h5.8a2 2 0 0 1 1.98 1.67l.23 1.4",key:"1kjonw"}],["path",{d:"m16.01 17.93-.23 1.4A2 2 0 0 1 13.8 21H9.5a5.96 5.96 0 0 0 1.49-3.98",key:"1zlm23"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const xm=te("Flower",[["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}],["path",{d:"M12 16.5A4.5 4.5 0 1 1 7.5 12 4.5 4.5 0 1 1 12 7.5a4.5 4.5 0 1 1 4.5 4.5 4.5 4.5 0 1 1-4.5 4.5",key:"14wa3c"}],["path",{d:"M12 7.5V9",key:"1oy5b0"}],["path",{d:"M7.5 12H9",key:"eltsq1"}],["path",{d:"M16.5 12H15",key:"vk5kw4"}],["path",{d:"M12 16.5V15",key:"k7eayi"}],["path",{d:"m8 8 1.88 1.88",key:"nxy4qf"}],["path",{d:"M14.12 9.88 16 8",key:"1lst6k"}],["path",{d:"m8 16 1.88-1.88",key:"h2eex1"}],["path",{d:"M14.12 14.12 16 16",key:"uqkrx3"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const gm=te("Fuel",[["line",{x1:"3",x2:"15",y1:"22",y2:"22",key:"xegly4"}],["line",{x1:"4",x2:"14",y1:"9",y2:"9",key:"xcnuvu"}],["path",{d:"M14 22V4a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v18",key:"16j0yd"}],["path",{d:"M14 13h2a2 2 0 0 1 2 2v2a2 2 0 0 0 2 2a2 2 0 0 0 2-2V9.83a2 2 0 0 0-.59-1.42L18 5",key:"7cu91f"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const bm=te("Gamepad2",[["line",{x1:"6",x2:"10",y1:"11",y2:"11",key:"1gktln"}],["line",{x1:"8",x2:"8",y1:"9",y2:"13",key:"qnk9ow"}],["line",{x1:"15",x2:"15.01",y1:"12",y2:"12",key:"krot7o"}],["line",{x1:"18",x2:"18.01",y1:"10",y2:"10",key:"1lcuu1"}],["path",{d:"M17.32 5H6.68a4 4 0 0 0-3.978 3.59c-.006.052-.01.101-.017.152C2.604 9.416 2 14.456 2 16a3 3 0 0 0 3 3c1 0 1.5-.5 2-1l1.414-1.414A2 2 0 0 1 9.828 16h4.344a2 2 0 0 1 1.414.586L17 18c.5.5 1 1 2 1a3 3 0 0 0 3-3c0-1.545-.604-6.584-.685-7.258-.007-.05-.011-.1-.017-.151A4 4 0 0 0 17.32 5z",key:"mfqc10"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const ym=te("Gem",[["path",{d:"M6 3h12l4 6-10 13L2 9Z",key:"1pcd5k"}],["path",{d:"M11 3 8 9l4 13 4-13-3-6",key:"1fcu3u"}],["path",{d:"M2 9h20",key:"16fsjt"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const ac=te("Gift",[["rect",{x:"3",y:"8",width:"18",height:"4",rx:"1",key:"bkv52"}],["path",{d:"M12 8v13",key:"1c76mn"}],["path",{d:"M19 12v7a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2v-7",key:"6wjy6b"}],["path",{d:"M7.5 8a2.5 2.5 0 0 1 0-5A4.8 8 0 0 1 12 8a4.8 8 0 0 1 4.5-5 2.5 2.5 0 0 1 0 5",key:"1ihvrl"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const vm=te("Glasses",[["circle",{cx:"6",cy:"15",r:"4",key:"vux9w4"}],["circle",{cx:"18",cy:"15",r:"4",key:"18o8ve"}],["path",{d:"M14 15a2 2 0 0 0-2-2 2 2 0 0 0-2 2",key:"1ag4bs"}],["path",{d:"M2.5 13 5 7c.7-1.3 1.4-2 3-2",key:"1hm1gs"}],["path",{d:"M21.5 13 19 7c-.7-1.3-1.5-2-3-2",key:"1r31ai"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const ic=te("GripVertical",[["circle",{cx:"9",cy:"12",r:"1",key:"1vctgf"}],["circle",{cx:"9",cy:"5",r:"1",key:"hp0tcf"}],["circle",{cx:"9",cy:"19",r:"1",key:"fkjjf6"}],["circle",{cx:"15",cy:"12",r:"1",key:"1tmaij"}],["circle",{cx:"15",cy:"5",r:"1",key:"19l28e"}],["circle",{cx:"15",cy:"19",r:"1",key:"f4zoj3"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const _m=te("Hammer",[["path",{d:"m15 12-8.373 8.373a1 1 0 1 1-3-3L12 9",key:"eefl8a"}],["path",{d:"m18 15 4-4",key:"16gjal"}],["path",{d:"m21.5 11.5-1.914-1.914A2 2 0 0 1 19 8.172V7l-2.26-2.26a6 6 0 0 0-4.202-1.756L9 2.96l.92.82A6.18 6.18 0 0 1 12 8.4V10l2 2h1.172a2 2 0 0 1 1.414.586L18.5 14.5",key:"b7pghm"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const wm=te("Hash",[["line",{x1:"4",x2:"20",y1:"9",y2:"9",key:"4lhtct"}],["line",{x1:"4",x2:"20",y1:"15",y2:"15",key:"vyu0kd"}],["line",{x1:"10",x2:"8",y1:"3",y2:"21",key:"1ggp8o"}],["line",{x1:"16",x2:"14",y1:"3",y2:"21",key:"weycgp"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const jm=te("Headphones",[["path",{d:"M3 14h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-7a9 9 0 0 1 18 0v7a2 2 0 0 1-2 2h-1a2 2 0 0 1-2-2v-3a2 2 0 0 1 2-2h3",key:"1xhozi"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Nm=te("Heart",[["path",{d:"M19 14c1.49-1.46 3-3.21 3-5.5A5.5 5.5 0 0 0 16.5 3c-1.76 0-3 .5-4.5 2-1.5-1.5-2.74-2-4.5-2A5.5 5.5 0 0 0 2 8.5c0 2.3 1.5 4.05 3 5.5l7 7Z",key:"c3ymky"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Ma=te("History",[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}],["path",{d:"M12 7v5l4 2",key:"1fdv2h"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const ys=te("House",[["path",{d:"M15 21v-8a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v8",key:"5wwlr5"}],["path",{d:"M3 10a2 2 0 0 1 .709-1.528l7-5.999a2 2 0 0 1 2.582 0l7 5.999A2 2 0 0 1 21 10v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z",key:"1d0kgt"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Cm=te("IceCreamCone",[["path",{d:"m7 11 4.08 10.35a1 1 0 0 0 1.84 0L17 11",key:"1v6356"}],["path",{d:"M17 7A5 5 0 0 0 7 7",key:"151p3v"}],["path",{d:"M17 7a2 2 0 0 1 0 4H7a2 2 0 0 1 0-4",key:"1sdaij"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const La=te("Images",[["path",{d:"M18 22H4a2 2 0 0 1-2-2V6",key:"pblm9e"}],["path",{d:"m22 13-1.296-1.296a2.41 2.41 0 0 0-3.408 0L11 18",key:"nf6bnh"}],["circle",{cx:"12",cy:"8",r:"2",key:"1822b1"}],["rect",{width:"16",height:"16",x:"6",y:"2",rx:"2",key:"12espp"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Em=te("Keyboard",[["path",{d:"M10 8h.01",key:"1r9ogq"}],["path",{d:"M12 12h.01",key:"1mp3jc"}],["path",{d:"M14 8h.01",key:"1primd"}],["path",{d:"M16 12h.01",key:"1l6xoz"}],["path",{d:"M18 8h.01",key:"emo2bl"}],["path",{d:"M6 8h.01",key:"x9i8wu"}],["path",{d:"M7 16h10",key:"wp8him"}],["path",{d:"M8 12h.01",key:"czm47f"}],["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",key:"18n3k1"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Sm=te("Lamp",[["path",{d:"M8 2h8l4 10H4L8 2Z",key:"9dma5w"}],["path",{d:"M12 12v6",key:"3ahymv"}],["path",{d:"M8 22v-2c0-1.1.9-2 2-2h4a2 2 0 0 1 2 2v2H8Z",key:"mwf4oh"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const km=te("Laptop",[["path",{d:"M20 16V7a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v9m16 0H4m16 0 1.28 2.55a1 1 0 0 1-.9 1.45H3.62a1 1 0 0 1-.9-1.45L4 16",key:"tarvll"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const rn=te("LogOut",[["path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4",key:"1uf3rs"}],["polyline",{points:"16 17 21 12 16 7",key:"1gabdz"}],["line",{x1:"21",x2:"9",y1:"12",y2:"12",key:"1uyos4"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Da=te("MapPin",[["path",{d:"M20 10c0 4.993-5.539 10.193-7.399 11.799a1 1 0 0 1-1.202 0C9.539 20.193 4 14.993 4 10a8 8 0 0 1 16 0",key:"1r0f0z"}],["circle",{cx:"12",cy:"10",r:"3",key:"ilqhr7"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Tm=te("Maximize2",[["polyline",{points:"15 3 21 3 21 9",key:"mznyad"}],["polyline",{points:"9 21 3 21 3 15",key:"1avn1i"}],["line",{x1:"21",x2:"14",y1:"3",y2:"10",key:"ota7mn"}],["line",{x1:"3",x2:"10",y1:"21",y2:"14",key:"1atl0r"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Am=te("Menu",[["line",{x1:"4",x2:"20",y1:"12",y2:"12",key:"1e0a9i"}],["line",{x1:"4",x2:"20",y1:"6",y2:"6",key:"1owob3"}],["line",{x1:"4",x2:"20",y1:"18",y2:"18",key:"yk5zj1"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Im=te("Milk",[["path",{d:"M8 2h8",key:"1ssgc1"}],["path",{d:"M9 2v2.789a4 4 0 0 1-.672 2.219l-.656.984A4 4 0 0 0 7 10.212V20a2 2 0 0 0 2 2h6a2 2 0 0 0 2-2v-9.789a4 4 0 0 0-.672-2.219l-.656-.984A4 4 0 0 1 15 4.788V2",key:"qtp12x"}],["path",{d:"M7 15a6.472 6.472 0 0 1 5 0 6.47 6.47 0 0 0 5 0",key:"ygeh44"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Om=te("Minus",[["path",{d:"M5 12h14",key:"1ays0h"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Rm=te("Moon",[["path",{d:"M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z",key:"a7tn18"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Pm=te("MousePointer2",[["path",{d:"M4.037 4.688a.495.495 0 0 1 .651-.651l16 6.5a.5.5 0 0 1-.063.947l-6.124 1.58a2 2 0 0 0-1.438 1.435l-1.579 6.126a.5.5 0 0 1-.947.063z",key:"edeuup"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Mm=te("Navigation",[["polygon",{points:"3 11 22 2 13 21 11 13 3 11",key:"1ltx0t"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const cc=te("PanelsTopLeft",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M3 9h18",key:"1pudct"}],["path",{d:"M9 21V9",key:"1oto5p"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Lm=te("PenTool",[["path",{d:"M15.707 21.293a1 1 0 0 1-1.414 0l-1.586-1.586a1 1 0 0 1 0-1.414l5.586-5.586a1 1 0 0 1 1.414 0l1.586 1.586a1 1 0 0 1 0 1.414z",key:"nt11vn"}],["path",{d:"m18 13-1.375-6.874a1 1 0 0 0-.746-.776L3.235 2.028a1 1 0 0 0-1.207 1.207L5.35 15.879a1 1 0 0 0 .776.746L13 18",key:"15qc1e"}],["path",{d:"m2.3 2.3 7.286 7.286",key:"1wuzzi"}],["circle",{cx:"11",cy:"11",r:"2",key:"xmgehs"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const $a=te("Phone",[["path",{d:"M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z",key:"foiqr5"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Dm=te("Pill",[["path",{d:"m10.5 20.5 10-10a4.95 4.95 0 1 0-7-7l-10 10a4.95 4.95 0 1 0 7 7Z",key:"wa1lgi"}],["path",{d:"m8.5 8.5 7 7",key:"rvfmvr"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const $m=te("Pizza",[["path",{d:"m12 14-1 1",key:"11onhr"}],["path",{d:"m13.75 18.25-1.25 1.42",key:"1yisr3"}],["path",{d:"M17.775 5.654a15.68 15.68 0 0 0-12.121 12.12",key:"1qtqk6"}],["path",{d:"M18.8 9.3a1 1 0 0 0 2.1 7.7",key:"fbbbr2"}],["path",{d:"M21.964 20.732a1 1 0 0 1-1.232 1.232l-18-5a1 1 0 0 1-.695-1.232A19.68 19.68 0 0 1 15.732 2.037a1 1 0 0 1 1.232.695z",key:"1hyfdd"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Fm=te("Sandwich",[["path",{d:"m2.37 11.223 8.372-6.777a2 2 0 0 1 2.516 0l8.371 6.777",key:"f1wd0e"}],["path",{d:"M21 15a1 1 0 0 1 1 1v2a1 1 0 0 1-1 1h-5.25",key:"1pfu07"}],["path",{d:"M3 15a1 1 0 0 0-1 1v2a1 1 0 0 0 1 1h9",key:"1oq9qw"}],["path",{d:"m6.67 15 6.13 4.6a2 2 0 0 0 2.8-.4l3.15-4.2",key:"1fnwu5"}],["rect",{width:"20",height:"4",x:"2",y:"11",rx:"1",key:"itshg"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Ls=te("Scan",[["path",{d:"M3 7V5a2 2 0 0 1 2-2h2",key:"aa7l1z"}],["path",{d:"M17 3h2a2 2 0 0 1 2 2v2",key:"4qcy5o"}],["path",{d:"M21 17v2a2 2 0 0 1-2 2h-2",key:"6vwrx8"}],["path",{d:"M7 21H5a2 2 0 0 1-2-2v-2",key:"ioqczr"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Um=te("Scissors",[["circle",{cx:"6",cy:"6",r:"3",key:"1lh9wr"}],["path",{d:"M8.12 8.12 12 12",key:"1alkpv"}],["path",{d:"M20 4 8.12 15.88",key:"xgtan2"}],["circle",{cx:"6",cy:"18",r:"3",key:"fqmcym"}],["path",{d:"M14.8 14.8 20 20",key:"ptml3r"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const zm=te("Send",[["path",{d:"M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z",key:"1ffxy3"}],["path",{d:"m21.854 2.147-10.94 10.939",key:"12cjpa"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Bm=te("Shirt",[["path",{d:"M20.38 3.46 16 2a4 4 0 0 1-8 0L3.62 3.46a2 2 0 0 0-1.34 2.23l.58 3.47a1 1 0 0 0 .99.84H6v10c0 1.1.9 2 2 2h8a2 2 0 0 0 2-2V10h2.15a1 1 0 0 0 .99-.84l.58-3.47a2 2 0 0 0-1.34-2.23z",key:"1wgbhj"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const qm=te("ShoppingBag",[["path",{d:"M6 2 3 6v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6l-3-4Z",key:"hou9p0"}],["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M16 10a4 4 0 0 1-8 0",key:"1ltviw"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Xr=te("ShoppingCart",[["circle",{cx:"8",cy:"21",r:"1",key:"jimo8o"}],["circle",{cx:"19",cy:"21",r:"1",key:"13723u"}],["path",{d:"M2.05 2.05h2l2.66 12.42a2 2 0 0 0 2 1.58h9.78a2 2 0 0 0 1.95-1.57l1.65-7.43H5.12",key:"9zh506"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Vm=te("Snowflake",[["line",{x1:"2",x2:"22",y1:"12",y2:"12",key:"1dnqot"}],["line",{x1:"12",x2:"12",y1:"2",y2:"22",key:"7eqyqh"}],["path",{d:"m20 16-4-4 4-4",key:"rquw4f"}],["path",{d:"m4 8 4 4-4 4",key:"12s3z9"}],["path",{d:"m16 4-4 4-4-4",key:"1tumq1"}],["path",{d:"m8 20 4-4 4 4",key:"9p200w"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Gm=te("Sofa",[["path",{d:"M20 9V6a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v3",key:"1dgpiv"}],["path",{d:"M2 16a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-5a2 2 0 0 0-4 0v1.5a.5.5 0 0 1-.5.5h-11a.5.5 0 0 1-.5-.5V11a2 2 0 0 0-4 0z",key:"xacw8m"}],["path",{d:"M4 18v2",key:"jwo5n2"}],["path",{d:"M20 18v2",key:"1ar1qi"}],["path",{d:"M12 4v9",key:"oqhhn3"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Hm=te("SprayCan",[["path",{d:"M3 3h.01",key:"159qn6"}],["path",{d:"M7 5h.01",key:"1hq22a"}],["path",{d:"M11 7h.01",key:"1osv80"}],["path",{d:"M3 7h.01",key:"1xzrh3"}],["path",{d:"M7 9h.01",key:"19b3jx"}],["path",{d:"M3 11h.01",key:"1eifu7"}],["rect",{width:"4",height:"4",x:"15",y:"5",key:"mri9e4"}],["path",{d:"m19 9 2 2v10c0 .6-.4 1-1 1h-6c-.6 0-1-.4-1-1V11l2-2",key:"aib6hk"}],["path",{d:"m13 14 8-2",key:"1d7bmk"}],["path",{d:"m13 19 8-2",key:"1y2vml"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const An=te("Star",[["path",{d:"M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z",key:"r04s7s"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Wm=te("Stethoscope",[["path",{d:"M11 2v2",key:"1539x4"}],["path",{d:"M5 2v2",key:"1yf1q8"}],["path",{d:"M5 3H4a2 2 0 0 0-2 2v4a6 6 0 0 0 12 0V5a2 2 0 0 0-2-2h-1",key:"rb5t3r"}],["path",{d:"M8 15a6 6 0 0 0 12 0v-3",key:"x18d4x"}],["circle",{cx:"20",cy:"10",r:"2",key:"ts1r5v"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Xm=te("Sun",[["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M12 20v2",key:"1lh1kg"}],["path",{d:"m4.93 4.93 1.41 1.41",key:"149t6j"}],["path",{d:"m17.66 17.66 1.41 1.41",key:"ptbguv"}],["path",{d:"M2 12h2",key:"1t8f8n"}],["path",{d:"M20 12h2",key:"1q8mjw"}],["path",{d:"m6.34 17.66-1.41 1.41",key:"1m8zz5"}],["path",{d:"m19.07 4.93-1.41 1.41",key:"1shlcs"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Ar=te("Trash2",[["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6",key:"4alrt4"}],["path",{d:"M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2",key:"v07s0e"}],["line",{x1:"10",x2:"10",y1:"11",y2:"17",key:"1uufr5"}],["line",{x1:"14",x2:"14",y1:"11",y2:"17",key:"xtxkd"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Jm=te("TreeDeciduous",[["path",{d:"M8 19a4 4 0 0 1-2.24-7.32A3.5 3.5 0 0 1 9 6.03V6a3 3 0 1 1 6 0v.04a3.5 3.5 0 0 1 3.24 5.65A4 4 0 0 1 16 19Z",key:"oadzkq"}],["path",{d:"M12 19v3",key:"npa21l"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Km=te("TrendingDown",[["polyline",{points:"22 17 13.5 8.5 8.5 13.5 2 7",key:"1r2t7k"}],["polyline",{points:"16 17 22 17 22 11",key:"11uiuu"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Ym=te("TrendingUp",[["polyline",{points:"22 7 13.5 15.5 8.5 10.5 2 17",key:"126l90"}],["polyline",{points:"16 7 22 7 22 13",key:"kwv8wd"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Qm=te("Truck",[["path",{d:"M14 18V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v11a1 1 0 0 0 1 1h2",key:"wrbu53"}],["path",{d:"M15 18H9",key:"1lyqi6"}],["path",{d:"M19 18h2a1 1 0 0 0 1-1v-3.65a1 1 0 0 0-.22-.624l-3.48-4.35A1 1 0 0 0 17.52 8H14",key:"lysw3i"}],["circle",{cx:"17",cy:"18",r:"2",key:"332jqn"}],["circle",{cx:"7",cy:"18",r:"2",key:"19iecd"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Zm=te("Tv",[["rect",{width:"20",height:"15",x:"2",y:"7",rx:"2",ry:"2",key:"10ag99"}],["polyline",{points:"17 2 12 7 7 2",key:"11pgbg"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const eh=te("Upload",[["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["polyline",{points:"17 8 12 3 7 8",key:"t8dd8p"}],["line",{x1:"12",x2:"12",y1:"3",y2:"15",key:"widbto"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const lc=te("UserCog",[["circle",{cx:"18",cy:"15",r:"3",key:"gjjjvw"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["path",{d:"M10 15H6a4 4 0 0 0-4 4v2",key:"1nfge6"}],["path",{d:"m21.7 16.4-.9-.3",key:"12j9ji"}],["path",{d:"m15.2 13.9-.9-.3",key:"1fdjdi"}],["path",{d:"m16.6 18.7.3-.9",key:"heedtr"}],["path",{d:"m19.1 12.2.3-.9",key:"1af3ki"}],["path",{d:"m19.6 18.7-.4-1",key:"1x9vze"}],["path",{d:"m16.8 12.3-.4-1",key:"vqeiwj"}],["path",{d:"m14.3 16.6 1-.4",key:"1qlj63"}],["path",{d:"m20.7 13.8 1-.4",key:"1v5t8k"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const th=te("UserX",[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["line",{x1:"17",x2:"22",y1:"8",y2:"13",key:"3nzzx3"}],["line",{x1:"22",x2:"17",y1:"8",y2:"13",key:"1swrse"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const rh=te("UtensilsCrossed",[["path",{d:"m16 2-2.3 2.3a3 3 0 0 0 0 4.2l1.8 1.8a3 3 0 0 0 4.2 0L22 8",key:"n7qcjb"}],["path",{d:"M15 15 3.3 3.3a4.2 4.2 0 0 0 0 6l7.3 7.3c.7.7 2 .7 2.8 0L15 15Zm0 0 7 7",key:"d0u48b"}],["path",{d:"m2.1 21.8 6.4-6.3",key:"yn04lh"}],["path",{d:"m19 5-7 7",key:"194lzd"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const nh=te("Volume2",[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z",key:"uqj9uw"}],["path",{d:"M16 9a5 5 0 0 1 0 6",key:"1q6k2b"}],["path",{d:"M19.364 18.364a9 9 0 0 0 0-12.728",key:"ijwkga"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const sh=te("VolumeX",[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z",key:"uqj9uw"}],["line",{x1:"22",x2:"16",y1:"9",y2:"15",key:"1ewh16"}],["line",{x1:"16",x2:"22",y1:"9",y2:"15",key:"5ykzw1"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const oh=te("Volume",[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z",key:"uqj9uw"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Ds=te("Wallet",[["path",{d:"M19 7V4a1 1 0 0 0-1-1H5a2 2 0 0 0 0 4h15a1 1 0 0 1 1 1v4h-3a2 2 0 0 0 0 4h3a1 1 0 0 0 1-1v-2a1 1 0 0 0-1-1",key:"18etb6"}],["path",{d:"M3 5v14a2 2 0 0 0 2 2h15a1 1 0 0 0 1-1v-4",key:"xoc0q4"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const ah=te("Watch",[["circle",{cx:"12",cy:"12",r:"6",key:"1vlfrh"}],["polyline",{points:"12 10 12 12 13 13",key:"19dquz"}],["path",{d:"m16.13 7.66-.81-4.05a2 2 0 0 0-2-1.61h-2.68a2 2 0 0 0-2 1.61l-.78 4.05",key:"18k57s"}],["path",{d:"m7.88 16.36.8 4a2 2 0 0 0 2 1.61h2.72a2 2 0 0 0 2-1.61l.81-4.05",key:"16ny36"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const ih=te("Wheat",[["path",{d:"M2 22 16 8",key:"60hf96"}],["path",{d:"M3.47 12.53 5 11l1.53 1.53a3.5 3.5 0 0 1 0 4.94L5 19l-1.53-1.53a3.5 3.5 0 0 1 0-4.94Z",key:"1rdhi6"}],["path",{d:"M7.47 8.53 9 7l1.53 1.53a3.5 3.5 0 0 1 0 4.94L9 15l-1.53-1.53a3.5 3.5 0 0 1 0-4.94Z",key:"1sdzmb"}],["path",{d:"M11.47 4.53 13 3l1.53 1.53a3.5 3.5 0 0 1 0 4.94L13 11l-1.53-1.53a3.5 3.5 0 0 1 0-4.94Z",key:"eoatbi"}],["path",{d:"M20 2h2v2a4 4 0 0 1-4 4h-2V6a4 4 0 0 1 4-4Z",key:"19rau1"}],["path",{d:"M11.47 17.47 13 19l-1.53 1.53a3.5 3.5 0 0 1-4.94 0L5 19l1.53-1.53a3.5 3.5 0 0 1 4.94 0Z",key:"tc8ph9"}],["path",{d:"M15.47 13.47 17 15l-1.53 1.53a3.5 3.5 0 0 1-4.94 0L9 15l1.53-1.53a3.5 3.5 0 0 1 4.94 0Z",key:"2m8kc5"}],["path",{d:"M19.47 9.47 21 11l-1.53 1.53a3.5 3.5 0 0 1-4.94 0L13 11l1.53-1.53a3.5 3.5 0 0 1 4.94 0Z",key:"vex3ng"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const ch=te("Wine",[["path",{d:"M8 22h8",key:"rmew8v"}],["path",{d:"M7 10h10",key:"1101jm"}],["path",{d:"M12 15v7",key:"t2xh3l"}],["path",{d:"M12 15a5 5 0 0 0 5-5c0-2-.5-4-2-8H9c-1.5 4-2 6-2 8a5 5 0 0 0 5 5Z",key:"10ffi3"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const lh=te("Wrench",[["path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z",key:"cbrjhi"}]]);var Fa=1,dh=.9,uh=.8,mh=.17,Zs=.1,eo=.999,hh=.9999,fh=.99,ph=/[\\\/_+.#"@\[\(\{&]/,xh=/[\\\/_+.#"@\[\(\{&]/g,gh=/[\s-]/,dc=/[\s-]/g;function xo(t,r,n,i,o,a,s){if(a===r.length)return o===t.length?Fa:fh;var c=`${o},${a}`;if(s[c]!==void 0)return s[c];for(var l=i.charAt(a),m=n.indexOf(l,o),u=0,d,h,p,f;m>=0;)d=xo(t,r,n,i,m+1,a+1,s),d>u&&(m===o?d*=Fa:ph.test(t.charAt(m-1))?(d*=uh,p=t.slice(o,m-1).match(xh),p&&o>0&&(d*=Math.pow(eo,p.length))):gh.test(t.charAt(m-1))?(d*=dh,f=t.slice(o,m-1).match(dc),f&&o>0&&(d*=Math.pow(eo,f.length))):(d*=mh,o>0&&(d*=Math.pow(eo,m-o))),t.charAt(m)!==r.charAt(a)&&(d*=hh)),(d<Zs&&n.charAt(m-1)===i.charAt(a+1)||i.charAt(a+1)===i.charAt(a)&&n.charAt(m-1)!==i.charAt(a))&&(h=xo(t,r,n,i,m+1,a+2,s),h*Zs>d&&(d=h*Zs)),d>u&&(u=d),m=n.indexOf(l,m+1);return s[c]=u,u}function Ua(t){return t.toLowerCase().replace(dc," ")}function bh(t,r,n){return t=n&&n.length>0?`${t+" "+n.join(" ")}`:t,xo(t,r,Ua(t),Ua(r),0,0,{})}function za(t,r){if(typeof t=="function")return t(r);t!=null&&(t.current=r)}function nn(...t){return r=>{let n=!1;const i=t.map(o=>{const a=za(o,r);return!n&&typeof a=="function"&&(n=!0),a});if(n)return()=>{for(let o=0;o<i.length;o++){const a=i[o];typeof a=="function"?a():za(t[o],null)}}}}var yh=Symbol.for("react.lazy"),vs=su[" use ".trim().toString()];function vh(t){return typeof t=="object"&&t!==null&&"then"in t}function uc(t){return t!=null&&typeof t=="object"&&"$$typeof"in t&&t.$$typeof===yh&&"_payload"in t&&vh(t._payload)}function _h(t){const r=wh(t),n=v.forwardRef((i,o)=>{let{children:a,...s}=i;uc(a)&&typeof vs=="function"&&(a=vs(a._payload));const c=v.Children.toArray(a),l=c.find(Nh);if(l){const m=l.props.children,u=c.map(d=>d===l?v.Children.count(m)>1?v.Children.only(null):v.isValidElement(m)?m.props.children:null:d);return e.jsx(r,{...s,ref:o,children:v.isValidElement(m)?v.cloneElement(m,void 0,u):null})}return e.jsx(r,{...s,ref:o,children:a})});return n.displayName=`${t}.Slot`,n}function wh(t){const r=v.forwardRef((n,i)=>{let{children:o,...a}=n;if(uc(o)&&typeof vs=="function"&&(o=vs(o._payload)),v.isValidElement(o)){const s=Eh(o),c=Ch(a,o.props);return o.type!==v.Fragment&&(c.ref=i?nn(i,s):s),v.cloneElement(o,c)}return v.Children.count(o)>1?v.Children.only(null):null});return r.displayName=`${t}.SlotClone`,r}var jh=Symbol("radix.slottable");function Nh(t){return v.isValidElement(t)&&typeof t.type=="function"&&"__radixId"in t.type&&t.type.__radixId===jh}function Ch(t,r){const n={...r};for(const i in r){const o=t[i],a=r[i];/^on[A-Z]/.test(i)?o&&a?n[i]=(...c)=>{const l=a(...c);return o(...c),l}:o&&(n[i]=o):i==="style"?n[i]={...o,...a}:i==="className"&&(n[i]=[o,a].filter(Boolean).join(" "))}return{...t,...n}}function Eh(t){var i,o;let r=(i=Object.getOwnPropertyDescriptor(t.props,"ref"))==null?void 0:i.get,n=r&&"isReactWarning"in r&&r.isReactWarning;return n?t.ref:(r=(o=Object.getOwnPropertyDescriptor(t,"ref"))==null?void 0:o.get,n=r&&"isReactWarning"in r&&r.isReactWarning,n?t.props.ref:t.props.ref||t.ref)}var Sh=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],wr=Sh.reduce((t,r)=>{const n=_h(`Primitive.${r}`),i=v.forwardRef((o,a)=>{const{asChild:s,...c}=o,l=s?n:r;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),e.jsx(l,{...c,ref:a})});return i.displayName=`Primitive.${r}`,{...t,[r]:i}},{}),yn='[cmdk-group=""]',to='[cmdk-group-items=""]',kh='[cmdk-group-heading=""]',mc='[cmdk-item=""]',Ba=`${mc}:not([aria-disabled="true"])`,go="cmdk-item-select",zr="data-value",Th=(t,r,n)=>bh(t,r,n),hc=v.createContext(void 0),zn=()=>v.useContext(hc),fc=v.createContext(void 0),Ho=()=>v.useContext(fc),pc=v.createContext(void 0),xc=v.forwardRef((t,r)=>{let n=Br(()=>{var U,Q;return{search:"",value:(Q=(U=t.value)!=null?U:t.defaultValue)!=null?Q:"",selectedItemId:void 0,filtered:{count:0,items:new Map,groups:new Set}}}),i=Br(()=>new Set),o=Br(()=>new Map),a=Br(()=>new Map),s=Br(()=>new Set),c=gc(t),{label:l,children:m,value:u,onValueChange:d,filter:h,shouldFilter:p,loop:f,disablePointerSelection:x=!1,vimBindings:g=!0,...b}=t,y=ir(),_=ir(),j=ir(),I=v.useRef(null),w=Uh();Ir(()=>{if(u!==void 0){let U=u.trim();n.current.value=U,N.emit()}},[u]),Ir(()=>{w(6,P)},[]);let N=v.useMemo(()=>({subscribe:U=>(s.current.add(U),()=>s.current.delete(U)),snapshot:()=>n.current,setState:(U,Q,B)=>{var z,H,Y,J;if(!Object.is(n.current[U],Q)){if(n.current[U]=Q,U==="search")k(),F(),w(1,T);else if(U==="value"){if(document.activeElement.hasAttribute("cmdk-input")||document.activeElement.hasAttribute("cmdk-root")){let ie=document.getElementById(j);ie?ie.focus():(z=document.getElementById(y))==null||z.focus()}if(w(7,()=>{var ie;n.current.selectedItemId=(ie=S())==null?void 0:ie.id,N.emit()}),B||w(5,P),((H=c.current)==null?void 0:H.value)!==void 0){let ie=Q??"";(J=(Y=c.current).onValueChange)==null||J.call(Y,ie);return}}N.emit()}},emit:()=>{s.current.forEach(U=>U())}}),[]),C=v.useMemo(()=>({value:(U,Q,B)=>{var z;Q!==((z=a.current.get(U))==null?void 0:z.value)&&(a.current.set(U,{value:Q,keywords:B}),n.current.filtered.items.set(U,A(Q,B)),w(2,()=>{F(),N.emit()}))},item:(U,Q)=>(i.current.add(U),Q&&(o.current.has(Q)?o.current.get(Q).add(U):o.current.set(Q,new Set([U]))),w(3,()=>{k(),F(),n.current.value||T(),N.emit()}),()=>{a.current.delete(U),i.current.delete(U),n.current.filtered.items.delete(U);let B=S();w(4,()=>{k(),(B==null?void 0:B.getAttribute("id"))===U&&T(),N.emit()})}),group:U=>(o.current.has(U)||o.current.set(U,new Set),()=>{a.current.delete(U),o.current.delete(U)}),filter:()=>c.current.shouldFilter,label:l||t["aria-label"],getDisablePointerSelection:()=>c.current.disablePointerSelection,listId:y,inputId:j,labelId:_,listInnerRef:I}),[]);function A(U,Q){var B,z;let H=(z=(B=c.current)==null?void 0:B.filter)!=null?z:Th;return U?H(U,n.current.search,Q):0}function F(){if(!n.current.search||c.current.shouldFilter===!1)return;let U=n.current.filtered.items,Q=[];n.current.filtered.groups.forEach(z=>{let H=o.current.get(z),Y=0;H.forEach(J=>{let ie=U.get(J);Y=Math.max(ie,Y)}),Q.push([z,Y])});let B=I.current;E().sort((z,H)=>{var Y,J;let ie=z.getAttribute("id"),ce=H.getAttribute("id");return((Y=U.get(ce))!=null?Y:0)-((J=U.get(ie))!=null?J:0)}).forEach(z=>{let H=z.closest(to);H?H.appendChild(z.parentElement===H?z:z.closest(`${to} > *`)):B.appendChild(z.parentElement===B?z:z.closest(`${to} > *`))}),Q.sort((z,H)=>H[1]-z[1]).forEach(z=>{var H;let Y=(H=I.current)==null?void 0:H.querySelector(`${yn}[${zr}="${encodeURIComponent(z[0])}"]`);Y==null||Y.parentElement.appendChild(Y)})}function T(){let U=E().find(B=>B.getAttribute("aria-disabled")!=="true"),Q=U==null?void 0:U.getAttribute(zr);N.setState("value",Q||void 0)}function k(){var U,Q,B,z;if(!n.current.search||c.current.shouldFilter===!1){n.current.filtered.count=i.current.size;return}n.current.filtered.groups=new Set;let H=0;for(let Y of i.current){let J=(Q=(U=a.current.get(Y))==null?void 0:U.value)!=null?Q:"",ie=(z=(B=a.current.get(Y))==null?void 0:B.keywords)!=null?z:[],ce=A(J,ie);n.current.filtered.items.set(Y,ce),ce>0&&H++}for(let[Y,J]of o.current)for(let ie of J)if(n.current.filtered.items.get(ie)>0){n.current.filtered.groups.add(Y);break}n.current.filtered.count=H}function P(){var U,Q,B;let z=S();z&&(((U=z.parentElement)==null?void 0:U.firstChild)===z&&((B=(Q=z.closest(yn))==null?void 0:Q.querySelector(kh))==null||B.scrollIntoView({block:"nearest"})),z.scrollIntoView({block:"nearest"}))}function S(){var U;return(U=I.current)==null?void 0:U.querySelector(`${mc}[aria-selected="true"]`)}function E(){var U;return Array.from(((U=I.current)==null?void 0:U.querySelectorAll(Ba))||[])}function O(U){let Q=E()[U];Q&&N.setState("value",Q.getAttribute(zr))}function R(U){var Q;let B=S(),z=E(),H=z.findIndex(J=>J===B),Y=z[H+U];(Q=c.current)!=null&&Q.loop&&(Y=H+U<0?z[z.length-1]:H+U===z.length?z[0]:z[H+U]),Y&&N.setState("value",Y.getAttribute(zr))}function D(U){let Q=S(),B=Q==null?void 0:Q.closest(yn),z;for(;B&&!z;)B=U>0?$h(B,yn):Fh(B,yn),z=B==null?void 0:B.querySelector(Ba);z?N.setState("value",z.getAttribute(zr)):R(U)}let $=()=>O(E().length-1),M=U=>{U.preventDefault(),U.metaKey?$():U.altKey?D(1):R(1)},X=U=>{U.preventDefault(),U.metaKey?O(0):U.altKey?D(-1):R(-1)};return v.createElement(wr.div,{ref:r,tabIndex:-1,...b,"cmdk-root":"",onKeyDown:U=>{var Q;(Q=b.onKeyDown)==null||Q.call(b,U);let B=U.nativeEvent.isComposing||U.keyCode===229;if(!(U.defaultPrevented||B))switch(U.key){case"n":case"j":{g&&U.ctrlKey&&M(U);break}case"ArrowDown":{M(U);break}case"p":case"k":{g&&U.ctrlKey&&X(U);break}case"ArrowUp":{X(U);break}case"Home":{U.preventDefault(),O(0);break}case"End":{U.preventDefault(),$();break}case"Enter":{U.preventDefault();let z=S();if(z){let H=new Event(go);z.dispatchEvent(H)}}}}},v.createElement("label",{"cmdk-label":"",htmlFor:C.inputId,id:C.labelId,style:Bh},l),$s(t,U=>v.createElement(fc.Provider,{value:N},v.createElement(hc.Provider,{value:C},U))))}),Ah=v.forwardRef((t,r)=>{var n,i;let o=ir(),a=v.useRef(null),s=v.useContext(pc),c=zn(),l=gc(t),m=(i=(n=l.current)==null?void 0:n.forceMount)!=null?i:s==null?void 0:s.forceMount;Ir(()=>{if(!m)return c.item(o,s==null?void 0:s.id)},[m]);let u=bc(o,a,[t.value,t.children,a],t.keywords),d=Ho(),h=br(w=>w.value&&w.value===u.current),p=br(w=>m||c.filter()===!1?!0:w.search?w.filtered.items.get(o)>0:!0);v.useEffect(()=>{let w=a.current;if(!(!w||t.disabled))return w.addEventListener(go,f),()=>w.removeEventListener(go,f)},[p,t.onSelect,t.disabled]);function f(){var w,N;x(),(N=(w=l.current).onSelect)==null||N.call(w,u.current)}function x(){d.setState("value",u.current,!0)}if(!p)return null;let{disabled:g,value:b,onSelect:y,forceMount:_,keywords:j,...I}=t;return v.createElement(wr.div,{ref:nn(a,r),...I,id:o,"cmdk-item":"",role:"option","aria-disabled":!!g,"aria-selected":!!h,"data-disabled":!!g,"data-selected":!!h,onPointerMove:g||c.getDisablePointerSelection()?void 0:x,onClick:g?void 0:f},t.children)}),Ih=v.forwardRef((t,r)=>{let{heading:n,children:i,forceMount:o,...a}=t,s=ir(),c=v.useRef(null),l=v.useRef(null),m=ir(),u=zn(),d=br(p=>o||u.filter()===!1?!0:p.search?p.filtered.groups.has(s):!0);Ir(()=>u.group(s),[]),bc(s,c,[t.value,t.heading,l]);let h=v.useMemo(()=>({id:s,forceMount:o}),[o]);return v.createElement(wr.div,{ref:nn(c,r),...a,"cmdk-group":"",role:"presentation",hidden:d?void 0:!0},n&&v.createElement("div",{ref:l,"cmdk-group-heading":"","aria-hidden":!0,id:m},n),$s(t,p=>v.createElement("div",{"cmdk-group-items":"",role:"group","aria-labelledby":n?m:void 0},v.createElement(pc.Provider,{value:h},p))))}),Oh=v.forwardRef((t,r)=>{let{alwaysRender:n,...i}=t,o=v.useRef(null),a=br(s=>!s.search);return!n&&!a?null:v.createElement(wr.div,{ref:nn(o,r),...i,"cmdk-separator":"",role:"separator"})}),Rh=v.forwardRef((t,r)=>{let{onValueChange:n,...i}=t,o=t.value!=null,a=Ho(),s=br(m=>m.search),c=br(m=>m.selectedItemId),l=zn();return v.useEffect(()=>{t.value!=null&&a.setState("search",t.value)},[t.value]),v.createElement(wr.input,{ref:r,...i,"cmdk-input":"",autoComplete:"off",autoCorrect:"off",spellCheck:!1,"aria-autocomplete":"list",role:"combobox","aria-expanded":!0,"aria-controls":l.listId,"aria-labelledby":l.labelId,"aria-activedescendant":c,id:l.inputId,type:"text",value:o?t.value:s,onChange:m=>{o||a.setState("search",m.target.value),n==null||n(m.target.value)}})}),Ph=v.forwardRef((t,r)=>{let{children:n,label:i="Suggestions",...o}=t,a=v.useRef(null),s=v.useRef(null),c=br(m=>m.selectedItemId),l=zn();return v.useEffect(()=>{if(s.current&&a.current){let m=s.current,u=a.current,d,h=new ResizeObserver(()=>{d=requestAnimationFrame(()=>{let p=m.offsetHeight;u.style.setProperty("--cmdk-list-height",p.toFixed(1)+"px")})});return h.observe(m),()=>{cancelAnimationFrame(d),h.unobserve(m)}}},[]),v.createElement(wr.div,{ref:nn(a,r),...o,"cmdk-list":"",role:"listbox",tabIndex:-1,"aria-activedescendant":c,"aria-label":i,id:l.listId},$s(t,m=>v.createElement("div",{ref:nn(s,l.listInnerRef),"cmdk-list-sizer":""},m)))}),Mh=v.forwardRef((t,r)=>{let{open:n,onOpenChange:i,overlayClassName:o,contentClassName:a,container:s,...c}=t;return v.createElement(Ki,{open:n,onOpenChange:i},v.createElement(Yi,{container:s},v.createElement(Fo,{"cmdk-overlay":"",className:o}),v.createElement(Uo,{"aria-label":t.label,"cmdk-dialog":"",className:a},v.createElement(xc,{ref:r,...c}))))}),Lh=v.forwardRef((t,r)=>br(n=>n.filtered.count===0)?v.createElement(wr.div,{ref:r,...t,"cmdk-empty":"",role:"presentation"}):null),Dh=v.forwardRef((t,r)=>{let{progress:n,children:i,label:o="Loading...",...a}=t;return v.createElement(wr.div,{ref:r,...a,"cmdk-loading":"",role:"progressbar","aria-valuenow":n,"aria-valuemin":0,"aria-valuemax":100,"aria-label":o},$s(t,s=>v.createElement("div",{"aria-hidden":!0},s)))}),Ct=Object.assign(xc,{List:Ph,Item:Ah,Input:Rh,Group:Ih,Separator:Oh,Dialog:Mh,Empty:Lh,Loading:Dh});function $h(t,r){let n=t.nextElementSibling;for(;n;){if(n.matches(r))return n;n=n.nextElementSibling}}function Fh(t,r){let n=t.previousElementSibling;for(;n;){if(n.matches(r))return n;n=n.previousElementSibling}}function gc(t){let r=v.useRef(t);return Ir(()=>{r.current=t}),r}var Ir=typeof window>"u"?v.useEffect:v.useLayoutEffect;function Br(t){let r=v.useRef();return r.current===void 0&&(r.current=t()),r}function br(t){let r=Ho(),n=()=>t(r.snapshot());return v.useSyncExternalStore(r.subscribe,n,n)}function bc(t,r,n,i=[]){let o=v.useRef(),a=zn();return Ir(()=>{var s;let c=(()=>{var m;for(let u of n){if(typeof u=="string")return u.trim();if(typeof u=="object"&&"current"in u)return u.current?(m=u.current.textContent)==null?void 0:m.trim():o.current}})(),l=i.map(m=>m.trim());a.value(t,c,l),(s=r.current)==null||s.setAttribute(zr,c),o.current=c}),o}var Uh=()=>{let[t,r]=v.useState(),n=Br(()=>new Map);return Ir(()=>{n.current.forEach(i=>i()),n.current=new Map},[t]),(i,o)=>{n.current.set(i,o),r({})}};function zh(t){let r=t.type;return typeof r=="function"?r(t.props):"render"in r?r.render(t.props):t}function $s({asChild:t,children:r},n){return t&&v.isValidElement(r)?v.cloneElement(zh(r),{ref:r.ref},n(r.props.children)):n(r)}var Bh={position:"absolute",width:"1px",height:"1px",padding:"0",margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0"};const Wo=v.forwardRef(({className:t,...r},n)=>e.jsx(Ct,{ref:n,className:Z("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",t),...r}));Wo.displayName=Ct.displayName;const qh=({children:t,...r})=>e.jsx(gt,{...r,children:e.jsx(bt,{className:"overflow-hidden p-0 shadow-lg",children:e.jsx(Wo,{className:"[&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-group]]:px-2 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-12 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-3 [&_[cmdk-item]_svg]:h-5 [&_[cmdk-item]_svg]:w-5",children:t})})}),Xo=v.forwardRef(({className:t,...r},n)=>e.jsxs("div",{className:"flex items-center border-b px-3","cmdk-input-wrapper":"",children:[e.jsx(zt,{className:"mr-2 h-4 w-4 shrink-0 opacity-50"}),e.jsx(Ct.Input,{ref:n,className:Z("flex h-11 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",t),...r})]}));Xo.displayName=Ct.Input.displayName;const Jo=v.forwardRef(({className:t,...r},n)=>e.jsx(Ct.List,{ref:n,className:Z("max-h-[300px] overflow-y-auto overflow-x-hidden",t),...r}));Jo.displayName=Ct.List.displayName;const Ko=v.forwardRef((t,r)=>e.jsx(Ct.Empty,{ref:r,className:"py-6 text-center text-sm",...t}));Ko.displayName=Ct.Empty.displayName;const Yo=v.forwardRef(({className:t,...r},n)=>e.jsx(Ct.Group,{ref:n,className:Z("overflow-hidden p-1 text-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",t),...r}));Yo.displayName=Ct.Group.displayName;const yc=v.forwardRef(({className:t,...r},n)=>e.jsx(Ct.Separator,{ref:n,className:Z("-mx-1 h-px bg-border",t),...r}));yc.displayName=Ct.Separator.displayName;const _s=v.forwardRef(({className:t,...r},n)=>e.jsx(Ct.Item,{ref:n,className:Z("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none data-[disabled=true]:pointer-events-none data-[selected='true']:bg-accent data-[selected=true]:text-accent-foreground data-[disabled=true]:opacity-50",t),...r}));_s.displayName=Ct.Item.displayName;const Vh=({open:t,onOpenChange:r,onNavigate:n,onAction:i})=>{const[o,a]=v.useState("");v.useEffect(()=>{const u=d=>{d.key==="k"&&(d.metaKey||d.ctrlKey)&&(d.preventDefault(),r(!t))};return document.addEventListener("keydown",u),()=>document.removeEventListener("keydown",u)},[t,r]);const s=v.useMemo(()=>[{id:"nav-pos",label:"نقطة البيع",icon:Un,category:"التنقل",keywords:["pos","نقطة","بيع","كاشير","cashier"],action:()=>n("pos")},{id:"nav-dashboard",label:"التحليلات",icon:cc,category:"التنقل",keywords:["dashboard","لوحة","تحكم","رئيسية","تحليلات","analytics","تقارير","reports"],action:()=>n("dashboard")},{id:"nav-invoices",label:"الفواتير",icon:ys,category:"التنقل",keywords:["invoices","فواتير","قائمة","list","معلقة","مرسلة","ملغاة"],action:()=>n("invoices")},{id:"nav-customers",label:"العملاء",icon:Rt,category:"التنقل",keywords:["customers","عملاء","زبائن","clients","ولاء","loyalty","عروض","promotions"],action:()=>n("customers")},{id:"nav-products",label:"المنتجات",icon:ht,category:"التنقل",keywords:["products","منتجات","مخزون","inventory","فئات","categories"],action:()=>n("products")},{id:"nav-administration",label:"الإدارة",icon:lc,category:"التنقل",keywords:["administration","إدارة","موظفين","employees","مصروفات","expenses","أداء","performance"],action:()=>n("administration")},{id:"nav-settings",label:"الإعدادات",icon:To,category:"التنقل",keywords:["settings","إعدادات","تفضيلات","preferences"],action:()=>n("settings")},{id:"action-new-invoice",label:"إنشاء فاتورة جديدة",icon:kt,category:"إجراءات سريعة",keywords:["new","invoice","create","جديدة","فاتورة","إنشاء"],action:()=>i("create-invoice")},{id:"action-new-customer",label:"إضافة عميل جديد",icon:kt,category:"إجراءات سريعة",keywords:["new","customer","add","جديد","عميل","إضافة"],action:()=>i("create-customer")},{id:"action-new-product",label:"إضافة منتج جديد",icon:kt,category:"إجراءات سريعة",keywords:["new","product","add","جديد","منتج","إضافة"],action:()=>i("create-product")},{id:"action-scan-barcode",label:"مسح باركود",icon:Ls,category:"إجراءات سريعة",keywords:["scan","barcode","مسح","باركود","qr"],action:()=>i("scan-barcode")},{id:"action-calculator",label:"فتح الحاسبة",icon:$i,category:"إجراءات سريعة",keywords:["calculator","حاسبة","calc"],action:()=>i("open-calculator")},{id:"search-invoices",label:"البحث في الفواتير",icon:zt,category:"بحث",keywords:["search","invoices","بحث","فواتير","find"],action:()=>i("search-invoices")},{id:"search-customers",label:"البحث في العملاء",icon:zt,category:"بحث",keywords:["search","customers","بحث","عملاء","find"],action:()=>i("search-customers")},{id:"search-products",label:"البحث في المنتجات",icon:zt,category:"بحث",keywords:["search","products","بحث","منتجات","find"],action:()=>i("search-products")}],[n,i]),c=v.useMemo(()=>{if(!o)return s;const u=o.toLowerCase();return s.filter(d=>d.label.toLowerCase().includes(u)||d.keywords.some(h=>h.toLowerCase().includes(u)))},[o,s]),l=v.useMemo(()=>{const u={};return c.forEach(d=>{u[d.category]||(u[d.category]=[]),u[d.category].push(d)}),u},[c]),m=u=>{u.action(),r(!1),a("")};return e.jsxs(qh,{open:t,onOpenChange:r,children:[e.jsx(Xo,{placeholder:"ابحث عن أي شيء... (اضغط Ctrl+K للفتح)",value:o,onValueChange:a}),e.jsxs(Jo,{children:[e.jsx(Ko,{children:"لا توجد نتائج"}),Object.entries(l).map(([u,d],h)=>e.jsxs("div",{children:[h>0&&e.jsx(yc,{}),e.jsx(Yo,{heading:u,children:d.map(p=>{const f=p.icon;return e.jsxs(_s,{onSelect:()=>m(p),className:"cursor-pointer",children:[e.jsx(f,{className:"ml-2 h-4 w-4"}),e.jsx("span",{children:p.label})]},p.id)})})]},u))]})]})},Gh=({open:t,onOpenChange:r})=>{const i=[{keys:["Ctrl","K"],description:"فتح لوحة الأوامر",category:"عام"},{keys:["?"],description:"عرض اختصارات لوحة المفاتيح",category:"عام"},{keys:["ESC"],description:"إغلاق / إلغاء",category:"عام"},{keys:["G","P"],description:"الانتقال إلى نقطة البيع",category:"التنقل"},{keys:["G","H"],description:"الانتقال إلى قائمة الفواتير",category:"التنقل"},{keys:["G","C"],description:"الانتقال إلى العملاء",category:"التنقل"},{keys:["G","I"],description:"الانتقال إلى المنتجات",category:"التنقل"},{keys:["G","A"],description:"الانتقال إلى التحليلات",category:"التنقل"},{keys:["G","S"],description:"الانتقال إلى الإعدادات",category:"التنقل"},{keys:["N"],description:"إنشاء فاتورة جديدة",category:"إجراءات"},{keys:["Ctrl","S"],description:"حفظ",category:"إجراءات"},{keys:["Ctrl","P"],description:"طباعة",category:"إجراءات"},{keys:["Ctrl","F"],description:"بحث",category:"إجراءات"},{keys:["Ctrl","N"],description:"إضافة عنصر جديد",category:"إجراءات"},{keys:["F1"],description:"عملية بيع جديدة",category:"نقطة البيع"},{keys:["F2"],description:"إتمام الدفع",category:"نقطة البيع"},{keys:["F3"],description:"مسح باركود",category:"نقطة البيع"},{keys:["F4"],description:"البحث عن منتج",category:"نقطة البيع"},{keys:["F5"],description:"فتح الحاسبة",category:"نقطة البيع"},{keys:["F7"],description:"طباعة الفاتورة",category:"نقطة البيع"},{keys:["F8"],description:"مسح السلة",category:"نقطة البيع"},{keys:["F9"],description:"إدارة الدرج النقدي",category:"نقطة البيع"},{keys:["F10"],description:"تقرير الشفت",category:"نقطة البيع"}].reduce((o,a)=>(o[a.category]||(o[a.category]=[]),o[a.category].push(a),o),{});return e.jsx(gt,{open:t,onOpenChange:r,children:e.jsxs(bt,{className:"max-w-2xl max-h-[80vh]",children:[e.jsxs(Tt,{children:[e.jsx(At,{className:"text-2xl",children:"اختصارات لوحة المفاتيح"}),e.jsx(kn,{children:"استخدم هذه الاختصارات لتسريع عملك في النظام"})]}),e.jsx(un,{className:"h-[500px] pr-4",children:Object.entries(i).map(([o,a],s)=>e.jsxs("div",{className:"mb-6",children:[s>0&&e.jsx(au,{className:"mb-4"}),e.jsx("h3",{className:"text-lg font-semibold mb-3 text-primary",children:o}),e.jsx("div",{className:"space-y-2",children:a.map((c,l)=>e.jsxs("div",{className:"flex items-center justify-between p-2 rounded hover:bg-muted/50",children:[e.jsx("span",{className:"text-sm",children:c.description}),e.jsx("div",{className:"flex gap-1",children:c.keys.map((m,u)=>e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Ae,{variant:"outline",className:"font-mono text-xs px-2 py-1",children:m}),u<c.keys.length-1&&e.jsx("span",{className:"text-muted-foreground text-xs",children:"+"})]},u))})]},l))})]},o))}),e.jsx("div",{className:"flex justify-end mt-4",children:e.jsx(Ae,{variant:"secondary",className:"text-xs",children:"اضغط ? في أي وقت لعرض هذه القائمة"})})]})})},Hh=t=>{const r=v.useCallback(n=>{var a,s,c,l,m,u;const i=n.target,o=i.tagName==="INPUT"||i.tagName==="TEXTAREA"||i.contentEditable==="true";if((n.ctrlKey||n.metaKey)&&n.key==="k"){n.preventDefault(),(a=t.onCommandPalette)==null||a.call(t);return}if(n.key==="?"&&!o){n.preventDefault(),(s=t.onHelp)==null||s.call(t);return}if(!(o&&!(n.ctrlKey||n.metaKey))){if(n.key==="g"&&!n.ctrlKey&&!n.metaKey&&!o){const d=h=>{var x;h.preventDefault();const f={p:"pos",d:"dashboard",h:"invoices",c:"customers",i:"products",a:"administration",s:"settings"}[h.key];f&&((x=t.onNavigate)==null||x.call(t,f)),window.removeEventListener("keydown",d)};window.addEventListener("keydown",d,{once:!0});return}if(n.key==="n"&&!n.ctrlKey&&!n.metaKey&&!o){n.preventDefault(),(c=t.onNewInvoice)==null||c.call(t);return}if((n.ctrlKey||n.metaKey)&&n.key==="s"){n.preventDefault(),(l=t.onSave)==null||l.call(t);return}if((n.ctrlKey||n.metaKey)&&n.key==="p"){n.preventDefault(),(m=t.onPrint)==null||m.call(t);return}if((n.ctrlKey||n.metaKey)&&n.key==="f"){n.preventDefault(),(u=t.onSearch)==null||u.call(t);return}}},[t]);v.useEffect(()=>(window.addEventListener("keydown",r),()=>window.removeEventListener("keydown",r)),[r])};function vc(t){return r=>typeof r===t}var Wh=vc("function"),Xh=t=>t===null,qa=t=>Object.prototype.toString.call(t).slice(8,-1)==="RegExp",Va=t=>!Jh(t)&&!Xh(t)&&(Wh(t)||typeof t=="object"),Jh=vc("undefined");function Kh(t,r){const{length:n}=t;if(n!==r.length)return!1;for(let i=n;i--!==0;)if(!pt(t[i],r[i]))return!1;return!0}function Yh(t,r){if(t.byteLength!==r.byteLength)return!1;const n=new DataView(t.buffer),i=new DataView(r.buffer);let o=t.byteLength;for(;o--;)if(n.getUint8(o)!==i.getUint8(o))return!1;return!0}function Qh(t,r){if(t.size!==r.size)return!1;for(const n of t.entries())if(!r.has(n[0]))return!1;for(const n of t.entries())if(!pt(n[1],r.get(n[0])))return!1;return!0}function Zh(t,r){if(t.size!==r.size)return!1;for(const n of t.entries())if(!r.has(n[0]))return!1;return!0}function pt(t,r){if(t===r)return!0;if(t&&Va(t)&&r&&Va(r)){if(t.constructor!==r.constructor)return!1;if(Array.isArray(t)&&Array.isArray(r))return Kh(t,r);if(t instanceof Map&&r instanceof Map)return Qh(t,r);if(t instanceof Set&&r instanceof Set)return Zh(t,r);if(ArrayBuffer.isView(t)&&ArrayBuffer.isView(r))return Yh(t,r);if(qa(t)&&qa(r))return t.source===r.source&&t.flags===r.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===r.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===r.toString();const n=Object.keys(t),i=Object.keys(r);if(n.length!==i.length)return!1;for(let o=n.length;o--!==0;)if(!Object.prototype.hasOwnProperty.call(r,n[o]))return!1;for(let o=n.length;o--!==0;){const a=n[o];if(!(a==="_owner"&&t.$$typeof)&&!pt(t[a],r[a]))return!1}return!0}return Number.isNaN(t)&&Number.isNaN(r)?!0:t===r}var ef=["Array","ArrayBuffer","AsyncFunction","AsyncGenerator","AsyncGeneratorFunction","Date","Error","Function","Generator","GeneratorFunction","HTMLElement","Map","Object","Promise","RegExp","Set","WeakMap","WeakSet"],tf=["bigint","boolean","null","number","string","symbol","undefined"];function Fs(t){const r=Object.prototype.toString.call(t).slice(8,-1);if(/HTML\w+Element/.test(r))return"HTMLElement";if(rf(r))return r}function Vt(t){return r=>Fs(r)===t}function rf(t){return ef.includes(t)}function hn(t){return r=>typeof r===t}function nf(t){return tf.includes(t)}var sf=["innerHTML","ownerDocument","style","attributes","nodeValue"];function me(t){if(t===null)return"null";switch(typeof t){case"bigint":return"bigint";case"boolean":return"boolean";case"number":return"number";case"string":return"string";case"symbol":return"symbol";case"undefined":return"undefined"}if(me.array(t))return"Array";if(me.plainFunction(t))return"Function";const r=Fs(t);return r||"Object"}me.array=Array.isArray;me.arrayOf=(t,r)=>!me.array(t)&&!me.function(r)?!1:t.every(n=>r(n));me.asyncGeneratorFunction=t=>Fs(t)==="AsyncGeneratorFunction";me.asyncFunction=Vt("AsyncFunction");me.bigint=hn("bigint");me.boolean=t=>t===!0||t===!1;me.date=Vt("Date");me.defined=t=>!me.undefined(t);me.domElement=t=>me.object(t)&&!me.plainObject(t)&&t.nodeType===1&&me.string(t.nodeName)&&sf.every(r=>r in t);me.empty=t=>me.string(t)&&t.length===0||me.array(t)&&t.length===0||me.object(t)&&!me.map(t)&&!me.set(t)&&Object.keys(t).length===0||me.set(t)&&t.size===0||me.map(t)&&t.size===0;me.error=Vt("Error");me.function=hn("function");me.generator=t=>me.iterable(t)&&me.function(t.next)&&me.function(t.throw);me.generatorFunction=Vt("GeneratorFunction");me.instanceOf=(t,r)=>!t||!r?!1:Object.getPrototypeOf(t)===r.prototype;me.iterable=t=>!me.nullOrUndefined(t)&&me.function(t[Symbol.iterator]);me.map=Vt("Map");me.nan=t=>Number.isNaN(t);me.null=t=>t===null;me.nullOrUndefined=t=>me.null(t)||me.undefined(t);me.number=t=>hn("number")(t)&&!me.nan(t);me.numericString=t=>me.string(t)&&t.length>0&&!Number.isNaN(Number(t));me.object=t=>!me.nullOrUndefined(t)&&(me.function(t)||typeof t=="object");me.oneOf=(t,r)=>me.array(t)?t.indexOf(r)>-1:!1;me.plainFunction=Vt("Function");me.plainObject=t=>{if(Fs(t)!=="Object")return!1;const r=Object.getPrototypeOf(t);return r===null||r===Object.getPrototypeOf({})};me.primitive=t=>me.null(t)||nf(typeof t);me.promise=Vt("Promise");me.propertyOf=(t,r,n)=>{if(!me.object(t)||!r)return!1;const i=t[r];return me.function(n)?n(i):me.defined(i)};me.regexp=Vt("RegExp");me.set=Vt("Set");me.string=hn("string");me.symbol=hn("symbol");me.undefined=hn("undefined");me.weakMap=Vt("WeakMap");me.weakSet=Vt("WeakSet");var he=me;function of(...t){return t.every(r=>he.string(r)||he.array(r)||he.plainObject(r))}function af(t,r,n){return _c(t,r)?[t,r].every(he.array)?!t.some(Ja(n))&&r.some(Ja(n)):[t,r].every(he.plainObject)?!Object.entries(t).some(Xa(n))&&Object.entries(r).some(Xa(n)):r===n:!1}function Ga(t,r,n){const{actual:i,key:o,previous:a,type:s}=n,c=Kt(t,o),l=Kt(r,o);let m=[c,l].every(he.number)&&(s==="increased"?c<l:c>l);return he.undefined(i)||(m=m&&l===i),he.undefined(a)||(m=m&&c===a),m}function Ha(t,r,n){const{key:i,type:o,value:a}=n,s=Kt(t,i),c=Kt(r,i),l=o==="added"?s:c,m=o==="added"?c:s;if(!he.nullOrUndefined(a)){if(he.defined(l)){if(he.array(l)||he.plainObject(l))return af(l,m,a)}else return pt(m,a);return!1}return[s,c].every(he.array)?!m.every(Qo(l)):[s,c].every(he.plainObject)?cf(Object.keys(l),Object.keys(m)):![s,c].every(u=>he.primitive(u)&&he.defined(u))&&(o==="added"?!he.defined(s)&&he.defined(c):he.defined(s)&&!he.defined(c))}function Wa(t,r,{key:n}={}){let i=Kt(t,n),o=Kt(r,n);if(!_c(i,o))throw new TypeError("Inputs have different types");if(!of(i,o))throw new TypeError("Inputs don't have length");return[i,o].every(he.plainObject)&&(i=Object.keys(i),o=Object.keys(o)),[i,o]}function Xa(t){return([r,n])=>he.array(t)?pt(t,n)||t.some(i=>pt(i,n)||he.array(n)&&Qo(n)(i)):he.plainObject(t)&&t[r]?!!t[r]&&pt(t[r],n):pt(t,n)}function cf(t,r){return r.some(n=>!t.includes(n))}function Ja(t){return r=>he.array(t)?t.some(n=>pt(n,r)||he.array(r)&&Qo(r)(n)):pt(t,r)}function vn(t,r){return he.array(t)?t.some(n=>pt(n,r)):pt(t,r)}function Qo(t){return r=>t.some(n=>pt(n,r))}function _c(...t){return t.every(he.array)||t.every(he.number)||t.every(he.plainObject)||t.every(he.string)}function Kt(t,r){return he.plainObject(t)||he.array(t)?he.string(r)?r.split(".").reduce((i,o)=>i&&i[o],t):he.number(r)?t[r]:t:t}function ws(t,r){if([t,r].some(he.nullOrUndefined))throw new Error("Missing required parameters");if(![t,r].every(u=>he.plainObject(u)||he.array(u)))throw new Error("Expected plain objects or array");return{added:(u,d)=>{try{return Ha(t,r,{key:u,type:"added",value:d})}catch{return!1}},changed:(u,d,h)=>{try{const p=Kt(t,u),f=Kt(r,u),x=he.defined(d),g=he.defined(h);if(x||g){const b=g?vn(h,p):!vn(d,p),y=vn(d,f);return b&&y}return[p,f].every(he.array)||[p,f].every(he.plainObject)?!pt(p,f):p!==f}catch{return!1}},changedFrom:(u,d,h)=>{if(!he.defined(u))return!1;try{const p=Kt(t,u),f=Kt(r,u),x=he.defined(h);return vn(d,p)&&(x?vn(h,f):!x)}catch{return!1}},decreased:(u,d,h)=>{if(!he.defined(u))return!1;try{return Ga(t,r,{key:u,actual:d,previous:h,type:"decreased"})}catch{return!1}},emptied:u=>{try{const[d,h]=Wa(t,r,{key:u});return!!d.length&&!h.length}catch{return!1}},filled:u=>{try{const[d,h]=Wa(t,r,{key:u});return!d.length&&!!h.length}catch{return!1}},increased:(u,d,h)=>{if(!he.defined(u))return!1;try{return Ga(t,r,{key:u,actual:d,previous:h,type:"increased"})}catch{return!1}},removed:(u,d)=>{try{return Ha(t,r,{key:u,type:"removed",value:d})}catch{return!1}}}}var lf=new Error("Element already at target scroll position"),df=new Error("Scroll cancelled"),uf=Math.min,Ka=Date.now,mf={left:Ya("scrollLeft"),top:Ya("scrollTop")};function Ya(t){return function(n,i,o,a){o=o||{},typeof o=="function"&&(a=o,o={}),typeof a!="function"&&(a=ff);var s=Ka(),c=n[t],l=o.ease||hf,m=isNaN(o.duration)?350:+o.duration,u=!1;return c===i?a(lf,n[t]):requestAnimationFrame(h),d;function d(){u=!0}function h(p){if(u)return a(df,n[t]);var f=Ka(),x=uf(1,(f-s)/m),g=l(x);n[t]=g*(i-c)+c,x<1?requestAnimationFrame(h):requestAnimationFrame(function(){a(null,n[t])})}}}function hf(t){return .5*(1-Math.cos(Math.PI*t))}function ff(){}const pf=Ln(mf);var wc={exports:{}};(function(t){(function(r,n){t.exports?t.exports=n():r.Scrollparent=n()})(Li,function(){function r(i){var o=getComputedStyle(i,null).getPropertyValue("overflow");return o.indexOf("scroll")>-1||o.indexOf("auto")>-1}function n(i){if(i instanceof HTMLElement||i instanceof SVGElement){for(var o=i.parentNode;o.parentNode;){if(r(o))return o;o=o.parentNode}return document.scrollingElement||document.documentElement}}return n})})(wc);var xf=wc.exports;const jc=Ln(xf);var gf=function(t){return Object.prototype.hasOwnProperty.call(t,"props")},bf=function(t,r){return t+In(r)},In=function(t){return t===null||typeof t=="boolean"||typeof t>"u"?"":typeof t=="number"?t.toString():typeof t=="string"?t:Array.isArray(t)?t.reduce(bf,""):gf(t)&&Object.prototype.hasOwnProperty.call(t.props,"children")?In(t.props.children):""};In.default=In;var yf=In;const Qa=Ln(yf);var vf=function(r){return _f(r)&&!wf(r)};function _f(t){return!!t&&typeof t=="object"}function wf(t){var r=Object.prototype.toString.call(t);return r==="[object RegExp]"||r==="[object Date]"||Cf(t)}var jf=typeof Symbol=="function"&&Symbol.for,Nf=jf?Symbol.for("react.element"):60103;function Cf(t){return t.$$typeof===Nf}function Ef(t){return Array.isArray(t)?[]:{}}function On(t,r){return r.clone!==!1&&r.isMergeableObject(t)?sn(Ef(t),t,r):t}function Sf(t,r,n){return t.concat(r).map(function(i){return On(i,n)})}function kf(t,r){if(!r.customMerge)return sn;var n=r.customMerge(t);return typeof n=="function"?n:sn}function Tf(t){return Object.getOwnPropertySymbols?Object.getOwnPropertySymbols(t).filter(function(r){return Object.propertyIsEnumerable.call(t,r)}):[]}function Za(t){return Object.keys(t).concat(Tf(t))}function Nc(t,r){try{return r in t}catch{return!1}}function Af(t,r){return Nc(t,r)&&!(Object.hasOwnProperty.call(t,r)&&Object.propertyIsEnumerable.call(t,r))}function If(t,r,n){var i={};return n.isMergeableObject(t)&&Za(t).forEach(function(o){i[o]=On(t[o],n)}),Za(r).forEach(function(o){Af(t,o)||(Nc(t,o)&&n.isMergeableObject(r[o])?i[o]=kf(o,n)(t[o],r[o],n):i[o]=On(r[o],n))}),i}function sn(t,r,n){n=n||{},n.arrayMerge=n.arrayMerge||Sf,n.isMergeableObject=n.isMergeableObject||vf,n.cloneUnlessOtherwiseSpecified=On;var i=Array.isArray(r),o=Array.isArray(t),a=i===o;return a?i?n.arrayMerge(t,r,n):If(t,r,n):On(r,n)}sn.all=function(r,n){if(!Array.isArray(r))throw new Error("first argument should be an array");return r.reduce(function(i,o){return sn(i,o,n)},{})};var Of=sn,Rf=Of;const Ft=Ln(Rf);/**!
 * @fileOverview Kickass library to create and place poppers near their reference elements.
 * @version 1.16.1
 * @license
 * Copyright (c) 2016 Federico Zivolo and contributors
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */var Bn=typeof window<"u"&&typeof document<"u"&&typeof navigator<"u",Pf=function(){for(var t=["Edge","Trident","Firefox"],r=0;r<t.length;r+=1)if(Bn&&navigator.userAgent.indexOf(t[r])>=0)return 1;return 0}();function Mf(t){var r=!1;return function(){r||(r=!0,window.Promise.resolve().then(function(){r=!1,t()}))}}function Lf(t){var r=!1;return function(){r||(r=!0,setTimeout(function(){r=!1,t()},Pf))}}var Df=Bn&&window.Promise,$f=Df?Mf:Lf;function Cc(t){var r={};return t&&r.toString.call(t)==="[object Function]"}function Lr(t,r){if(t.nodeType!==1)return[];var n=t.ownerDocument.defaultView,i=n.getComputedStyle(t,null);return r?i[r]:i}function Zo(t){return t.nodeName==="HTML"?t:t.parentNode||t.host}function qn(t){if(!t)return document.body;switch(t.nodeName){case"HTML":case"BODY":return t.ownerDocument.body;case"#document":return t.body}var r=Lr(t),n=r.overflow,i=r.overflowX,o=r.overflowY;return/(auto|scroll|overlay)/.test(n+o+i)?t:qn(Zo(t))}function Ec(t){return t&&t.referenceNode?t.referenceNode:t}var ei=Bn&&!!(window.MSInputMethodContext&&document.documentMode),ti=Bn&&/MSIE 10/.test(navigator.userAgent);function fn(t){return t===11?ei:t===10?ti:ei||ti}function on(t){if(!t)return document.documentElement;for(var r=fn(10)?document.body:null,n=t.offsetParent||null;n===r&&t.nextElementSibling;)n=(t=t.nextElementSibling).offsetParent;var i=n&&n.nodeName;return!i||i==="BODY"||i==="HTML"?t?t.ownerDocument.documentElement:document.documentElement:["TH","TD","TABLE"].indexOf(n.nodeName)!==-1&&Lr(n,"position")==="static"?on(n):n}function Ff(t){var r=t.nodeName;return r==="BODY"?!1:r==="HTML"||on(t.firstElementChild)===t}function bo(t){return t.parentNode!==null?bo(t.parentNode):t}function js(t,r){if(!t||!t.nodeType||!r||!r.nodeType)return document.documentElement;var n=t.compareDocumentPosition(r)&Node.DOCUMENT_POSITION_FOLLOWING,i=n?t:r,o=n?r:t,a=document.createRange();a.setStart(i,0),a.setEnd(o,0);var s=a.commonAncestorContainer;if(t!==s&&r!==s||i.contains(o))return Ff(s)?s:on(s);var c=bo(t);return c.host?js(c.host,r):js(t,bo(r).host)}function an(t){var r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"top",n=r==="top"?"scrollTop":"scrollLeft",i=t.nodeName;if(i==="BODY"||i==="HTML"){var o=t.ownerDocument.documentElement,a=t.ownerDocument.scrollingElement||o;return a[n]}return t[n]}function Uf(t,r){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,i=an(r,"top"),o=an(r,"left"),a=n?-1:1;return t.top+=i*a,t.bottom+=i*a,t.left+=o*a,t.right+=o*a,t}function ri(t,r){var n=r==="x"?"Left":"Top",i=n==="Left"?"Right":"Bottom";return parseFloat(t["border"+n+"Width"])+parseFloat(t["border"+i+"Width"])}function ni(t,r,n,i){return Math.max(r["offset"+t],r["scroll"+t],n["client"+t],n["offset"+t],n["scroll"+t],fn(10)?parseInt(n["offset"+t])+parseInt(i["margin"+(t==="Height"?"Top":"Left")])+parseInt(i["margin"+(t==="Height"?"Bottom":"Right")]):0)}function Sc(t){var r=t.body,n=t.documentElement,i=fn(10)&&getComputedStyle(n);return{height:ni("Height",r,n,i),width:ni("Width",r,n,i)}}var zf=function(t,r){if(!(t instanceof r))throw new TypeError("Cannot call a class as a function")},Bf=function(){function t(r,n){for(var i=0;i<n.length;i++){var o=n[i];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(r,o.key,o)}}return function(r,n,i){return n&&t(r.prototype,n),i&&t(r,i),r}}(),cn=function(t,r,n){return r in t?Object.defineProperty(t,r,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[r]=n,t},Pt=Object.assign||function(t){for(var r=1;r<arguments.length;r++){var n=arguments[r];for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(t[i]=n[i])}return t};function yr(t){return Pt({},t,{right:t.left+t.width,bottom:t.top+t.height})}function yo(t){var r={};try{if(fn(10)){r=t.getBoundingClientRect();var n=an(t,"top"),i=an(t,"left");r.top+=n,r.left+=i,r.bottom+=n,r.right+=i}else r=t.getBoundingClientRect()}catch{}var o={left:r.left,top:r.top,width:r.right-r.left,height:r.bottom-r.top},a=t.nodeName==="HTML"?Sc(t.ownerDocument):{},s=a.width||t.clientWidth||o.width,c=a.height||t.clientHeight||o.height,l=t.offsetWidth-s,m=t.offsetHeight-c;if(l||m){var u=Lr(t);l-=ri(u,"x"),m-=ri(u,"y"),o.width-=l,o.height-=m}return yr(o)}function ea(t,r){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,i=fn(10),o=r.nodeName==="HTML",a=yo(t),s=yo(r),c=qn(t),l=Lr(r),m=parseFloat(l.borderTopWidth),u=parseFloat(l.borderLeftWidth);n&&o&&(s.top=Math.max(s.top,0),s.left=Math.max(s.left,0));var d=yr({top:a.top-s.top-m,left:a.left-s.left-u,width:a.width,height:a.height});if(d.marginTop=0,d.marginLeft=0,!i&&o){var h=parseFloat(l.marginTop),p=parseFloat(l.marginLeft);d.top-=m-h,d.bottom-=m-h,d.left-=u-p,d.right-=u-p,d.marginTop=h,d.marginLeft=p}return(i&&!n?r.contains(c):r===c&&c.nodeName!=="BODY")&&(d=Uf(d,r)),d}function qf(t){var r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1,n=t.ownerDocument.documentElement,i=ea(t,n),o=Math.max(n.clientWidth,window.innerWidth||0),a=Math.max(n.clientHeight,window.innerHeight||0),s=r?0:an(n),c=r?0:an(n,"left"),l={top:s-i.top+i.marginTop,left:c-i.left+i.marginLeft,width:o,height:a};return yr(l)}function kc(t){var r=t.nodeName;if(r==="BODY"||r==="HTML")return!1;if(Lr(t,"position")==="fixed")return!0;var n=Zo(t);return n?kc(n):!1}function Tc(t){if(!t||!t.parentElement||fn())return document.documentElement;for(var r=t.parentElement;r&&Lr(r,"transform")==="none";)r=r.parentElement;return r||document.documentElement}function ta(t,r,n,i){var o=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1,a={top:0,left:0},s=o?Tc(t):js(t,Ec(r));if(i==="viewport")a=qf(s,o);else{var c=void 0;i==="scrollParent"?(c=qn(Zo(r)),c.nodeName==="BODY"&&(c=t.ownerDocument.documentElement)):i==="window"?c=t.ownerDocument.documentElement:c=i;var l=ea(c,s,o);if(c.nodeName==="HTML"&&!kc(s)){var m=Sc(t.ownerDocument),u=m.height,d=m.width;a.top+=l.top-l.marginTop,a.bottom=u+l.top,a.left+=l.left-l.marginLeft,a.right=d+l.left}else a=l}n=n||0;var h=typeof n=="number";return a.left+=h?n:n.left||0,a.top+=h?n:n.top||0,a.right-=h?n:n.right||0,a.bottom-=h?n:n.bottom||0,a}function Vf(t){var r=t.width,n=t.height;return r*n}function Ac(t,r,n,i,o){var a=arguments.length>5&&arguments[5]!==void 0?arguments[5]:0;if(t.indexOf("auto")===-1)return t;var s=ta(n,i,a,o),c={top:{width:s.width,height:r.top-s.top},right:{width:s.right-r.right,height:s.height},bottom:{width:s.width,height:s.bottom-r.bottom},left:{width:r.left-s.left,height:s.height}},l=Object.keys(c).map(function(h){return Pt({key:h},c[h],{area:Vf(c[h])})}).sort(function(h,p){return p.area-h.area}),m=l.filter(function(h){var p=h.width,f=h.height;return p>=n.clientWidth&&f>=n.clientHeight}),u=m.length>0?m[0].key:l[0].key,d=t.split("-")[1];return u+(d?"-"+d:"")}function Ic(t,r,n){var i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:null,o=i?Tc(r):js(r,Ec(n));return ea(n,o,i)}function Oc(t){var r=t.ownerDocument.defaultView,n=r.getComputedStyle(t),i=parseFloat(n.marginTop||0)+parseFloat(n.marginBottom||0),o=parseFloat(n.marginLeft||0)+parseFloat(n.marginRight||0),a={width:t.offsetWidth+o,height:t.offsetHeight+i};return a}function Ns(t){var r={left:"right",right:"left",bottom:"top",top:"bottom"};return t.replace(/left|right|bottom|top/g,function(n){return r[n]})}function Rc(t,r,n){n=n.split("-")[0];var i=Oc(t),o={width:i.width,height:i.height},a=["right","left"].indexOf(n)!==-1,s=a?"top":"left",c=a?"left":"top",l=a?"height":"width",m=a?"width":"height";return o[s]=r[s]+r[l]/2-i[l]/2,n===c?o[c]=r[c]-i[m]:o[c]=r[Ns(c)],o}function Vn(t,r){return Array.prototype.find?t.find(r):t.filter(r)[0]}function Gf(t,r,n){if(Array.prototype.findIndex)return t.findIndex(function(o){return o[r]===n});var i=Vn(t,function(o){return o[r]===n});return t.indexOf(i)}function Pc(t,r,n){var i=n===void 0?t:t.slice(0,Gf(t,"name",n));return i.forEach(function(o){o.function&&console.warn("`modifier.function` is deprecated, use `modifier.fn`!");var a=o.function||o.fn;o.enabled&&Cc(a)&&(r.offsets.popper=yr(r.offsets.popper),r.offsets.reference=yr(r.offsets.reference),r=a(r,o))}),r}function Hf(){if(!this.state.isDestroyed){var t={instance:this,styles:{},arrowStyles:{},attributes:{},flipped:!1,offsets:{}};t.offsets.reference=Ic(this.state,this.popper,this.reference,this.options.positionFixed),t.placement=Ac(this.options.placement,t.offsets.reference,this.popper,this.reference,this.options.modifiers.flip.boundariesElement,this.options.modifiers.flip.padding),t.originalPlacement=t.placement,t.positionFixed=this.options.positionFixed,t.offsets.popper=Rc(this.popper,t.offsets.reference,t.placement),t.offsets.popper.position=this.options.positionFixed?"fixed":"absolute",t=Pc(this.modifiers,t),this.state.isCreated?this.options.onUpdate(t):(this.state.isCreated=!0,this.options.onCreate(t))}}function Mc(t,r){return t.some(function(n){var i=n.name,o=n.enabled;return o&&i===r})}function ra(t){for(var r=[!1,"ms","Webkit","Moz","O"],n=t.charAt(0).toUpperCase()+t.slice(1),i=0;i<r.length;i++){var o=r[i],a=o?""+o+n:t;if(typeof document.body.style[a]<"u")return a}return null}function Wf(){return this.state.isDestroyed=!0,Mc(this.modifiers,"applyStyle")&&(this.popper.removeAttribute("x-placement"),this.popper.style.position="",this.popper.style.top="",this.popper.style.left="",this.popper.style.right="",this.popper.style.bottom="",this.popper.style.willChange="",this.popper.style[ra("transform")]=""),this.disableEventListeners(),this.options.removeOnDestroy&&this.popper.parentNode.removeChild(this.popper),this}function Lc(t){var r=t.ownerDocument;return r?r.defaultView:window}function Dc(t,r,n,i){var o=t.nodeName==="BODY",a=o?t.ownerDocument.defaultView:t;a.addEventListener(r,n,{passive:!0}),o||Dc(qn(a.parentNode),r,n,i),i.push(a)}function Xf(t,r,n,i){n.updateBound=i,Lc(t).addEventListener("resize",n.updateBound,{passive:!0});var o=qn(t);return Dc(o,"scroll",n.updateBound,n.scrollParents),n.scrollElement=o,n.eventsEnabled=!0,n}function Jf(){this.state.eventsEnabled||(this.state=Xf(this.reference,this.options,this.state,this.scheduleUpdate))}function Kf(t,r){return Lc(t).removeEventListener("resize",r.updateBound),r.scrollParents.forEach(function(n){n.removeEventListener("scroll",r.updateBound)}),r.updateBound=null,r.scrollParents=[],r.scrollElement=null,r.eventsEnabled=!1,r}function Yf(){this.state.eventsEnabled&&(cancelAnimationFrame(this.scheduleUpdate),this.state=Kf(this.reference,this.state))}function na(t){return t!==""&&!isNaN(parseFloat(t))&&isFinite(t)}function vo(t,r){Object.keys(r).forEach(function(n){var i="";["width","height","top","right","bottom","left"].indexOf(n)!==-1&&na(r[n])&&(i="px"),t.style[n]=r[n]+i})}function Qf(t,r){Object.keys(r).forEach(function(n){var i=r[n];i!==!1?t.setAttribute(n,r[n]):t.removeAttribute(n)})}function Zf(t){return vo(t.instance.popper,t.styles),Qf(t.instance.popper,t.attributes),t.arrowElement&&Object.keys(t.arrowStyles).length&&vo(t.arrowElement,t.arrowStyles),t}function ep(t,r,n,i,o){var a=Ic(o,r,t,n.positionFixed),s=Ac(n.placement,a,r,t,n.modifiers.flip.boundariesElement,n.modifiers.flip.padding);return r.setAttribute("x-placement",s),vo(r,{position:n.positionFixed?"fixed":"absolute"}),n}function tp(t,r){var n=t.offsets,i=n.popper,o=n.reference,a=Math.round,s=Math.floor,c=function(b){return b},l=a(o.width),m=a(i.width),u=["left","right"].indexOf(t.placement)!==-1,d=t.placement.indexOf("-")!==-1,h=l%2===m%2,p=l%2===1&&m%2===1,f=r?u||d||h?a:s:c,x=r?a:c;return{left:f(p&&!d&&r?i.left-1:i.left),top:x(i.top),bottom:x(i.bottom),right:f(i.right)}}var rp=Bn&&/Firefox/i.test(navigator.userAgent);function np(t,r){var n=r.x,i=r.y,o=t.offsets.popper,a=Vn(t.instance.modifiers,function(_){return _.name==="applyStyle"}).gpuAcceleration;a!==void 0&&console.warn("WARNING: `gpuAcceleration` option moved to `computeStyle` modifier and will not be supported in future versions of Popper.js!");var s=a!==void 0?a:r.gpuAcceleration,c=on(t.instance.popper),l=yo(c),m={position:o.position},u=tp(t,window.devicePixelRatio<2||!rp),d=n==="bottom"?"top":"bottom",h=i==="right"?"left":"right",p=ra("transform"),f=void 0,x=void 0;if(d==="bottom"?c.nodeName==="HTML"?x=-c.clientHeight+u.bottom:x=-l.height+u.bottom:x=u.top,h==="right"?c.nodeName==="HTML"?f=-c.clientWidth+u.right:f=-l.width+u.right:f=u.left,s&&p)m[p]="translate3d("+f+"px, "+x+"px, 0)",m[d]=0,m[h]=0,m.willChange="transform";else{var g=d==="bottom"?-1:1,b=h==="right"?-1:1;m[d]=x*g,m[h]=f*b,m.willChange=d+", "+h}var y={"x-placement":t.placement};return t.attributes=Pt({},y,t.attributes),t.styles=Pt({},m,t.styles),t.arrowStyles=Pt({},t.offsets.arrow,t.arrowStyles),t}function $c(t,r,n){var i=Vn(t,function(c){var l=c.name;return l===r}),o=!!i&&t.some(function(c){return c.name===n&&c.enabled&&c.order<i.order});if(!o){var a="`"+r+"`",s="`"+n+"`";console.warn(s+" modifier is required by "+a+" modifier in order to work, be sure to include it before "+a+"!")}return o}function sp(t,r){var n;if(!$c(t.instance.modifiers,"arrow","keepTogether"))return t;var i=r.element;if(typeof i=="string"){if(i=t.instance.popper.querySelector(i),!i)return t}else if(!t.instance.popper.contains(i))return console.warn("WARNING: `arrow.element` must be child of its popper element!"),t;var o=t.placement.split("-")[0],a=t.offsets,s=a.popper,c=a.reference,l=["left","right"].indexOf(o)!==-1,m=l?"height":"width",u=l?"Top":"Left",d=u.toLowerCase(),h=l?"left":"top",p=l?"bottom":"right",f=Oc(i)[m];c[p]-f<s[d]&&(t.offsets.popper[d]-=s[d]-(c[p]-f)),c[d]+f>s[p]&&(t.offsets.popper[d]+=c[d]+f-s[p]),t.offsets.popper=yr(t.offsets.popper);var x=c[d]+c[m]/2-f/2,g=Lr(t.instance.popper),b=parseFloat(g["margin"+u]),y=parseFloat(g["border"+u+"Width"]),_=x-t.offsets.popper[d]-b-y;return _=Math.max(Math.min(s[m]-f,_),0),t.arrowElement=i,t.offsets.arrow=(n={},cn(n,d,Math.round(_)),cn(n,h,""),n),t}function op(t){return t==="end"?"start":t==="start"?"end":t}var Fc=["auto-start","auto","auto-end","top-start","top","top-end","right-start","right","right-end","bottom-end","bottom","bottom-start","left-end","left","left-start"],ro=Fc.slice(3);function si(t){var r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1,n=ro.indexOf(t),i=ro.slice(n+1).concat(ro.slice(0,n));return r?i.reverse():i}var no={FLIP:"flip",CLOCKWISE:"clockwise",COUNTERCLOCKWISE:"counterclockwise"};function ap(t,r){if(Mc(t.instance.modifiers,"inner")||t.flipped&&t.placement===t.originalPlacement)return t;var n=ta(t.instance.popper,t.instance.reference,r.padding,r.boundariesElement,t.positionFixed),i=t.placement.split("-")[0],o=Ns(i),a=t.placement.split("-")[1]||"",s=[];switch(r.behavior){case no.FLIP:s=[i,o];break;case no.CLOCKWISE:s=si(i);break;case no.COUNTERCLOCKWISE:s=si(i,!0);break;default:s=r.behavior}return s.forEach(function(c,l){if(i!==c||s.length===l+1)return t;i=t.placement.split("-")[0],o=Ns(i);var m=t.offsets.popper,u=t.offsets.reference,d=Math.floor,h=i==="left"&&d(m.right)>d(u.left)||i==="right"&&d(m.left)<d(u.right)||i==="top"&&d(m.bottom)>d(u.top)||i==="bottom"&&d(m.top)<d(u.bottom),p=d(m.left)<d(n.left),f=d(m.right)>d(n.right),x=d(m.top)<d(n.top),g=d(m.bottom)>d(n.bottom),b=i==="left"&&p||i==="right"&&f||i==="top"&&x||i==="bottom"&&g,y=["top","bottom"].indexOf(i)!==-1,_=!!r.flipVariations&&(y&&a==="start"&&p||y&&a==="end"&&f||!y&&a==="start"&&x||!y&&a==="end"&&g),j=!!r.flipVariationsByContent&&(y&&a==="start"&&f||y&&a==="end"&&p||!y&&a==="start"&&g||!y&&a==="end"&&x),I=_||j;(h||b||I)&&(t.flipped=!0,(h||b)&&(i=s[l+1]),I&&(a=op(a)),t.placement=i+(a?"-"+a:""),t.offsets.popper=Pt({},t.offsets.popper,Rc(t.instance.popper,t.offsets.reference,t.placement)),t=Pc(t.instance.modifiers,t,"flip"))}),t}function ip(t){var r=t.offsets,n=r.popper,i=r.reference,o=t.placement.split("-")[0],a=Math.floor,s=["top","bottom"].indexOf(o)!==-1,c=s?"right":"bottom",l=s?"left":"top",m=s?"width":"height";return n[c]<a(i[l])&&(t.offsets.popper[l]=a(i[l])-n[m]),n[l]>a(i[c])&&(t.offsets.popper[l]=a(i[c])),t}function cp(t,r,n,i){var o=t.match(/((?:\-|\+)?\d*\.?\d*)(.*)/),a=+o[1],s=o[2];if(!a)return t;if(s.indexOf("%")===0){var c=void 0;switch(s){case"%p":c=n;break;case"%":case"%r":default:c=i}var l=yr(c);return l[r]/100*a}else if(s==="vh"||s==="vw"){var m=void 0;return s==="vh"?m=Math.max(document.documentElement.clientHeight,window.innerHeight||0):m=Math.max(document.documentElement.clientWidth,window.innerWidth||0),m/100*a}else return a}function lp(t,r,n,i){var o=[0,0],a=["right","left"].indexOf(i)!==-1,s=t.split(/(\+|\-)/).map(function(u){return u.trim()}),c=s.indexOf(Vn(s,function(u){return u.search(/,|\s/)!==-1}));s[c]&&s[c].indexOf(",")===-1&&console.warn("Offsets separated by white space(s) are deprecated, use a comma (,) instead.");var l=/\s*,\s*|\s+/,m=c!==-1?[s.slice(0,c).concat([s[c].split(l)[0]]),[s[c].split(l)[1]].concat(s.slice(c+1))]:[s];return m=m.map(function(u,d){var h=(d===1?!a:a)?"height":"width",p=!1;return u.reduce(function(f,x){return f[f.length-1]===""&&["+","-"].indexOf(x)!==-1?(f[f.length-1]=x,p=!0,f):p?(f[f.length-1]+=x,p=!1,f):f.concat(x)},[]).map(function(f){return cp(f,h,r,n)})}),m.forEach(function(u,d){u.forEach(function(h,p){na(h)&&(o[d]+=h*(u[p-1]==="-"?-1:1))})}),o}function dp(t,r){var n=r.offset,i=t.placement,o=t.offsets,a=o.popper,s=o.reference,c=i.split("-")[0],l=void 0;return na(+n)?l=[+n,0]:l=lp(n,a,s,c),c==="left"?(a.top+=l[0],a.left-=l[1]):c==="right"?(a.top+=l[0],a.left+=l[1]):c==="top"?(a.left+=l[0],a.top-=l[1]):c==="bottom"&&(a.left+=l[0],a.top+=l[1]),t.popper=a,t}function up(t,r){var n=r.boundariesElement||on(t.instance.popper);t.instance.reference===n&&(n=on(n));var i=ra("transform"),o=t.instance.popper.style,a=o.top,s=o.left,c=o[i];o.top="",o.left="",o[i]="";var l=ta(t.instance.popper,t.instance.reference,r.padding,n,t.positionFixed);o.top=a,o.left=s,o[i]=c,r.boundaries=l;var m=r.priority,u=t.offsets.popper,d={primary:function(p){var f=u[p];return u[p]<l[p]&&!r.escapeWithReference&&(f=Math.max(u[p],l[p])),cn({},p,f)},secondary:function(p){var f=p==="right"?"left":"top",x=u[f];return u[p]>l[p]&&!r.escapeWithReference&&(x=Math.min(u[f],l[p]-(p==="right"?u.width:u.height))),cn({},f,x)}};return m.forEach(function(h){var p=["left","top"].indexOf(h)!==-1?"primary":"secondary";u=Pt({},u,d[p](h))}),t.offsets.popper=u,t}function mp(t){var r=t.placement,n=r.split("-")[0],i=r.split("-")[1];if(i){var o=t.offsets,a=o.reference,s=o.popper,c=["bottom","top"].indexOf(n)!==-1,l=c?"left":"top",m=c?"width":"height",u={start:cn({},l,a[l]),end:cn({},l,a[l]+a[m]-s[m])};t.offsets.popper=Pt({},s,u[i])}return t}function hp(t){if(!$c(t.instance.modifiers,"hide","preventOverflow"))return t;var r=t.offsets.reference,n=Vn(t.instance.modifiers,function(i){return i.name==="preventOverflow"}).boundaries;if(r.bottom<n.top||r.left>n.right||r.top>n.bottom||r.right<n.left){if(t.hide===!0)return t;t.hide=!0,t.attributes["x-out-of-boundaries"]=""}else{if(t.hide===!1)return t;t.hide=!1,t.attributes["x-out-of-boundaries"]=!1}return t}function fp(t){var r=t.placement,n=r.split("-")[0],i=t.offsets,o=i.popper,a=i.reference,s=["left","right"].indexOf(n)!==-1,c=["top","left"].indexOf(n)===-1;return o[s?"left":"top"]=a[n]-(c?o[s?"width":"height"]:0),t.placement=Ns(r),t.offsets.popper=yr(o),t}var pp={shift:{order:100,enabled:!0,fn:mp},offset:{order:200,enabled:!0,fn:dp,offset:0},preventOverflow:{order:300,enabled:!0,fn:up,priority:["left","right","top","bottom"],padding:5,boundariesElement:"scrollParent"},keepTogether:{order:400,enabled:!0,fn:ip},arrow:{order:500,enabled:!0,fn:sp,element:"[x-arrow]"},flip:{order:600,enabled:!0,fn:ap,behavior:"flip",padding:5,boundariesElement:"viewport",flipVariations:!1,flipVariationsByContent:!1},inner:{order:700,enabled:!1,fn:fp},hide:{order:800,enabled:!0,fn:hp},computeStyle:{order:850,enabled:!0,fn:np,gpuAcceleration:!0,x:"bottom",y:"right"},applyStyle:{order:900,enabled:!0,fn:Zf,onLoad:ep,gpuAcceleration:void 0}},xp={placement:"bottom",positionFixed:!1,eventsEnabled:!0,removeOnDestroy:!1,onCreate:function(){},onUpdate:function(){},modifiers:pp},Rn=function(){function t(r,n){var i=this,o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};zf(this,t),this.scheduleUpdate=function(){return requestAnimationFrame(i.update)},this.update=$f(this.update.bind(this)),this.options=Pt({},t.Defaults,o),this.state={isDestroyed:!1,isCreated:!1,scrollParents:[]},this.reference=r&&r.jquery?r[0]:r,this.popper=n&&n.jquery?n[0]:n,this.options.modifiers={},Object.keys(Pt({},t.Defaults.modifiers,o.modifiers)).forEach(function(s){i.options.modifiers[s]=Pt({},t.Defaults.modifiers[s]||{},o.modifiers?o.modifiers[s]:{})}),this.modifiers=Object.keys(this.options.modifiers).map(function(s){return Pt({name:s},i.options.modifiers[s])}).sort(function(s,c){return s.order-c.order}),this.modifiers.forEach(function(s){s.enabled&&Cc(s.onLoad)&&s.onLoad(i.reference,i.popper,i.options,s,i.state)}),this.update();var a=this.options.eventsEnabled;a&&this.enableEventListeners(),this.state.eventsEnabled=a}return Bf(t,[{key:"update",value:function(){return Hf.call(this)}},{key:"destroy",value:function(){return Wf.call(this)}},{key:"enableEventListeners",value:function(){return Jf.call(this)}},{key:"disableEventListeners",value:function(){return Yf.call(this)}}]),t}();Rn.Utils=(typeof window<"u"?window:global).PopperUtils;Rn.placements=Fc;Rn.Defaults=xp;var gp=["innerHTML","ownerDocument","style","attributes","nodeValue"],bp=["Array","ArrayBuffer","AsyncFunction","AsyncGenerator","AsyncGeneratorFunction","Date","Error","Function","Generator","GeneratorFunction","HTMLElement","Map","Object","Promise","RegExp","Set","WeakMap","WeakSet"],yp=["bigint","boolean","null","number","string","symbol","undefined"];function Us(t){var r=Object.prototype.toString.call(t).slice(8,-1);if(/HTML\w+Element/.test(r))return"HTMLElement";if(vp(r))return r}function Gt(t){return function(r){return Us(r)===t}}function vp(t){return bp.includes(t)}function pn(t){return function(r){return typeof r===t}}function _p(t){return yp.includes(t)}function G(t){if(t===null)return"null";switch(typeof t){case"bigint":return"bigint";case"boolean":return"boolean";case"number":return"number";case"string":return"string";case"symbol":return"symbol";case"undefined":return"undefined"}if(G.array(t))return"Array";if(G.plainFunction(t))return"Function";var r=Us(t);return r||"Object"}G.array=Array.isArray;G.arrayOf=function(t,r){return!G.array(t)&&!G.function(r)?!1:t.every(function(n){return r(n)})};G.asyncGeneratorFunction=function(t){return Us(t)==="AsyncGeneratorFunction"};G.asyncFunction=Gt("AsyncFunction");G.bigint=pn("bigint");G.boolean=function(t){return t===!0||t===!1};G.date=Gt("Date");G.defined=function(t){return!G.undefined(t)};G.domElement=function(t){return G.object(t)&&!G.plainObject(t)&&t.nodeType===1&&G.string(t.nodeName)&&gp.every(function(r){return r in t})};G.empty=function(t){return G.string(t)&&t.length===0||G.array(t)&&t.length===0||G.object(t)&&!G.map(t)&&!G.set(t)&&Object.keys(t).length===0||G.set(t)&&t.size===0||G.map(t)&&t.size===0};G.error=Gt("Error");G.function=pn("function");G.generator=function(t){return G.iterable(t)&&G.function(t.next)&&G.function(t.throw)};G.generatorFunction=Gt("GeneratorFunction");G.instanceOf=function(t,r){return!t||!r?!1:Object.getPrototypeOf(t)===r.prototype};G.iterable=function(t){return!G.nullOrUndefined(t)&&G.function(t[Symbol.iterator])};G.map=Gt("Map");G.nan=function(t){return Number.isNaN(t)};G.null=function(t){return t===null};G.nullOrUndefined=function(t){return G.null(t)||G.undefined(t)};G.number=function(t){return pn("number")(t)&&!G.nan(t)};G.numericString=function(t){return G.string(t)&&t.length>0&&!Number.isNaN(Number(t))};G.object=function(t){return!G.nullOrUndefined(t)&&(G.function(t)||typeof t=="object")};G.oneOf=function(t,r){return G.array(t)?t.indexOf(r)>-1:!1};G.plainFunction=Gt("Function");G.plainObject=function(t){if(Us(t)!=="Object")return!1;var r=Object.getPrototypeOf(t);return r===null||r===Object.getPrototypeOf({})};G.primitive=function(t){return G.null(t)||_p(typeof t)};G.promise=Gt("Promise");G.propertyOf=function(t,r,n){if(!G.object(t)||!r)return!1;var i=t[r];return G.function(n)?n(i):G.defined(i)};G.regexp=Gt("RegExp");G.set=Gt("Set");G.string=pn("string");G.symbol=pn("symbol");G.undefined=pn("undefined");G.weakMap=Gt("WeakMap");G.weakSet=Gt("WeakSet");function Uc(t){return function(r){return typeof r===t}}var wp=Uc("function"),jp=function(t){return t===null},oi=function(t){return Object.prototype.toString.call(t).slice(8,-1)==="RegExp"},ai=function(t){return!Np(t)&&!jp(t)&&(wp(t)||typeof t=="object")},Np=Uc("undefined"),_o=function(t){var r=typeof Symbol=="function"&&Symbol.iterator,n=r&&t[r],i=0;if(n)return n.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&i>=t.length&&(t=void 0),{value:t&&t[i++],done:!t}}};throw new TypeError(r?"Object is not iterable.":"Symbol.iterator is not defined.")};function Cp(t,r){var n=t.length;if(n!==r.length)return!1;for(var i=n;i--!==0;)if(!Nt(t[i],r[i]))return!1;return!0}function Ep(t,r){if(t.byteLength!==r.byteLength)return!1;for(var n=new DataView(t.buffer),i=new DataView(r.buffer),o=t.byteLength;o--;)if(n.getUint8(o)!==i.getUint8(o))return!1;return!0}function Sp(t,r){var n,i,o,a;if(t.size!==r.size)return!1;try{for(var s=_o(t.entries()),c=s.next();!c.done;c=s.next()){var l=c.value;if(!r.has(l[0]))return!1}}catch(d){n={error:d}}finally{try{c&&!c.done&&(i=s.return)&&i.call(s)}finally{if(n)throw n.error}}try{for(var m=_o(t.entries()),u=m.next();!u.done;u=m.next()){var l=u.value;if(!Nt(l[1],r.get(l[0])))return!1}}catch(d){o={error:d}}finally{try{u&&!u.done&&(a=m.return)&&a.call(m)}finally{if(o)throw o.error}}return!0}function kp(t,r){var n,i;if(t.size!==r.size)return!1;try{for(var o=_o(t.entries()),a=o.next();!a.done;a=o.next()){var s=a.value;if(!r.has(s[0]))return!1}}catch(c){n={error:c}}finally{try{a&&!a.done&&(i=o.return)&&i.call(o)}finally{if(n)throw n.error}}return!0}function Nt(t,r){if(t===r)return!0;if(t&&ai(t)&&r&&ai(r)){if(t.constructor!==r.constructor)return!1;if(Array.isArray(t)&&Array.isArray(r))return Cp(t,r);if(t instanceof Map&&r instanceof Map)return Sp(t,r);if(t instanceof Set&&r instanceof Set)return kp(t,r);if(ArrayBuffer.isView(t)&&ArrayBuffer.isView(r))return Ep(t,r);if(oi(t)&&oi(r))return t.source===r.source&&t.flags===r.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===r.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===r.toString();var n=Object.keys(t),i=Object.keys(r);if(n.length!==i.length)return!1;for(var o=n.length;o--!==0;)if(!Object.prototype.hasOwnProperty.call(r,n[o]))return!1;for(var o=n.length;o--!==0;){var a=n[o];if(!(a==="_owner"&&t.$$typeof)&&!Nt(t[a],r[a]))return!1}return!0}return Number.isNaN(t)&&Number.isNaN(r)?!0:t===r}function Tp(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return t.every(function(n){return G.string(n)||G.array(n)||G.plainObject(n)})}function Ap(t,r,n){return zc(t,r)?[t,r].every(G.array)?!t.some(ui(n))&&r.some(ui(n)):[t,r].every(G.plainObject)?!Object.entries(t).some(di(n))&&Object.entries(r).some(di(n)):r===n:!1}function ii(t,r,n){var i=n.actual,o=n.key,a=n.previous,s=n.type,c=Yt(t,o),l=Yt(r,o),m=[c,l].every(G.number)&&(s==="increased"?c<l:c>l);return G.undefined(i)||(m=m&&l===i),G.undefined(a)||(m=m&&c===a),m}function ci(t,r,n){var i=n.key,o=n.type,a=n.value,s=Yt(t,i),c=Yt(r,i),l=o==="added"?s:c,m=o==="added"?c:s;if(!G.nullOrUndefined(a)){if(G.defined(l)){if(G.array(l)||G.plainObject(l))return Ap(l,m,a)}else return Nt(m,a);return!1}return[s,c].every(G.array)?!m.every(sa(l)):[s,c].every(G.plainObject)?Ip(Object.keys(l),Object.keys(m)):![s,c].every(function(u){return G.primitive(u)&&G.defined(u)})&&(o==="added"?!G.defined(s)&&G.defined(c):G.defined(s)&&!G.defined(c))}function li(t,r,n){var i=n===void 0?{}:n,o=i.key,a=Yt(t,o),s=Yt(r,o);if(!zc(a,s))throw new TypeError("Inputs have different types");if(!Tp(a,s))throw new TypeError("Inputs don't have length");return[a,s].every(G.plainObject)&&(a=Object.keys(a),s=Object.keys(s)),[a,s]}function di(t){return function(r){var n=r[0],i=r[1];return G.array(t)?Nt(t,i)||t.some(function(o){return Nt(o,i)||G.array(i)&&sa(i)(o)}):G.plainObject(t)&&t[n]?!!t[n]&&Nt(t[n],i):Nt(t,i)}}function Ip(t,r){return r.some(function(n){return!t.includes(n)})}function ui(t){return function(r){return G.array(t)?t.some(function(n){return Nt(n,r)||G.array(r)&&sa(r)(n)}):Nt(t,r)}}function _n(t,r){return G.array(t)?t.some(function(n){return Nt(n,r)}):Nt(t,r)}function sa(t){return function(r){return t.some(function(n){return Nt(n,r)})}}function zc(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return t.every(G.array)||t.every(G.number)||t.every(G.plainObject)||t.every(G.string)}function Yt(t,r){if(G.plainObject(t)||G.array(t)){if(G.string(r)){var n=r.split(".");return n.reduce(function(i,o){return i&&i[o]},t)}return G.number(r)?t[r]:t}return t}function Op(t,r){if([t,r].some(G.nullOrUndefined))throw new Error("Missing required parameters");if(![t,r].every(function(d){return G.plainObject(d)||G.array(d)}))throw new Error("Expected plain objects or array");var n=function(d,h){try{return ci(t,r,{key:d,type:"added",value:h})}catch{return!1}},i=function(d,h,p){try{var f=Yt(t,d),x=Yt(r,d),g=G.defined(h),b=G.defined(p);if(g||b){var y=b?_n(p,f):!_n(h,f),_=_n(h,x);return y&&_}return[f,x].every(G.array)||[f,x].every(G.plainObject)?!Nt(f,x):f!==x}catch{return!1}},o=function(d,h,p){if(!G.defined(d))return!1;try{var f=Yt(t,d),x=Yt(r,d),g=G.defined(p);return _n(h,f)&&(g?_n(p,x):!g)}catch{return!1}},a=function(d,h){return G.defined(d)?i(d,h):!1},s=function(d,h,p){if(!G.defined(d))return!1;try{return ii(t,r,{key:d,actual:h,previous:p,type:"decreased"})}catch{return!1}},c=function(d){try{var h=li(t,r,{key:d}),p=h[0],f=h[1];return!!p.length&&!f.length}catch{return!1}},l=function(d){try{var h=li(t,r,{key:d}),p=h[0],f=h[1];return!p.length&&!!f.length}catch{return!1}},m=function(d,h,p){if(!G.defined(d))return!1;try{return ii(t,r,{key:d,actual:h,previous:p,type:"increased"})}catch{return!1}},u=function(d,h){try{return ci(t,r,{key:d,type:"removed",value:h})}catch{return!1}};return{added:n,changed:i,changedFrom:o,changedTo:a,decreased:s,emptied:c,filled:l,increased:m,removed:u}}function mi(t,r){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(t);r&&(i=i.filter(function(o){return Object.getOwnPropertyDescriptor(t,o).enumerable})),n.push.apply(n,i)}return n}function Ye(t){for(var r=1;r<arguments.length;r++){var n=arguments[r]!=null?arguments[r]:{};r%2?mi(Object(n),!0).forEach(function(i){mt(t,i,n[i])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):mi(Object(n)).forEach(function(i){Object.defineProperty(t,i,Object.getOwnPropertyDescriptor(n,i))})}return t}function Gn(t,r){if(!(t instanceof r))throw new TypeError("Cannot call a class as a function")}function Rp(t,r){for(var n=0;n<r.length;n++){var i=r[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,qc(i.key),i)}}function Hn(t,r,n){return r&&Rp(t.prototype,r),Object.defineProperty(t,"prototype",{writable:!1}),t}function mt(t,r,n){return r=qc(r),r in t?Object.defineProperty(t,r,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[r]=n,t}function Wn(t,r){if(typeof r!="function"&&r!==null)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(r&&r.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),Object.defineProperty(t,"prototype",{writable:!1}),r&&wo(t,r)}function Cs(t){return Cs=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(n){return n.__proto__||Object.getPrototypeOf(n)},Cs(t)}function wo(t,r){return wo=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(i,o){return i.__proto__=o,i},wo(t,r)}function Pp(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}function Mp(t,r){if(t==null)return{};var n={},i=Object.keys(t),o,a;for(a=0;a<i.length;a++)o=i[a],!(r.indexOf(o)>=0)&&(n[o]=t[o]);return n}function Bc(t,r){if(t==null)return{};var n=Mp(t,r),i,o;if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(t);for(o=0;o<a.length;o++)i=a[o],!(r.indexOf(i)>=0)&&Object.prototype.propertyIsEnumerable.call(t,i)&&(n[i]=t[i])}return n}function nr(t){if(t===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}function Lp(t,r){if(r&&(typeof r=="object"||typeof r=="function"))return r;if(r!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return nr(t)}function Xn(t){var r=Pp();return function(){var i=Cs(t),o;if(r){var a=Cs(this).constructor;o=Reflect.construct(i,arguments,a)}else o=i.apply(this,arguments);return Lp(this,o)}}function Dp(t,r){if(typeof t!="object"||t===null)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var i=n.call(t,r||"default");if(typeof i!="object")return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return(r==="string"?String:Number)(t)}function qc(t){var r=Dp(t,"string");return typeof r=="symbol"?r:String(r)}var $p={flip:{padding:20},preventOverflow:{padding:10}},Fp="The typeValidator argument must be a function with the signature function(props, propName, componentName).",Up="The error message is optional, but must be a string if provided.";function zp(t,r,n,i){return typeof t=="boolean"?t:typeof t=="function"?t(r,n,i):t?!!t:!1}function Bp(t,r){return Object.hasOwnProperty.call(t,r)}function qp(t,r,n,i){return new Error("Required ".concat(t[r]," `").concat(r,"` was not specified in `").concat(n,"`."))}function Vp(t,r){if(typeof t!="function")throw new TypeError(Fp);if(r&&typeof r!="string")throw new TypeError(Up)}function hi(t,r,n){return Vp(t,n),function(i,o,a){for(var s=arguments.length,c=new Array(s>3?s-3:0),l=3;l<s;l++)c[l-3]=arguments[l];return zp(r,i,o,a)?Bp(i,o)?t.apply(void 0,[i,o,a].concat(c)):qp(i,o,a):t.apply(void 0,[i,o,a].concat(c))}}var Le={INIT:"init",IDLE:"idle",OPENING:"opening",OPEN:"open",CLOSING:"closing",ERROR:"error"},wn=cs.createPortal!==void 0;function Xt(){return!!(typeof window<"u"&&window.document&&window.document.createElement)}function so(){return"ontouchstart"in window&&/Mobi/.test(navigator.userAgent)}function ss(t){var r=t.title,n=t.data,i=t.warn,o=i===void 0?!1:i,a=t.debug,s=a===void 0?!1:a,c=o?console.warn||console.error:console.log;s&&r&&n&&(console.groupCollapsed("%creact-floater: ".concat(r),"color: #9b00ff; font-weight: bold; font-size: 12px;"),Array.isArray(n)?n.forEach(function(l){G.plainObject(l)&&l.key?c.apply(console,[l.key,l.value]):c.apply(console,[l])}):c.apply(console,[n]),console.groupEnd())}function Gp(t,r,n){var i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;t.addEventListener(r,n,i)}function Hp(t,r,n){var i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;t.removeEventListener(r,n,i)}function Wp(t,r,n){var i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1,o;o=function(s){n(s),Hp(t,r,o)},Gp(t,r,o,i)}function fi(){}var Vc=function(t){Wn(n,t);var r=Xn(n);function n(){return Gn(this,n),r.apply(this,arguments)}return Hn(n,[{key:"componentDidMount",value:function(){Xt()&&(this.node||this.appendNode(),wn||this.renderPortal())}},{key:"componentDidUpdate",value:function(){Xt()&&(wn||this.renderPortal())}},{key:"componentWillUnmount",value:function(){!Xt()||!this.node||(wn||cs.unmountComponentAtNode(this.node),this.node&&this.node.parentNode===document.body&&(document.body.removeChild(this.node),this.node=void 0))}},{key:"appendNode",value:function(){var o=this.props,a=o.id,s=o.zIndex;this.node||(this.node=document.createElement("div"),a&&(this.node.id=a),s&&(this.node.style.zIndex=s),document.body.appendChild(this.node))}},{key:"renderPortal",value:function(){if(!Xt())return null;var o=this.props,a=o.children,s=o.setRef;if(this.node||this.appendNode(),wn)return cs.createPortal(a,this.node);var c=cs.unstable_renderSubtreeIntoContainer(this,a.length>1?we.createElement("div",null,a):a[0],this.node);return s(c),null}},{key:"renderReact16",value:function(){var o=this.props,a=o.hasChildren,s=o.placement,c=o.target;return a?this.renderPortal():c||s==="center"?this.renderPortal():null}},{key:"render",value:function(){return wn?this.renderReact16():null}}]),n}(we.Component);mt(Vc,"propTypes",{children:ae.oneOfType([ae.element,ae.array]),hasChildren:ae.bool,id:ae.oneOfType([ae.string,ae.number]),placement:ae.string,setRef:ae.func.isRequired,target:ae.oneOfType([ae.object,ae.string]),zIndex:ae.number});var Gc=function(t){Wn(n,t);var r=Xn(n);function n(){return Gn(this,n),r.apply(this,arguments)}return Hn(n,[{key:"parentStyle",get:function(){var o=this.props,a=o.placement,s=o.styles,c=s.arrow.length,l={pointerEvents:"none",position:"absolute",width:"100%"};return a.startsWith("top")?(l.bottom=0,l.left=0,l.right=0,l.height=c):a.startsWith("bottom")?(l.left=0,l.right=0,l.top=0,l.height=c):a.startsWith("left")?(l.right=0,l.top=0,l.bottom=0):a.startsWith("right")&&(l.left=0,l.top=0),l}},{key:"render",value:function(){var o=this.props,a=o.placement,s=o.setArrowRef,c=o.styles,l=c.arrow,m=l.color,u=l.display,d=l.length,h=l.margin,p=l.position,f=l.spread,x={display:u,position:p},g,b=f,y=d;return a.startsWith("top")?(g="0,0 ".concat(b/2,",").concat(y," ").concat(b,",0"),x.bottom=0,x.marginLeft=h,x.marginRight=h):a.startsWith("bottom")?(g="".concat(b,",").concat(y," ").concat(b/2,",0 0,").concat(y),x.top=0,x.marginLeft=h,x.marginRight=h):a.startsWith("left")?(y=f,b=d,g="0,0 ".concat(b,",").concat(y/2," 0,").concat(y),x.right=0,x.marginTop=h,x.marginBottom=h):a.startsWith("right")&&(y=f,b=d,g="".concat(b,",").concat(y," ").concat(b,",0 0,").concat(y/2),x.left=0,x.marginTop=h,x.marginBottom=h),we.createElement("div",{className:"__floater__arrow",style:this.parentStyle},we.createElement("span",{ref:s,style:x},we.createElement("svg",{width:b,height:y,version:"1.1",xmlns:"http://www.w3.org/2000/svg"},we.createElement("polygon",{points:g,fill:m}))))}}]),n}(we.Component);mt(Gc,"propTypes",{placement:ae.string.isRequired,setArrowRef:ae.func.isRequired,styles:ae.object.isRequired});var Xp=["color","height","width"];function Hc(t){var r=t.handleClick,n=t.styles,i=n.color,o=n.height,a=n.width,s=Bc(n,Xp);return we.createElement("button",{"aria-label":"close",onClick:r,style:s,type:"button"},we.createElement("svg",{width:"".concat(a,"px"),height:"".concat(o,"px"),viewBox:"0 0 18 18",version:"1.1",xmlns:"http://www.w3.org/2000/svg",preserveAspectRatio:"xMidYMid"},we.createElement("g",null,we.createElement("path",{d:"M8.13911129,9.00268191 L0.171521827,17.0258467 C-0.0498027049,17.248715 -0.0498027049,17.6098394 0.171521827,17.8327545 C0.28204354,17.9443526 0.427188206,17.9998706 0.572051765,17.9998706 C0.71714958,17.9998706 0.862013139,17.9443526 0.972581703,17.8327545 L9.0000937,9.74924618 L17.0276057,17.8327545 C17.1384085,17.9443526 17.2832721,17.9998706 17.4281356,17.9998706 C17.5729992,17.9998706 17.718097,17.9443526 17.8286656,17.8327545 C18.0499901,17.6098862 18.0499901,17.2487618 17.8286656,17.0258467 L9.86135722,9.00268191 L17.8340066,0.973848225 C18.0553311,0.750979934 18.0553311,0.389855532 17.8340066,0.16694039 C17.6126821,-0.0556467968 17.254037,-0.0556467968 17.0329467,0.16694039 L9.00042166,8.25611765 L0.967006424,0.167268345 C0.745681892,-0.0553188426 0.387317931,-0.0553188426 0.165993399,0.167268345 C-0.0553311331,0.390136635 -0.0553311331,0.751261038 0.165993399,0.974176179 L8.13920499,9.00268191 L8.13911129,9.00268191 Z",fill:i}))))}Hc.propTypes={handleClick:ae.func.isRequired,styles:ae.object.isRequired};function Wc(t){var r=t.content,n=t.footer,i=t.handleClick,o=t.open,a=t.positionWrapper,s=t.showCloseButton,c=t.title,l=t.styles,m={content:we.isValidElement(r)?r:we.createElement("div",{className:"__floater__content",style:l.content},r)};return c&&(m.title=we.isValidElement(c)?c:we.createElement("div",{className:"__floater__title",style:l.title},c)),n&&(m.footer=we.isValidElement(n)?n:we.createElement("div",{className:"__floater__footer",style:l.footer},n)),(s||a)&&!G.boolean(o)&&(m.close=we.createElement(Hc,{styles:l.close,handleClick:i})),we.createElement("div",{className:"__floater__container",style:l.container},m.close,m.title,m.content,m.footer)}Wc.propTypes={content:ae.node.isRequired,footer:ae.node,handleClick:ae.func.isRequired,open:ae.bool,positionWrapper:ae.bool.isRequired,showCloseButton:ae.bool.isRequired,styles:ae.object.isRequired,title:ae.node};var Xc=function(t){Wn(n,t);var r=Xn(n);function n(){return Gn(this,n),r.apply(this,arguments)}return Hn(n,[{key:"style",get:function(){var o=this.props,a=o.disableAnimation,s=o.component,c=o.placement,l=o.hideArrow,m=o.status,u=o.styles,d=u.arrow.length,h=u.floater,p=u.floaterCentered,f=u.floaterClosing,x=u.floaterOpening,g=u.floaterWithAnimation,b=u.floaterWithComponent,y={};return l||(c.startsWith("top")?y.padding="0 0 ".concat(d,"px"):c.startsWith("bottom")?y.padding="".concat(d,"px 0 0"):c.startsWith("left")?y.padding="0 ".concat(d,"px 0 0"):c.startsWith("right")&&(y.padding="0 0 0 ".concat(d,"px"))),[Le.OPENING,Le.OPEN].indexOf(m)!==-1&&(y=Ye(Ye({},y),x)),m===Le.CLOSING&&(y=Ye(Ye({},y),f)),m===Le.OPEN&&!a&&(y=Ye(Ye({},y),g)),c==="center"&&(y=Ye(Ye({},y),p)),s&&(y=Ye(Ye({},y),b)),Ye(Ye({},h),y)}},{key:"render",value:function(){var o=this.props,a=o.component,s=o.handleClick,c=o.hideArrow,l=o.setFloaterRef,m=o.status,u={},d=["__floater"];return a?we.isValidElement(a)?u.content=we.cloneElement(a,{closeFn:s}):u.content=a({closeFn:s}):u.content=we.createElement(Wc,this.props),m===Le.OPEN&&d.push("__floater__open"),c||(u.arrow=we.createElement(Gc,this.props)),we.createElement("div",{ref:l,className:d.join(" "),style:this.style},we.createElement("div",{className:"__floater__body"},u.content,u.arrow))}}]),n}(we.Component);mt(Xc,"propTypes",{component:ae.oneOfType([ae.func,ae.element]),content:ae.node,disableAnimation:ae.bool.isRequired,footer:ae.node,handleClick:ae.func.isRequired,hideArrow:ae.bool.isRequired,open:ae.bool,placement:ae.string.isRequired,positionWrapper:ae.bool.isRequired,setArrowRef:ae.func.isRequired,setFloaterRef:ae.func.isRequired,showCloseButton:ae.bool,status:ae.string.isRequired,styles:ae.object.isRequired,title:ae.node});var Jc=function(t){Wn(n,t);var r=Xn(n);function n(){return Gn(this,n),r.apply(this,arguments)}return Hn(n,[{key:"render",value:function(){var o=this.props,a=o.children,s=o.handleClick,c=o.handleMouseEnter,l=o.handleMouseLeave,m=o.setChildRef,u=o.setWrapperRef,d=o.style,h=o.styles,p;if(a)if(we.Children.count(a)===1)if(!we.isValidElement(a))p=we.createElement("span",null,a);else{var f=G.function(a.type)?"innerRef":"ref";p=we.cloneElement(we.Children.only(a),mt({},f,m))}else p=a;return p?we.createElement("span",{ref:u,style:Ye(Ye({},h),d),onClick:s,onMouseEnter:c,onMouseLeave:l},p):null}}]),n}(we.Component);mt(Jc,"propTypes",{children:ae.node,handleClick:ae.func.isRequired,handleMouseEnter:ae.func.isRequired,handleMouseLeave:ae.func.isRequired,setChildRef:ae.func.isRequired,setWrapperRef:ae.func.isRequired,style:ae.object,styles:ae.object.isRequired});var Jp={zIndex:100};function Kp(t){var r=Ft(Jp,t.options||{});return{wrapper:{cursor:"help",display:"inline-flex",flexDirection:"column",zIndex:r.zIndex},wrapperPosition:{left:-1e3,position:"absolute",top:-1e3,visibility:"hidden"},floater:{display:"inline-block",filter:"drop-shadow(0 0 3px rgba(0, 0, 0, 0.3))",maxWidth:300,opacity:0,position:"relative",transition:"opacity 0.3s",visibility:"hidden",zIndex:r.zIndex},floaterOpening:{opacity:1,visibility:"visible"},floaterWithAnimation:{opacity:1,transition:"opacity 0.3s, transform 0.2s",visibility:"visible"},floaterWithComponent:{maxWidth:"100%"},floaterClosing:{opacity:0,visibility:"visible"},floaterCentered:{left:"50%",position:"fixed",top:"50%",transform:"translate(-50%, -50%)"},container:{backgroundColor:"#fff",color:"#666",minHeight:60,minWidth:200,padding:20,position:"relative",zIndex:10},title:{borderBottom:"1px solid #555",color:"#555",fontSize:18,marginBottom:5,paddingBottom:6,paddingRight:18},content:{fontSize:15},close:{backgroundColor:"transparent",border:0,borderRadius:0,color:"#555",fontSize:0,height:15,outline:"none",padding:10,position:"absolute",right:0,top:0,width:15,WebkitAppearance:"none"},footer:{borderTop:"1px solid #ccc",fontSize:13,marginTop:10,paddingTop:5},arrow:{color:"#fff",display:"inline-flex",length:16,margin:8,position:"absolute",spread:32},options:r}}var Yp=["arrow","flip","offset"],Qp=["position","top","right","bottom","left"],oa=function(t){Wn(n,t);var r=Xn(n);function n(i){var o;return Gn(this,n),o=r.call(this,i),mt(nr(o),"setArrowRef",function(a){o.arrowRef=a}),mt(nr(o),"setChildRef",function(a){o.childRef=a}),mt(nr(o),"setFloaterRef",function(a){o.floaterRef=a}),mt(nr(o),"setWrapperRef",function(a){o.wrapperRef=a}),mt(nr(o),"handleTransitionEnd",function(){var a=o.state.status,s=o.props.callback;o.wrapperPopper&&o.wrapperPopper.instance.update(),o.setState({status:a===Le.OPENING?Le.OPEN:Le.IDLE},function(){var c=o.state.status;s(c===Le.OPEN?"open":"close",o.props)})}),mt(nr(o),"handleClick",function(){var a=o.props,s=a.event,c=a.open;if(!G.boolean(c)){var l=o.state,m=l.positionWrapper,u=l.status;(o.event==="click"||o.event==="hover"&&m)&&(ss({title:"click",data:[{event:s,status:u===Le.OPEN?"closing":"opening"}],debug:o.debug}),o.toggle())}}),mt(nr(o),"handleMouseEnter",function(){var a=o.props,s=a.event,c=a.open;if(!(G.boolean(c)||so())){var l=o.state.status;o.event==="hover"&&l===Le.IDLE&&(ss({title:"mouseEnter",data:[{key:"originalEvent",value:s}],debug:o.debug}),clearTimeout(o.eventDelayTimeout),o.toggle())}}),mt(nr(o),"handleMouseLeave",function(){var a=o.props,s=a.event,c=a.eventDelay,l=a.open;if(!(G.boolean(l)||so())){var m=o.state,u=m.status,d=m.positionWrapper;o.event==="hover"&&(ss({title:"mouseLeave",data:[{key:"originalEvent",value:s}],debug:o.debug}),c?[Le.OPENING,Le.OPEN].indexOf(u)!==-1&&!d&&!o.eventDelayTimeout&&(o.eventDelayTimeout=setTimeout(function(){delete o.eventDelayTimeout,o.toggle()},c*1e3)):o.toggle(Le.IDLE))}}),o.state={currentPlacement:i.placement,needsUpdate:!1,positionWrapper:i.wrapperOptions.position&&!!i.target,status:Le.INIT,statusWrapper:Le.INIT},o._isMounted=!1,o.hasMounted=!1,Xt()&&window.addEventListener("load",function(){o.popper&&o.popper.instance.update(),o.wrapperPopper&&o.wrapperPopper.instance.update()}),o}return Hn(n,[{key:"componentDidMount",value:function(){if(Xt()){var o=this.state.positionWrapper,a=this.props,s=a.children,c=a.open,l=a.target;this._isMounted=!0,ss({title:"init",data:{hasChildren:!!s,hasTarget:!!l,isControlled:G.boolean(c),positionWrapper:o,target:this.target,floater:this.floaterRef},debug:this.debug}),this.hasMounted||(this.initPopper(),this.hasMounted=!0),!s&&l&&G.boolean(c)}}},{key:"componentDidUpdate",value:function(o,a){if(Xt()){var s=this.props,c=s.autoOpen,l=s.open,m=s.target,u=s.wrapperOptions,d=Op(a,this.state),h=d.changedFrom,p=d.changed;if(o.open!==l){var f;G.boolean(l)&&(f=l?Le.OPENING:Le.CLOSING),this.toggle(f)}(o.wrapperOptions.position!==u.position||o.target!==m)&&this.changeWrapperPosition(this.props),p("status",Le.IDLE)&&l?this.toggle(Le.OPEN):h("status",Le.INIT,Le.IDLE)&&c&&this.toggle(Le.OPEN),this.popper&&p("status",Le.OPENING)&&this.popper.instance.update(),this.floaterRef&&(p("status",Le.OPENING)||p("status",Le.CLOSING))&&Wp(this.floaterRef,"transitionend",this.handleTransitionEnd),p("needsUpdate",!0)&&this.rebuildPopper()}}},{key:"componentWillUnmount",value:function(){Xt()&&(this._isMounted=!1,this.popper&&this.popper.instance.destroy(),this.wrapperPopper&&this.wrapperPopper.instance.destroy())}},{key:"initPopper",value:function(){var o=this,a=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.target,s=this.state.positionWrapper,c=this.props,l=c.disableFlip,m=c.getPopper,u=c.hideArrow,d=c.offset,h=c.placement,p=c.wrapperOptions,f=h==="top"||h==="bottom"?"flip":["right","bottom-end","top-end","left","top-start","bottom-start"];if(h==="center")this.setState({status:Le.IDLE});else if(a&&this.floaterRef){var x=this.options,g=x.arrow,b=x.flip,y=x.offset,_=Bc(x,Yp);new Rn(a,this.floaterRef,{placement:h,modifiers:Ye({arrow:Ye({enabled:!u,element:this.arrowRef},g),flip:Ye({enabled:!l,behavior:f},b),offset:Ye({offset:"0, ".concat(d,"px")},y)},_),onCreate:function(w){var N;if(o.popper=w,!((N=o.floaterRef)!==null&&N!==void 0&&N.isConnected)){o.setState({needsUpdate:!0});return}m(w,"floater"),o._isMounted&&o.setState({currentPlacement:w.placement,status:Le.IDLE}),h!==w.placement&&setTimeout(function(){w.instance.update()},1)},onUpdate:function(w){o.popper=w;var N=o.state.currentPlacement;o._isMounted&&w.placement!==N&&o.setState({currentPlacement:w.placement})}})}if(s){var j=G.undefined(p.offset)?0:p.offset;new Rn(this.target,this.wrapperRef,{placement:p.placement||h,modifiers:{arrow:{enabled:!1},offset:{offset:"0, ".concat(j,"px")},flip:{enabled:!1}},onCreate:function(w){o.wrapperPopper=w,o._isMounted&&o.setState({statusWrapper:Le.IDLE}),m(w,"wrapper"),h!==w.placement&&setTimeout(function(){w.instance.update()},1)}})}}},{key:"rebuildPopper",value:function(){var o=this;this.floaterRefInterval=setInterval(function(){var a;(a=o.floaterRef)!==null&&a!==void 0&&a.isConnected&&(clearInterval(o.floaterRefInterval),o.setState({needsUpdate:!1}),o.initPopper())},50)}},{key:"changeWrapperPosition",value:function(o){var a=o.target,s=o.wrapperOptions;this.setState({positionWrapper:s.position&&!!a})}},{key:"toggle",value:function(o){var a=this.state.status,s=a===Le.OPEN?Le.CLOSING:Le.OPENING;G.undefined(o)||(s=o),this.setState({status:s})}},{key:"debug",get:function(){var o=this.props.debug;return o||Xt()&&"ReactFloaterDebug"in window&&!!window.ReactFloaterDebug}},{key:"event",get:function(){var o=this.props,a=o.disableHoverToClick,s=o.event;return s==="hover"&&so()&&!a?"click":s}},{key:"options",get:function(){var o=this.props.options;return Ft($p,o||{})}},{key:"styles",get:function(){var o=this,a=this.state,s=a.status,c=a.positionWrapper,l=a.statusWrapper,m=this.props.styles,u=Ft(Kp(m),m);if(c){var d;[Le.IDLE].indexOf(s)===-1||[Le.IDLE].indexOf(l)===-1?d=u.wrapperPosition:d=this.wrapperPopper.styles,u.wrapper=Ye(Ye({},u.wrapper),d)}if(this.target){var h=window.getComputedStyle(this.target);this.wrapperStyles?u.wrapper=Ye(Ye({},u.wrapper),this.wrapperStyles):["relative","static"].indexOf(h.position)===-1&&(this.wrapperStyles={},c||(Qp.forEach(function(p){o.wrapperStyles[p]=h[p]}),u.wrapper=Ye(Ye({},u.wrapper),this.wrapperStyles),this.target.style.position="relative",this.target.style.top="auto",this.target.style.right="auto",this.target.style.bottom="auto",this.target.style.left="auto"))}return u}},{key:"target",get:function(){if(!Xt())return null;var o=this.props.target;return o?G.domElement(o)?o:document.querySelector(o):this.childRef||this.wrapperRef}},{key:"render",value:function(){var o=this.state,a=o.currentPlacement,s=o.positionWrapper,c=o.status,l=this.props,m=l.children,u=l.component,d=l.content,h=l.disableAnimation,p=l.footer,f=l.hideArrow,x=l.id,g=l.open,b=l.showCloseButton,y=l.style,_=l.target,j=l.title,I=we.createElement(Jc,{handleClick:this.handleClick,handleMouseEnter:this.handleMouseEnter,handleMouseLeave:this.handleMouseLeave,setChildRef:this.setChildRef,setWrapperRef:this.setWrapperRef,style:y,styles:this.styles.wrapper},m),w={};return s?w.wrapperInPortal=I:w.wrapperAsChildren=I,we.createElement("span",null,we.createElement(Vc,{hasChildren:!!m,id:x,placement:a,setRef:this.setFloaterRef,target:_,zIndex:this.styles.options.zIndex},we.createElement(Xc,{component:u,content:d,disableAnimation:h,footer:p,handleClick:this.handleClick,hideArrow:f||a==="center",open:g,placement:a,positionWrapper:s,setArrowRef:this.setArrowRef,setFloaterRef:this.setFloaterRef,showCloseButton:b,status:c,styles:this.styles,title:j}),w.wrapperInPortal),w.wrapperAsChildren)}}]),n}(we.Component);mt(oa,"propTypes",{autoOpen:ae.bool,callback:ae.func,children:ae.node,component:hi(ae.oneOfType([ae.func,ae.element]),function(t){return!t.content}),content:hi(ae.node,function(t){return!t.component}),debug:ae.bool,disableAnimation:ae.bool,disableFlip:ae.bool,disableHoverToClick:ae.bool,event:ae.oneOf(["hover","click"]),eventDelay:ae.number,footer:ae.node,getPopper:ae.func,hideArrow:ae.bool,id:ae.oneOfType([ae.string,ae.number]),offset:ae.number,open:ae.bool,options:ae.object,placement:ae.oneOf(["top","top-start","top-end","bottom","bottom-start","bottom-end","left","left-start","left-end","right","right-start","right-end","auto","center"]),showCloseButton:ae.bool,style:ae.object,styles:ae.object,target:ae.oneOfType([ae.object,ae.string]),title:ae.node,wrapperOptions:ae.shape({offset:ae.number,placement:ae.oneOf(["top","top-start","top-end","bottom","bottom-start","bottom-end","left","left-start","left-end","right","right-start","right-end","auto"]),position:ae.bool})});mt(oa,"defaultProps",{autoOpen:!1,callback:fi,debug:!1,disableAnimation:!1,disableFlip:!1,disableHoverToClick:!1,event:"click",eventDelay:.4,getPopper:fi,hideArrow:!1,offset:15,placement:"bottom",showCloseButton:!1,styles:{},target:null,wrapperOptions:{position:!1}});var Zp=Object.defineProperty,e0=(t,r,n)=>r in t?Zp(t,r,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[r]=n,pe=(t,r,n)=>e0(t,typeof r!="symbol"?r+"":r,n),Be={INIT:"init",START:"start",STOP:"stop",RESET:"reset",PREV:"prev",NEXT:"next",GO:"go",CLOSE:"close",SKIP:"skip",UPDATE:"update"},Dt={TOUR_START:"tour:start",STEP_BEFORE:"step:before",BEACON:"beacon",TOOLTIP:"tooltip",STEP_AFTER:"step:after",TOUR_END:"tour:end",TOUR_STATUS:"tour:status",TARGET_NOT_FOUND:"error:target_not_found",ERROR:"error"},Ee={INIT:"init",READY:"ready",BEACON:"beacon",TOOLTIP:"tooltip",COMPLETE:"complete",ERROR:"error"},Oe={IDLE:"idle",READY:"ready",WAITING:"waiting",RUNNING:"running",PAUSED:"paused",SKIPPED:"skipped",FINISHED:"finished",ERROR:"error"};function hr(){var t;return!!(typeof window<"u"&&((t=window.document)!=null&&t.createElement))}function Kc(t){return t?t.getBoundingClientRect():null}function t0(t=!1){const{body:r,documentElement:n}=document;if(!r||!n)return 0;if(t){const i=[r.scrollHeight,r.offsetHeight,n.clientHeight,n.scrollHeight,n.offsetHeight].sort((a,s)=>a-s),o=Math.floor(i.length/2);return i.length%2===0?(i[o-1]+i[o])/2:i[o]}return Math.max(r.scrollHeight,r.offsetHeight,n.clientHeight,n.scrollHeight,n.offsetHeight)}function or(t){if(typeof t=="string")try{return document.querySelector(t)}catch{return null}return t}function r0(t){return!t||t.nodeType!==1?null:getComputedStyle(t)}function Pn(t,r,n){if(!t)return Cr();const i=jc(t);if(i){if(i.isSameNode(Cr()))return n?document:Cr();if(!(i.scrollHeight>i.offsetHeight)&&!r)return i.style.overflow="initial",Cr()}return i}function zs(t,r){if(!t)return!1;const n=Pn(t,r);return n?!n.isSameNode(Cr()):!1}function n0(t){return t.offsetParent!==document.body}function ln(t,r="fixed"){if(!t||!(t instanceof HTMLElement))return!1;const{nodeName:n}=t,i=r0(t);return n==="BODY"||n==="HTML"?!1:i&&i.position===r?!0:t.parentNode?ln(t.parentNode,r):!1}function s0(t){var r;if(!t)return!1;let n=t;for(;n&&n!==document.body;){if(n instanceof HTMLElement){const{display:i,visibility:o}=getComputedStyle(n);if(i==="none"||o==="hidden")return!1}n=(r=n.parentElement)!=null?r:null}return!0}function o0(t,r,n){var i,o,a;const s=Kc(t),c=Pn(t,n),l=zs(t,n),m=ln(t);let u=0,d=(i=s==null?void 0:s.top)!=null?i:0;if(l&&m){const h=(o=t==null?void 0:t.offsetTop)!=null?o:0,p=(a=c==null?void 0:c.scrollTop)!=null?a:0;d=h-p}else c instanceof HTMLElement&&(u=c.scrollTop,!l&&!ln(t)&&(d+=u),c.isSameNode(Cr())||(d+=Cr().scrollTop));return Math.floor(d-r)}function a0(t,r,n){var i;if(!t)return 0;const{offsetTop:o=0,scrollTop:a=0}=(i=jc(t))!=null?i:{};let s=t.getBoundingClientRect().top+a;o&&(zs(t,n)||n0(t))&&(s-=o);const c=Math.floor(s-r);return c<0?0:c}function Cr(){var t;return(t=document.scrollingElement)!=null?t:document.documentElement}function i0(t,r){const{duration:n,element:i}=r;return new Promise((o,a)=>{const{scrollTop:s}=i,c=t>s?t-s:s-t;pf.top(i,t,{duration:c<100?50:n},l=>l&&l.message!=="Element already at target scroll position"?a(l):o())})}var jn=ls.createPortal!==void 0;function Yc(t=navigator.userAgent){let r=t;return typeof window>"u"?r="node":document.documentMode?r="ie":/Edge/.test(t)?r="edge":window.opera||t.includes(" OPR/")?r="opera":typeof window.InstallTrigger<"u"?r="firefox":window.chrome?r="chrome":/(Version\/([\d._]+).*Safari|CriOS|FxiOS| Mobile\/)/.test(t)&&(r="safari"),r}function ms(t){return Object.prototype.toString.call(t).slice(8,-1).toLowerCase()}function Jt(t,r={}){const{defaultValue:n,step:i,steps:o}=r;let a=Qa(t);if(a)(a.includes("{step}")||a.includes("{steps}"))&&i&&o&&(a=a.replace("{step}",i.toString()).replace("{steps}",o.toString()));else if(v.isValidElement(t)&&!Object.values(t.props).length&&ms(t.type)==="function"){const s=t.type({});a=Jt(s,r)}else a=Qa(n);return a}function c0(t,r){return!he.plainObject(t)||!he.array(r)?!1:Object.keys(t).every(n=>r.includes(n))}function l0(t){const r=/^#?([\da-f])([\da-f])([\da-f])$/i,n=t.replace(r,(o,a,s,c)=>a+a+s+s+c+c),i=/^#?([\da-f]{2})([\da-f]{2})([\da-f]{2})$/i.exec(n);return i?[parseInt(i[1],16),parseInt(i[2],16),parseInt(i[3],16)]:[]}function pi(t){return t.disableBeacon||t.placement==="center"}function xi(){return!["chrome","safari","firefox","opera"].includes(Yc())}function Or({data:t,debug:r=!1,title:n,warn:i=!1}){const o=i?console.warn||console.error:console.log;r&&(n&&t?(console.groupCollapsed(`%creact-joyride: ${n}`,"color: #ff0044; font-weight: bold; font-size: 12px;"),Array.isArray(t)?t.forEach(a=>{he.plainObject(a)&&a.key?o.apply(console,[a.key,a.value]):o.apply(console,[a])}):o.apply(console,[t]),console.groupEnd()):console.error("Missing title or data props"))}function d0(t){return Object.keys(t)}function Qc(t,...r){if(!he.plainObject(t))throw new TypeError("Expected an object");const n={};for(const i in t)({}).hasOwnProperty.call(t,i)&&(r.includes(i)||(n[i]=t[i]));return n}function u0(t,...r){if(!he.plainObject(t))throw new TypeError("Expected an object");if(!r.length)return t;const n={};for(const i in t)({}).hasOwnProperty.call(t,i)&&r.includes(i)&&(n[i]=t[i]);return n}function jo(t,r,n){const i=a=>a.replace("{step}",String(r)).replace("{steps}",String(n));if(ms(t)==="string")return i(t);if(!v.isValidElement(t))return t;const{children:o}=t.props;if(ms(o)==="string"&&o.includes("{step}"))return v.cloneElement(t,{children:i(o)});if(Array.isArray(o))return v.cloneElement(t,{children:o.map(a=>typeof a=="string"?i(a):jo(a,r,n))});if(ms(t.type)==="function"&&!Object.values(t.props).length){const a=t.type({});return jo(a,r,n)}return t}function m0(t){const{isFirstStep:r,lifecycle:n,previousLifecycle:i,scrollToFirstStep:o,step:a,target:s}=t;return!a.disableScrolling&&(!r||o||n===Ee.TOOLTIP)&&a.placement!=="center"&&(!a.isFixed||!ln(s))&&i!==n&&[Ee.BEACON,Ee.TOOLTIP].includes(n)}var h0={options:{preventOverflow:{boundariesElement:"scrollParent"}},wrapperOptions:{offset:-18,position:!0}},Zc={back:"Back",close:"Close",last:"Last",next:"Next",nextLabelWithProgress:"Next (Step {step} of {steps})",open:"Open the dialog",skip:"Skip"},f0={event:"click",placement:"bottom",offset:10,disableBeacon:!1,disableCloseOnEsc:!1,disableOverlay:!1,disableOverlayClose:!1,disableScrollParentFix:!1,disableScrolling:!1,hideBackButton:!1,hideCloseButton:!1,hideFooter:!1,isFixed:!1,locale:Zc,showProgress:!1,showSkipButton:!1,spotlightClicks:!1,spotlightPadding:10},p0={continuous:!1,debug:!1,disableCloseOnEsc:!1,disableOverlay:!1,disableOverlayClose:!1,disableScrolling:!1,disableScrollParentFix:!1,getHelpers:void 0,hideBackButton:!1,run:!0,scrollOffset:20,scrollDuration:300,scrollToFirstStep:!1,showSkipButton:!1,showProgress:!1,spotlightClicks:!1,spotlightPadding:10,steps:[]},x0={arrowColor:"#fff",backgroundColor:"#fff",beaconSize:36,overlayColor:"rgba(0, 0, 0, 0.5)",primaryColor:"#f04",spotlightShadow:"0 0 15px rgba(0, 0, 0, 0.5)",textColor:"#333",width:380,zIndex:100},Nn={backgroundColor:"transparent",border:0,borderRadius:0,color:"#555",cursor:"pointer",fontSize:16,lineHeight:1,padding:8,WebkitAppearance:"none"},gi={borderRadius:4,position:"absolute"};function g0(t,r){var n,i,o,a,s;const{floaterProps:c,styles:l}=t,m=Ft((n=r.floaterProps)!=null?n:{},c??{}),u=Ft(l??{},(i=r.styles)!=null?i:{}),d=Ft(x0,u.options||{}),h=r.placement==="center"||r.disableBeacon;let{width:p}=d;window.innerWidth>480&&(p=380),"width"in d&&(p=typeof d.width=="number"&&window.innerWidth<d.width?window.innerWidth-30:d.width);const f={bottom:0,left:0,overflow:"hidden",position:"absolute",right:0,top:0,zIndex:d.zIndex},x={beacon:{...Nn,display:h?"none":"inline-block",height:d.beaconSize,position:"relative",width:d.beaconSize,zIndex:d.zIndex},beaconInner:{animation:"joyride-beacon-inner 1.2s infinite ease-in-out",backgroundColor:d.primaryColor,borderRadius:"50%",display:"block",height:"50%",left:"50%",opacity:.7,position:"absolute",top:"50%",transform:"translate(-50%, -50%)",width:"50%"},beaconOuter:{animation:"joyride-beacon-outer 1.2s infinite ease-in-out",backgroundColor:`rgba(${l0(d.primaryColor).join(",")}, 0.2)`,border:`2px solid ${d.primaryColor}`,borderRadius:"50%",boxSizing:"border-box",display:"block",height:"100%",left:0,opacity:.9,position:"absolute",top:0,transformOrigin:"center",width:"100%"},tooltip:{backgroundColor:d.backgroundColor,borderRadius:5,boxSizing:"border-box",color:d.textColor,fontSize:16,maxWidth:"100%",padding:15,position:"relative",width:p},tooltipContainer:{lineHeight:1.4,textAlign:"center"},tooltipTitle:{fontSize:18,margin:0},tooltipContent:{padding:"20px 10px"},tooltipFooter:{alignItems:"center",display:"flex",justifyContent:"flex-end",marginTop:15},tooltipFooterSpacer:{flex:1},buttonNext:{...Nn,backgroundColor:d.primaryColor,borderRadius:4,color:"#fff"},buttonBack:{...Nn,color:d.primaryColor,marginLeft:"auto",marginRight:5},buttonClose:{...Nn,color:d.textColor,height:14,padding:15,position:"absolute",right:0,top:0,width:14},buttonSkip:{...Nn,color:d.textColor,fontSize:14},overlay:{...f,backgroundColor:d.overlayColor,mixBlendMode:"hard-light"},overlayLegacy:{...f},overlayLegacyCenter:{...f,backgroundColor:d.overlayColor},spotlight:{...gi,backgroundColor:"gray"},spotlightLegacy:{...gi,boxShadow:`0 0 0 9999px ${d.overlayColor}, ${d.spotlightShadow}`},floaterStyles:{arrow:{color:(s=(a=(o=m==null?void 0:m.styles)==null?void 0:o.arrow)==null?void 0:a.color)!=null?s:d.arrowColor},options:{zIndex:d.zIndex+100}},options:d};return Ft(x,u)}function b0(t){return u0(t,"beaconComponent","disableCloseOnEsc","disableOverlay","disableOverlayClose","disableScrolling","disableScrollParentFix","floaterProps","hideBackButton","hideCloseButton","locale","showProgress","showSkipButton","spotlightClicks","spotlightPadding","styles","tooltipComponent")}function $r(t,r){var n,i,o,a,s,c;const l=r??{},m=Ft.all([f0,b0(t),l],{isMergeableObject:he.plainObject}),u=g0(t,m),d=zs(or(m.target),m.disableScrollParentFix),h=Ft.all([h0,(n=t.floaterProps)!=null?n:{},(i=m.floaterProps)!=null?i:{}]);return h.offset=m.offset,h.styles=Ft((o=h.styles)!=null?o:{},u.floaterStyles),h.offset+=(s=(a=t.spotlightPadding)!=null?a:m.spotlightPadding)!=null?s:0,m.placementBeacon&&h.wrapperOptions&&(h.wrapperOptions.placement=m.placementBeacon),d&&h.options.preventOverflow&&(h.options.preventOverflow.boundariesElement="window"),{...m,locale:Ft.all([Zc,(c=t.locale)!=null?c:{},m.locale||{}]),floaterProps:h,styles:Qc(u,"floaterStyles")}}function el(t,r=!1){return he.plainObject(t)?t.target?!0:(Or({title:"validateStep",data:"target is missing from the step",warn:!0,debug:r}),!1):(Or({title:"validateStep",data:"step must be an object",warn:!0,debug:r}),!1)}function bi(t,r=!1){return he.array(t)?t.every(n=>el(n,r)):(Or({title:"validateSteps",data:"steps must be an array",warn:!0,debug:r}),!1)}var tl={action:"init",controlled:!1,index:0,lifecycle:Ee.INIT,origin:null,size:0,status:Oe.IDLE},yi=d0(Qc(tl,"controlled","size")),y0=class{constructor(t){pe(this,"beaconPopper"),pe(this,"tooltipPopper"),pe(this,"data",new Map),pe(this,"listener"),pe(this,"store",new Map),pe(this,"addListener",o=>{this.listener=o}),pe(this,"setSteps",o=>{const{size:a,status:s}=this.getState(),c={size:o.length,status:s};this.data.set("steps",o),s===Oe.WAITING&&!a&&o.length&&(c.status=Oe.RUNNING),this.setState(c)}),pe(this,"getPopper",o=>o==="beacon"?this.beaconPopper:this.tooltipPopper),pe(this,"setPopper",(o,a)=>{o==="beacon"?this.beaconPopper=a:this.tooltipPopper=a}),pe(this,"cleanupPoppers",()=>{this.beaconPopper=null,this.tooltipPopper=null}),pe(this,"close",(o=null)=>{const{index:a,status:s}=this.getState();s===Oe.RUNNING&&this.setState({...this.getNextState({action:Be.CLOSE,index:a+1,origin:o})})}),pe(this,"go",o=>{const{controlled:a,status:s}=this.getState();if(a||s!==Oe.RUNNING)return;const c=this.getSteps()[o];this.setState({...this.getNextState({action:Be.GO,index:o}),status:c?s:Oe.FINISHED})}),pe(this,"info",()=>this.getState()),pe(this,"next",()=>{const{index:o,status:a}=this.getState();a===Oe.RUNNING&&this.setState(this.getNextState({action:Be.NEXT,index:o+1}))}),pe(this,"open",()=>{const{status:o}=this.getState();o===Oe.RUNNING&&this.setState({...this.getNextState({action:Be.UPDATE,lifecycle:Ee.TOOLTIP})})}),pe(this,"prev",()=>{const{index:o,status:a}=this.getState();a===Oe.RUNNING&&this.setState({...this.getNextState({action:Be.PREV,index:o-1})})}),pe(this,"reset",(o=!1)=>{const{controlled:a}=this.getState();a||this.setState({...this.getNextState({action:Be.RESET,index:0}),status:o?Oe.RUNNING:Oe.READY})}),pe(this,"skip",()=>{const{status:o}=this.getState();o===Oe.RUNNING&&this.setState({action:Be.SKIP,lifecycle:Ee.INIT,status:Oe.SKIPPED})}),pe(this,"start",o=>{const{index:a,size:s}=this.getState();this.setState({...this.getNextState({action:Be.START,index:he.number(o)?o:a},!0),status:s?Oe.RUNNING:Oe.WAITING})}),pe(this,"stop",(o=!1)=>{const{index:a,status:s}=this.getState();[Oe.FINISHED,Oe.SKIPPED].includes(s)||this.setState({...this.getNextState({action:Be.STOP,index:a+(o?1:0)}),status:Oe.PAUSED})}),pe(this,"update",o=>{var a,s;if(!c0(o,yi))throw new Error(`State is not valid. Valid keys: ${yi.join(", ")}`);this.setState({...this.getNextState({...this.getState(),...o,action:(a=o.action)!=null?a:Be.UPDATE,origin:(s=o.origin)!=null?s:null},!0)})});const{continuous:r=!1,stepIndex:n,steps:i=[]}=t??{};this.setState({action:Be.INIT,controlled:he.number(n),continuous:r,index:he.number(n)?n:0,lifecycle:Ee.INIT,origin:null,status:i.length?Oe.READY:Oe.IDLE},!0),this.beaconPopper=null,this.tooltipPopper=null,this.listener=null,this.setSteps(i)}getState(){return this.store.size?{action:this.store.get("action")||"",controlled:this.store.get("controlled")||!1,index:parseInt(this.store.get("index"),10),lifecycle:this.store.get("lifecycle")||"",origin:this.store.get("origin")||null,size:this.store.get("size")||0,status:this.store.get("status")||""}:{...tl}}getNextState(t,r=!1){var n,i,o,a,s;const{action:c,controlled:l,index:m,size:u,status:d}=this.getState(),h=he.number(t.index)?t.index:m,p=l&&!r?m:Math.min(Math.max(h,0),u);return{action:(n=t.action)!=null?n:c,controlled:l,index:p,lifecycle:(i=t.lifecycle)!=null?i:Ee.INIT,origin:(o=t.origin)!=null?o:null,size:(a=t.size)!=null?a:u,status:p===u?Oe.FINISHED:(s=t.status)!=null?s:d}}getSteps(){const t=this.data.get("steps");return Array.isArray(t)?t:[]}hasUpdatedState(t){const r=JSON.stringify(t),n=JSON.stringify(this.getState());return r!==n}setState(t,r=!1){const n=this.getState(),{action:i,index:o,lifecycle:a,origin:s=null,size:c,status:l}={...n,...t};this.store.set("action",i),this.store.set("index",o),this.store.set("lifecycle",a),this.store.set("origin",s),this.store.set("size",c),this.store.set("status",l),r&&(this.store.set("controlled",t.controlled),this.store.set("continuous",t.continuous)),this.listener&&this.hasUpdatedState(n)&&this.listener(this.getState())}getHelpers(){return{close:this.close,go:this.go,info:this.info,next:this.next,open:this.open,prev:this.prev,reset:this.reset,skip:this.skip}}};function v0(t){return new y0(t)}function _0({styles:t}){return v.createElement("div",{key:"JoyrideSpotlight",className:"react-joyride__spotlight","data-test-id":"spotlight",style:t})}var w0=_0,j0=class extends v.Component{constructor(){super(...arguments),pe(this,"isActive",!1),pe(this,"resizeTimeout"),pe(this,"scrollTimeout"),pe(this,"scrollParent"),pe(this,"state",{isScrolling:!1,mouseOverSpotlight:!1,showSpotlight:!0}),pe(this,"hideSpotlight",()=>{const{continuous:t,disableOverlay:r,lifecycle:n}=this.props,i=[Ee.INIT,Ee.BEACON,Ee.COMPLETE,Ee.ERROR];return r||(t?i.includes(n):n!==Ee.TOOLTIP)}),pe(this,"handleMouseMove",t=>{const{mouseOverSpotlight:r}=this.state,{height:n,left:i,position:o,top:a,width:s}=this.spotlightStyles,c=o==="fixed"?t.clientY:t.pageY,l=o==="fixed"?t.clientX:t.pageX,m=c>=a&&c<=a+n,d=l>=i&&l<=i+s&&m;d!==r&&this.updateState({mouseOverSpotlight:d})}),pe(this,"handleScroll",()=>{const{target:t}=this.props,r=or(t);if(this.scrollParent!==document){const{isScrolling:n}=this.state;n||this.updateState({isScrolling:!0,showSpotlight:!1}),clearTimeout(this.scrollTimeout),this.scrollTimeout=window.setTimeout(()=>{this.updateState({isScrolling:!1,showSpotlight:!0})},50)}else ln(r,"sticky")&&this.updateState({})}),pe(this,"handleResize",()=>{clearTimeout(this.resizeTimeout),this.resizeTimeout=window.setTimeout(()=>{this.isActive&&this.forceUpdate()},100)})}componentDidMount(){const{debug:t,disableScrolling:r,disableScrollParentFix:n=!1,target:i}=this.props,o=or(i);this.scrollParent=Pn(o??document.body,n,!0),this.isActive=!0,window.addEventListener("resize",this.handleResize)}componentDidUpdate(t){var r;const{disableScrollParentFix:n,lifecycle:i,spotlightClicks:o,target:a}=this.props,{changed:s}=ws(t,this.props);if(s("target")||s("disableScrollParentFix")){const c=or(a);this.scrollParent=Pn(c??document.body,n,!0)}s("lifecycle",Ee.TOOLTIP)&&((r=this.scrollParent)==null||r.addEventListener("scroll",this.handleScroll,{passive:!0}),setTimeout(()=>{const{isScrolling:c}=this.state;c||this.updateState({showSpotlight:!0})},100)),(s("spotlightClicks")||s("disableOverlay")||s("lifecycle"))&&(o&&i===Ee.TOOLTIP?window.addEventListener("mousemove",this.handleMouseMove,!1):i!==Ee.TOOLTIP&&window.removeEventListener("mousemove",this.handleMouseMove))}componentWillUnmount(){var t;this.isActive=!1,window.removeEventListener("mousemove",this.handleMouseMove),window.removeEventListener("resize",this.handleResize),clearTimeout(this.resizeTimeout),clearTimeout(this.scrollTimeout),(t=this.scrollParent)==null||t.removeEventListener("scroll",this.handleScroll)}get overlayStyles(){const{mouseOverSpotlight:t}=this.state,{disableOverlayClose:r,placement:n,styles:i}=this.props;let o=i.overlay;return xi()&&(o=n==="center"?i.overlayLegacyCenter:i.overlayLegacy),{cursor:r?"default":"pointer",height:t0(),pointerEvents:t?"none":"auto",...o}}get spotlightStyles(){var t,r,n;const{showSpotlight:i}=this.state,{disableScrollParentFix:o=!1,spotlightClicks:a,spotlightPadding:s=0,styles:c,target:l}=this.props,m=or(l),u=Kc(m),d=ln(m),h=o0(m,s,o);return{...xi()?c.spotlightLegacy:c.spotlight,height:Math.round(((t=u==null?void 0:u.height)!=null?t:0)+s*2),left:Math.round(((r=u==null?void 0:u.left)!=null?r:0)-s),opacity:i?1:0,pointerEvents:a?"none":"auto",position:d?"fixed":"absolute",top:h,transition:"opacity 0.2s",width:Math.round(((n=u==null?void 0:u.width)!=null?n:0)+s*2)}}updateState(t){this.isActive&&this.setState(r=>({...r,...t}))}render(){const{showSpotlight:t}=this.state,{onClickOverlay:r,placement:n}=this.props,{hideSpotlight:i,overlayStyles:o,spotlightStyles:a}=this;if(i())return null;let s=n!=="center"&&t&&v.createElement(w0,{styles:a});if(Yc()==="safari"){const{mixBlendMode:c,zIndex:l,...m}=o;s=v.createElement("div",{style:{...m}},s),delete o.backgroundColor}return v.createElement("div",{className:"react-joyride__overlay","data-test-id":"overlay",onClick:r,role:"presentation",style:o},s)}},N0=class extends v.Component{constructor(){super(...arguments),pe(this,"node",null)}componentDidMount(){const{id:t}=this.props;hr()&&(this.node=document.createElement("div"),this.node.id=t,document.body.appendChild(this.node),jn||this.renderReact15())}componentDidUpdate(){hr()&&(jn||this.renderReact15())}componentWillUnmount(){!hr()||!this.node||(jn||ls.unmountComponentAtNode(this.node),this.node.parentNode===document.body&&(document.body.removeChild(this.node),this.node=null))}renderReact15(){if(!hr())return;const{children:t}=this.props;this.node&&ls.unstable_renderSubtreeIntoContainer(this,t,this.node)}renderReact16(){if(!hr()||!jn)return null;const{children:t}=this.props;return this.node?ls.createPortal(t,this.node):null}render(){return jn?this.renderReact16():null}},C0=class{constructor(t,r){if(pe(this,"element"),pe(this,"options"),pe(this,"canBeTabbed",n=>{const{tabIndex:i}=n;return i===null||i<0?!1:this.canHaveFocus(n)}),pe(this,"canHaveFocus",n=>{const i=/input|select|textarea|button|object/,o=n.nodeName.toLowerCase();return(i.test(o)&&!n.getAttribute("disabled")||o==="a"&&!!n.getAttribute("href"))&&this.isVisible(n)}),pe(this,"findValidTabElements",()=>[].slice.call(this.element.querySelectorAll("*"),0).filter(this.canBeTabbed)),pe(this,"handleKeyDown",n=>{const{code:i="Tab"}=this.options;n.code===i&&this.interceptTab(n)}),pe(this,"interceptTab",n=>{n.preventDefault();const i=this.findValidTabElements(),{shiftKey:o}=n;if(!i.length)return;let a=document.activeElement?i.indexOf(document.activeElement):0;a===-1||!o&&a+1===i.length?a=0:o&&a===0?a=i.length-1:a+=o?-1:1,i[a].focus()}),pe(this,"isHidden",n=>{const i=n.offsetWidth<=0&&n.offsetHeight<=0,o=window.getComputedStyle(n);return i&&!n.innerHTML?!0:i&&o.getPropertyValue("overflow")!=="visible"||o.getPropertyValue("display")==="none"}),pe(this,"isVisible",n=>{let i=n;for(;i;)if(i instanceof HTMLElement){if(i===document.body)break;if(this.isHidden(i))return!1;i=i.parentNode}return!0}),pe(this,"removeScope",()=>{window.removeEventListener("keydown",this.handleKeyDown)}),pe(this,"checkFocus",n=>{document.activeElement!==n&&(n.focus(),window.requestAnimationFrame(()=>this.checkFocus(n)))}),pe(this,"setFocus",()=>{const{selector:n}=this.options;if(!n)return;const i=this.element.querySelector(n);i&&window.requestAnimationFrame(()=>this.checkFocus(i))}),!(t instanceof HTMLElement))throw new TypeError("Invalid parameter: element must be an HTMLElement");this.element=t,this.options=r,window.addEventListener("keydown",this.handleKeyDown,!1),this.setFocus()}},E0=class extends v.Component{constructor(t){if(super(t),pe(this,"beacon",null),pe(this,"setBeaconRef",o=>{this.beacon=o}),t.beaconComponent)return;const r=document.head||document.getElementsByTagName("head")[0],n=document.createElement("style");n.id="joyride-beacon-animation",t.nonce&&n.setAttribute("nonce",t.nonce),n.appendChild(document.createTextNode(`
        @keyframes joyride-beacon-inner {
          20% {
            opacity: 0.9;
          }
        
          90% {
            opacity: 0.7;
          }
        }
        
        @keyframes joyride-beacon-outer {
          0% {
            transform: scale(1);
          }
        
          45% {
            opacity: 0.7;
            transform: scale(0.75);
          }
        
          100% {
            opacity: 0.9;
            transform: scale(1);
          }
        }
      `)),r.appendChild(n)}componentDidMount(){const{shouldFocus:t}=this.props;setTimeout(()=>{he.domElement(this.beacon)&&t&&this.beacon.focus()},0)}componentWillUnmount(){const t=document.getElementById("joyride-beacon-animation");t!=null&&t.parentNode&&t.parentNode.removeChild(t)}render(){const{beaconComponent:t,continuous:r,index:n,isLastStep:i,locale:o,onClickOrHover:a,size:s,step:c,styles:l}=this.props,m=Jt(o.open),u={"aria-label":m,onClick:a,onMouseEnter:a,ref:this.setBeaconRef,title:m};let d;if(t){const h=t;d=v.createElement(h,{continuous:r,index:n,isLastStep:i,size:s,step:c,...u})}else d=v.createElement("button",{key:"JoyrideBeacon",className:"react-joyride__beacon","data-test-id":"button-beacon",style:l.beacon,type:"button",...u},v.createElement("span",{style:l.beaconInner}),v.createElement("span",{style:l.beaconOuter}));return d}};function S0({styles:t,...r}){const{color:n,height:i,width:o,...a}=t;return we.createElement("button",{style:a,type:"button",...r},we.createElement("svg",{height:typeof i=="number"?`${i}px`:i,preserveAspectRatio:"xMidYMid",version:"1.1",viewBox:"0 0 18 18",width:typeof o=="number"?`${o}px`:o,xmlns:"http://www.w3.org/2000/svg"},we.createElement("g",null,we.createElement("path",{d:"M8.13911129,9.00268191 L0.171521827,17.0258467 C-0.0498027049,17.248715 -0.0498027049,17.6098394 0.171521827,17.8327545 C0.28204354,17.9443526 0.427188206,17.9998706 0.572051765,17.9998706 C0.71714958,17.9998706 0.862013139,17.9443526 0.972581703,17.8327545 L9.0000937,9.74924618 L17.0276057,17.8327545 C17.1384085,17.9443526 17.2832721,17.9998706 17.4281356,17.9998706 C17.5729992,17.9998706 17.718097,17.9443526 17.8286656,17.8327545 C18.0499901,17.6098862 18.0499901,17.2487618 17.8286656,17.0258467 L9.86135722,9.00268191 L17.8340066,0.973848225 C18.0553311,0.750979934 18.0553311,0.389855532 17.8340066,0.16694039 C17.6126821,-0.0556467968 17.254037,-0.0556467968 17.0329467,0.16694039 L9.00042166,8.25611765 L0.967006424,0.167268345 C0.745681892,-0.0553188426 0.387317931,-0.0553188426 0.165993399,0.167268345 C-0.0553311331,0.390136635 -0.0553311331,0.751261038 0.165993399,0.974176179 L8.13920499,9.00268191 L8.13911129,9.00268191 Z",fill:n}))))}var k0=S0;function T0(t){const{backProps:r,closeProps:n,index:i,isLastStep:o,primaryProps:a,skipProps:s,step:c,tooltipProps:l}=t,{content:m,hideBackButton:u,hideCloseButton:d,hideFooter:h,showSkipButton:p,styles:f,title:x}=c,g={};return g.primary=v.createElement("button",{"data-test-id":"button-primary",style:f.buttonNext,type:"button",...a}),p&&!o&&(g.skip=v.createElement("button",{"aria-live":"off","data-test-id":"button-skip",style:f.buttonSkip,type:"button",...s})),!u&&i>0&&(g.back=v.createElement("button",{"data-test-id":"button-back",style:f.buttonBack,type:"button",...r})),g.close=!d&&v.createElement(k0,{"data-test-id":"button-close",styles:f.buttonClose,...n}),v.createElement("div",{key:"JoyrideTooltip","aria-label":Jt(x??m),className:"react-joyride__tooltip",style:f.tooltip,...l},v.createElement("div",{style:f.tooltipContainer},x&&v.createElement("h1",{"aria-label":Jt(x),style:f.tooltipTitle},x),v.createElement("div",{style:f.tooltipContent},m)),!h&&v.createElement("div",{style:f.tooltipFooter},v.createElement("div",{style:f.tooltipFooterSpacer},g.skip),g.back,g.primary),g.close)}var A0=T0,I0=class extends v.Component{constructor(){super(...arguments),pe(this,"handleClickBack",t=>{t.preventDefault();const{helpers:r}=this.props;r.prev()}),pe(this,"handleClickClose",t=>{t.preventDefault();const{helpers:r}=this.props;r.close("button_close")}),pe(this,"handleClickPrimary",t=>{t.preventDefault();const{continuous:r,helpers:n}=this.props;if(!r){n.close("button_primary");return}n.next()}),pe(this,"handleClickSkip",t=>{t.preventDefault();const{helpers:r}=this.props;r.skip()}),pe(this,"getElementsProps",()=>{const{continuous:t,index:r,isLastStep:n,setTooltipRef:i,size:o,step:a}=this.props,{back:s,close:c,last:l,next:m,nextLabelWithProgress:u,skip:d}=a.locale,h=Jt(s),p=Jt(c),f=Jt(l),x=Jt(m),g=Jt(d);let b=c,y=p;if(t){if(b=m,y=x,a.showProgress&&!n){const _=Jt(u,{step:r+1,steps:o});b=jo(u,r+1,o),y=_}n&&(b=l,y=f)}return{backProps:{"aria-label":h,children:s,"data-action":"back",onClick:this.handleClickBack,role:"button",title:h},closeProps:{"aria-label":p,children:c,"data-action":"close",onClick:this.handleClickClose,role:"button",title:p},primaryProps:{"aria-label":y,children:b,"data-action":"primary",onClick:this.handleClickPrimary,role:"button",title:y},skipProps:{"aria-label":g,children:d,"data-action":"skip",onClick:this.handleClickSkip,role:"button",title:g},tooltipProps:{"aria-modal":!0,ref:i,role:"alertdialog"}}})}render(){const{continuous:t,index:r,isLastStep:n,setTooltipRef:i,size:o,step:a}=this.props,{beaconComponent:s,tooltipComponent:c,...l}=a;let m;if(c){const u={...this.getElementsProps(),continuous:t,index:r,isLastStep:n,size:o,step:l,setTooltipRef:i},d=c;m=v.createElement(d,{...u})}else m=v.createElement(A0,{...this.getElementsProps(),continuous:t,index:r,isLastStep:n,size:o,step:a});return m}},O0=class extends v.Component{constructor(){super(...arguments),pe(this,"scope",null),pe(this,"tooltip",null),pe(this,"handleClickHoverBeacon",t=>{const{step:r,store:n}=this.props;t.type==="mouseenter"&&r.event!=="hover"||n.update({lifecycle:Ee.TOOLTIP})}),pe(this,"setTooltipRef",t=>{this.tooltip=t}),pe(this,"setPopper",(t,r)=>{var n;const{action:i,lifecycle:o,step:a,store:s}=this.props;r==="wrapper"?s.setPopper("beacon",t):s.setPopper("tooltip",t),s.getPopper("beacon")&&(s.getPopper("tooltip")||a.placement==="center")&&o===Ee.INIT&&s.update({action:i,lifecycle:Ee.READY}),(n=a.floaterProps)!=null&&n.getPopper&&a.floaterProps.getPopper(t,r)}),pe(this,"renderTooltip",t=>{const{continuous:r,helpers:n,index:i,size:o,step:a}=this.props;return v.createElement(I0,{continuous:r,helpers:n,index:i,isLastStep:i+1===o,setTooltipRef:this.setTooltipRef,size:o,step:a,...t})})}componentDidMount(){const{debug:t,index:r}=this.props;Or({title:`step:${r}`,data:[{key:"props",value:this.props}],debug:t})}componentDidUpdate(t){var r;const{action:n,callback:i,continuous:o,controlled:a,debug:s,helpers:c,index:l,lifecycle:m,shouldScroll:u,status:d,step:h,store:p}=this.props,{changed:f,changedFrom:x}=ws(t,this.props),g=c.info(),b=o&&n!==Be.CLOSE&&(l>0||n===Be.PREV),y=f("action")||f("index")||f("lifecycle")||f("status"),_=x("lifecycle",[Ee.TOOLTIP,Ee.INIT],Ee.INIT),j=f("action",[Be.NEXT,Be.PREV,Be.SKIP,Be.CLOSE]),I=a&&l===t.index;if(j&&(_||I)&&i({...g,index:t.index,lifecycle:Ee.COMPLETE,step:t.step,type:Dt.STEP_AFTER}),h.placement==="center"&&d===Oe.RUNNING&&f("index")&&n!==Be.START&&m===Ee.INIT&&p.update({lifecycle:Ee.READY}),y){const w=or(h.target),N=!!w;N&&s0(w)?(x("status",Oe.READY,Oe.RUNNING)||x("lifecycle",Ee.INIT,Ee.READY))&&i({...g,step:h,type:Dt.STEP_BEFORE}):(console.warn(N?"Target not visible":"Target not mounted",h),i({...g,type:Dt.TARGET_NOT_FOUND,step:h}),a||p.update({index:l+(n===Be.PREV?-1:1)}))}x("lifecycle",Ee.INIT,Ee.READY)&&p.update({lifecycle:pi(h)||b?Ee.TOOLTIP:Ee.BEACON}),f("index")&&Or({title:`step:${m}`,data:[{key:"props",value:this.props}],debug:s}),f("lifecycle",Ee.BEACON)&&i({...g,step:h,type:Dt.BEACON}),f("lifecycle",Ee.TOOLTIP)&&(i({...g,step:h,type:Dt.TOOLTIP}),u&&this.tooltip&&(this.scope=new C0(this.tooltip,{selector:"[data-action=primary]"}),this.scope.setFocus())),x("lifecycle",[Ee.TOOLTIP,Ee.INIT],Ee.INIT)&&((r=this.scope)==null||r.removeScope(),p.cleanupPoppers())}componentWillUnmount(){var t;(t=this.scope)==null||t.removeScope()}get open(){const{lifecycle:t,step:r}=this.props;return pi(r)||t===Ee.TOOLTIP}render(){const{continuous:t,debug:r,index:n,nonce:i,shouldScroll:o,size:a,step:s}=this.props,c=or(s.target);return!el(s)||!he.domElement(c)?null:v.createElement("div",{key:`JoyrideStep-${n}`,className:"react-joyride__step"},v.createElement(oa,{...s.floaterProps,component:this.renderTooltip,debug:r,getPopper:this.setPopper,id:`react-joyride-step-${n}`,open:this.open,placement:s.placement,target:s.target},v.createElement(E0,{beaconComponent:s.beaconComponent,continuous:t,index:n,isLastStep:n+1===a,locale:s.locale,nonce:i,onClickOrHover:this.handleClickHoverBeacon,shouldFocus:o,size:a,step:s,styles:s.styles})))}},rl=class extends v.Component{constructor(t){super(t),pe(this,"helpers"),pe(this,"store"),pe(this,"callback",s=>{const{callback:c}=this.props;he.function(c)&&c(s)}),pe(this,"handleKeyboard",s=>{const{index:c,lifecycle:l}=this.state,{steps:m}=this.props,u=m[c];l===Ee.TOOLTIP&&s.code==="Escape"&&u&&!u.disableCloseOnEsc&&this.store.close("keyboard")}),pe(this,"handleClickOverlay",()=>{const{index:s}=this.state,{steps:c}=this.props;$r(this.props,c[s]).disableOverlayClose||this.helpers.close("overlay")}),pe(this,"syncState",s=>{this.setState(s)});const{debug:r,getHelpers:n,run:i=!0,stepIndex:o}=t;this.store=v0({...t,controlled:i&&he.number(o)}),this.helpers=this.store.getHelpers();const{addListener:a}=this.store;Or({title:"init",data:[{key:"props",value:this.props},{key:"state",value:this.state}],debug:r}),a(this.syncState),n&&n(this.helpers),this.state=this.store.getState()}componentDidMount(){if(!hr())return;const{debug:t,disableCloseOnEsc:r,run:n,steps:i}=this.props,{start:o}=this.store;bi(i,t)&&n&&o(),r||document.body.addEventListener("keydown",this.handleKeyboard,{passive:!0})}componentDidUpdate(t,r){if(!hr())return;const{action:n,controlled:i,index:o,status:a}=this.state,{debug:s,run:c,stepIndex:l,steps:m}=this.props,{stepIndex:u,steps:d}=t,{reset:h,setSteps:p,start:f,stop:x,update:g}=this.store,{changed:b}=ws(t,this.props),{changed:y,changedFrom:_}=ws(r,this.state),j=$r(this.props,m[o]),I=!pt(d,m),w=he.number(l)&&b("stepIndex"),N=or(j.target);if(I&&(bi(m,s)?p(m):console.warn("Steps are not valid",m)),b("run")&&(c?f(l):x()),w){let F=he.number(u)&&u<l?Be.NEXT:Be.PREV;n===Be.STOP&&(F=Be.START),[Oe.FINISHED,Oe.SKIPPED].includes(a)||g({action:n===Be.CLOSE?Be.CLOSE:F,index:l,lifecycle:Ee.INIT})}!i&&a===Oe.RUNNING&&o===0&&!N&&(this.store.update({index:o+1}),this.callback({...this.state,type:Dt.TARGET_NOT_FOUND,step:j}));const C={...this.state,index:o,step:j};if(y("action",[Be.NEXT,Be.PREV,Be.SKIP,Be.CLOSE])&&y("status",Oe.PAUSED)){const F=$r(this.props,m[r.index]);this.callback({...C,index:r.index,lifecycle:Ee.COMPLETE,step:F,type:Dt.STEP_AFTER})}if(y("status",[Oe.FINISHED,Oe.SKIPPED])){const F=$r(this.props,m[r.index]);i||this.callback({...C,index:r.index,lifecycle:Ee.COMPLETE,step:F,type:Dt.STEP_AFTER}),this.callback({...C,type:Dt.TOUR_END,step:F,index:r.index}),h()}else _("status",[Oe.IDLE,Oe.READY],Oe.RUNNING)?this.callback({...C,type:Dt.TOUR_START}):(y("status")||y("action",Be.RESET))&&this.callback({...C,type:Dt.TOUR_STATUS});this.scrollToStep(r)}componentWillUnmount(){const{disableCloseOnEsc:t}=this.props;t||document.body.removeEventListener("keydown",this.handleKeyboard)}scrollToStep(t){const{index:r,lifecycle:n,status:i}=this.state,{debug:o,disableScrollParentFix:a=!1,scrollDuration:s,scrollOffset:c=20,scrollToFirstStep:l=!1,steps:m}=this.props,u=$r(this.props,m[r]),d=or(u.target),h=m0({isFirstStep:r===0,lifecycle:n,previousLifecycle:t.lifecycle,scrollToFirstStep:l,step:u,target:d});if(i===Oe.RUNNING&&h){const p=zs(d,a),f=Pn(d,a);let x=Math.floor(a0(d,c,a))||0;Or({title:"scrollToStep",data:[{key:"index",value:r},{key:"lifecycle",value:n},{key:"status",value:i}],debug:o});const g=this.store.getPopper("beacon"),b=this.store.getPopper("tooltip");if(n===Ee.BEACON&&g){const{offsets:y,placement:_}=g;!["bottom"].includes(_)&&!p&&(x=Math.floor(y.popper.top-c))}else if(n===Ee.TOOLTIP&&b){const{flipped:y,offsets:_,placement:j}=b;["top","right","left"].includes(j)&&!y&&!p?x=Math.floor(_.popper.top-c):x-=u.spotlightPadding}x=x>=0?x:0,i===Oe.RUNNING&&i0(x,{element:f,duration:s}).then(()=>{setTimeout(()=>{var y;(y=this.store.getPopper("tooltip"))==null||y.instance.update()},10)})}}render(){if(!hr())return null;const{index:t,lifecycle:r,status:n}=this.state,{continuous:i=!1,debug:o=!1,nonce:a,scrollToFirstStep:s=!1,steps:c}=this.props,l=n===Oe.RUNNING,m={};if(l&&c[t]){const u=$r(this.props,c[t]);m.step=v.createElement(O0,{...this.state,callback:this.callback,continuous:i,debug:o,helpers:this.helpers,nonce:a,shouldScroll:!u.disableScrolling&&(t!==0||s),step:u,store:this.store}),m.overlay=v.createElement(N0,{id:"react-joyride-portal"},v.createElement(j0,{...u,continuous:i,debug:o,lifecycle:r,onClickOverlay:this.handleClickOverlay}))}return v.createElement("div",{className:"react-joyride"},m.step,m.overlay)}};pe(rl,"defaultProps",p0);var R0=rl;function nl(t,r){const n=()=>{if(typeof window>"u")return r;try{const s=window.localStorage.getItem(t);return s?JSON.parse(s):r}catch(s){return console.warn(`Error reading localStorage key "${t}":`,s),r}},[i,o]=v.useState(n),a=s=>{try{const c=s instanceof Function?s(i):s;o(c),typeof window<"u"&&window.localStorage.setItem(t,JSON.stringify(c))}catch(c){console.warn(`Error setting localStorage key "${t}":`,c)}};return v.useEffect(()=>{o(n())},[]),[i,a]}const oo=({tourId:t,steps:r,autoStart:n=!1,forceStart:i=!1,onComplete:o})=>{const[a,s]=nl(`tour-completed-${t}`,!1),[c,l]=v.useState(!1);v.useEffect(()=>{if(n&&!a){const u=setTimeout(()=>l(!0),500);return()=>clearTimeout(u)}},[n,a]),v.useEffect(()=>{if(i){s(!1);const u=setTimeout(()=>l(!0),300);return()=>clearTimeout(u)}},[i,s]);const m=u=>{const{status:d}=u;(d==="finished"||d==="skipped")&&(s(!0),l(!1),o==null||o())};return e.jsx(e.Fragment,{children:e.jsx(R0,{steps:r,run:c,continuous:!0,showProgress:!0,showSkipButton:!0,scrollToFirstStep:!0,callback:m,styles:{options:{primaryColor:"hsl(var(--primary))",textColor:"hsl(var(--foreground))",backgroundColor:"hsl(var(--background))",arrowColor:"hsl(var(--background))",overlayColor:"rgba(0, 0, 0, 0.5)",zIndex:1e4},tooltip:{borderRadius:"var(--radius)",fontSize:"14px"},tooltipContent:{padding:"20px"},buttonNext:{backgroundColor:"hsl(var(--primary))",color:"hsl(var(--primary-foreground))",borderRadius:"var(--radius)",padding:"8px 16px"},buttonBack:{color:"hsl(var(--muted-foreground))",marginLeft:"8px"},buttonSkip:{color:"hsl(var(--muted-foreground))"}},locale:{back:"السابق",close:"إغلاق",last:"إنهاء",next:"التالي",skip:"تخطي"}})})},P0=[{target:"body",content:e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-bold mb-2",children:"مرحباً بك في نظام نقطة البيع!"}),e.jsx("p",{children:"دعنا نأخذك في جولة سريعة لتتعرف على الميزات الأساسية"})]}),placement:"center",disableBeacon:!0},{target:'[data-tour="product-grid"]',content:"اضغط على أي منتج لإضافته إلى السلة. يمكنك استخدام البحث للعثور على المنتجات بسرعة.",placement:"bottom"},{target:'[data-tour="cart"]',content:"هنا تظهر المنتجات المضافة. يمكنك تعديل الكميات أو حذف المنتجات.",placement:"left"},{target:'[data-tour="checkout-button"]',content:"عندما تنتهي، اضغط هنا لإتمام عملية الشراء وإنشاء الفاتورة.",placement:"top"},{target:'[data-tour="barcode-scanner"]',content:"استخدم ماسح الباركود (F3) لإضافة المنتجات بسرعة.",placement:"bottom"}],M0=[{target:"body",content:e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-bold mb-2",children:"إدارة الفواتير"}),e.jsx("p",{children:"تعلم كيفية إنشاء وإدارة الفواتير بكفاءة"})]}),placement:"center",disableBeacon:!0},{target:'[data-tour="new-invoice-button"]',content:"اضغط هنا لإنشاء فاتورة جديدة. يمكنك أيضاً استخدام Ctrl+N.",placement:"bottom"},{target:'[data-tour="invoice-list"]',content:"هنا تظهر جميع فواتيرك. يمكنك البحث والفلترة والفرز.",placement:"top"},{target:'[data-tour="invoice-actions"]',content:"لكل فاتورة، يمكنك عرضها، تعديلها، طباعتها، أو إرسالها.",placement:"left"}],L0=[{target:"body",content:e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-bold mb-2",children:"مرحباً بك في الإعدادات!"}),e.jsx("p",{children:"هنا يمكنك تخصيص النظام حسب احتياجاتك"})]}),placement:"center",disableBeacon:!0},{target:'[data-tour="settings-company"]',content:"أدخل بيانات شركتك: الاسم، الشعار، وكلمة المرور",placement:"bottom"},{target:'[data-tour="settings-invoice"]',content:"تخصيص إعدادات الطباعة والفاتورة",placement:"bottom"},{target:'[data-tour="settings-theme"]',content:"اختر المظهر الفاتح أو الداكن",placement:"bottom"},{target:'[data-tour="settings-sound"]',content:"تفعيل أو تعطيل الأصوات في النظام",placement:"bottom"},{target:'[data-tour="settings-currency"]',content:"اختر العملة المستخدمة في النظام",placement:"bottom"},{target:'[data-tour="settings-offline"]',content:"إعدادات العمل بدون إنترنت والتخزين المحلي",placement:"bottom"},{target:'[data-tour="settings-app"]',content:"ثبّت التطبيق على جهازك للعمل بشكل أسرع",placement:"bottom"}],D0=[{keys:["Ctrl","K"],description:"فتح لوحة الأوامر",category:"عام"},{keys:["?"],description:"عرض اختصارات لوحة المفاتيح",category:"عام"},{keys:["ESC"],description:"إغلاق / إلغاء",category:"عام"},{keys:["G","P"],description:"الانتقال إلى نقطة البيع",category:"التنقل"},{keys:["G","H"],description:"الانتقال إلى قائمة الفواتير",category:"التنقل"},{keys:["G","C"],description:"الانتقال إلى العملاء",category:"التنقل"},{keys:["G","I"],description:"الانتقال إلى المنتجات",category:"التنقل"},{keys:["G","A"],description:"الانتقال إلى التحليلات",category:"التنقل"},{keys:["G","S"],description:"الانتقال إلى الإعدادات",category:"التنقل"},{keys:["N"],description:"إنشاء فاتورة جديدة",category:"إجراءات"},{keys:["Ctrl","S"],description:"حفظ",category:"إجراءات"},{keys:["Ctrl","P"],description:"طباعة",category:"إجراءات"},{keys:["Ctrl","F"],description:"بحث",category:"إجراءات"},{keys:["Ctrl","N"],description:"إضافة عنصر جديد",category:"إجراءات"},{keys:["F1"],description:"عملية بيع جديدة",category:"نقطة البيع"},{keys:["F2"],description:"إتمام الدفع",category:"نقطة البيع"},{keys:["F3"],description:"مسح باركود",category:"نقطة البيع"},{keys:["F4"],description:"البحث عن منتج",category:"نقطة البيع"},{keys:["F5"],description:"فتح الحاسبة",category:"نقطة البيع"},{keys:["F7"],description:"طباعة الفاتورة",category:"نقطة البيع"},{keys:["F8"],description:"مسح السلة",category:"نقطة البيع"},{keys:["F9"],description:"إدارة الدرج النقدي",category:"نقطة البيع"},{keys:["F10"],description:"تقرير الشفت",category:"نقطة البيع"}],$0={عام:e.jsx(cm,{className:"h-5 w-5"}),التنقل:e.jsx(Mm,{className:"h-5 w-5"}),إجراءات:e.jsx(zo,{className:"h-5 w-5"}),"نقطة البيع":e.jsx(Xr,{className:"h-5 w-5"})},F0={عام:"bg-blue-500/10 text-blue-600 dark:text-blue-400 border-blue-200 dark:border-blue-800",التنقل:"bg-green-500/10 text-green-600 dark:text-green-400 border-green-200 dark:border-green-800",إجراءات:"bg-purple-500/10 text-purple-600 dark:text-purple-400 border-purple-200 dark:border-purple-800","نقطة البيع":"bg-orange-500/10 text-orange-600 dark:text-orange-400 border-orange-200 dark:border-orange-800"},U0=()=>{const t=D0.reduce((r,n)=>(r[n.category]||(r[n.category]=[]),r[n.category].push(n),r),{});return e.jsx("div",{className:"space-y-6",children:e.jsxs(fe,{children:[e.jsx(De,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-primary/10 rounded-lg",children:e.jsx(Em,{className:"h-6 w-6 text-primary"})}),e.jsxs("div",{children:[e.jsx($e,{className:"text-xl",children:"اختصارات لوحة المفاتيح"}),e.jsx(kr,{children:"استخدم هذه الاختصارات لتسريع عملك في النظام"})]})]})}),e.jsxs(ve,{children:[e.jsx("div",{className:"grid gap-6 md:grid-cols-2",children:Object.entries(t).map(([r,n],i)=>e.jsxs(fe,{className:`${F0[r]} border`,children:[e.jsx(De,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center gap-2",children:[$0[r],e.jsx($e,{className:"text-lg",children:r})]})}),e.jsx(ve,{className:"pt-0",children:e.jsx("div",{className:"space-y-2",children:n.map((o,a)=>e.jsxs("div",{className:"flex items-center justify-between p-2 rounded-lg bg-background/50 hover:bg-background/80 transition-colors",children:[e.jsx("span",{className:"text-sm text-foreground",children:o.description}),e.jsx("div",{className:"flex gap-1",children:o.keys.map((s,c)=>e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Ae,{variant:"outline",className:"font-mono text-xs px-2 py-1 bg-background",children:s}),c<o.keys.length-1&&e.jsx("span",{className:"text-muted-foreground text-xs",children:"+"})]},c))})]},a))})})]},r))}),e.jsx("div",{className:"mt-6 flex justify-center",children:e.jsxs(Ae,{variant:"secondary",className:"text-sm px-4 py-2",children:["💡 اضغط ",e.jsx("kbd",{className:"mx-1 px-2 py-1 bg-muted rounded font-mono",children:"?"})," في أي وقت لعرض هذه القائمة"]})})]})]})})},z0=[{id:"pos-tour",title:"جولة نقطة البيع",description:"تعلم كيفية استخدام نظام نقطة البيع وإتمام عمليات البيع بسرعة",icon:e.jsx(Xr,{className:"h-6 w-6"}),color:"bg-green-500/10 text-green-600 dark:text-green-400 border-green-200 dark:border-green-800",targetTab:"pos"},{id:"invoices-tour",title:"جولة الفواتير",description:"تعلم كيفية إنشاء وإدارة الفواتير بكفاءة",icon:e.jsx(It,{className:"h-6 w-6"}),color:"bg-orange-500/10 text-orange-600 dark:text-orange-400 border-orange-200 dark:border-orange-800",targetTab:"invoices"},{id:"settings-tour",title:"جولة الإعدادات",description:"تعرف على جميع إعدادات النظام وكيفية تخصيصها",icon:e.jsx(To,{className:"h-6 w-6"}),color:"bg-slate-500/10 text-slate-600 dark:text-slate-400 border-slate-200 dark:border-slate-800",targetTab:"settings"},{id:"customers-tour",title:"جولة العملاء",description:"تعلم كيفية إدارة العملاء وبرنامج الولاء",icon:e.jsx(Rt,{className:"h-6 w-6"}),color:"bg-cyan-500/10 text-cyan-600 dark:text-cyan-400 border-cyan-200 dark:border-cyan-800",targetTab:"customers"}],B0=({onStartTour:t})=>{const r=o=>localStorage.getItem(`tour-completed-${o}`)==="true",n=o=>{localStorage.removeItem(`tour-completed-${o}`),window.dispatchEvent(new Event("storage"))},i=o=>{localStorage.removeItem(`tour-completed-${o.id}`),t?t(o.id,o.targetTab):window.location.href=`/?tab=${o.targetTab}&startTour=${o.id}`};return e.jsx("div",{className:"space-y-6",children:e.jsxs(fe,{children:[e.jsx(De,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-primary/10 rounded-lg",children:e.jsx(Oa,{className:"h-6 w-6 text-primary"})}),e.jsxs("div",{children:[e.jsx($e,{className:"text-xl",children:"الجولات التعريفية"}),e.jsx(kr,{children:"اختر جولة لتتعرف على ميزات النظام خطوة بخطوة"})]})]})}),e.jsxs(ve,{children:[e.jsx("div",{className:"grid gap-4 md:grid-cols-2",children:z0.map(o=>{const a=r(o.id);return e.jsx(fe,{className:`${o.color} border transition-all hover:shadow-md`,children:e.jsx(ve,{className:"p-4",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"p-3 bg-background/80 rounded-xl",children:o.icon}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"font-semibold text-foreground",children:o.title}),a&&e.jsxs(Ae,{variant:"secondary",className:"text-xs bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400",children:[e.jsx(As,{className:"h-3 w-3 ml-1"}),"مكتملة"]})]}),e.jsx("p",{className:"text-sm text-muted-foreground leading-relaxed",children:o.description}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsxs(V,{size:"sm",onClick:()=>i(o),className:"gap-2",children:[e.jsx(Ur,{className:"h-4 w-4"}),a?"إعادة الجولة":"ابدأ الجولة"]}),a&&e.jsxs(V,{size:"sm",variant:"ghost",onClick:()=>n(o.id),className:"gap-2",children:[e.jsx(xs,{className:"h-4 w-4"}),"إعادة تعيين"]})]})]})]})})},o.id)})}),e.jsxs("div",{className:"mt-6 p-4 bg-muted/50 rounded-lg",children:[e.jsxs("h4",{className:"font-medium mb-2 flex items-center gap-2",children:[e.jsx(Oa,{className:"h-4 w-4 text-primary"}),"نصائح"]}),e.jsxs("ul",{className:"text-sm text-muted-foreground space-y-1 list-disc list-inside",children:[e.jsx("li",{children:"الجولات تفاعلية وتظهر خطوة بخطوة"}),e.jsx("li",{children:"يمكنك تخطي أي جولة في أي وقت"}),e.jsx("li",{children:"الجولات المكتملة يمكن إعادتها في أي وقت"}),e.jsx("li",{children:"كل جولة تشرح الميزات الأساسية للقسم"})]})]})]})]})})},ao=768;function Dr(){const[t,r]=v.useState(void 0);return v.useEffect(()=>{const n=window.matchMedia(`(max-width: ${ao-1}px)`),i=()=>{r(window.innerWidth<ao)};return n.addEventListener("change",i),r(window.innerWidth<ao),()=>n.removeEventListener("change",i)},[]),!!t}const vi={pos:"bg-green-500 hover:bg-green-600 text-white shadow-green-500/30",invoices:"bg-orange-500 hover:bg-orange-600 text-white shadow-orange-500/30",products:"bg-teal-500 hover:bg-teal-600 text-white shadow-teal-500/30",customers:"bg-cyan-500 hover:bg-cyan-600 text-white shadow-cyan-500/30",suppliers:"bg-amber-500 hover:bg-amber-600 text-white shadow-amber-500/30",expenses:"bg-red-500 hover:bg-red-600 text-white shadow-red-500/30",administration:"bg-indigo-500 hover:bg-indigo-600 text-white shadow-indigo-500/30",dashboard:"bg-purple-500 hover:bg-purple-600 text-white shadow-purple-500/30",settings:"bg-gray-500 hover:bg-gray-600 text-white shadow-gray-500/30"},_i={pos:"hover:bg-green-100 dark:hover:bg-green-900/30 hover:text-green-700 dark:hover:text-green-300",invoices:"hover:bg-orange-100 dark:hover:bg-orange-900/30 hover:text-orange-700 dark:hover:text-orange-300",products:"hover:bg-teal-100 dark:hover:bg-teal-900/30 hover:text-teal-700 dark:hover:text-teal-300",customers:"hover:bg-cyan-100 dark:hover:bg-cyan-900/30 hover:text-cyan-700 dark:hover:text-cyan-300",suppliers:"hover:bg-amber-100 dark:hover:bg-amber-900/30 hover:text-amber-700 dark:hover:text-amber-300",expenses:"hover:bg-red-100 dark:hover:bg-red-900/30 hover:text-red-700 dark:hover:text-red-300",administration:"hover:bg-indigo-100 dark:hover:bg-indigo-900/30 hover:text-indigo-700 dark:hover:text-indigo-300",dashboard:"hover:bg-purple-100 dark:hover:bg-purple-900/30 hover:text-purple-700 dark:hover:text-purple-300",settings:"hover:bg-gray-200 dark:hover:bg-gray-700 hover:text-gray-700 dark:hover:text-gray-300"},q0=({activeTab:t,onNavigate:r,menuItems:n})=>{const i=Dr(),o=v.useRef(null),a=v.useRef(null);return v.useEffect(()=>{i&&o.current&&a.current&&o.current.scrollIntoView({behavior:"smooth",block:"nearest",inline:"center"})},[t,i]),i?e.jsx("nav",{className:"bg-background border-b border-border sticky top-[52px] z-30 shadow-sm",children:e.jsx("div",{ref:a,className:"flex items-center gap-2 px-2 py-2.5 overflow-x-auto scrollbar-hide scroll-smooth",style:{scrollSnapType:"x mandatory"},children:n.map(s=>e.jsxs("button",{ref:t===s.id?o:null,onClick:()=>r(s.id),className:Z("flex flex-col items-center justify-center min-w-[72px] min-h-[56px] px-3 py-2.5 rounded-xl transition-all duration-200 touch-manipulation","active:scale-95",t===s.id?Z(vi[s.id]||"bg-primary text-primary-foreground","shadow-lg"):Z("bg-accent/30 text-muted-foreground",_i[s.id]||"hover:bg-accent hover:text-foreground")),style:{scrollSnapAlign:"center"},children:[e.jsx(s.icon,{className:Z("h-6 w-6 mb-1",t===s.id&&"animate-in zoom-in-50 duration-200")}),e.jsx("span",{className:Z("text-[11px] font-medium whitespace-nowrap",t===s.id&&"font-bold"),children:s.label})]},s.id))})}):e.jsx("nav",{className:"bg-background border-b border-border px-4 py-3 sticky top-[60px] z-30 shadow-sm",children:e.jsx("div",{className:"flex items-center justify-center gap-1.5 max-w-7xl mx-auto flex-wrap",children:n.map(s=>e.jsxs("button",{onClick:()=>r(s.id),className:Z("flex items-center gap-1.5 px-3 py-2 rounded-xl transition-all duration-200 whitespace-nowrap touch-manipulation","hover:scale-105 active:scale-95",t===s.id?Z(vi[s.id]||"bg-primary text-primary-foreground","shadow-lg font-semibold"):Z("bg-accent/40 text-muted-foreground font-medium",_i[s.id]||"hover:bg-accent hover:text-foreground")),children:[e.jsx(s.icon,{className:Z("h-4 w-4 flex-shrink-0",t===s.id&&"animate-in zoom-in-50 duration-200")}),e.jsx("span",{className:"text-sm",children:s.label})]},s.id))})})},Ot=()=>{const{user:t,token:r,sellerData:n,login:i,logout:o}=tr();return{seller:n?{id:n.id,seller_name:n.seller_name,username:n.username||(t==null?void 0:t.username)||"",is_trial:n.is_trial===1||n.is_trial===!0,enable_thermal_printing:n.enable_thermal_printing===1||n.enable_thermal_printing===!0,seller_logo_url:n.seller_logo_url,invoice_type:n.invoice_type,enable_fawatrah:n.enable_fawatrah===1||n.enable_fawatrah===!0||n.enable_fawatrah===void 0}:null,token:r,login:async(s,c)=>{const l=await i(s,c);return l.success?{}:{error:l.error||"Login failed"}},logout:o}},V0={dashboard:[{value:"executive",label:"نظرة عامة"},{value:"analytics",label:"التحليلات"},{value:"reports",label:"التقارير المتقدمة"}],invoices:[{value:"home",label:"الكل"},{value:"pending",label:"معلقة"},{value:"sent",label:"مرسلة"},{value:"cancelled",label:"ملغاة"}],customers:[{value:"list",label:"قائمة العملاء"},{value:"loyalty",label:"برنامج الولاء"},{value:"promotions",label:"العروض"}],products:[{value:"products-list",label:"قائمة المنتجات"},{value:"categories",label:"إدارة الفئات"},{value:"stocktake",label:"الجرد"},{value:"stocktake-reasons",label:"أسباب الفروقات"},{value:"stocktake-reports",label:"تقارير الجرد"}],expenses:[{value:"list",label:"قائمة المصروفات"},{value:"categories",label:"فئات المصروفات"},{value:"report",label:"تقرير المصروفات"}],suppliers:[{value:"list",label:"قائمة الموردين"},{value:"orders",label:"أوامر الشراء"},{value:"payments",label:"المدفوعات"},{value:"reports",label:"التقارير"}],administration:[{value:"employees",label:"الموظفين"},{value:"performance",label:"أداء الموظفين"},{value:"shifts",label:"إدارة الشفتات"},{value:"shifts-reports",label:"تقارير الشفتات"},{value:"cash-movements",label:"حركات الدرج"},{value:"audit-log",label:"سجل التدقيق"}],settings:[{value:"company",label:"بيانات الشركة"},{value:"invoice",label:"الفاتورة"},{value:"theme",label:"المظهر"},{value:"sound",label:"الأصوات"},{value:"currency",label:"العملة"},{value:"offline",label:"الوضع المحلي"},{value:"sync-report",label:"تقرير المزامنة"},{value:"app",label:"التطبيق"},{value:"shortcuts",label:"الاختصارات"},{value:"tour",label:"جولة تعريفية"}]},G0={dashboard:"bg-purple-500 text-white hover:bg-purple-600",invoices:"bg-orange-500 text-white hover:bg-orange-600",customers:"bg-cyan-500 text-white hover:bg-cyan-600",products:"bg-teal-500 text-white hover:bg-teal-600",expenses:"bg-red-500 text-white hover:bg-red-600",suppliers:"bg-amber-500 text-white hover:bg-amber-600",administration:"bg-indigo-500 text-white hover:bg-indigo-600",settings:"bg-slate-500 text-white hover:bg-slate-600"},H0=({activeTab:t,activeSubTab:r,onSubTabChange:n})=>{const{seller:i}=Ot(),{currentEmployee:o}=lt(),a=(i==null?void 0:i.enable_fawatrah)===!0||(i==null?void 0:i.enable_fawatrah)==1,s=Dr(),c=we.useMemo(()=>{const h=V0[t];if(!h)return null;if(t==="invoices"&&!a)return h.filter(p=>p.value!=="pending"&&p.value!=="sent");if(t==="products"&&o){const p=o.is_owner===!0||o.is_owner==1,f=o.role==="admin"||o.role==="owner"||o.role==="manager";if(p||f)return h;const x=o.can_view_stocktake===!0||o.can_view_stocktake==1,g=o.can_create_stocktake===!0||o.can_create_stocktake==1,b=o.can_approve_stocktake===!0||o.can_approve_stocktake==1;return h.filter(y=>!!(y.value==="products-list"||y.value==="categories"||y.value==="stocktake"&&x||y.value==="stocktake-reasons"&&(g||b)||y.value==="stocktake-reports"&&x))}return h},[t,a,o]),l=we.useRef(null),[m,u]=we.useState({left:!1,right:!1}),d=we.useCallback(()=>{const h=l.current;h&&u({left:h.scrollLeft>10,right:h.scrollLeft<h.scrollWidth-h.clientWidth-10})},[]);return we.useEffect(()=>{d();const h=l.current;if(h)return h.addEventListener("scroll",d),()=>h.removeEventListener("scroll",d)},[d]),c?e.jsx("div",{className:"bg-muted/50 dark:bg-gray-800 border-b border-border sticky top-0 z-30 backdrop-blur-sm",children:e.jsxs("div",{className:"relative",children:[s&&m.right&&e.jsx("div",{className:"absolute left-0 top-0 bottom-0 w-8 bg-gradient-to-r from-transparent to-muted/80 pointer-events-none z-10 flex items-center justify-start",children:e.jsx(Ms,{className:"h-4 w-4 text-muted-foreground"})}),s&&m.left&&e.jsx("div",{className:"absolute right-0 top-0 bottom-0 w-8 bg-gradient-to-l from-transparent to-muted/80 pointer-events-none z-10 flex items-center justify-end",children:e.jsx(Go,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx("div",{ref:l,className:Z("py-3 flex gap-1.5",s?"px-4 overflow-x-auto scrollbar-hide snap-x snap-mandatory":"px-4 justify-center flex-wrap"),dir:"rtl",children:c.map(h=>e.jsx("button",{onClick:()=>n(h.value),"data-tour":t==="settings"?`settings-${h.value}`:void 0,className:Z("rounded-lg transition-all whitespace-nowrap font-cairo font-medium snap-start",s?"px-4 py-2.5 text-sm min-w-[80px] touch-target":"px-3 py-2 text-sm",r===h.value?G0[t]||"bg-primary text-primary-foreground shadow-sm":"hover:bg-accent hover:text-accent-foreground bg-background/50"),children:h.label},h.value))})]})}):null},W0=({open:t,onOpenChange:r,onNavigate:n})=>{const{seller:i}=Ot(),[o,a]=v.useState(""),[s,c]=v.useState([]),[l,m]=v.useState(!1),[u,d]=v.useState(0);v.useEffect(()=>{t||(a(""),c([]),d(0))},[t]),v.useEffect(()=>{const x=setTimeout(async()=>{if(!o||o.length<2||!(i!=null&&i.id)){c([]);return}m(!0);const g=o.toLowerCase(),b=localStorage.getItem(xe);try{const[y,_,j]=await Promise.all([fetch(`${W.GET_ALL("invoices")}&token=${b}&seller_id=${i.id}`),fetch(`${W.GET_ALL("customers")}&token=${b}&seller_id=${i.id}`),fetch(`${W.GET_ALL("products")}&token=${b}&seller_id=${i.id}`)]),[I,w,N]=await Promise.all([y.json(),_.json(),j.json()]),C=I.data||[],A=w.data||[],F=N.data||[],T=[];C.filter(E=>(E.invoice_number||"").toLowerCase().includes(g)||(E.customer_name||"").toLowerCase().includes(g)).slice(0,10).forEach(E=>{T.push({id:E.id,type:"invoice",title:`فاتورة ${E.invoice_number}`,subtitle:E.customer_name||"عميل غير معروف",metadata:`${E.total_amount} دينار - ${new Date(E.invoice_date).toLocaleDateString("ar")}`,icon:It,action:()=>{n("invoice",E.id),r(!1)}})}),A.filter(E=>(E.customer_name||"").toLowerCase().includes(g)||(E.phone_number||"").toLowerCase().includes(g)||(E.customer_number||"").toLowerCase().includes(g)).slice(0,10).forEach(E=>{T.push({id:E.id,type:"customer",title:E.customer_name||"عميل",subtitle:E.phone_number||"لا يوجد رقم",metadata:E.customer_number?`رقم: ${E.customer_number}`:void 0,icon:Rt,action:()=>{n("customer",E.id),r(!1)}})}),F.filter(E=>(E.product_name||"").toLowerCase().includes(g)||(E.barcode||"").toLowerCase().includes(g)||(E.sku||"").toLowerCase().includes(g)).slice(0,10).forEach(E=>{T.push({id:E.id,type:"product",title:E.product_name,subtitle:E.barcode||E.sku||"لا يوجد باركود",metadata:E.unit_price?`${E.unit_price} دينار`:void 0,icon:ht,action:()=>{n("product",E.id),r(!1)}})}),c(T),d(0)}catch(y){console.error("Search error:",y)}finally{m(!1)}},300);return()=>clearTimeout(x)},[o,i==null?void 0:i.id,n,r]);const h=f=>{f.key==="ArrowDown"?(f.preventDefault(),d(x=>Math.min(x+1,s.length-1))):f.key==="ArrowUp"?(f.preventDefault(),d(x=>Math.max(x-1,0))):f.key==="Enter"&&s[u]&&(f.preventDefault(),s[u].action())},p=f=>{switch(f){case"invoice":return e.jsx(Ae,{variant:"outline",className:"text-xs",children:"فاتورة"});case"customer":return e.jsx(Ae,{variant:"secondary",className:"text-xs",children:"عميل"});case"product":return e.jsx(Ae,{variant:"default",className:"text-xs",children:"منتج"})}};return e.jsx(gt,{open:t,onOpenChange:r,children:e.jsxs(bt,{className:"max-w-2xl p-0",children:[e.jsxs(Tt,{className:"px-4 pt-4 pb-0",children:[e.jsx(At,{className:"sr-only",children:"بحث شامل"}),e.jsxs("div",{className:"relative",children:[e.jsx(zt,{className:"absolute right-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Te,{value:o,onChange:f=>a(f.target.value),onKeyDown:h,placeholder:"ابحث في الفواتير، العملاء، المنتجات... (Ctrl+F)",className:"pr-10 h-12 text-base border-0 focus-visible:ring-0",autoFocus:!0})]})]}),e.jsxs(un,{className:"max-h-[400px] border-t",children:[l&&e.jsx("div",{className:"p-8 text-center text-muted-foreground",children:"جاري البحث..."}),!l&&o&&s.length===0&&e.jsxs("div",{className:"p-8 text-center",children:[e.jsx(zt,{className:"h-12 w-12 text-muted-foreground/50 mx-auto mb-3"}),e.jsxs("p",{className:"text-muted-foreground",children:['لا توجد نتائج لـ "',o,'"']})]}),!l&&s.length>0&&e.jsx("div",{className:"py-2",children:s.map((f,x)=>{const g=f.icon;return e.jsxs("button",{onClick:f.action,className:Z("w-full px-4 py-3 flex items-center gap-3 hover:bg-muted/50 transition-colors text-right",x===u&&"bg-muted/70"),children:[e.jsx("div",{className:Z("flex-shrink-0 w-10 h-10 rounded-lg flex items-center justify-center",f.type==="invoice"&&"bg-blue-100 text-blue-600 dark:bg-blue-900/30 dark:text-blue-400",f.type==="customer"&&"bg-green-100 text-green-600 dark:bg-green-900/30 dark:text-green-400",f.type==="product"&&"bg-purple-100 text-purple-600 dark:bg-purple-900/30 dark:text-purple-400"),children:e.jsx(g,{className:"h-5 w-5"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("h4",{className:"text-sm font-medium truncate",children:f.title}),p(f.type)]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:f.subtitle}),f.metadata&&e.jsx("p",{className:"text-xs text-muted-foreground/70 mt-0.5",children:f.metadata})]})]},f.id)})}),!o&&e.jsxs("div",{className:"p-8 text-center",children:[e.jsxs("div",{className:"grid grid-cols-3 gap-4 mb-4",children:[e.jsxs("div",{className:"p-3 rounded-lg border bg-muted/30",children:[e.jsx(It,{className:"h-6 w-6 mx-auto mb-2 text-muted-foreground"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"الفواتير"})]}),e.jsxs("div",{className:"p-3 rounded-lg border bg-muted/30",children:[e.jsx(Rt,{className:"h-6 w-6 mx-auto mb-2 text-muted-foreground"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"العملاء"})]}),e.jsxs("div",{className:"p-3 rounded-lg border bg-muted/30",children:[e.jsx(ht,{className:"h-6 w-6 mx-auto mb-2 text-muted-foreground"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"المنتجات"})]})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"ابدأ الكتابة للبحث في جميع البيانات"})]})]}),e.jsxs("div",{className:"border-t px-4 py-2 flex items-center justify-between text-xs text-muted-foreground",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("span",{children:"↑↓ للتنقل"}),e.jsx("span",{children:"↵ للاختيار"}),e.jsx("span",{children:"ESC للإغلاق"})]}),e.jsxs("span",{children:[s.length," نتيجة"]})]})]})})},X0=10;let Hr=null,Mn=[],hs=[],os=null;const No=()=>{hs.forEach(t=>t({notification:Hr,history:Mn}))},er=(t,r="info",n=4e3)=>(os&&clearTimeout(os),Hr={id:Date.now().toString(),message:t,type:r,duration:n,timestamp:new Date},Mn=[Hr,...Mn].slice(0,X0),No(),os=setTimeout(()=>{Hr=null,No(),os=null},n),Hr.id),J0=()=>{Mn=[],No()};er.success=(t,r)=>er(t,"success",r);er.error=(t,r)=>er(t,"error",r);er.warning=(t,r)=>er(t,"warning",r);er.info=(t,r)=>er(t,"info",r);const K0=()=>{const[t,r]=v.useState(Hr),[n,i]=v.useState(Mn);return v.useEffect(()=>{const o=a=>{r(a.notification),i(a.history)};return hs.push(o),()=>{hs=hs.filter(a=>a!==o)}},[]),{notification:t,history:n,notify:er,clearHistory:J0}},Y0=()=>r=>{const n=r.description||r.title||"",i=r.variant==="destructive"?"error":"success";return er(n,i,r.duration),{id:Date.now().toString(),dismiss:()=>{},update:()=>{}}},et=()=>{const[t]=v.useState([]);return{toast:Y0(),toasts:t,dismiss:()=>{}}},yt=t=>{if(typeof t!="number"||isNaN(t)||!isFinite(t))return console.warn("⚠️ roundToNineDecimals - Invalid input:",t),0;console.log("🔢 Rounding to 9 decimals:",t);const r=Math.round(t*1e9)/1e9;return console.log("✅ Rounded result:",r),r},Co=(t,r)=>{const n=r===-1?0:r||0;if(n===0)return t;const i=t/(1+n/100);return yt(i)},sl=(t,r)=>{const n=r===-1?0:r||0;if(n===0)return t;const i=t*(1+n/100);return yt(i)},xt=(t,r)=>{const n=Number(t.quantity)||1,i=Number(t.unitPrice)||0,o=Number(t.discountAmount)||0,a=Number(t.taxPercent)||0,s=t.taxCalculationMode||"tax_exclusive",c=t.existingLineExtensionAmount;if(console.log("🔢 Government calculation for line with STRING TO NUMBER FIX:",{quantity:n,unitPrice:i,discountAmount:o,taxPercent:a,taxCalculationMode:s,existingLineExtensionAmount:c}),typeof n!="number"||isNaN(n)||n<0)return console.error("❌ Invalid quantity in calculation:",n),{lineExtensionAmount:c||0,taxAmount:0,roundingAmount:0,discountAmount:yt(o||0),unitPriceBeforeTax:0,unitPriceAfterTax:0};if(typeof i!="number"||isNaN(i)||i<0)return console.error("❌ Invalid unit price in calculation:",i),{lineExtensionAmount:c||0,taxAmount:0,roundingAmount:0,discountAmount:yt(o||0),unitPriceBeforeTax:0,unitPriceAfterTax:0};const l=a===-1?0:a||0;a===-1&&console.log("🚫 Item is EXEMPT (tax percentage -1), using 0% for calculations");let m,u;s==="tax_inclusive"?(console.log("💡 Tax-inclusive mode: Input price includes tax, calculating pre-tax price"),u=i,m=Co(i,l)):(console.log("💡 Tax-exclusive mode: Input price is pre-tax"),m=i,u=sl(i,l)),console.log("📊 Price breakdown:",{unitPriceBeforeTax:m,unitPriceAfterTax:u,effectiveTaxPercent:l});const d=yt(n*m-(o||0));console.log("🔢 Return Invoice LineExtensionAmount calculation:",{quantity:n,unitPriceBeforeTax:m,discountAmount:o||0,calculation:`${n} * ${m} - ${o||0}`,result:d});const h=yt(d*(l/100));console.log("🔢 Return Invoice TaxAmount calculation:",{lineExtensionAmount:d,effectiveTaxPercent:l,calculation:`${d} * ${l/100}`,result:h});const p=r!==void 0?r:yt(d+h);console.log("🔢 Return Invoice RoundingAmount calculation:",{lineExtensionAmount:d,taxAmount:h,calculation:`${d} + ${h}`,result:p,expected:"Should match TaxInclusiveAmount at invoice level"});const f={lineExtensionAmount:d,taxAmount:h,roundingAmount:p,discountAmount:yt(o||0),unitPriceBeforeTax:m,unitPriceAfterTax:u};return console.log("✅ Government calculation result with DISCOUNT MISMATCH FIX (9-decimal precision):",f),f},lr=(t,r)=>{if(console.log("🔢 Calculating invoice totals for",t.length,"lines"),!t||t.length===0)return console.warn("⚠️ No line results provided for invoice totals calculation"),{allowanceChargeAmount:0,totalTaxAmount:0,taxExclusiveAmount:0,taxInclusiveAmount:0};const n=0,i=yt(t.reduce((c,l)=>c+(l.taxAmount||0),0)),o=yt(t.reduce((c,l)=>c+(l.lineExtensionAmount||0),0));console.log("📊 TaxExclusiveAmount calculation (FIXED - discount at line level):",{lineExtensionAmountSum:o,discountAmountSum:t.reduce((c,l)=>c+(l.discountAmount||0),0),explanation:"TaxExclusiveAmount = Sum(lineExtensionAmount) - discount already applied at line level"});const a=yt(o+i);console.log("🔍 Validation - TaxExclusiveAmount + TaxAmount = TaxInclusiveAmount:",{taxExclusiveAmount:o,totalTaxAmount:i,taxInclusiveAmount:a,formula:`${o} + ${i} = ${a}`,isValid:!0});const s={allowanceChargeAmount:n,totalTaxAmount:i,taxExclusiveAmount:o,taxInclusiveAmount:a};return console.log("✅ Invoice totals calculated (FIXED - discount at line level):",s),s},ft=t=>typeof t!="number"||isNaN(t)||!isFinite(t)?"0.00":t.toFixed(2),Q0=(t,r=9)=>{if(typeof t!="number"||isNaN(t)||!isFinite(t))return"0";const n=Math.pow(10,r);return(Math.round(t*n)/n).toFixed(r).replace(/\.?0+$/,"")},wi=t=>typeof t!="number"||isNaN(t)?"0":Q0(t,9),Me=t=>{let r=typeof t=="string"?parseFloat(t):t;if(typeof r!="number"||isNaN(r)||!isFinite(r))return console.warn(`⚠️ Invalid number for government formatting: ${t}, defaulting to '0.00'`),"0.00";t=r;const n=Math.pow(10,9);let o=(Math.round(t*n)/n).toFixed(9);o=o.replace(/0+$/,"");const a=o.indexOf(".");if(a===-1)o+=".00";else{const s=o.substring(a+1);s.length<2&&(o+="0".repeat(2-s.length))}return console.log(`✅ Government amount formatted: ${t} -> ${o}`),o},Z0=t=>{const r=t.match(/\.(\d+)$/);return r?r[1].length<=9:!0},Ke=t=>{if(typeof t!="number"||isNaN(t)||!isFinite(t))return console.warn(`⚠️ Invalid number for XML formatting: ${t}, defaulting to '0'`),"0";const r=Math.round(t*1e9)/1e9,n=wi(r);if(!Z0(n)){console.error(`❌ Decimal compliance failed for value: ${t} -> ${n}`);const i=Math.round(t*1e9)/1e9,o=wi(i);return console.log(`🔧 Force-corrected decimal: ${n} -> ${o}`),o}return console.log(`✅ XML amount formatted compliant: ${t} -> ${n}`),n},Ut=t=>(console.log("🏷️ Determining tax category code for tax percent:",t),t===-1?(console.log("✅ Tax category: Z (Exempt - displays as 0% in XML)"),"Z"):t===0?(console.log("✅ Tax category: O (Zero-rated)"),"O"):t>0?(console.log("✅ Tax category: S (Standard rate)"),"S"):(console.log("⚠️ Invalid tax percent, defaulting to S (Standard rate)"),"S")),ex=t=>{switch(t){case"Z":return"معفي من الضريبة";case"O":return"معدل صفر";case"S":return"معدل قياسي";default:return"غير محدد"}},tt=t=>t?t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;"):"",tx=(t,r)=>{const n=(t||"").trim();if(!n)return"";const i=n.replace(/\D/g,"");return i||""},ji=(t,r)=>{const n=new RegExp(`<${r}[^>]*>([^<]*)</${r}>`,"i"),i=t.match(n);return i?i[1].trim():""},Ni=(t,r)=>{const n=t.match(new RegExp(`<cac:${r}>[\\s\\S]*?<cbc:RegistrationName>([^<]*)</cbc:RegistrationName>[\\s\\S]*?</cac:${r}>`,"i"));return n?n[1].trim():""},Ci=(t,r)=>{const n=t.match(new RegExp(`<cac:${r}>[\\s\\S]*?<cbc:CompanyID>([^<]*)</cbc:CompanyID>[\\s\\S]*?</cac:${r}>`,"i"));return n?n[1].trim():""},rx=t=>{const r=t.match(/<cac:AccountingCustomerParty>[\s\S]*?<cbc:ID schemeID="([^"]*)">([^<]*)<\/cbc:ID>[\s\S]*?<\/cac:AccountingCustomerParty>/i);return r?{schemeID:r[1],id:r[2].trim()}:{schemeID:"NIN",id:""}},nx=t=>{const r=t.match(/<cac:SellerSupplierParty>[\s\S]*?<cbc:ID>([^<]*)<\/cbc:ID>[\s\S]*?<\/cac:SellerSupplierParty>/i);return r?r[1].trim():""},sx=t=>{const r=t.match(/<cbc:Telephone>([^<]*)<\/cbc:Telephone>/i);return r?r[1].trim():""},Es=(t,r)=>{const n=new RegExp(`<cbc:${r} currencyID="JO[D]?">([^<]*)</cbc:${r}>`,"i"),i=t.match(n);return i?i[1].trim():"0.00"},ox=t=>{const r=[];console.log("🔍 Validating return invoice XML structure...");const n=t.match(/<cbc:InvoiceTypeCode[^>]*>([^<]*)<\/cbc:InvoiceTypeCode>/);(!n||n[1]!=="381")&&r.push(`❌ InvoiceTypeCode should be 381 for returns, found: ${(n==null?void 0:n[1])||"none"}`),t.includes("<cac:BillingReference>")||r.push("❌ Return invoice must have BillingReference section");const i=t.match(/<cac:BillingReference>[\s\S]*?<cbc:UUID>([^<]*)<\/cbc:UUID>/i);return(!i||!i[1]||i[1].length<30)&&r.push("❌ Return invoice must reference original invoice UUID in BillingReference"),r.length>0?(console.error("❌ RETURN INVOICE XML VALIDATION FAILED:"),r.forEach(o=>console.error("  "+o))):(console.log("✅ Return invoice XML validation passed"),console.log("   - InvoiceTypeCode: 381 ✓"),console.log("   - BillingReference: exists ✓"),console.log("   - Original UUID: referenced ✓")),{isValid:r.length===0,errors:r}},ax=(t,r)=>{var s,c;console.log("📋 ===== EXTRACTING INVOICE LINES FOR RETURN ====="),console.log("📄 Original XML length:",t.length);const n=/<cac:InvoiceLine>([\s\S]*?)<\/cac:InvoiceLine>/gi,i=[];let o,a=0;for(;(o=n.exec(t))!==null;){a++;const l=o[1],m=ji(l,"cbc:ID")||a.toString(),u=ji(l,"cbc:InvoicedQuantity")||"1",d=Es(l,"LineExtensionAmount")||"0.00",h=Es(l,"PriceAmount")||"0.00",p=l.match(/<cbc:Name>([^<]*)<\/cbc:Name>/i),f=p?tt(p[1].trim()):"منتج";console.log(`📦 Line ${a}:`),console.log(`   - ID: ${m}`),console.log(`   - Name: ${f}`),console.log(`   - Quantity: ${u}`),console.log(`   - LineExtensionAmount: ${d}`),console.log(`   - PriceAmount: ${h}`),console.log("   - Tax Percent: 0.00 (FORCED ZERO for return)");const x=l.match(/<cbc:TaxAmount[^>]*>([^<]*)<\/cbc:TaxAmount>/i),g=x?x[1].trim():"0.00",b=l.match(/<cbc:Percent>([^<]*)<\/cbc:Percent>/i),y=b?b[1].trim():"16",_=l.match(/<cac:TaxCategory>[\s\S]*?<cbc:ID[^>]*>([^<]*)<\/cbc:ID>/i),j=_?_[1].trim():"S",I=parseFloat(d)||0,w=parseFloat(g)||0,N=I+w,C=d.includes(".")&&((s=d.split(".")[1])==null?void 0:s.length)||2,A=g.includes(".")&&((c=g.split(".")[1])==null?void 0:c.length)||2,F=Math.max(C,A,2),T=N.toFixed(F);console.log(`📦 Line ${a} - PRESERVING ORIGINAL TAX:`),console.log(`   - TaxAmount: ${g}`),console.log(`   - TaxPercent: ${y}`),console.log(`   - TaxCategory: ${j}`),console.log(`   - RoundingAmount: ${T}`);const k=`
  <cac:InvoiceLine>
    <cbc:ID>${m}</cbc:ID>
    <cbc:InvoicedQuantity unitCode="PCE">${u}</cbc:InvoicedQuantity>
    <cbc:LineExtensionAmount currencyID="JO">${d}</cbc:LineExtensionAmount>
    <cac:TaxTotal>
      <cbc:TaxAmount currencyID="JO">${g}</cbc:TaxAmount>
      <cbc:RoundingAmount currencyID="JO">${T}</cbc:RoundingAmount>
      <cac:TaxSubtotal>
        <cbc:TaxAmount currencyID="JO">${g}</cbc:TaxAmount>
        <cac:TaxCategory>
          <cbc:ID schemeAgencyID="6" schemeID="UN/ECE 5305">${j}</cbc:ID>
          <cbc:Percent>${y}</cbc:Percent>
          <cac:TaxScheme>
            <cbc:ID schemeAgencyID="6" schemeID="UN/ECE 5153">VAT</cbc:ID>
          </cac:TaxScheme>
        </cac:TaxCategory>
      </cac:TaxSubtotal>
    </cac:TaxTotal>
    <cac:Item>
      <cbc:Name>${f}</cbc:Name>
    </cac:Item>
    <cac:Price>
      <cbc:PriceAmount currencyID="JO">${h}</cbc:PriceAmount>
      <cac:AllowanceCharge>
        <cbc:ChargeIndicator>false</cbc:ChargeIndicator>
        <cbc:AllowanceChargeReasonCode>95</cbc:AllowanceChargeReasonCode>
        <cbc:AllowanceChargeReason>${tt(r)}</cbc:AllowanceChargeReason>
        <cbc:Amount currencyID="JO">0.00</cbc:Amount>
      </cac:AllowanceCharge>
    </cac:Price>
  </cac:InvoiceLine>`;i.push(k)}return console.log(`✅ Extracted and converted ${i.length} invoice lines with ORIGINAL TAX VALUES`),i.length===0&&(console.warn("⚠️ WARNING: No invoice lines found in original XML!"),console.log("📄 First 1000 chars of XML:",t.substring(0,1e3))),i.join(`
`)},ix=`<?xml version="1.0" encoding="UTF-8"?>
<Invoice xmlns="urn:oasis:names:specification:ubl:schema:xsd:Invoice-2" xmlns:cac="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2" xmlns:cbc="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2" xmlns:ext="urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2">
  <cbc:ProfileID>reporting:1.0</cbc:ProfileID>
  <cbc:ID>{{INVOICE_NUMBER}}</cbc:ID>
  <cbc:UUID>{{UUID}}</cbc:UUID>
  <cbc:IssueDate>{{INVOICE_DATE}}</cbc:IssueDate>
  <cbc:InvoiceTypeCode name="012">381</cbc:InvoiceTypeCode>
  <cbc:Note>{{RETURN_REASON}}</cbc:Note>
  <cbc:DocumentCurrencyCode>JOD</cbc:DocumentCurrencyCode>
  <cbc:TaxCurrencyCode>JOD</cbc:TaxCurrencyCode>
  <cac:BillingReference>
    <cac:InvoiceDocumentReference>
      <cbc:ID>{{ORIGINAL_INVOICE_NUMBER}}</cbc:ID>
      <cbc:UUID>{{ORIGINAL_INVOICE_UUID}}</cbc:UUID>
      <cbc:DocumentDescription>{{ORIGINAL_INVOICE_TOTAL}}</cbc:DocumentDescription>
    </cac:InvoiceDocumentReference>
  </cac:BillingReference>
  <cac:AdditionalDocumentReference>
    <cbc:ID>ICV</cbc:ID>
    <cbc:UUID>{{INVOICE_COUNTER}}</cbc:UUID>
  </cac:AdditionalDocumentReference>
  <cac:AccountingSupplierParty>
    <cac:Party>
      <cac:PostalAddress>
        <cac:Country>
          <cbc:IdentificationCode>JO</cbc:IdentificationCode>
        </cac:Country>
      </cac:PostalAddress>
      <cac:PartyTaxScheme>
        <cbc:CompanyID>{{SELLER_TAX_NUMBER}}</cbc:CompanyID>
        <cac:TaxScheme>
          <cbc:ID>VAT</cbc:ID>
        </cac:TaxScheme>
      </cac:PartyTaxScheme>
      <cac:PartyLegalEntity>
        <cbc:RegistrationName>{{SELLER_NAME}}</cbc:RegistrationName>
      </cac:PartyLegalEntity>
    </cac:Party>
  </cac:AccountingSupplierParty>
  <cac:AccountingCustomerParty>
    <cac:Party>
      <cac:PartyIdentification>
        <cbc:ID schemeID="{{CUSTOMER_TYPE}}">{{CUSTOMER_NUMBER}}</cbc:ID>
      </cac:PartyIdentification>
      <cac:PostalAddress>
        <cbc:CityName>{{CUSTOMER_CITY}}</cbc:CityName>
        <cac:Country>
          <cbc:IdentificationCode>JO</cbc:IdentificationCode>
        </cac:Country>
      </cac:PostalAddress>
      <cac:PartyTaxScheme>
        <cbc:CompanyID>{{CUSTOMER_TAX_NUMBER}}</cbc:CompanyID>
        <cac:TaxScheme>
          <cbc:ID>VAT</cbc:ID>
        </cac:TaxScheme>
      </cac:PartyTaxScheme>
      <cac:PartyLegalEntity>
        <cbc:RegistrationName>{{CUSTOMER_NAME}}</cbc:RegistrationName>
      </cac:PartyLegalEntity>
    </cac:Party>
    <cac:AccountingContact>
      <cbc:Telephone>{{CUSTOMER_PHONE}}</cbc:Telephone>
    </cac:AccountingContact>
  </cac:AccountingCustomerParty>
  <cac:SellerSupplierParty>
    <cac:Party>
      <cac:PartyIdentification>
        <cbc:ID>{{SELLER_INCOME_NUMBER}}</cbc:ID>
      </cac:PartyIdentification>
    </cac:Party>
  </cac:SellerSupplierParty>
  <cac:PaymentMeans>
    <cbc:PaymentMeansCode>10</cbc:PaymentMeansCode>
    <cbc:InstructionNote>{{RETURN_REASON}}</cbc:InstructionNote>
  </cac:PaymentMeans>
  <cac:AllowanceCharge>
    <cbc:ChargeIndicator>false</cbc:ChargeIndicator>
    <cbc:AllowanceChargeReasonCode>95</cbc:AllowanceChargeReasonCode>
    <cbc:AllowanceChargeReason>discount</cbc:AllowanceChargeReason>
    <cbc:Amount currencyID="JO">0.00</cbc:Amount>
  </cac:AllowanceCharge>
  <cac:TaxTotal>
    <cbc:TaxAmount currencyID="JO">{{TOTAL_TAX_AMOUNT}}</cbc:TaxAmount>
    <cac:TaxSubtotal>
      <cbc:TaxableAmount currencyID="JO">{{TAX_EXCLUSIVE_AMOUNT}}</cbc:TaxableAmount>
      <cbc:TaxAmount currencyID="JO">{{TOTAL_TAX_AMOUNT}}</cbc:TaxAmount>
      <cac:TaxCategory>
        <cbc:ID schemeAgencyID="6" schemeID="UN/ECE 5305">S</cbc:ID>
        <cbc:Percent>{{TAX_PERCENT}}</cbc:Percent>
        <cac:TaxScheme>
          <cbc:ID schemeAgencyID="6" schemeID="UN/ECE 5153">VAT</cbc:ID>
        </cac:TaxScheme>
      </cac:TaxCategory>
    </cac:TaxSubtotal>
  </cac:TaxTotal>
  <cac:LegalMonetaryTotal>
    <cbc:TaxExclusiveAmount currencyID="JO">{{TAX_EXCLUSIVE_AMOUNT}}</cbc:TaxExclusiveAmount>
    <cbc:TaxInclusiveAmount currencyID="JO">{{TAX_INCLUSIVE_AMOUNT}}</cbc:TaxInclusiveAmount>
    <cbc:AllowanceTotalAmount currencyID="JO">0.00</cbc:AllowanceTotalAmount>
    <cbc:PayableAmount currencyID="JO">{{TAX_INCLUSIVE_AMOUNT}}</cbc:PayableAmount>
  </cac:LegalMonetaryTotal>
{{INVOICE_LINES}}
</Invoice>`,cx=(t,r,n,i,o,a,s,c)=>{console.log("🔄 generateReturnXmlFromOriginal: Using TEMPLATE-BASED approach..."),console.log("📝 Return reason:",n),console.log("📝 Original invoice number:",a),console.log("📝 Original UUID:",s),console.log("📝 Original total:",c);let l=t;if(t.match(/^[A-Za-z0-9+/=]+$/)&&!t.includes("<")){console.log("⚠️ Original XML appears to be Base64 encoded, decoding...");try{const k=atob(t);(k.includes("<?xml")||k.includes("<Invoice"))&&(l=k,console.log("✅ Successfully decoded Base64 XML"))}catch{console.log("❌ Base64 decode failed, using original")}}console.log("📋 Extracting values from original XML...");const m=Ni(l,"AccountingSupplierParty")||"البائع",u=Ci(l,"AccountingSupplierParty")||"",d=nx(l)||"",h=rx(l),p=Ni(l,"AccountingCustomerParty")||"عميل نقدي",f=Ci(l,"AccountingCustomerParty")||h.id||"",x=sx(l)||"",g=l.match(/<cac:AccountingCustomerParty>[\s\S]*?<cbc:CityName>([^<]*)<\/cbc:CityName>[\s\S]*?<\/cac:AccountingCustomerParty>/i),b=g?g[1].trim():"",y=Es(l,"TaxExclusiveAmount")||"0.00",_=Es(l,"TaxInclusiveAmount")||c||"0.00",j=l.match(/<cac:TaxTotal>[\s\S]*?<cbc:TaxAmount[^>]*>([^<]*)<\/cbc:TaxAmount>/i),I=j?j[1].trim():"0.00",w=l.match(/<cac:TaxCategory>[\s\S]*?<cbc:Percent>([^<]*)<\/cbc:Percent>/i),N=w?w[1].trim():"16";console.log("📊 Extracted values - PRESERVING ORIGINAL TAX:"),console.log("   - Seller Name:",m),console.log("   - Seller Tax Number:",u),console.log("   - Seller Income Number:",d),console.log("   - Customer Type:",h.schemeID),console.log("   - Customer Number:",h.id),console.log("   - Customer Name:",p),console.log("   - Customer Tax Number:",f),console.log("   - Customer City:",b),console.log("   - Customer Phone:",x),console.log("   - Tax Exclusive Amount:",y),console.log("   - Tax Inclusive Amount:",_),console.log("   - Total Tax Amount:",I),console.log("   - Tax Percent:",N);let C=ix;const A=tt(n),F=new Date().toISOString().split("T")[0];C=C.replace(/\{\{INVOICE_NUMBER\}\}/g,r),C=C.replace(/\{\{UUID\}\}/g,i),C=C.replace(/\{\{INVOICE_DATE\}\}/g,F),C=C.replace(/\{\{RETURN_REASON\}\}/g,A),C=C.replace(/\{\{INVOICE_COUNTER\}\}/g,o),C=C.replace(/\{\{ORIGINAL_INVOICE_NUMBER\}\}/g,a),C=C.replace(/\{\{ORIGINAL_INVOICE_UUID\}\}/g,s),C=C.replace(/\{\{ORIGINAL_INVOICE_TOTAL\}\}/g,c),C=C.replace(/\{\{SELLER_NAME\}\}/g,tt(m)),C=C.replace(/\{\{SELLER_TAX_NUMBER\}\}/g,u),C=C.replace(/\{\{SELLER_INCOME_NUMBER\}\}/g,d),C=C.replace(/\{\{CUSTOMER_TYPE\}\}/g,h.schemeID||"NIN"),C=C.replace(/\{\{CUSTOMER_NUMBER\}\}/g,h.id||""),C=C.replace(/\{\{CUSTOMER_NAME\}\}/g,tt(p)),C=C.replace(/\{\{CUSTOMER_TAX_NUMBER\}\}/g,f),C=C.replace(/\{\{CUSTOMER_CITY\}\}/g,tt(b)),C=C.replace(/\{\{CUSTOMER_PHONE\}\}/g,x),C=C.replace(/\{\{TAX_EXCLUSIVE_AMOUNT\}\}/g,y),C=C.replace(/\{\{TAX_INCLUSIVE_AMOUNT\}\}/g,_),C=C.replace(/\{\{TOTAL_TAX_AMOUNT\}\}/g,I),C=C.replace(/\{\{TAX_PERCENT\}\}/g,N);const T=ax(l,n);return C=C.replace(/\{\{INVOICE_LINES\}\}/g,T),console.log("✅ generateReturnXmlFromOriginal: Template-based XML generation complete"),console.log("📄 Generated XML length:",C.length),console.log("📄 XML contains PaymentMeans:",C.includes("<cac:PaymentMeans>")?"YES ✅":"NO ❌"),console.log("📄 XML contains InstructionNote:",C.includes("<cbc:InstructionNote>")?"YES ✅":"NO ❌"),console.log("📄 XML contains TaxSubtotal:",C.includes("<cac:TaxSubtotal>")?"YES ✅":"NO ❌"),console.log("📄 XML contains TaxCategory S:",C.includes('<cbc:ID schemeAgencyID="6" schemeID="UN/ECE 5305">S</cbc:ID>')?"YES ✅":"NO ❌"),C},Jr=t=>{console.log("🔄 Mapping UI invoice type to Arabic:",t);const n={general_tax:"ضريبة عامة",income:"دخل","ضريبة عامة":"ضريبة عامة","مبيعات عامة":"ضريبة عامة",دخل:"دخل"}[t]||"دخل";return console.log("✅ Mapped to Arabic type:",n),n},lx=(t,r=!1)=>{console.log("🔄 Mapping to template type:",{uiInvoiceType:t,isReturn:r});const n=Jr(t);let i;n==="ضريبة عامة"?i="general_tax_invoice":i="regular_invoice";const o=r?i==="general_tax_invoice"?"general_tax_return_invoice":"return_invoice":i;return console.log("✅ Final template type determined:",o),o},dx=t=>{console.log("🔍 Detecting invoice type from XML content...");const r=t.includes('currencyID="JO"'),n=t.includes('currencyID="JOD"');return r&&!n?(console.log('✅ Detected as GENERAL TAX invoice (uses currencyID="JO")'),"general_tax"):(console.log('✅ Detected as INCOME invoice (uses currencyID="JOD")'),"income")},ux=(t,r="دخل")=>{if(console.log("🔍 Mapping payment method:",{paymentMethod:t,invoiceType:r}),Jr(r)==="ضريبة عامة"){const o={نقدي:"012",ذمم:"022"}[t]||"012";return console.log("✅ General tax invoice code mapped:",o),o}else{const o={نقدي:"011",ذمم:"021"}[t]||"011";return console.log("✅ Income invoice code mapped:",o),o}},Jn=t=>{try{console.log("🔤 Input string for Base64 encoding:",t.substring(0,200)+"..."),console.log("🔤 Contains Arabic test:",/[\u0600-\u06FF]/.test(t)?"YES ✅":"NO ❌");const n=new TextEncoder().encode(t);let i="";for(let a=0;a<n.length;a++)i+=String.fromCharCode(n[a]);const o=btoa(i);console.log("✅ Base64 encoding successful, length:",o.length);try{const a=atob(o),s=new TextDecoder().decode(new Uint8Array([...a].map(c=>c.charCodeAt(0))));console.log("✅ Validation successful, Arabic preserved:",/[\u0600-\u06FF]/.test(s)?"YES ✅":"NO ❌")}catch(a){console.warn("⚠️ Validation failed but continuing:",a)}return o}catch(r){console.error("❌ Error in Base64 encoding:",r);try{console.log("🔄 Trying fallback encoding method...");const n=btoa(unescape(encodeURIComponent(t)));return console.log("✅ Fallback encoding successful"),n}catch(n){return console.error("❌ Fallback encoding failed:",n),""}}},mx=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(t){const r=Math.random()*16|0;return(t=="x"?r:r&3|8).toString(16)}),hx=async t=>{try{console.log("🔍 Fetching XML template from PHP API for type:",t);const r=localStorage.getItem(xe),i=await(await fetch(`${oe()}${W.GET_ALL("xml_templates")}`,{headers:{Authorization:`Bearer ${r}`}})).json();if(!i.success)throw new Error(i.message||"Failed to fetch templates");const a=(i.data||[]).find(s=>s.template_type===t&&s.is_active===!0);if(a&&a.xml_structure)return console.log("✅ Template loaded from PHP API successfully"),console.log("📄 Template details:",{id:a.id,name:a.template_name,type:t,contentLength:a.xml_structure.length}),a.xml_structure;throw new Error("No template data found")}catch(r){return console.error("❌ Failed to fetch XML template from PHP API for type:",t,r),console.log("🔄 Using fallback template for:",t),t==="return_invoice"?px():t==="general_tax_invoice"?xx():t==="general_tax_return_invoice"?gx():fx()}},fx=()=>`<?xml version="1.0" encoding="UTF-8"?>
<Invoice xmlns="urn:oasis:names:specification:ubl:schema:xsd:Invoice-2" xmlns:cac="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2" xmlns:cbc="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2" xmlns:ext="urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2">
  <cbc:ProfileID>reporting:1.0</cbc:ProfileID>
  <cbc:ID>{{INVOICE_NUMBER}}</cbc:ID>
  <cbc:UUID>{{UUID}}</cbc:UUID>
  <cbc:IssueDate>{{INVOICE_DATE}}</cbc:IssueDate>
  <cbc:InvoiceTypeCode name="{{PAYMENT_METHOD}}">388</cbc:InvoiceTypeCode>
  <cbc:Note>{{NOTES}}</cbc:Note>
  <cbc:DocumentCurrencyCode>JOD</cbc:DocumentCurrencyCode>
  <cbc:TaxCurrencyCode>JOD</cbc:TaxCurrencyCode>
  <cac:AdditionalDocumentReference>
    <cbc:ID>ICV</cbc:ID>
    <cbc:UUID>{{INVOICE_COUNTER}}</cbc:UUID>
  </cac:AdditionalDocumentReference>
  <cac:AccountingSupplierParty>
    <cac:Party>
      <cac:PostalAddress>
        <cac:Country>
          <cbc:IdentificationCode>JO</cbc:IdentificationCode>
        </cac:Country>
      </cac:PostalAddress>
      <cac:PartyTaxScheme>
        <cbc:CompanyID>{{SELLER_TAX_NUMBER}}</cbc:CompanyID>
        <cac:TaxScheme>
          <cbc:ID>VAT</cbc:ID>
        </cac:TaxScheme>
      </cac:PartyTaxScheme>
      <cac:PartyLegalEntity>
        <cbc:RegistrationName>{{SELLER_NAME}}</cbc:RegistrationName>
      </cac:PartyLegalEntity>
    </cac:Party>
  </cac:AccountingSupplierParty>
  <cac:AccountingCustomerParty>
    <cac:Party>
      <cac:PartyIdentification>
        <cbc:ID schemeID="{{CUSTOMER_TYPE}}">{{CUSTOMER_NUMBER}}</cbc:ID>
      </cac:PartyIdentification>
      <cac:PostalAddress>
        <cbc:PostalZone></cbc:PostalZone>
        <cac:Country>
          <cbc:IdentificationCode>JO</cbc:IdentificationCode>
        </cac:Country>
      </cac:PostalAddress>
      <cac:PartyTaxScheme>
        <cac:TaxScheme>
          <cbc:ID>VAT</cbc:ID>
        </cac:TaxScheme>
      </cac:PartyTaxScheme>
      <cac:PartyLegalEntity>
        <cbc:RegistrationName>{{CUSTOMER_NAME}}</cbc:RegistrationName>
      </cac:PartyLegalEntity>
    </cac:Party>
    <cac:AccountingContact>
      <cbc:Telephone>{{CUSTOMER_PHONE}}</cbc:Telephone>
    </cac:AccountingContact>
  </cac:AccountingCustomerParty>
  <cac:SellerSupplierParty>
    <cac:Party>
      <cac:PartyIdentification>
        <cbc:ID>{{SELLER_INCOME_NUMBER}}</cbc:ID>
      </cac:PartyIdentification>
    </cac:Party>
  </cac:SellerSupplierParty>
  <cac:PaymentMeans>
    <cbc:PaymentMeansCode listID="UN/ECE 4461">10</cbc:PaymentMeansCode>
    <cbc:InstructionNote>{{PAYMENT_METHOD}}</cbc:InstructionNote>
  </cac:PaymentMeans>
  <cac:AllowanceCharge>
    <cbc:ChargeIndicator>false</cbc:ChargeIndicator>
    <cbc:AllowanceChargeReason>discount</cbc:AllowanceChargeReason>
    <cbc:Amount currencyID="JOD">{{ALLOWANCE_CHARGE_AMOUNT}}</cbc:Amount>
  </cac:AllowanceCharge>
  <cac:LegalMonetaryTotal>
    <cbc:TaxExclusiveAmount currencyID="JOD">{{TAX_EXCLUSIVE_AMOUNT}}</cbc:TaxExclusiveAmount>
    <cbc:TaxInclusiveAmount currencyID="JOD">{{TAX_INCLUSIVE_AMOUNT}}</cbc:TaxInclusiveAmount>
    <cbc:AllowanceTotalAmount currencyID="JOD">{{ALLOWANCE_CHARGE_AMOUNT}}</cbc:AllowanceTotalAmount>
    <cbc:PayableAmount currencyID="JOD">{{TAX_INCLUSIVE_AMOUNT}}</cbc:PayableAmount>
  </cac:LegalMonetaryTotal>
  {{INVOICE_LINES}}
</Invoice>`,px=()=>`<?xml version="1.0" encoding="UTF-8"?>
<Invoice xmlns="urn:oasis:names:specification:ubl:schema:xsd:Invoice-2" xmlns:cac="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2" xmlns:cbc="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2" xmlns:ext="urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2">
  <cbc:ProfileID>reporting:1.0</cbc:ProfileID>
  <cbc:ID>{{INVOICE_NUMBER}}</cbc:ID>
  <cbc:UUID>{{UUID}}</cbc:UUID>
  <cbc:IssueDate>{{INVOICE_DATE}}</cbc:IssueDate>
  <cbc:InvoiceTypeCode name="{{PAYMENT_METHOD}}">381</cbc:InvoiceTypeCode>
  <cbc:Note>{{RETURN_REASON}}</cbc:Note>
  <cbc:DocumentCurrencyCode>JOD</cbc:DocumentCurrencyCode>
  <cbc:TaxCurrencyCode>JOD</cbc:TaxCurrencyCode>
  <cac:BillingReference>
    <cac:InvoiceDocumentReference>
      <cbc:ID>{{ORIGINAL_INVOICE_NUMBER}}</cbc:ID>
      <cbc:UUID>{{ORIGINAL_INVOICE_UUID}}</cbc:UUID>
      <cbc:DocumentDescription>{{ORIGINAL_INVOICE_TOTAL}}</cbc:DocumentDescription>
    </cac:InvoiceDocumentReference>
  </cac:BillingReference>
  <cac:AdditionalDocumentReference>
    <cbc:ID>ICV</cbc:ID>
    <cbc:UUID>{{INVOICE_COUNTER}}</cbc:UUID>
  </cac:AdditionalDocumentReference>
  <cac:AccountingSupplierParty>
    <cac:Party>
      <cac:PostalAddress>
        <cac:Country>
          <cbc:IdentificationCode>JO</cbc:IdentificationCode>
        </cac:Country>
      </cac:PostalAddress>
      <cac:PartyTaxScheme>
        <cbc:CompanyID>{{SELLER_TAX_NUMBER}}</cbc:CompanyID>
        <cac:TaxScheme>
          <cbc:ID>VAT</cbc:ID>
        </cac:TaxScheme>
      </cac:PartyTaxScheme>
      <cac:PartyLegalEntity>
        <cbc:RegistrationName>{{SELLER_NAME}}</cbc:RegistrationName>
      </cac:PartyLegalEntity>
    </cac:Party>
  </cac:AccountingSupplierParty>
  <cac:AccountingCustomerParty>
    <cac:Party>
      <cac:PartyIdentification>
        <cbc:ID schemeID="{{CUSTOMER_TYPE}}">{{CUSTOMER_NUMBER}}</cbc:ID>
      </cac:PartyIdentification>
      <cac:PostalAddress>
        <cbc:PostalZone></cbc:PostalZone>
        <cac:Country>
          <cbc:IdentificationCode>JO</cbc:IdentificationCode>
        </cac:Country>
      </cac:PostalAddress>
      <cac:PartyTaxScheme>
        <cac:TaxScheme>
          <cbc:ID>VAT</cbc:ID>
        </cac:TaxScheme>
      </cac:PartyTaxScheme>
      <cac:PartyLegalEntity>
        <cbc:RegistrationName>{{CUSTOMER_NAME}}</cbc:RegistrationName>
      </cac:PartyLegalEntity>
    </cac:Party>
    <cac:AccountingContact>
      <cbc:Telephone>{{CUSTOMER_PHONE}}</cbc:Telephone>
    </cac:AccountingContact>
  </cac:AccountingCustomerParty>
  <cac:SellerSupplierParty>
    <cac:Party>
      <cac:PartyIdentification>
        <cbc:ID>{{SELLER_SUPPLIER_ID}}</cbc:ID>
      </cac:PartyIdentification>
    </cac:Party>
  </cac:SellerSupplierParty>
  <cac:PaymentMeans>
    <cbc:PaymentMeansCode listID="UN/ECE 4461">10</cbc:PaymentMeansCode>
    <cbc:InstructionNote>{{RETURN_REASON}}</cbc:InstructionNote>
  </cac:PaymentMeans>
  <cac:AllowanceCharge>
    <cbc:ChargeIndicator>false</cbc:ChargeIndicator>
    <cbc:AllowanceChargeReason>discount</cbc:AllowanceChargeReason>
    <cbc:Amount currencyID="JOD">{{ALLOWANCE_CHARGE_AMOUNT}}</cbc:Amount>
  </cac:AllowanceCharge>
  <cac:LegalMonetaryTotal>
    <cbc:TaxExclusiveAmount currencyID="JOD">{{TAX_EXCLUSIVE_AMOUNT}}</cbc:TaxExclusiveAmount>
    <cbc:TaxInclusiveAmount currencyID="JOD">{{TAX_INCLUSIVE_AMOUNT}}</cbc:TaxInclusiveAmount>
    <cbc:AllowanceTotalAmount currencyID="JOD">{{ALLOWANCE_CHARGE_AMOUNT}}</cbc:AllowanceTotalAmount>
    <cbc:PayableAmount currencyID="JOD">{{TAX_INCLUSIVE_AMOUNT}}</cbc:PayableAmount>
  </cac:LegalMonetaryTotal>
  {{INVOICE_LINES}}
</Invoice>`,xx=()=>`<?xml version="1.0" encoding="UTF-8"?>
<Invoice xmlns="urn:oasis:names:specification:ubl:schema:xsd:Invoice-2" xmlns:cac="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2" xmlns:cbc="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2" xmlns:ext="urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2">
  <cbc:ProfileID>reporting:1.0</cbc:ProfileID>
  <cbc:ID>{{INVOICE_NUMBER}}</cbc:ID>
  <cbc:UUID>{{UUID}}</cbc:UUID>
  <cbc:IssueDate>{{INVOICE_DATE}}</cbc:IssueDate>
  <cbc:InvoiceTypeCode name="{{PAYMENT_METHOD}}">388</cbc:InvoiceTypeCode>
  <cbc:Note>{{NOTES}}</cbc:Note>
  <cbc:DocumentCurrencyCode>JOD</cbc:DocumentCurrencyCode>
  <cbc:TaxCurrencyCode>JOD</cbc:TaxCurrencyCode>
  <cac:AdditionalDocumentReference>
    <cbc:ID>ICV</cbc:ID>
    <cbc:UUID>{{INVOICE_COUNTER}}</cbc:UUID>
  </cac:AdditionalDocumentReference>
  <cac:AccountingSupplierParty>
    <cac:Party>
      <cac:PostalAddress>
        <cac:Country>
          <cbc:IdentificationCode>JO</cbc:IdentificationCode>
        </cac:Country>
      </cac:PostalAddress>
      <cac:PartyTaxScheme>
        <cbc:CompanyID>{{SELLER_TAX_NUMBER}}</cbc:CompanyID>
        <cac:TaxScheme>
          <cbc:ID>VAT</cbc:ID>
        </cac:TaxScheme>
      </cac:PartyTaxScheme>
      <cac:PartyLegalEntity>
        <cbc:RegistrationName>{{SELLER_NAME}}</cbc:RegistrationName>
      </cac:PartyLegalEntity>
    </cac:Party>
  </cac:AccountingSupplierParty>
  <cac:AccountingCustomerParty>
    <cac:Party>
      <cac:PartyIdentification>
        <cbc:ID schemeID="{{CUSTOMER_TYPE}}">{{CUSTOMER_NUMBER}}</cbc:ID>
      </cac:PartyIdentification>
      <cac:PostalAddress>
        <cbc:PostalZone></cbc:PostalZone>
        <cbc:CountrySubentityCode>{{CUSTOMER_TYPE}}</cbc:CountrySubentityCode>
        <cac:Country>
          <cbc:IdentificationCode>JO</cbc:IdentificationCode>
        </cac:Country>
      </cac:PostalAddress>
      <cac:PartyTaxScheme>
        <cbc:CompanyID>{{CUSTOMER_NUMBER}}</cbc:CompanyID>
        <cac:TaxScheme>
          <cbc:ID>VAT</cbc:ID>
        </cac:TaxScheme>
      </cac:PartyTaxScheme>
      <cac:PartyLegalEntity>
        <cbc:RegistrationName>{{CUSTOMER_NAME}}</cbc:RegistrationName>
      </cac:PartyLegalEntity>
    </cac:Party>
    <cac:AccountingContact>
      <cbc:Telephone>{{CUSTOMER_PHONE}}</cbc:Telephone>
    </cac:AccountingContact>
  </cac:AccountingCustomerParty>
  <cac:SellerSupplierParty>
    <cac:Party>
      <cac:PartyIdentification>
        <cbc:ID>{{SELLER_INCOME_NUMBER}}</cbc:ID>
      </cac:PartyIdentification>
    </cac:Party>
  </cac:SellerSupplierParty>
  <cac:AllowanceCharge>
    <cbc:ChargeIndicator>false</cbc:ChargeIndicator>
    <cbc:AllowanceChargeReason>discount</cbc:AllowanceChargeReason>
    <cbc:Amount currencyID="JO">{{ALLOWANCE_CHARGE_AMOUNT}}</cbc:Amount>
  </cac:AllowanceCharge>
  <cac:TaxTotal>
    <cbc:TaxAmount currencyID="JO">{{TOTAL_TAX_AMOUNT}}</cbc:TaxAmount>
  </cac:TaxTotal>
  <cac:LegalMonetaryTotal>
    <cbc:TaxExclusiveAmount currencyID="JO">{{TAX_EXCLUSIVE_AMOUNT}}</cbc:TaxExclusiveAmount>
    <cbc:TaxInclusiveAmount currencyID="JO">{{TAX_INCLUSIVE_AMOUNT}}</cbc:TaxInclusiveAmount>
    <cbc:AllowanceTotalAmount currencyID="JO">{{ALLOWANCE_CHARGE_AMOUNT}}</cbc:AllowanceTotalAmount>
    <cbc:PayableAmount currencyID="JO">{{TAX_INCLUSIVE_AMOUNT}}</cbc:PayableAmount>
  </cac:LegalMonetaryTotal>
  {{INVOICE_LINES}}
</Invoice>`,gx=()=>`<?xml version="1.0" encoding="UTF-8"?>
<Invoice xmlns="urn:oasis:names:specification:ubl:schema:xsd:Invoice-2" xmlns:cac="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2" xmlns:cbc="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2" xmlns:ext="urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2">
  <cbc:ProfileID>reporting:1.0</cbc:ProfileID>
  <cbc:ID>{{INVOICE_NUMBER}}</cbc:ID>
  <cbc:UUID>{{UUID}}</cbc:UUID>
  <cbc:IssueDate>{{INVOICE_DATE}}</cbc:IssueDate>
  <cbc:InvoiceTypeCode name="012">381</cbc:InvoiceTypeCode>
  <cbc:Note>{{RETURN_REASON}}</cbc:Note>
  <cbc:DocumentCurrencyCode>JOD</cbc:DocumentCurrencyCode>
  <cbc:TaxCurrencyCode>JOD</cbc:TaxCurrencyCode>
  <cac:BillingReference>
    <cac:InvoiceDocumentReference>
      <cbc:ID>{{ORIGINAL_INVOICE_NUMBER}}</cbc:ID>
      <cbc:UUID>{{ORIGINAL_INVOICE_UUID}}</cbc:UUID>
      <cbc:DocumentDescription>{{ORIGINAL_INVOICE_TOTAL}}</cbc:DocumentDescription>
    </cac:InvoiceDocumentReference>
  </cac:BillingReference>
  <cac:AdditionalDocumentReference>
    <cbc:ID>ICV</cbc:ID>
    <cbc:UUID>{{INVOICE_COUNTER}}</cbc:UUID>
  </cac:AdditionalDocumentReference>
  <cac:AccountingSupplierParty>
    <cac:Party>
      <cac:PostalAddress>
        <cac:Country>
          <cbc:IdentificationCode>JO</cbc:IdentificationCode>
        </cac:Country>
      </cac:PostalAddress>
      <cac:PartyTaxScheme>
        <cbc:CompanyID>{{SELLER_TAX_NUMBER}}</cbc:CompanyID>
        <cac:TaxScheme>
          <cbc:ID>VAT</cbc:ID>
        </cac:TaxScheme>
      </cac:PartyTaxScheme>
      <cac:PartyLegalEntity>
        <cbc:RegistrationName>{{SELLER_NAME}}</cbc:RegistrationName>
      </cac:PartyLegalEntity>
    </cac:Party>
  </cac:AccountingSupplierParty>
  <cac:AccountingCustomerParty>
    <cac:Party>
      <cac:PartyIdentification>
        <cbc:ID schemeID="{{CUSTOMER_TYPE}}">{{CUSTOMER_NUMBER}}</cbc:ID>
      </cac:PartyIdentification>
      <cac:PostalAddress>
        <cbc:PostalZone></cbc:PostalZone>
        <cbc:CountrySubentityCode>{{CUSTOMER_TYPE}}</cbc:CountrySubentityCode>
        <cac:Country>
          <cbc:IdentificationCode>JO</cbc:IdentificationCode>
        </cac:Country>
      </cac:PostalAddress>
      <cac:PartyTaxScheme>
        <cbc:CompanyID>{{CUSTOMER_TAX_NUMBER}}</cbc:CompanyID>
        <cac:TaxScheme>
          <cbc:ID>VAT</cbc:ID>
        </cac:TaxScheme>
      </cac:PartyTaxScheme>
      <cac:PartyLegalEntity>
        <cbc:RegistrationName>{{CUSTOMER_NAME}}</cbc:RegistrationName>
      </cac:PartyLegalEntity>
    </cac:Party>
    <cac:AccountingContact>
      <cbc:Telephone>{{CUSTOMER_PHONE}}</cbc:Telephone>
    </cac:AccountingContact>
  </cac:AccountingCustomerParty>
  <cac:SellerSupplierParty>
    <cac:Party>
      <cac:PartyIdentification>
        <cbc:ID>{{SELLER_INCOME_NUMBER}}</cbc:ID>
      </cac:PartyIdentification>
    </cac:Party>
  </cac:SellerSupplierParty>
  <cac:PaymentMeans>
    <cbc:PaymentMeansCode>10</cbc:PaymentMeansCode>
    <cbc:InstructionNote>{{RETURN_REASON}}</cbc:InstructionNote>
  </cac:PaymentMeans>
  <cac:AllowanceCharge>
    <cbc:ID>10</cbc:ID>
    <cbc:ChargeIndicator>false</cbc:ChargeIndicator>
    <cbc:AllowanceChargeReasonCode>discount</cbc:AllowanceChargeReasonCode>
    <cbc:AllowanceChargeReason>{{RETURN_REASON}}</cbc:AllowanceChargeReason>
    <cbc:Amount currencyID="JO">0.00</cbc:Amount>
  </cac:AllowanceCharge>
  <cac:TaxTotal>
    <cbc:TaxAmount currencyID="JO">0.00</cbc:TaxAmount>
    <cac:TaxSubtotal>
      <cbc:TaxableAmount currencyID="JO">{{RETURN_TOTAL}}</cbc:TaxableAmount>
      <cbc:TaxAmount currencyID="JO">0.00</cbc:TaxAmount>
      <cac:TaxCategory>
        <cbc:ID schemeAgencyID="6" schemeID="UN/ECE 5305">O</cbc:ID>
        <cbc:Percent>0.00</cbc:Percent>
        <cac:TaxScheme>
          <cbc:ID schemeAgencyID="6" schemeID="UN/ECE 5153">VAT</cbc:ID>
        </cac:TaxScheme>
      </cac:TaxCategory>
    </cac:TaxSubtotal>
  </cac:TaxTotal>
  <cac:LegalMonetaryTotal>
    <cbc:TaxExclusiveAmount currencyID="JO">{{RETURN_TOTAL}}</cbc:TaxExclusiveAmount>
    <cbc:TaxInclusiveAmount currencyID="JO">{{RETURN_TOTAL}}</cbc:TaxInclusiveAmount>
    <cbc:AllowanceTotalAmount currencyID="JO">0.00</cbc:AllowanceTotalAmount>
    <cbc:PayableAmount currencyID="JO">{{RETURN_TOTAL}}</cbc:PayableAmount>
  </cac:LegalMonetaryTotal>
  {{INVOICE_LINES}}
</Invoice>`,Bs=async(t,r,n,i,o,a,s,c)=>{var w,N,C;console.log("🚀 Starting XML generation..."),console.log("📊 Invoice number:",t),console.log("💰 Total:",r),console.log("📦 Items count:",i.length),console.log("🏪 Seller:",o.seller_name),console.log("⚙️ Options:",c);const l=String(a),m=mx();console.log("🆔 Generated UUID:",m);const u=n.invoice_type||o.invoice_type||"دخل";console.log("📋 Effective invoice type:",u,"(from invoiceData:",n.invoice_type,", sellerData:",o.invoice_type,")");const d=lx(u,(c==null?void 0:c.isReturn)||!1);console.log("📄 Template type:",d);const h=await hx(d),p=u,f=Jr(p)==="ضريبة عامة";console.log("🧮 Invoice type for calculations:",p,"isGeneralTax:",f);const x=ux(n.payment_method||"نقدي",p),g=i.map(A=>xt({quantity:A.quantity,unitPrice:A.unit_price,discountAmount:A.discount_amount||0,taxPercent:A.tax_percent||0,taxCalculationMode:n.tax_calculation_mode||"tax_exclusive",existingLineExtensionAmount:A.line_extension_amount}));let b=lr(g);console.log("💰 Calculated totals:",b),c!=null&&c.isReturn&&(console.log("🔄 Return invoice: PRESERVING original tax values (not zeroing!)"),console.log("💰 Return invoice totals (with original taxes):",b));const y=!(c!=null&&c.isReturn)&&(c==null?void 0:c.originalXmlStrings);let _=h.replace(/\{\{INVOICE_NUMBER\}\}/g,tt(t)).replace(/\{\{UUID\}\}/g,m).replace(/\{\{INVOICE_DATE\}\}/g,n.invoice_date).replace(/\{\{INVOICE_COUNTER\}\}/g,l).replace(/\{\{NOTES\}\}/g,tt(c!=null&&c.isReturn&&(c!=null&&c.returnReason)?c.returnReason:n.notes||"")).replace(/\{\{SELLER_NAME\}\}/g,tt(o.seller_name)).replace(/\{\{SELLER_TAX_NUMBER\}\}/g,tt(o.tax_number)).replace(/\{\{SELLER_INCOME_NUMBER\}\}/g,tt(o.income_number)).replace(/\{\{SELLER_SUPPLIER_ID\}\}/g,tt(o.income_number)).replace(/\{\{CUSTOMER_NAME\}\}/g,tt(n.customer_name||"عميل نقدي")).replace(/\{\{CUSTOMER_NUMBER\}\}/g,tt(tx(n.customer_number,n.customer_type))).replace(/\{\{CUSTOMER_TYPE\}\}/g,tt(n.customer_type||"NIN")).replace(/\{\{CUSTOMER_PHONE\}\}/g,tt(n.phone_number||"")).replace(/\{\{PAYMENT_METHOD\}\}/g,x);if(_=_.replace(/\{\{CUSTOMER_TAX_NUMBER\}\}/g,tt(n.customer_number||"")),c!=null&&c.isReturn){console.log("🔄 ===== RETURN INVOICE PROCESSING (PRESERVING TAXES) ====="),console.log("📊 Calculated totals from line items:",b);let A="";c.returnReason&&c.returnReason.trim().length>0?A=c.returnReason.trim():A=`إرجاع فاتورة رقم ${c.originalInvoiceNumber||"غير محدد"}`,console.log("📝 Return reason text:",A),_=_.replace(/\{\{ALLOWANCE_CHARGE_AMOUNT\}\}/g,Me(b.allowanceChargeAmount||0)).replace(/\{\{DISCOUNT_AMOUNT\}\}/g,Me(b.allowanceChargeAmount||0)).replace(/\{\{TAX_EXCLUSIVE_AMOUNT\}\}/g,Me(b.taxExclusiveAmount)).replace(/\{\{TAX_INCLUSIVE_AMOUNT\}\}/g,Me(b.taxInclusiveAmount)).replace(/\{\{TOTAL_TAX_AMOUNT\}\}/g,Me(b.totalTaxAmount)).replace(/\{\{TOTAL_TAX_BEFORE_DISCOUNT\}\}/g,Me(b.totalTaxAmount)).replace(/\{\{TAX_PERCENT\}\}/g,Me(((w=i[0])==null?void 0:w.tax_percent)||16)),_=_.replace(/\{\{RETURN_REASON\}\}/g,tt(A)).replace(/\{\{ORIGINAL_INVOICE_NUMBER\}\}/g,tt(c.originalInvoiceNumber||"")).replace(/\{\{ORIGINAL_INVOICE_UUID\}\}/g,tt(c.originalInvoiceUUID||"")).replace(/\{\{ORIGINAL_INVOICE_TOTAL\}\}/g,Me(b.taxInclusiveAmount)),_=_.replace(/\{\{RETURN_TOTAL\}\}/g,Me(b.taxInclusiveAmount)),console.log("✅ Return invoice with preserved taxes:"),console.log("   TaxExclusiveAmount:",Me(b.taxExclusiveAmount)),console.log("   TaxInclusiveAmount:",Me(b.taxInclusiveAmount)),console.log("   TotalTaxAmount:",Me(b.totalTaxAmount))}else if(y&&(c!=null&&c.originalXmlStrings)){const A=c.originalXmlStrings;_=_.replace(/\{\{ALLOWANCE_CHARGE_AMOUNT\}\}/g,A.allowanceChargeAmount||Me(b.allowanceChargeAmount)).replace(/\{\{DISCOUNT_AMOUNT\}\}/g,A.allowanceChargeAmount||Me(b.allowanceChargeAmount)).replace(/\{\{TAX_EXCLUSIVE_AMOUNT\}\}/g,A.taxExclusiveAmount||Me(b.taxExclusiveAmount)).replace(/\{\{TAX_INCLUSIVE_AMOUNT\}\}/g,A.taxInclusiveAmount||Me(b.taxInclusiveAmount)).replace(/\{\{TOTAL_TAX_AMOUNT\}\}/g,A.totalTaxAmount||Me(b.totalTaxAmount)).replace(/\{\{TOTAL_TAX_BEFORE_DISCOUNT\}\}/g,Me(b.totalTaxAmount)).replace(/\{\{TAX_PERCENT\}\}/g,Me(((N=i[0])==null?void 0:N.tax_percent)||16))}else _=_.replace(/\{\{ALLOWANCE_CHARGE_AMOUNT\}\}/g,Me(b.allowanceChargeAmount)).replace(/\{\{DISCOUNT_AMOUNT\}\}/g,Me(b.allowanceChargeAmount)).replace(/\{\{TAX_EXCLUSIVE_AMOUNT\}\}/g,Me(b.taxExclusiveAmount)).replace(/\{\{TAX_INCLUSIVE_AMOUNT\}\}/g,Me(b.taxInclusiveAmount)).replace(/\{\{TOTAL_TAX_AMOUNT\}\}/g,Me(b.totalTaxAmount)).replace(/\{\{TOTAL_TAX_BEFORE_DISCOUNT\}\}/g,Me(b.totalTaxAmount)).replace(/\{\{TAX_PERCENT\}\}/g,Me(((C=i[0])==null?void 0:C.tax_percent)||16));c!=null&&c.isReturn||(_=_.replace(/\{\{RETURN_REASON\}\}/g,"").replace(/\{\{ORIGINAL_INVOICE_NUMBER\}\}/g,"").replace(/\{\{ORIGINAL_INVOICE_UUID\}\}/g,"").replace(/\{\{ORIGINAL_INVOICE_TOTAL\}\}/g,""));let j="";i.forEach((A,F)=>{const T=F+1,k=g[F],P=y&&A.xml_unit_price&&A.xml_quantity&&A.xml_line_total,E=(typeof A.quantity=="string"?parseFloat(A.quantity):A.quantity)||1,O=P?A.xml_quantity:Me(E);let R,D;if(c!=null&&c.isReturn)if(A.xml_unit_price&&A.xml_line_total)D=A.xml_unit_price,R=A.xml_line_total,console.log(`📋 Return line ${T}: EXACT ORIGINAL - PriceAmount=${D}, LineExt=${R}`);else{const z=typeof A.unit_price=="string"?parseFloat(A.unit_price):A.unit_price||0;D=Me(z),R=Me(z*E),console.log(`📋 Return line ${T}: Fallback - PriceAmount=${D}, LineExt=${R}`)}else{R=P?A.xml_line_total:Me(k.lineExtensionAmount);const z=E>0?k.lineExtensionAmount/E:k.unitPriceBeforeTax;D=P?A.xml_unit_price:Me(z)}const $=Me(A.tax_percent||16),M=Me(k.taxAmount),U=Me(k.roundingAmount||0),Q=A.tax_category_code||Ut(A.tax_percent||16),B=`
        <cac:InvoiceLine>
            <cbc:ID>${T}</cbc:ID>
            <cbc:InvoicedQuantity unitCode="PCE">${O}</cbc:InvoicedQuantity>
            <cbc:LineExtensionAmount currencyID="JO">${R}</cbc:LineExtensionAmount>
            <cac:TaxTotal>
                <cbc:TaxAmount currencyID="JO">${M}</cbc:TaxAmount>
                <cbc:RoundingAmount currencyID="JO">${U}</cbc:RoundingAmount>
                <cac:TaxSubtotal>
                    <cbc:TaxableAmount currencyID="JO">${R}</cbc:TaxableAmount>
                    <cbc:TaxAmount currencyID="JO">${M}</cbc:TaxAmount>
                    <cac:TaxCategory>
                        <cbc:ID schemeAgencyID="6" schemeID="UN/ECE 5305">${Q}</cbc:ID>
                        <cbc:Percent>${$}</cbc:Percent>
                        <cac:TaxScheme>
                            <cbc:ID schemeAgencyID="6" schemeID="UN/ECE 5153">VAT</cbc:ID>
                        </cac:TaxScheme>
                    </cac:TaxCategory>
                </cac:TaxSubtotal>
            </cac:TaxTotal>
            <cac:Item>
                <cbc:Name>${tt(A.item_name||"منتج")}</cbc:Name>
            </cac:Item>
            <cac:Price>
                <cbc:PriceAmount currencyID="JO">${D}</cbc:PriceAmount>
                <cac:AllowanceCharge>
                    <cbc:ChargeIndicator>false</cbc:ChargeIndicator>
                    <cbc:AllowanceChargeReason>DISCOUNT</cbc:AllowanceChargeReason>
                    <cbc:Amount currencyID="JO">0.000000000</cbc:Amount>
                </cac:AllowanceCharge>
            </cac:Price>
        </cac:InvoiceLine>`;j+=B}),_=_.replace("{{INVOICE_LINES}}",j),_=_.replace(/<cac:InvoiceLine>[\s\S]*?\{\{[A-Z_]+\}\}[\s\S]*?<\/cac:InvoiceLine>/g,"");const I=_.match(/\{\{[A-Z_]+\}\}/g);return I&&I.length>0&&(console.warn("⚠️ Found remaining placeholders before cleanup:",I),_=_.replace(/\{\{[A-Z_]+\}\}/g,""),console.log("🧹 Cleaned up remaining placeholders")),console.log("✅ XML generation complete"),console.log("📄 XML length:",_.length),_},ol=async t=>{try{console.log("🔢 Generating invoice number and ICV for seller:",t);const r=localStorage.getItem(xe),n=await fetch(`${oe()}${W.GET_BY_ID("sellers",t)}`,{headers:r?{Authorization:`Bearer ${r}`}:{}});if(!n.ok)throw new Error("Failed to fetch seller data");const o=(await n.json()).data;if(!o)throw new Error("Seller not found");const a=o.invoice_number_prefix||"EIN",s=(o.current_invoice_counter||0)+1,c=(o.current_icv_counter||0)+1;await fetch(`${oe()}${W.UPDATE("sellers",t)}`,{method:"POST",headers:{"Content-Type":"application/json",...r?{Authorization:`Bearer ${r}`}:{}},body:JSON.stringify({current_invoice_counter:s,current_icv_counter:c})});const l=`${a}-${s}`;return console.log("✅ Generated invoice number and ICV:",{invoiceNumber:l,icv:c}),{invoiceNumber:l,icv:c}}catch(r){console.error("❌ Error generating invoice number and ICV:",r);const n=`EIN-${Date.now()}-${Math.floor(Math.random()*1e3)}`;return console.log("🆘 Using emergency fallback:",n),{invoiceNumber:n,icv:1}}},bx=async t=>(await ol(t)).invoiceNumber,Ly=async(t,r,n)=>{try{console.log("🚀 Sending invoice to government API with UPDATED logic:",r),console.log("🔑 Using seller ID:",n);const i=localStorage.getItem(xe);let o="دخل";if(n)try{const l=await fetch(`${oe()}${W.GET_BY_ID("sellers",n)}`,{headers:i?{Authorization:`Bearer ${i}`}:{}});if(l.ok){const m=await l.json();m.data&&m.data.invoice_type&&(o=m.data.invoice_type,console.log("✅ Retrieved seller invoice type:",o))}else console.warn("⚠️ Could not fetch seller invoice type, using default:",o)}catch(l){console.warn("⚠️ Error fetching seller data:",l)}const a={xml_base64:t,invoice_number:r,seller_id:n};console.log("📤 Request body prepared with seller invoice type:",{invoiceNumber:r,sellerId:n,sellerInvoiceType:o,xmlDataLength:t.length});const s=await fetch(`${oe()}government-invoice.php`,{method:"POST",headers:{"Content-Type":"application/json",...i?{Authorization:`Bearer ${i}`}:{}},body:JSON.stringify(a)});if(!s.ok){const l=await s.text();throw console.error("❌ Government API error:",l),new Error(l)}const c=await s.json();return console.log("✅ Government API response:",c),c}catch(i){throw console.error("❌ Error calling government API:",i),i}};var yx="Label",al=v.forwardRef((t,r)=>e.jsx(Lt.label,{...t,ref:r,onMouseDown:n=>{var o;n.target.closest("button, input, select, textarea")||((o=t.onMouseDown)==null||o.call(t,n),!n.defaultPrevented&&n.detail>1&&n.preventDefault())}}));al.displayName=yx;var il=al;const vx=Gi("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),_e=v.forwardRef(({className:t,...r},n)=>e.jsx(il,{ref:n,className:Z(vx(),t),...r}));_e.displayName=il.displayName;const _x=t=>({individual:"فرد",business:"شركة",government:"حكومة",NIN:"رقم وطني",TIN:"رقم ضريبي",CRN:"رقم تجاري"})[t]||t,wx=t=>_x(t),jx=["البلقاء","معان","مادبا","المفرق","الكرك","جرش","إربد","الزرقاء","الطفيلة","العقبة","عمان","عجلون"],cl=({customers:t,invoiceData:r,setInvoiceData:n})=>{const[i,o]=v.useState("select"),a=l=>{const m=t.find(u=>u.id===l);m&&n({...r,customer_id:l,customer_name:m.customer_name,customer_number:m.customer_number,customer_type:m.customer_type,phone_number:m.phone_number||"",city:m.city||""})},s=({children:l})=>e.jsxs("div",{className:"flex items-center gap-1",children:[l,e.jsx(An,{className:"h-3 w-3 text-red-500 fill-red-500"})]}),c=new Date().toISOString().split("T")[0];return e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"bg-red-50 border border-red-200 rounded-lg p-3",children:e.jsxs("div",{className:"flex items-center gap-2 text-red-800 text-sm",children:[e.jsx(An,{className:"h-4 w-4 text-red-500 fill-red-500"}),e.jsx("span",{className:"font-semibold",children:"الحقول المطلوبة:"}),e.jsx("span",{children:"اسم العميل، تاريخ الفاتورة، وطريقة الدفع"})]})}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(_e,{htmlFor:"customer",className:"text-blue-900 font-semibold text-sm md:text-base",children:e.jsx(s,{children:"العميل"})}),e.jsxs(Fi,{value:i,onValueChange:l=>o(l),children:[e.jsxs(Ui,{className:"grid w-full grid-cols-2 mb-2 h-8 md:h-10",children:[e.jsx(Vr,{value:"select",className:"text-xs md:text-sm",children:"من القائمة"}),e.jsx(Vr,{value:"manual",className:"text-xs md:text-sm",children:"إدخال يدوي"})]}),e.jsx(Gr,{value:"select",children:e.jsxs(vt,{onValueChange:a,children:[e.jsx(_t,{className:"border-2 border-blue-200 focus:border-blue-400 h-10 md:h-12",children:e.jsx(wt,{placeholder:"اختر العميل"})}),e.jsx(jt,{children:t.map(l=>e.jsx(Je,{value:l.id,children:l.customer_name},l.id))})]})}),e.jsx(Gr,{value:"manual",children:e.jsxs("div",{className:"space-y-3",children:[e.jsx(Te,{placeholder:"اسم العميل",value:r.customer_name,onChange:l=>n({...r,customer_name:l.target.value}),className:"border-2 border-blue-200 focus:border-blue-400 h-10 md:h-12 text-sm md:text-base"}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:[e.jsx(Te,{placeholder:"رقم العميل",value:r.customer_number,onChange:l=>n({...r,customer_number:l.target.value}),className:"border-2 border-blue-200 focus:border-blue-400 h-10 md:h-12 text-sm md:text-base"}),e.jsxs(vt,{value:r.customer_type,onValueChange:l=>n({...r,customer_type:l}),children:[e.jsx(_t,{className:"border-2 border-blue-200 focus:border-blue-400 h-10 md:h-12",children:e.jsx(wt,{placeholder:"نوع الرقم"})}),e.jsxs(jt,{children:[e.jsx(Je,{value:"NIN",children:"الرقم الوطني للمشتري"}),e.jsx(Je,{value:"PN",children:"الرقم الشخصي لغير الأردني"}),e.jsx(Je,{value:"TN",children:"الرقم الضريبي للمشتري"})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:[e.jsx(Te,{placeholder:"رقم الهاتف",value:r.phone_number,onChange:l=>n({...r,phone_number:l.target.value}),className:"border-2 border-blue-200 focus:border-blue-400 h-10 md:h-12 text-sm md:text-base"}),e.jsxs(vt,{value:r.city,onValueChange:l=>n({...r,city:l}),children:[e.jsx(_t,{className:"border-2 border-blue-200 focus:border-blue-400 h-10 md:h-12",children:e.jsx(wt,{placeholder:"المدينة"})}),e.jsx(jt,{className:"bg-white z-50",children:jx.map(l=>e.jsx(Je,{value:l,children:l},l))})]})]})]})})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(_e,{htmlFor:"invoice_date",className:"text-blue-900 font-semibold text-sm md:text-base",children:e.jsx(s,{children:"تاريخ الفاتورة"})}),e.jsx(Te,{id:"invoice_date",type:"date",value:r.invoice_date,max:c,onChange:l=>n({...r,invoice_date:l.target.value}),className:"border-2 border-blue-200 focus:border-blue-400 h-10 md:h-12 text-sm md:text-base"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1 font-cairo",children:"لا يمكن اختيار تاريخ في المستقبل"})]}),e.jsxs("div",{children:[e.jsx(_e,{htmlFor:"payment_method",className:"text-blue-900 font-semibold text-sm md:text-base",children:e.jsx(s,{children:"طريقة الدفع"})}),e.jsxs(vt,{value:r.payment_method,onValueChange:l=>n({...r,payment_method:l}),children:[e.jsx(_t,{className:"border-2 border-blue-200 focus:border-blue-400 h-10 md:h-12",children:e.jsx(wt,{})}),e.jsxs(jt,{children:[e.jsx(Je,{value:"نقدي",children:"نقدي"}),e.jsx(Je,{value:"ذمم",children:"ذمم"})]})]})]})]})]}),r.customer_name&&e.jsxs(fe,{className:"bg-white border-2 border-green-200",children:[e.jsx(De,{className:"pb-3",children:e.jsxs($e,{className:"text-green-900 flex items-center gap-2 text-base md:text-lg",children:[e.jsx(Bt,{className:"h-4 w-4 md:h-5 md:w-5"}),"تفاصيل العميل"]})}),e.jsx(ve,{children:e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3 text-xs md:text-sm",children:[e.jsxs("div",{children:[e.jsx("strong",{children:"الاسم:"})," ",r.customer_name]}),e.jsxs("div",{children:[e.jsx("strong",{children:"الرقم:"})," ",r.customer_number]}),e.jsxs("div",{children:[e.jsx("strong",{children:"نوع الرقم:"})," ",wx(r.customer_type)]}),e.jsxs("div",{children:[e.jsx("strong",{children:"الهاتف:"})," ",r.phone_number]}),e.jsxs("div",{children:[e.jsx("strong",{children:"المدينة:"})," ",r.city]}),e.jsxs("div",{children:[e.jsx("strong",{children:"طريقة الدفع:"})," ",r.payment_method]})]})})]})]})},Er=({value:t,onChange:r,className:n="",disabled:i=!1,id:o,placeholder:a,step:s="0.001",min:c="0",minValue:l,showValidation:m=!1})=>{const[u,d]=we.useState(!1),[h,p]=we.useState(""),f=g=>{const b=g.target.value;if(b===""){r(0),d(!1),p("");return}const y=parseFloat(b);if(!isNaN(y)){if(l!==void 0&&y<l){d(!0),p(`القيمة يجب أن تكون ${l} أو أكثر`);return}d(!1),p(""),r(y)}},x=`${n} ${u?"border-red-500 focus:border-red-500":""}`;return e.jsxs("div",{className:"space-y-1",children:[e.jsx(Te,{id:o,type:"number",step:s,min:c,value:t||"",onChange:f,className:x,disabled:i,placeholder:a}),m&&u&&e.jsx("p",{className:"text-sm text-red-600 font-cairo",children:h})]})};var aa="Radio",[Nx,ll]=Fn(aa),[Cx,Ex]=Nx(aa),dl=v.forwardRef((t,r)=>{const{__scopeRadio:n,name:i,checked:o=!1,required:a,disabled:s,value:c="on",onCheck:l,form:m,...u}=t,[d,h]=v.useState(null),p=Mr(r,g=>h(g)),f=v.useRef(!1),x=d?m||!!d.closest("form"):!0;return e.jsxs(Cx,{scope:n,checked:o,disabled:s,children:[e.jsx(Lt.button,{type:"button",role:"radio","aria-checked":o,"data-state":hl(o),"data-disabled":s?"":void 0,disabled:s,value:c,...u,ref:p,onClick:cr(t.onClick,g=>{o||l==null||l(),x&&(f.current=g.isPropagationStopped(),f.current||g.stopPropagation())})}),x&&e.jsx(Sx,{control:d,bubbles:!f.current,name:i,value:c,checked:o,required:a,disabled:s,form:m,style:{transform:"translateX(-100%)"}})]})});dl.displayName=aa;var ul="RadioIndicator",ml=v.forwardRef((t,r)=>{const{__scopeRadio:n,forceMount:i,...o}=t,a=Ex(ul,n);return e.jsx(Ps,{present:i||a.checked,children:e.jsx(Lt.span,{"data-state":hl(a.checked),"data-disabled":a.disabled?"":void 0,...o,ref:r})})});ml.displayName=ul;var Sx=t=>{const{control:r,checked:n,bubbles:i=!0,...o}=t,a=v.useRef(null),s=Pu(n),c=gu(r);return v.useEffect(()=>{const l=a.current,m=window.HTMLInputElement.prototype,d=Object.getOwnPropertyDescriptor(m,"checked").set;if(s!==n&&d){const h=new Event("click",{bubbles:i});d.call(l,n),l.dispatchEvent(h)}},[s,n,i]),e.jsx("input",{type:"radio","aria-hidden":!0,defaultChecked:n,...o,tabIndex:-1,ref:a,style:{...t.style,...c,position:"absolute",pointerEvents:"none",opacity:0,margin:0}})};function hl(t){return t?"checked":"unchecked"}var kx=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],ia="RadioGroup",[Tx,Dy]=Fn(ia,[Qi,ll]),fl=Qi(),pl=ll(),[Ax,Ix]=Tx(ia),xl=v.forwardRef((t,r)=>{const{__scopeRadioGroup:n,name:i,defaultValue:o,value:a,required:s=!1,disabled:c=!1,orientation:l,dir:m,loop:u=!0,onValueChange:d,...h}=t,p=fl(n),f=bu(m),[x,g]=Zi({prop:a,defaultProp:o,onChange:d});return e.jsx(Ax,{scope:n,name:i,required:s,disabled:c,value:x,onValueChange:g,children:e.jsx(yu,{asChild:!0,...p,orientation:l,dir:f,loop:u,children:e.jsx(Lt.div,{role:"radiogroup","aria-required":s,"aria-orientation":l,"data-disabled":c?"":void 0,dir:f,...h,ref:r})})})});xl.displayName=ia;var gl="RadioGroupItem",bl=v.forwardRef((t,r)=>{const{__scopeRadioGroup:n,disabled:i,...o}=t,a=Ix(gl,n),s=a.disabled||i,c=fl(n),l=pl(n),m=v.useRef(null),u=Mr(r,m),d=a.value===o.value,h=v.useRef(!1);return v.useEffect(()=>{const p=x=>{kx.includes(x.key)&&(h.current=!0)},f=()=>h.current=!1;return document.addEventListener("keydown",p),document.addEventListener("keyup",f),()=>{document.removeEventListener("keydown",p),document.removeEventListener("keyup",f)}},[]),e.jsx(vu,{asChild:!0,...c,focusable:!s,active:d,children:e.jsx(dl,{disabled:s,required:a.required,checked:d,...l,...o,name:a.name,ref:u,onCheck:()=>a.onValueChange(o.value),onKeyDown:cr(p=>{p.key==="Enter"&&p.preventDefault()}),onFocus:cr(o.onFocus,()=>{var p;h.current&&((p=m.current)==null||p.click())})})})});bl.displayName=gl;var Ox="RadioGroupIndicator",yl=v.forwardRef((t,r)=>{const{__scopeRadioGroup:n,...i}=t,o=pl(n);return e.jsx(ml,{...o,...i,ref:r})});yl.displayName=Ox;var vl=xl,_l=bl,Rx=yl;const ca=v.forwardRef(({className:t,...r},n)=>e.jsx(vl,{className:Z("grid gap-2",t),...r,ref:n}));ca.displayName=vl.displayName;const Ss=v.forwardRef(({className:t,...r},n)=>e.jsx(_l,{ref:n,className:Z("aspect-square h-4 w-4 rounded-full border border-primary text-primary ring-offset-background focus:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",t),...r,children:e.jsx(Rx,{className:"flex items-center justify-center",children:e.jsx(am,{className:"h-2.5 w-2.5 fill-current text-current"})})}));Ss.displayName=_l.displayName;const Px=({item:t,onFieldChange:r,taxCalculationMode:n="tax_exclusive"})=>{const[i,o]=v.useState("before_tax"),[a,s]=v.useState(t.unit_price||0),[c,l]=v.useState(t.price_after_tax||0);v.useEffect(()=>{s(t.unit_price||0),l(t.price_after_tax||0)},[t.id]);const m=[{value:-1,label:"السلعة او الخدمة معفية"},{value:0,label:"0%"},{value:1,label:"1%"},{value:2,label:"2%"},{value:3,label:"3%"},{value:4,label:"4%"},{value:5,label:"5%"},{value:6,label:"6%"},{value:7,label:"7%"},{value:8,label:"8%"},{value:9,label:"9%"},{value:10,label:"10%"},{value:11,label:"11%"},{value:12,label:"12%"},{value:13,label:"13%"},{value:14,label:"14%"},{value:15,label:"15%"},{value:16,label:"16%"}],u=_=>{const j=typeof t.tax_percent=="number"?t.tax_percent:16;if(_==="after_tax"&&i==="before_tax"){const I=h();l(I)}else if(_==="before_tax"&&i==="after_tax"){const w=yt(Co(c,j));s(w)}o(_)},d=(_,j)=>{const I=typeof t.tax_percent=="number"?t.tax_percent:16;if(j==="before_tax")s(_),r("unit_price",_);else if(j==="after_tax"){l(_);const w=yt(Co(_,I));r("unit_price",w)}},h=()=>{const _=typeof t.tax_percent=="number"?t.tax_percent:16,j=t.unit_price||0,I=t.discount_amount||0,w=t.quantity||1,N=I/w,C=Math.max(0,j-N);return yt(sl(C,_))},p=_=>{r("discount_amount",_)},f=({children:_})=>e.jsxs("div",{className:"flex items-center gap-1",children:[_,e.jsx(An,{className:"h-3 w-3 text-red-500 fill-red-500"})]}),x=_=>{const j=Number(_);console.log("🔄 Tax percent changed to:",j),r("tax_percent",j)},g=typeof t.tax_percent=="number"?t.tax_percent:16;console.log("🔍 Current tax percent for item:",{itemId:t.id,taxPercent:t.tax_percent,currentTaxPercent:g,categoryCode:t.tax_category_code,typeofTaxPercent:typeof t.tax_percent});const b=Ut(g),y=ex(b);return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-4",children:[e.jsx(_e,{className:"text-sm font-medium text-blue-900 mb-3 block",children:"اختر طريقة إدخال السعر"}),e.jsxs(ca,{value:i,onValueChange:u,className:"flex flex-col sm:flex-row gap-4",children:[e.jsxs("div",{className:"flex items-center space-x-2 space-x-reverse",children:[e.jsx(Ss,{value:"before_tax",id:"before_tax"}),e.jsx(_e,{htmlFor:"before_tax",className:"cursor-pointer",children:"إدخال السعر قبل الضريبة"})]}),e.jsxs("div",{className:"flex items-center space-x-2 space-x-reverse",children:[e.jsx(Ss,{value:"after_tax",id:"after_tax"}),e.jsx(_e,{htmlFor:"after_tax",className:"cursor-pointer",children:"إدخال السعر بعد الضريبة"})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4",children:[e.jsxs("div",{children:[e.jsx(_e,{htmlFor:`quantity-${t.id}`,className:"text-sm font-medium text-gray-700",children:e.jsx(f,{children:"الكمية"})}),e.jsx(Er,{value:t.quantity||1,onChange:_=>r("quantity",_),className:"font-cairo border-green-300 focus:border-green-500"})]}),e.jsxs("div",{children:[e.jsx(_e,{htmlFor:`unit-price-before-${t.id}`,className:"text-sm font-medium text-gray-700",children:e.jsxs(f,{children:["سعر الوحدة قبل الضريبة (د.أ)",i==="before_tax"&&e.jsx("span",{className:"text-blue-600 font-semibold",children:" 📝 إدخال"}),i==="after_tax"&&e.jsx("span",{className:"text-green-600 font-semibold",children:" 🔢 محسوب"})]})}),e.jsx(Er,{value:i==="before_tax"?a:t.unit_price||0,onChange:_=>d(_,"before_tax"),className:`font-cairo ${i==="before_tax"?"border-blue-300 focus:border-blue-500 bg-white":"border-green-300 bg-green-50"}`,disabled:i!=="before_tax"})]}),e.jsxs("div",{children:[e.jsx(_e,{htmlFor:`unit-price-after-${t.id}`,className:"text-sm font-medium text-gray-700",children:e.jsxs(f,{children:["سعر الوحدة بعد الضريبة (د.أ)",i==="after_tax"&&e.jsx("span",{className:"text-blue-600 font-semibold",children:" 📝 إدخال"}),i==="before_tax"&&e.jsx("span",{className:"text-green-600 font-semibold",children:" 🔢 محسوب"})]})}),e.jsx(Er,{value:i==="after_tax"?c:h(),onChange:_=>d(_,"after_tax"),className:`font-cairo ${i==="after_tax"?"border-blue-300 focus:border-blue-500 bg-white":"border-green-300 bg-green-50"}`,disabled:i!=="after_tax"})]}),e.jsxs("div",{children:[e.jsx(_e,{className:"text-sm font-medium text-gray-700",children:e.jsx(f,{children:"نسبة الضريبة"})}),e.jsxs(vt,{value:g.toString(),onValueChange:x,children:[e.jsx(_t,{className:"font-cairo",children:e.jsx(wt,{placeholder:"اختر نسبة الضريبة"})}),e.jsx(jt,{className:"font-cairo",children:m.map(_=>e.jsx(Je,{value:_.value.toString(),children:_.label},_.value))})]}),e.jsxs("div",{className:"text-xs text-gray-500 mt-1",children:["فئة الضريبة: ",y," (",b,")"]})]}),e.jsxs("div",{children:[e.jsxs(_e,{htmlFor:`line-total-${t.id}`,className:"text-sm font-medium text-gray-700",children:["المجموع النهائي (د.أ) ",e.jsx("span",{className:"text-blue-600",children:"🔢"})]}),e.jsx(Te,{id:`line-total-${t.id}`,type:"text",value:Ke(t.line_total||0),readOnly:!0,className:"font-cairo bg-blue-50 border-blue-300"})]}),e.jsxs("div",{className:"col-span-full grid grid-cols-1 sm:grid-cols-3 gap-4 bg-gray-50 p-3 rounded",children:[e.jsxs("div",{children:[e.jsx(_e,{className:"text-sm font-medium text-gray-700",children:"المبلغ قبل الضريبة (د.أ)"}),e.jsx(Te,{type:"text",value:Ke(t.line_extension_amount||0),readOnly:!0,className:"font-cairo bg-white"})]}),e.jsxs("div",{children:[e.jsx(_e,{className:"text-sm font-medium text-gray-700",children:"مبلغ الضريبة (د.أ)"}),e.jsx(Te,{type:"text",value:Ke(t.tax_amount||0),readOnly:!0,className:"font-cairo bg-white"})]}),e.jsxs("div",{children:[e.jsx(_e,{htmlFor:`discount-${t.id}`,className:"text-sm font-medium text-gray-700",children:"مبلغ الخصم (د.أ)"}),e.jsx(Er,{value:t.discount_amount||0,onChange:p,className:"font-cairo border-green-300 focus:border-green-500"})]})]})]})]})};function jr(){const[t,r]=v.useState({isOnline:typeof navigator<"u"?navigator.onLine:!0,wasOffline:!1,lastOnlineAt:null,lastOfflineAt:null}),n=v.useCallback(()=>{r(a=>({...a,isOnline:!0,wasOffline:!0,lastOnlineAt:new Date}))},[]),i=v.useCallback(()=>{r(a=>({...a,isOnline:!1,lastOfflineAt:new Date}))},[]),o=v.useCallback(()=>{r(a=>({...a,wasOffline:!1}))},[]);return v.useEffect(()=>(window.addEventListener("online",n),window.addEventListener("offline",i),()=>{window.removeEventListener("online",n),window.removeEventListener("offline",i)}),[n,i]),{...t,resetWasOffline:o}}function la(){const{user:t,sellerData:r}=tr(),n=dn(),{isOnline:i}=jr(),o=v.useRef(!1),a=(r==null?void 0:r.id)||(t==null?void 0:t.seller_id)||(t==null?void 0:t.id),s=vr({queryKey:["products",a],queryFn:async()=>{var y;if(!a)return console.log("useProducts - no sellerId, returning empty"),[];const p=localStorage.getItem(xe),f=JSON.stringify({seller_id:a}),x=`${oe()}${W.GET_ALL("products")}&filters=${encodeURIComponent(f)}&orderBy=created_at&orderDir=DESC&limit=500`;console.log("useProducts - SENDING REQUEST for seller:",a);const g=await fetch(x,{headers:p?{Authorization:`Bearer ${p}`}:{}});if(!g.ok)throw new Error("Failed to fetch products");const b=await g.json();return console.log("useProducts - received:",(y=b.data)==null?void 0:y.length,"products"),b.data||[]},enabled:!!a,staleTime:0,gcTime:30*60*1e3});v.useEffect(()=>{!i&&!o.current?(o.current=!0,Ge.error("انقطع الاتصال بالإنترنت",{description:"البيع غير متاح - يرجى التحقق من اتصالك",duration:5e3})):i&&o.current&&(o.current=!1,Ge.success("تم استعادة الاتصال",{description:"جاري تحديث البيانات...",duration:3e3}),s.refetch())},[i,s]);const c=v.useCallback((p,f)=>{n.setQueryData(["products",a],x=>x&&x.map(g=>{if(g.id===p&&g.track_inventory){const b=Math.max(0,(Number(g.stock_quantity)||0)-f);return console.log(`⚡ [Optimistic] ${g.product_name}: ${g.stock_quantity} → ${b}`),{...g,stock_quantity:b}}return g}))},[n,a]),l=v.useCallback(p=>{n.setQueryData(["products",a],f=>f&&f.map(x=>{const g=p.find(b=>b.product_id===x.id);if(g&&x.track_inventory){const b=Math.max(0,(Number(x.stock_quantity)||0)-g.quantity);return console.log(`⚡ [Optimistic Cart] ${x.product_name}: ${x.stock_quantity} → ${b}`),{...x,stock_quantity:b}}return x}))},[n,a]),m=v.useCallback(async()=>(console.log("🔄 [Products] Force refetching..."),await n.invalidateQueries({queryKey:["products",a]}),s.refetch()),[n,a,s]),u=$t({mutationFn:async p=>{const f=localStorage.getItem(xe),x=await fetch(`${oe()}${W.CREATE("products")}`,{method:"POST",headers:{"Content-Type":"application/json",...f?{Authorization:`Bearer ${f}`}:{}},body:JSON.stringify({...p,seller_id:a})});if(!x.ok)throw new Error("Failed to create product");return x.json()},onSuccess:()=>{n.invalidateQueries({queryKey:["products",a]})}}),d=$t({mutationFn:async({id:p,...f})=>{const x=localStorage.getItem(xe),g=await fetch(`${oe()}${W.UPDATE("products",p)}`,{method:"POST",headers:{"Content-Type":"application/json",...x?{Authorization:`Bearer ${x}`}:{}},body:JSON.stringify(f)});if(!g.ok)throw new Error("Failed to update product");return g.json()},onSuccess:()=>{n.invalidateQueries({queryKey:["products",a]})}}),h=$t({mutationFn:async p=>{const f=localStorage.getItem(xe),x=await fetch(`${oe()}${W.DELETE("products",p)}`,{method:"POST",headers:f?{Authorization:`Bearer ${f}`}:{}});if(!x.ok)throw new Error("Failed to delete product");return x.json()},onSuccess:()=>{n.invalidateQueries({queryKey:["products",a]})}});return{...s,data:s.data||[],products:s.data||[],isLoading:s.isLoading,isOfflineData:!1,offlineProductsCount:0,refetch:s.refetch,forceRefetch:m,updateStockOptimistically:c,updateCartStockOptimistically:l,sellerId:a,createProduct:u.mutateAsync,updateProduct:d.mutateAsync,deleteProduct:h.mutateAsync}}const wl=({items:t,onItemsChange:r,isGeneralTax:n,taxCalculationMode:i="tax_exclusive"})=>{const[o,a]=v.useState({}),{data:s=[]}=la(),c=f=>{const x=o[f]||"";return s.filter(g=>{var b;return g.product_name.toLowerCase().includes(x.toLowerCase())||((b=g.description)==null?void 0:b.toLowerCase().includes(x.toLowerCase()))})},l=(f,x)=>{a(g=>({...g,[f]:x}))};console.log("🛍️ InvoiceItems - Available products:",s.length),console.log("🔄 InvoiceItems - Tax calculation mode:",i);const m=({children:f})=>e.jsxs("div",{className:"flex items-center gap-1",children:[f,e.jsx(An,{className:"h-3 w-3 text-red-500 fill-red-500"})]}),u=()=>{const f=n?16:0,x={id:`item-${Date.now()}`,item_name:"",quantity:1,unit_price:0,line_total:0,tax_percent:f,tax_amount:0,discount_amount:0,price_after_tax:0,price_before_tax:0,line_extension_amount:0,rounding_amount:0,product_id:void 0,tax_category_code:Ut(f)};console.log("➕ Adding new item with tax category:",x),r([...t,x])},d=f=>{console.log("🗑️ Removing item:",f);const x=t.filter(g=>g.id!==f);a(g=>{const b={...g};return delete b[f],b}),r(x)},h=(f,x,g)=>{console.log("🔄 InvoiceItems - Updating item:",{id:f,field:x,value:g,taxCalculationMode:i});const b=t.map(y=>{if(y.id===f){const _={...y,[x]:g};if(x==="tax_percent"){const j=Ut(g);_.tax_category_code=j,console.log("🏷️ Auto-updating tax category code to:",j,"for tax percent:",g)}if(n){const j=Number(x==="quantity"?g:_.quantity||1),I=Number(x==="unit_price"?g:_.unit_price||0),w=Number(x==="tax_percent"?g:_.tax_percent||16),N=Number(x==="discount_amount"?g:_.discount_amount||0),C=xt({quantity:j,unitPrice:I,taxPercent:w,discountAmount:N,taxCalculationMode:i});_.line_extension_amount=C.lineExtensionAmount,_.tax_amount=C.taxAmount,_.rounding_amount=C.roundingAmount,_.line_total=C.roundingAmount,_.price_before_tax=C.unitPriceBeforeTax,_.price_after_tax=C.unitPriceAfterTax}else{const j=Number(x==="quantity"?g:_.quantity||1),I=Number(x==="unit_price"?g:_.unit_price||0),w=Number(x==="discount_amount"?g:_.discount_amount||0),N=xt({quantity:j,unitPrice:I,taxPercent:0,discountAmount:w,taxCalculationMode:"tax_exclusive"});_.line_extension_amount=N.lineExtensionAmount,_.rounding_amount=N.roundingAmount,_.line_total=N.roundingAmount,_.tax_amount=0,_.price_after_tax=I,_.price_before_tax=I,_.tax_category_code=null}return console.log("✅ Updated item with calculations and tax category:",_),_}return y});console.log("🔄 InvoiceItems - Calling onItemsChange with updated items"),r(b)},p=(f,x)=>{const g=s.find(y=>y.id===x);if(!g)return;console.log("🛍️ Selected product:",g);const b=t.map(y=>{if(y.id===f){const _=n?Number(g.tax_percent)||16:0,j={...y,item_name:g.product_name,unit_price:Number(g.unit_price)||0,product_id:g.id,tax_percent:_,tax_category_code:Ut(_)},I=Number(j.quantity)||1,w=Number(j.unit_price)||0,N=Number(j.tax_percent)||0,C=Number(j.discount_amount)||0;if(n){const A=xt({quantity:I,unitPrice:w,taxPercent:N,discountAmount:C,taxCalculationMode:i});j.line_extension_amount=A.lineExtensionAmount,j.tax_amount=A.taxAmount,j.price_after_tax=A.unitPriceAfterTax,j.price_before_tax=A.unitPriceBeforeTax,j.rounding_amount=A.roundingAmount,j.line_total=A.roundingAmount}else{const A=xt({quantity:I,unitPrice:w,taxPercent:0,discountAmount:C,taxCalculationMode:"tax_exclusive"});j.tax_amount=0,j.price_after_tax=w,j.price_before_tax=w,j.line_extension_amount=A.lineExtensionAmount,j.rounding_amount=A.roundingAmount,j.line_total=A.roundingAmount,j.tax_category_code=null}return console.log("✅ Updated item with product data and tax category:",j),j}return y});r(b)};return e.jsxs(fe,{className:"shadow-lg border-2 border-blue-200",children:[e.jsx(De,{className:"bg-gradient-to-r from-blue-50 to-indigo-50",children:e.jsxs($e,{className:"flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4 text-blue-900",children:[e.jsx("span",{className:"text-lg sm:text-xl",children:"بنود الفاتورة"}),e.jsxs(V,{onClick:u,className:"bg-gradient-to-r from-blue-500 to-blue-600 hover:from-blue-600 hover:to-blue-700 w-full sm:w-auto",children:[e.jsx(kt,{className:"h-4 w-4 ml-1"}),"إضافة بند"]})]})}),e.jsxs(ve,{className:"p-4 sm:p-6",children:[e.jsx("div",{className:"bg-red-50 border border-red-200 rounded-lg p-3 mb-4",children:e.jsxs("div",{className:"flex items-center gap-2 text-red-800 text-sm",children:[e.jsx(An,{className:"h-4 w-4 text-red-500 fill-red-500"}),e.jsx("span",{className:"font-semibold",children:"الحقول المطلوبة لكل بند:"}),e.jsxs("span",{children:["اسم المنتج/الخدمة، الكمية، السعر (يجب أن يكون أكبر من صفر)",n&&"، نسبة الضريبة"]})]})}),t.length===0?e.jsxs("div",{className:"text-center py-8 text-gray-500",children:[e.jsx("p",{children:"لا توجد بنود في الفاتورة"}),e.jsx("p",{className:"text-sm",children:'اضغط "إضافة بند" لإضافة منتج أو خدمة'})]}):e.jsx("div",{className:"space-y-6",children:t.map((f,x)=>{const g=c(f.id);return e.jsxs(fe,{className:`border-2 shadow-md ${x%2===0?"bg-white border-slate-300":"bg-gradient-to-br from-blue-25 to-slate-50 border-blue-300"}`,children:[e.jsx(De,{className:`border-b-2 p-4 ${x%2===0?"bg-gradient-to-r from-slate-100 to-blue-100 border-slate-300":"bg-gradient-to-r from-blue-100 to-indigo-150 border-blue-300"}`,children:e.jsxs("div",{className:"flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4",children:[e.jsxs("h4",{className:`text-lg font-semibold font-cairo ${x%2===0?"text-slate-800":"text-blue-900"}`,children:["البند ",x+1,n&&f.tax_category_code&&e.jsx("span",{className:"text-sm ml-2 px-2 py-1 bg-gray-200 rounded",children:f.tax_category_code})]}),e.jsxs(V,{variant:"outline",size:"sm",onClick:()=>d(f.id),className:"text-red-600 hover:bg-red-100 border-red-300 w-full sm:w-auto",children:[e.jsx(Ar,{className:"h-4 w-4 ml-1"}),"حذف البند"]})]})}),e.jsx(ve,{className:"p-4",children:e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"grid grid-cols-1 gap-4",children:e.jsxs("div",{children:[e.jsx(_e,{htmlFor:`item-name-${f.id}`,className:"text-sm font-medium text-gray-700",children:e.jsx(m,{children:"اسم المنتج/الخدمة"})}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"relative",children:[e.jsx(zt,{className:"absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 h-4 w-4"}),e.jsx(Te,{placeholder:"البحث في المنتجات...",value:o[f.id]||"",onChange:b=>l(f.id,b.target.value),className:"pr-10 font-cairo"})]}),e.jsxs(vt,{onValueChange:b=>p(f.id,b),children:[e.jsx(_t,{className:"font-cairo",children:e.jsx(wt,{placeholder:"اختر منتج موجود أو أدخل اسم جديد"})}),e.jsx(jt,{className:"font-cairo max-h-60 overflow-y-auto",children:g.map(b=>e.jsx(Je,{value:b.id,children:e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"font-medium",children:b.product_name}),e.jsxs("span",{className:"text-sm text-gray-500",children:[Number(b.unit_price||0).toFixed(2)," د.أ",n&&b.tax_percent!==void 0&&e.jsxs("span",{className:"mx-2",children:["- ضريبة: ",b.tax_percent===-1?"معفي":`${b.tax_percent}%`]})]})]})},b.id))})]}),e.jsx(Te,{id:`item-name-${f.id}`,value:f.item_name,onChange:b=>h(f.id,"item_name",b.target.value),placeholder:"أو أدخل اسم المنتج/الخدمة يدوياً",className:"font-cairo border-green-300 focus:border-green-500"})]})]})}),n?e.jsx(Px,{item:f,onFieldChange:(b,y)=>h(f.id,b,y),taxCalculationMode:i}):e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4",children:[e.jsxs("div",{children:[e.jsx(_e,{htmlFor:`quantity-${f.id}`,className:"text-sm font-medium text-gray-700",children:e.jsx(m,{children:"الكمية"})}),e.jsx(Er,{value:f.quantity||1,onChange:b=>h(f.id,"quantity",b),className:"font-cairo border-green-300 focus:border-green-500",minValue:.001,showValidation:!0})]}),e.jsxs("div",{children:[e.jsx(_e,{htmlFor:`unit-price-${f.id}`,className:"text-sm font-medium text-gray-700",children:e.jsx(m,{children:"سعر الوحدة (د.أ)"})}),e.jsx(Er,{value:f.unit_price||0,onChange:b=>h(f.id,"unit_price",b),className:"font-cairo border-green-300 focus:border-green-500",minValue:.01,showValidation:!0})]}),e.jsxs("div",{children:[e.jsx(_e,{htmlFor:`discount-${f.id}`,className:"text-sm font-medium text-gray-700",children:"قيمة الخصم (د.أ)"}),e.jsx(Er,{value:f.discount_amount||0,onChange:b=>h(f.id,"discount_amount",b),className:"font-cairo border-green-300 focus:border-green-500"})]}),e.jsxs("div",{children:[e.jsxs(_e,{htmlFor:`line-total-${f.id}`,className:"text-sm font-medium text-gray-700",children:["المجموع (د.أ) ",e.jsx("span",{className:"text-blue-600",children:"🔢"})]}),e.jsx(Te,{id:`line-total-${f.id}`,type:"text",value:Ke(f.line_total||0),readOnly:!0,className:"font-cairo bg-blue-50 border-blue-300"})]})]})]})})]},f.id)})})]})]})},jl=t=>{if(t===0)return"صفر دينار فقط";const r=Math.floor(t),n=Math.round((t-r)*100);let i="";return r>0&&(i+=Wr(r),i+=" "+Mx(r)),n>0&&(r>0&&(i+=" و"),i+=Wr(n),i+=" "+Lx(n)),i+" فقط"},Wr=t=>{if(t===0)return"";const r=["","واحد","اثنان","ثلاثة","أربعة","خمسة","ستة","سبعة","ثمانية","تسعة","عشرة","أحد عشر","اثنا عشر","ثلاثة عشر","أربعة عشر","خمسة عشر","ستة عشر","سبعة عشر","ثمانية عشر","تسعة عشر"],n=["","","عشرون","ثلاثون","أربعون","خمسون","ستون","سبعون","ثمانون","تسعون"],i=["","مائة","مائتان","ثلاثمائة","أربعمائة","خمسمائة","ستمائة","سبعمائة","ثمانمائة","تسعمائة"];if(t<20)return r[t];if(t<100){const o=Math.floor(t/10),a=t%10;return n[o]+(a>0?" و"+r[a]:"")}if(t<1e3){const o=Math.floor(t/100),a=t%100;let s=i[o];return a>0&&(s+=" و"+Wr(a)),s}if(t<1e6){const o=Math.floor(t/1e3),a=t%1e3;let s="";return o===1?s="ألف":o===2?s="ألفان":o<11?s=Wr(o)+" آلاف":s=Wr(o)+" ألف",a>0&&(s+=" و"+Wr(a)),s}return t.toString()},Mx=t=>t===1?"دينار":t===2?"ديناران":t>=3&&t<=10?"دنانير":"دينار",Lx=t=>t===1?"قرش":t===2?"قرشان":t>=3&&t<=10?"قروش":"قرش",Dx={show_company_name:!0,show_company_logo:!0,show_fawtra_logo:!0,show_tax_number:!0,show_income_number:!0,show_invoice_type_badge:!0,show_header_image:!0,show_invoice_number:!0,show_invoice_date:!0,show_payment_method:!0,show_cashier_name:!1,show_currency:!0,show_customer_name:!0,show_customer_number:!0,show_customer_phone:!0,show_customer_city:!0,show_postal_code:!0,show_item_number:!0,show_item_description:!0,show_item_quantity:!0,show_item_unit_price:!0,show_item_amount:!0,show_item_discount:!0,show_item_tax_percent:!0,show_item_tax_amount:!0,show_item_total:!0,show_subtotal:!0,show_total_before_tax:!0,show_total_tax:!0,show_total_discount:!0,show_final_total:!0,show_amount_in_words:!0,show_payment_info:!0,show_notes:!0,show_qr_code:!0,show_signature_field:!0,show_footer_text:!0,show_footer_image:!0,show_thank_you_message:!0,custom_thank_you_message:"شكراً لتعاملكم معنا",custom_footer_text:"",custom_invoice_title:"فاتورة ضريبية",custom_return_title:"فاتورة إرجاع"},ye=t=>t===!0||t===1||t==="1",$x=(t,r,n,i,o,a,s,c,l,m,u)=>{const d={...Dx,...u},h="https://storage.googleapis.com/glide-prod.appspot.com/uploads-v2/k2KSBN8aq7bqzPN59sGg/pub/tV2mLYngjoLtD4RRxw7m.jpg",p=ye(d.show_company_logo)&&(s==null?void 0:s.show_company_logo)!==!1,f=(s==null?void 0:s.seller_logo_url)||"",x=ye(d.show_header_image)&&(s==null?void 0:s.invoice_header_url)||"",g=ye(d.show_footer_image)&&(s==null?void 0:s.invoice_footer_url)||"",b=(s==null?void 0:s.enable_fawatrah)===!0||(s==null?void 0:s.enable_fawatrah)==1||(s==null?void 0:s.enable_fawatrah)==="1",y=(s==null?void 0:s.enable_bw_print)===!0||(s==null?void 0:s.enable_bw_print)==1||(s==null?void 0:s.enable_bw_print)==="1"||(s==null?void 0:s.enable_bw_print)===void 0,_=a!=null&&a.is_return?d.custom_return_title||"فاتورة ارجاع":b?d.custom_invoice_title||"فاتورة ضريبية":"فاتورة",j=(n==null?void 0:n.payment_method)||"نقدي",I=(s==null?void 0:s.seller_name)||"اسم الشركة/المورد",w=(s==null?void 0:s.tax_number)||"---",N=(s==null?void 0:s.income_number)||"---",C=t,A="JOD",F=(n==null?void 0:n.invoice_date)||new Date().toISOString().split("T")[0],T=(n==null?void 0:n.customer_name)||"",k=(n==null?void 0:n.customer_number)||"",P=(n==null?void 0:n.phone_number)||"",S=(n==null?void 0:n.city)||"",E="",O=Number(l==null?void 0:l.tax_inclusive_amount)||Number(r)||0,R=Number(l==null?void 0:l.tax_exclusive_amount)||0,D=Number(l==null?void 0:l.total_tax_amount)||0,$=Number(l==null?void 0:l.allowance_charge_amount)||0,M=m==="income"||m==="دخل",X=i.reduce((se,q)=>{const ne=Number(q.rounding_amount)||Number(q.line_total)||0;return se+ne},0);function U(){let se="<tr>";ye(d.show_item_number)&&(se+="<th>#</th>"),ye(d.show_item_description)&&(se+="<th>الوصف</th>"),ye(d.show_item_quantity)&&(se+="<th>الكمية</th>"),ye(d.show_item_unit_price)&&(se+="<th>سعر الوحدة</th>"),ye(d.show_item_amount)&&(se+="<th>المبلغ</th>"),ye(d.show_item_discount)&&(se+="<th>الخصم</th>"),!M&&ye(d.show_item_tax_percent)&&(se+="<th>نسبة الضريبة</th>"),!M&&ye(d.show_item_tax_amount)&&(se+="<th>مقدار الضريبة</th>"),ye(d.show_item_total)&&(se+="<th>الإجمالي</th>"),se+="</tr>";let q=`<table class="invoice-table">
<thead>${se}</thead>
<tbody>
`;return i.forEach((ne,re)=>{const de=Number(ne.rounding_amount)||Number(ne.line_total)||0,ze=ne.xml_unit_price?parseFloat(ne.xml_unit_price):Number(ne.unit_price);let Ce="<tr>";ye(d.show_item_number)&&(Ce+=`<td>${re+1}</td>`),ye(d.show_item_description)&&(Ce+=`<td>${ne.item_name}</td>`),ye(d.show_item_quantity)&&(Ce+=`<td>${ne.quantity}</td>`),ye(d.show_item_unit_price)&&(Ce+=`<td>${Number(ze||0).toFixed(6)}</td>`),ye(d.show_item_amount)&&(Ce+=`<td>${(Number(ne.unit_price||0)*Number(ne.quantity||0)).toFixed(2)}</td>`),ye(d.show_item_discount)&&(Ce+=`<td>${Number(ne.discount_amount||0).toFixed(2)}</td>`),!M&&ye(d.show_item_tax_percent)&&(Ce+=`<td>${ne.tax_percent===-1?"معفية":(Number(ne.tax_percent)||0)+"%"}</td>`),!M&&ye(d.show_item_tax_amount)&&(Ce+=`<td>${Number(ne.tax_amount||0).toFixed(2)}</td>`),ye(d.show_item_total)&&(Ce+=`<td>${Number(de||0).toFixed(2)}</td>`),Ce+="</tr>",q+=Ce}),q+=`</tbody>
</table>`,q}function Q(){let se=0;return ye(d.show_item_number)&&se++,ye(d.show_item_description)&&se++,ye(d.show_item_quantity)&&se++,ye(d.show_item_unit_price)&&se++,ye(d.show_item_amount)&&se++,ye(d.show_item_discount)&&se++,!M&&ye(d.show_item_tax_percent)&&se++,!M&&ye(d.show_item_tax_amount)&&se++,ye(d.show_item_total)&&se++,se-1}const B=Q().toString();function z(){return n!=null&&n.is_return?`
    <table style="font-size: 10pt !important; width: 100%;">
      <tr class="total-row"><td colspan="${B}">رقم الفاتورة الاصلية المرتجعة</td>
        <td>${(a==null?void 0:a.original_invoice_number)||"---"}</td></tr>
      <tr class="total-row"><td colspan="${B}">القيمة الاصلية للفاتورة المرتجعة<span style="margin-right: 5px;">(${A})</span></td>
        <td>${(a==null?void 0:a.original_invoice_total)!=null?Number(a.original_invoice_total).toFixed(2):"---"}</td></tr>
      <tr class="total-row"><td colspan="${B}">بيان سبب الارجاع</td>
        <td>${(a==null?void 0:a.return_reason)||"---"}</td></tr>
    </table>
    `:""}function H(){if(!ye(d.show_notes))return"";const se=c&&c.trim()?c.trim():"لا يوجد ملاحظات";return`
    <div style="margin: 10px 0; padding: 8px; background: linear-gradient(135deg, #f8faff 0%, #e8f2ff 100%); border-radius: 8px; border: 1px solid #d4e7ff; direction: rtl;">
      <div style="display: flex; align-items: center; margin-bottom: 5px;">
        <span style="font-size: 14px; margin-left: 6px;">${c&&c.trim()?"📝":"📋"}</span>
        <h3 style="margin: 0; font-size: 14px; font-weight: 700; color: #2563eb;">ملاحظات الفاتورة</h3>
      </div>
      <div style="background: rgba(255,255,255,0.9); padding: 8px; border-radius: 6px; border: 1px solid #dbeafe;">
        <p style="margin: 0; font-size: 12px; line-height: 1.4; color: #374151;">${se}</p>
      </div>
    </div>
    `}const Y=d.custom_footer_text||(s==null?void 0:s.footer_text)||"",J=ye(d.show_footer_text)&&Y?`
    <p style="text-align: center; font-size: 10px; color: black; background-color: white; padding: 6px; direction: rtl;">
      ${Y}
    </p>
  `:"",ie=ye(d.show_thank_you_message)?`
    <p style="text-align: center; font-size: 12px; color: #2563eb; margin: 10px 0;">
      ${d.custom_thank_you_message||"شكراً لتعاملكم معنا"}
    </p>
  `:"",ce=`
    :root {
      --arabic-fonts: 'Cairo', 'Amiri', 'Noto Sans Arabic', Arial, sans-serif;
    }
    * { box-sizing: border-box; }
    body {
      font-family: var(--arabic-fonts);
      direction: rtl;
      margin: 0 !important;
      padding: 0 !important;
      background: #fff;
      font-size: 13px;
    }
    .arabic-invoice-title {
      font-size: 22px;
      font-weight: 700;
      color: ${y?"#000":"#2376d1"};
      text-align: center;
      margin: 0 0 10px 0;
    }
    .invoice-container {
      width: 100%;
      margin: 0 auto;
      background: white;
      border-radius: 8px;
      ${y?"":"box-shadow: 0 2px 16px 0 rgba(64,104,153,.08);"}
      padding: 8mm !important;
      border: 1px solid ${y?"#000":"#e5e5e5"};
    }
    .header-footer-img { width: 100%; max-width: 100%; height: auto; margin: 0 0 8px 0; }
    .invoice-table, .header-table, table {
      width: 100%;
      border-collapse: collapse;
      text-align: right;
      background: #fff;
    }
    .invoice-table th, .invoice-table td, .header-table td {
      border: 1px solid ${y?"#000":"#e5e5e5"};
      padding: 6px 4px;
      font-size: 13px;
      color: #000;
    }
    .invoice-table th { 
      background: ${y?"#f0f0f0":"#f0f7ff"}; 
      font-weight: bold; 
      font-size: 12px; 
      color: #000;
    }
    .total-row { 
      background: ${y?"#f0f0f0":"#e5f6fb"}; 
      font-weight: bold; 
      font-size: 13px; 
      color: #000;
    }
    .sign-row { 
      background: ${y?"#f5f5f5":"#fff7e0"}; 
      color: ${y?"#000":"#998100"}; 
      font-size: 13px; 
    }
    /* Print optimization */
    @media print {
      body { margin: 0 !important; padding: 0 !important; font-size: 11px; }
      .invoice-container { margin: 0 !important; padding: 6mm !important; box-shadow: none !important; }
      .custom-button { display: none !important; }
      
      ${y?`
      * {
        -webkit-print-color-adjust: exact !important;
        print-color-adjust: exact !important;
      }
      `:""}
    }
    @page { size: A4 portrait; margin: 6mm; }
    .custom-button {
      font-size: 14px;
      padding: 8px 16px;
      margin: 4px 6px;
      border: none;
      border-radius: 6px;
      background: linear-gradient(to right,#2187ff,#0949a8);
      color: white;
      cursor: pointer;
    }
  `;let ke="",be=ye(d.show_qr_code)&&!!o;function Se(se){return`https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=${encodeURIComponent(se)}`}be&&o&&(o.startsWith("http")?ke=o:ke=Se(o));function je(){return`
      <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;">
        ${ye(d.show_fawtra_logo)&&b?`<img src="${h}" style="max-width:120px;max-height:120px;object-fit:contain;" alt="شعار فوتره">`:'<div style="width:120px;"></div>'}
        ${p&&f?`<img src="${f}" style="max-width:120px;max-height:120px;object-fit:contain;margin:0 12px;" alt="شعار الشركة">`:'<div style="width:120px;margin:0 12px;"></div>'}
        ${be&&ke?`<div style="padding:4px;background:#fff;border:2px solid #323F66;border-radius:8px;">
                <img src="${ke}" width="120" height="120" style="width:120px;height:120px;object-fit:contain;" alt="QR Code">
             </div>`:b?`<div style="width:128px;min-height:120px;display:flex;flex-direction:column;align-items:center;justify-content:center;border:2px dashed #bc1e1e;background:#ffefef;color:#bc1e1e;font-weight:bold;font-size:12px;border-radius:6px;text-align:center;padding:8px;">
                    <span style="font-size:20px;margin-bottom:4px;">🚫</span>
                    <span style="font-size:11px;">هذه الفاتورة<br/>لم ترسل بعد<br/>الى نظام فوترة</span>
                 </div>`:'<div style="width:120px;"></div>'}
      </div>
    `}function Re(){const se=[];return ye(d.show_customer_name)&&se.push({header:"اسم المشتري",value:T}),ye(d.show_customer_number)&&se.push({header:"الوثيقة",value:k}),ye(d.show_customer_phone)&&se.push({header:"رقم الهاتف",value:P}),ye(d.show_customer_city)&&se.push({header:"المدينة",value:S}),ye(d.show_postal_code)&&se.push({header:"الرمز البريدي",value:E}),se.length===0?"":`
    <table class="invoice-table">
      <thead>
        <tr>${se.map(q=>`<th>${q.header}</th>`).join("")}</tr>
      </thead>
      <tbody>
        <tr>${se.map(q=>`<td>${q.value}</td>`).join("")}</tr>
      </tbody>
    </table>
    `}function We(){let se="";return ye(d.show_subtotal)&&(se+=`<tr class="total-row"><td colspan="${B}">المجموع (${A})</td><td>${X.toFixed(2)}</td></tr>`),!M&&ye(d.show_total_before_tax)&&(se+=`<tr class="total-row"><td colspan="${B}">المبلغ قبل الضريبة (${A})</td><td>${R.toFixed(2)}</td></tr>`),!M&&ye(d.show_total_tax)&&(se+=`<tr class="total-row"><td colspan="${B}">مجموع الضريبة (${A})</td><td>${D.toFixed(2)}</td></tr>`),ye(d.show_total_discount)&&(se+=`<tr class="total-row"><td colspan="${B}">مجموع الخصم (${A})</td><td>${$.toFixed(2)}</td></tr>`),ye(d.show_final_total)&&(se+=`<tr class="total-row"><td colspan="${B}">إجمالي الفاتورة (${A})</td><td>${O.toFixed(2)}</td></tr>`),ye(d.show_amount_in_words)&&(se+=`<tr class="total-row"><td colspan="${parseInt(B)+1}" style="text-align: right;">المبلغ كتابةً: ${jl(O)}</td></tr>`),ye(d.show_signature_field)&&(se+=`<tr class="sign-row"><td colspan="${parseInt(B)+1}" style="text-align: right;">توقيع المستلم</td></tr>`),`<table class="invoice-table" style="font-size: 13px !important;">${se}</table>`}return`
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
  <meta charset="UTF-8">
  <title>فاتورة إلكترونية</title>
  <link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;700&display=swap" rel="stylesheet">
  <style>${ce}</style>
</head>
<body>
  <div style="text-align: center; margin: 8px 0;">
    <button class="custom-button" onclick="window.generatePDF()">📥 تحميل PDF</button>
    <button class="custom-button" onclick="window.printInvoice()">🖨️ طباعة الفاتورة</button>
  </div>
  <div class="invoice-container" id="invoice-wrapper">
    ${x?`<img src="${x}" class="header-footer-img" alt="Header">`:""}

    ${je()}
    
    ${ye(d.show_invoice_type_badge)?`<div class="arabic-invoice-title">${_}</div>`:""}
    ${ye(d.show_payment_method)?`<div class="arabic-invoice-title" style="font-size:14px; font-weight:400; margin-bottom:10px;">${j}</div>`:""}

    <!-- معلومات الشركة والفاتورة -->
    <table class="header-table" style="margin-bottom:10px;">
      <tr>
        <td style="width: 50%;">
          ${ye(d.show_company_name)?`<div style="border-bottom: 1px solid #eee; padding: 4px 0; font-size: 12px;">${I}</div>`:""}
          ${b&&ye(d.show_tax_number)?`<div style="border-bottom: 1px solid #eee; padding: 4px 0; font-size: 12px;"><strong>الرقم الضريبي</strong>: ${w}</div>`:""}
          ${b&&ye(d.show_income_number)?`<div style="padding: 4px 0; font-size: 12px;"><strong>تسلسل مصدر الدخل</strong>: ${N}</div>`:""}
        </td>
        <td style="width: 50%;">
          ${ye(d.show_invoice_number)?`<div style="border-bottom: 1px solid #eee; padding: 4px 0; font-size: 12px;"><strong>رقم الفاتورة</strong>: ${C}</div>`:""}
          ${ye(d.show_invoice_date)?`<div style="border-bottom: 1px solid #eee; padding: 4px 0; font-size: 12px;"><strong>تاريخ الإصدار</strong>: ${F}</div>`:""}
          ${ye(d.show_invoice_type_badge)?`<div style="border-bottom: 1px solid #eee; padding: 4px 0; font-size: 12px;"><strong>نوع الفاتورة</strong>: ${_}</div>`:""}
          ${ye(d.show_currency)?`<div style="padding: 4px 0; font-size: 12px;"><strong>نوع العملة</strong>: ${A}</div>`:""}
        </td>
      </tr>
    </table>

    ${Re()}

    <div style="font-size: 13px; margin-top:10px; margin-bottom: 5px;"><strong>تفاصيل المواد</strong></div>

    ${U()}

    ${We()}

    ${z()}

    ${H()}

    ${ie}

    ${J}
    ${g?`<img src="${g}" class="header-footer-img" alt="Footer">`:""}
  </div>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js"><\/script>
  <script>
      window.generatePDF = async function() {
        try {
          if (typeof html2pdf === 'undefined') {
            alert('لم يتم تحميل مكتبة PDF.');
            return;
          }
          if (document.fonts && document.fonts.ready) await document.fonts.ready;
          var elem = document.getElementById("invoice-wrapper");
          var pdfName = "${C}".replace(/[\\\\/:*?"<>|]/g, '');
          html2pdf().set({
            margin: [6, 6, 6, 6],
            filename: pdfName + '.pdf',
            image: { type: 'jpeg', quality: 0.95 },
            html2canvas: { scale: 2.5, backgroundColor: '#fff', useCORS: true, width: 794, height: 1123 },
            jsPDF: { unit: 'mm', format: 'a4', orientation: 'portrait' }
          }).from(elem).save();
        } catch(err) {
          alert('حدث خطأ: ' + err.message);
        }
      };
      window.printInvoice = function() {
        try {
          var content = document.getElementById("invoice-wrapper").innerHTML;
          content = content.replace(/<script[\\s\\S]*?>[\\s\\S]*?<\\/script>/gi, '');
          var w = window.open('', '_blank', 'width=700,height=900');
          w.document.open();
          w.document.write(\`<html lang="ar" dir="rtl"><head><title>طباعة</title><link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;700&display=swap" rel="stylesheet"><style>${ce}</style></head><body><div class="invoice-container">\${content}</div><script>window.onload=function(){window.print();window.close();}<\\/script></body></html>\`);
          w.document.close();
        } catch(err) {
          alert('خطأ: '+err.message);
        }
      };
  <\/script>
</body>
</html>
  `},Nl=t=>`https://api.qrserver.com/v1/create-qr-code/?size=300x300&data=${encodeURIComponent(t)}`,qt=t=>{var a,s,c,l;if(!t)return null;let r;try{r=typeof t=="string"?JSON.parse(t):t}catch{return console.log("❌ Failed to parse apiResponse as JSON"),null}const n=[(a=r==null?void 0:r.data)==null?void 0:a.EINV_QR,r==null?void 0:r.EINV_QR,r==null?void 0:r.qr_code,r==null?void 0:r.qrCode,(s=r==null?void 0:r.data)==null?void 0:s.qr_code,(c=r==null?void 0:r.result)==null?void 0:c.qr_code,(l=r==null?void 0:r.response)==null?void 0:l.qr_code];for(const m of n)if(m&&typeof m=="string"&&m.length>0)return console.log("✅ Found QR data:",m.substring(0,50)+"..."),m;const i=m=>{if(!m||typeof m!="object")return null;for(const u of Object.keys(m)){if(u.toLowerCase().includes("qr")&&typeof m[u]=="string"&&m[u].length>0)return console.log("✅ Found QR data (deep search):",m[u].substring(0,50)+"..."),m[u];const d=i(m[u]);if(d)return d}return null},o=i(r);return o||(console.log("❌ No QR data found in API response"),null)},Cl=({invoiceData:t,items:r,total:n,loading:i,sellerLoading:o=!1,sellerData:a,onSave:s,isEdit:c=!1})=>{et();const[l,m]=v.useState(null),[u,d]=v.useState(void 0),h=Mt();v.useEffect(()=>{p(),f()},[]);const p=async()=>{try{const y=localStorage.getItem(xe);let _;h?_=`${nt}${W.GET_BY_ID("sellers",h)}&token=${y||""}`:_=`${nt}${W.GET_ALL("sellers")}&token=${y||""}`;const I=await(await fetch(_)).json();I.success&&(h?m(I.data):I.data&&I.data.length>0&&m(I.data[0]))}catch(y){console.error("Error fetching seller data:",y)}},f=async()=>{try{if(!t||!(t.customer_number&&t.invoice_date))return;const y=localStorage.getItem(xe),_=`${nt}${W.GET_ALL("invoices")}&token=${y||""}`,I=await(await fetch(_)).json();if(I.success&&I.data){const w=I.data.find(N=>N.customer_number===t.customer_number&&N.invoice_date===t.invoice_date);if(w!=null&&w.api_response){const N=qt(w.api_response);if(N){d(Nl(N));return}}}d(void 0)}catch{d(void 0)}},x=async()=>{const y=t.is_return?"فاتورة إرجاع - غير مرسلة":"فاتورة جديدة - غير مرسلة";await s(y)},g=i||o,b=o?"جاري تحميل بيانات البائع...":c?"حفظ التعديلات":"انشاء وحفظ الفاتورة";return e.jsxs("div",{className:"space-y-4",children:[e.jsx(fe,{className:"bg-gradient-to-r from-green-50 to-emerald-50 border-2 border-green-200",children:e.jsxs(ve,{className:"p-3 md:p-4",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"text-base md:text-lg font-bold text-green-900",children:"المجموع الإجمالي للفاتورة:"}),e.jsxs("span",{className:"text-xl md:text-2xl font-bold text-green-700",children:[Math.abs(Number(n||0)).toFixed(2)," د.أ"]})]}),t.is_return&&e.jsxs("div",{className:"mt-2 text-sm text-orange-700",children:[e.jsxs("p",{children:["سبب الإرجاع: ",t.return_reason]}),e.jsxs("p",{children:["نوع الدفع: ",t.return_payment_type]}),t.original_invoice_number&&e.jsxs("p",{children:["الفاتورة الأصلية: ",t.original_invoice_number]})]})]})}),e.jsxs("div",{className:"flex flex-col gap-3",children:[e.jsxs(V,{onClick:x,disabled:g,className:`h-12 md:h-14 text-sm md:text-base px-8 md:px-12 w-full ${o?"bg-gray-400 hover:bg-gray-400 cursor-not-allowed":"bg-gradient-to-r from-blue-500 to-blue-600 hover:from-blue-600 hover:to-blue-700"}`,children:[e.jsx(Dn,{className:"h-4 w-4 md:h-5 md:w-5 ml-2"}),b]}),o&&e.jsx("p",{className:"text-sm text-gray-600 text-center font-cairo",children:"يرجى الانتظار حتى يتم تحميل بيانات البائع لضمان تطبيق الضرائب بشكل صحيح"})]})]})},Fx=({invoiceData:t,items:r,total:n,invoiceNumber:i,sellerData:o,notes:a})=>{const{calculatedTotals:s,calculatedItems:c}=v.useMemo(()=>{console.log("🔄 InvoicePreview: Using government calculations for display consistency");const l=t.invoice_type||(o==null?void 0:o.invoice_type)||"دخل",m=Jr(l);console.log("🎯 Invoice type for calculations:",{raw:l,mapped:m});const u=r.map(h=>{const p=m==="دخل"?0:h.tax_percent||0;return xt({quantity:h.quantity,unitPrice:h.unit_price,discountAmount:h.discount_amount||0,taxPercent:p,existingLineExtensionAmount:h.line_extension_amount})}),d=lr(u);return console.log("✅ Government calculations for preview:",{invoiceType:m,totals:d,itemCount:r.length}),{calculatedTotals:d,calculatedItems:u}},[r,t.invoice_type,o==null?void 0:o.invoice_type]);return e.jsx("div",{className:"space-y-4 font-cairo",dir:"rtl",children:e.jsxs(fe,{children:[e.jsx(De,{children:e.jsxs($e,{className:"text-center text-xl font-bold",children:["فاتورة رقم: ",i]})}),e.jsxs(ve,{className:"space-y-6",children:[o&&e.jsxs("div",{className:"border-b pb-4",children:[e.jsx("h3",{className:"font-bold text-lg mb-2",children:"بيانات البائع:"}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-2 text-sm",children:[e.jsxs("div",{children:[e.jsx("strong",{children:"اسم البائع:"})," ",o.seller_name]}),e.jsxs("div",{children:[e.jsx("strong",{children:"الرقم الضريبي:"})," ",o.tax_number]}),e.jsxs("div",{children:[e.jsx("strong",{children:"رقم الدخل:"})," ",o.income_number]})]})]}),e.jsxs("div",{className:"border-b pb-4",children:[e.jsx("h3",{className:"font-bold text-lg mb-2",children:"بيانات العميل:"}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-2 text-sm",children:[e.jsxs("div",{children:[e.jsx("strong",{children:"اسم العميل:"})," ",t.customer_name]}),e.jsxs("div",{children:[e.jsx("strong",{children:"رقم العميل:"})," ",t.customer_number]}),e.jsxs("div",{children:[e.jsx("strong",{children:"نوع العميل:"})," ",t.customer_type]}),e.jsxs("div",{children:[e.jsx("strong",{children:"رقم الهاتف:"})," ",t.phone_number]}),e.jsxs("div",{children:[e.jsx("strong",{children:"المدينة:"})," ",t.city]}),e.jsxs("div",{children:[e.jsx("strong",{children:"طريقة الدفع:"})," ",t.payment_method]})]})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-bold text-lg mb-2",children:"عناصر الفاتورة:"}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full border-collapse border border-gray-300 text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-gray-100",children:[e.jsx("th",{className:"border border-gray-300 p-2 text-right",children:"المنتج"}),e.jsx("th",{className:"border border-gray-300 p-2 text-center",children:"الكمية"}),e.jsx("th",{className:"border border-gray-300 p-2 text-center",children:"السعر"}),!Jr(t.invoice_type||(o==null?void 0:o.invoice_type)||"دخل").includes("دخل")&&e.jsx("th",{className:"border border-gray-300 p-2 text-center",children:"الضريبة"}),e.jsx("th",{className:"border border-gray-300 p-2 text-center",children:"المجموع"})]})}),e.jsx("tbody",{children:r.map((l,m)=>{const u=c[m],h=Jr(t.invoice_type||(o==null?void 0:o.invoice_type)||"دخل")==="دخل",p=u.discountAmount||0,f=h?4:5;return e.jsxs(we.Fragment,{children:[e.jsxs("tr",{children:[e.jsx("td",{className:"border border-gray-300 p-2 text-right",children:l.item_name}),e.jsx("td",{className:"border border-gray-300 p-2 text-center",children:l.quantity}),e.jsxs("td",{className:"border border-gray-300 p-2 text-center",children:[ft(l.unit_price)," د.أ"]}),!h&&e.jsx("td",{className:"border border-gray-300 p-2 text-center",children:l.tax_percent===-1?"معفية":`${ft(u.taxAmount)} د.أ`}),e.jsxs("td",{className:"border border-gray-300 p-2 text-center font-bold",children:[ft(u.roundingAmount)," د.أ"]})]}),p>0&&e.jsxs("tr",{children:[e.jsx("td",{className:"border border-gray-300 p-2 text-right text-red-600",colSpan:f-1,children:"خصم على المنتج"}),e.jsxs("td",{className:"border border-gray-300 p-2 text-center text-red-600 font-medium",children:["-",ft(p)," د.أ"]})]})]},l.id||m)})})]})})]}),e.jsx("div",{className:"border-t pt-4",children:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"font-semibold",children:"المجموع قبل الضريبة:"}),e.jsxs("span",{className:"font-semibold",children:[ft(s.taxExclusiveAmount)," د.أ"]})]}),s.totalTaxAmount>0&&e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"font-semibold",children:"إجمالي الضريبة:"}),e.jsxs("span",{className:"font-semibold",children:[ft(s.totalTaxAmount)," د.أ"]})]}),s.allowanceChargeAmount>0&&e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"font-semibold",children:"إجمالي الخصم:"}),e.jsxs("span",{className:"font-semibold",children:[ft(s.allowanceChargeAmount)," د.أ"]})]}),e.jsxs("div",{className:"flex justify-between items-center border-t pt-2",children:[e.jsx("span",{className:"font-bold text-lg",children:"المجموع الإجمالي:"}),e.jsxs("span",{className:"font-bold text-lg text-blue-600",children:[ft(s.taxInclusiveAmount)," د.أ"]})]})]})}),e.jsxs("div",{className:"border-t pt-4",children:[e.jsx("h3",{className:"font-bold text-lg mb-2",children:"ملاحظات الفاتورة:"}),e.jsx("div",{className:"bg-yellow-50 border border-yellow-200 rounded-lg p-4 min-h-[60px]",children:a&&a.trim()?e.jsx("p",{className:"text-gray-800 font-cairo leading-relaxed whitespace-pre-wrap",children:a.trim()}):e.jsx("p",{className:"text-gray-400 font-cairo italic",children:"لا توجد ملاحظات"})})]})]})]})})},as=new Map,qr=new Map,is={static:0,semiStatic:0,dynamic:0,realtime:0};function Ux(t){return t.includes("products")||t.includes("product_categories")||t.includes("expense_categories")||t.includes("customers")||t.includes("suppliers")||t.includes("xml_templates")||t.includes("invoice_display_settings")?is.static:t.includes("employees")||t.includes("sellers")?is.semiStatic:t.includes("invoices")||t.includes("shifts")||t.includes("cash_drawer")||t.includes("expenses")||t.includes("audit_log")?is.dynamic:is.semiStatic}function zx(t={requireAuth:!0}){const[r,n]=v.useState(!1),[i,o]=v.useState(null),a=v.useCallback(()=>localStorage.getItem(xe),[]),s=v.useCallback(async(h,p="GET",f)=>{const x=`${p}:${h}:${JSON.stringify(f||{})}`;if(p==="GET"){const _=qr.get(x),j=Ux(h);if(_&&j>0){const I=Date.now()-_.timestamp;if(I<j)return _.data;if(I<j*2){const w=_.data;return setTimeout(()=>{Bx(h,x)},0),w}}}if(as.has(x))return as.get(x);n(!0),o(null);const g=new AbortController,y=(async()=>{try{const _=a();let j=`${oe()}${h}`;t.requireAuth&&_&&(j+=(j.includes("?")?"&":"?")+`token=${_}`);const I={method:p,headers:{"Content-Type":"application/json"},signal:g.signal};f&&p!=="GET"&&(I.body=JSON.stringify(f));const N=await(await fetch(j,I)).json();return N.success?p==="GET"&&qr.set(x,{data:N,timestamp:Date.now()}):o(N.message),N}catch(_){if(_ instanceof Error&&_.name==="AbortError")return{success:!1,message:"Request cancelled",data:null};const j=_ instanceof Error?_.message:"خطأ في الاتصال بالخادم";return o(j),{success:!1,message:j,data:null}}finally{n(!1),as.delete(x)}})();return as.set(x,y),y},[a,t.requireAuth]),c=v.useCallback(h=>s(h,"GET"),[s]),l=v.useCallback((h,p)=>s(h,"POST",p),[s]),m=v.useCallback((h,p)=>s(h,"PUT",p),[s]),u=v.useCallback(h=>s(h,"DELETE"),[s]),d=v.useCallback(h=>{if(h)for(const p of qr.keys())p.includes(h)&&qr.delete(p);else qr.clear()},[]);return{isLoading:r,error:i,get:c,post:l,put:m,del:u,request:s,invalidateCache:d}}async function Bx(t,r){try{const n=localStorage.getItem("pos_auth_token");let i=`${oe()}${t}`;n&&(i+=(i.includes("?")?"&":"?")+`token=${n}`);const a=await(await fetch(i,{method:"GET",headers:{"Content-Type":"application/json"}})).json();a.success&&qr.set(r,{data:a,timestamp:Date.now()})}catch(n){console.debug("Background refresh failed:",n)}}function qx(t,r){let n=null;return(...i)=>{n&&clearTimeout(n),n=setTimeout(()=>t(...i),r)}}function da(t,r={}){const{get:n,post:i,invalidateCache:o}=zx(),[a,s]=v.useState([]),[c,l]=v.useState([]),[m,u]=v.useState(0),[d,h]=v.useState(!1),[p,f]=v.useState(null);v.useRef(!1);const{autoFetch:x=!0,page:g=1,limit:b=50,search:y="",searchFields:_=[],filters:j={},orderBy:I="id",orderDir:w="DESC"}=r,N=v.useCallback(async()=>{const R=await n(W.GET_COLUMNS(t));return R.success&&l(R.data),R},[n,t]),C=v.useCallback(async R=>{h(!0),f(null);const D={...r,...R};let $=W.GET_ALL(t);const M=new URLSearchParams;M.append("page",String(D.page||g)),M.append("limit",String(D.limit||b)),(D.orderBy||I)&&M.append("order_by",D.orderBy||I),(D.orderDir||w)&&M.append("order_dir",D.orderDir||w),(D.search||y)&&M.append("search",D.search||y),(D.searchFields||_).length>0&&M.append("search_fields",(D.searchFields||_).join(","));const X={...D.filters||j};Object.entries(X).forEach(([U,Q])=>{Q!=null&&Q!==""&&(M.append(`filter[${U}]`,String(Q)),U==="seller_id"&&M.append("seller_id",String(Q)))}),Object.keys(X).length>0&&M.append("filters",JSON.stringify(X)),M.append("_t",String(Date.now())),$+=`&${M.toString()}`;try{const U=await n($);return U.success?(s(U.data),u(U.total||U.data.length)):f(U.message),U}finally{h(!1)}},[n,t,g,b,y,_,j,I,w,r]),A=v.useMemo(()=>qx(R=>{C({search:R})},300),[C]),F=v.useCallback(R=>{A(R)},[A]),T=v.useCallback(async R=>await n(W.GET_BY_ID(t,String(R))),[n,t]),k=v.useCallback(async R=>{h(!0);const D=`temp-${Date.now()}`,$={...R,id:D};s(M=>[$,...M]);try{const M=await i(W.CREATE(t),R);return M.success?(s(X=>X.map(U=>U.id===D?M.data:U)),o(t),await C()):s(X=>X.filter(U=>U.id!==D)),M}catch(M){throw s(X=>X.filter(U=>U.id!==D)),M}finally{h(!1)}},[i,t,o,C]),P=v.useCallback(async(R,D)=>{h(!0);const $=[...a];s(M=>M.map(X=>X.id===R?{...X,...D}:X));try{const M=await i(W.UPDATE(t,String(R)),D);return M.success?(s(X=>X.map(U=>U.id===R?M.data:U)),o(t),await C()):s($),M}catch(M){throw s($),M}finally{h(!1)}},[i,t,a,o,C]),S=v.useCallback(async R=>{h(!0);const D=[...a];s($=>$.filter(M=>M.id!==R));try{const $=await i(W.DELETE(t,String(R)),{});return $.success?(o(t),await C()):s(D),$}catch($){throw s(D),$}finally{h(!1)}},[i,t,a,o,C]),E=v.useCallback(async R=>{h(!0);const D=[...a];s($=>$.filter(M=>!R.includes(M.id)));try{const $=await i(W.BULK_DELETE(t),{ids:R});return $.success?(o(t),await C()):s(D),$}catch($){throw s(D),$}finally{h(!1)}},[i,t,a,o,C]),O=v.useRef("");return v.useEffect(()=>{if(x&&t){const R=JSON.stringify(j),D=Object.values(j).some(M=>M!=null&&M!==""),$=R!==O.current;D&&$&&(console.log("useCrud - fetching with filters:",j),O.current=R,C(),N())}},[t,x,JSON.stringify(j)]),{data:a,columns:c,total:m,isLoading:d,error:p,fetchAll:C,fetchById:T,fetchColumns:N,create:k,update:P,remove:S,bulkDelete:E,searchData:F,refetch:C}}function Vx(){const{user:t,sellerData:r}=tr(),{isOnline:n}=jr(),i=(r==null?void 0:r.id)||(t==null?void 0:t.seller_id)||null,o=da("customers",{autoFetch:!!i,filters:i?{seller_id:i}:{},orderBy:"created_at",orderDir:"DESC"});return{...o,customers:o.data,isLoading:o.isLoading||!i,error:o.error,isOfflineData:!1,isOnline:n}}function Gx(){const{user:t,sellerData:r}=tr(),{isOnline:n}=jr(),i=(r==null?void 0:r.id)||(t==null?void 0:t.seller_id)||null,o=da("products",{autoFetch:!!i,filters:i?{seller_id:i}:{},orderBy:"created_at",orderDir:"DESC"});return{...o,products:o.data,isLoading:o.isLoading||!i,error:o.error,isOfflineData:!1,isOnline:n}}const Kn=()=>{const{hasPermission:t,currentEmployee:r,isOwnerOrAdmin:n}=lt(),{toast:i}=et(),o=v.useCallback(async(c,l,m)=>n()||t(c)?l():(i({title:"غير مصرح",description:m||"ليس لديك صلاحية لتنفيذ هذه العملية",variant:"destructive"}),null),[t,n,i]),a=v.useCallback((c,l)=>n()||t(c)?!0:(i({title:"غير مصرح",description:l||"ليس لديك صلاحية لتنفيذ هذه العملية",variant:"destructive"}),!1),[t,n,i]),s=v.useCallback(c=>n()?!0:t(c),[t,n]);return{guardedAction:o,checkPermission:a,silentCheck:s,hasPermission:t,isOwnerOrAdmin:n,currentEmployee:r}},Hx=({items:t,taxCalculationMode:r="tax_exclusive"})=>{console.log("🧮 InvoiceTotalsSection - Calculating totals with mode:",r);const n=t.map(s=>xt({quantity:s.quantity||1,unitPrice:s.unit_price||0,discountAmount:s.discount_amount||0,taxPercent:s.tax_percent||0,taxCalculationMode:r})),i=lr(n);console.log("✅ InvoiceTotalsSection - Government calculation totals:",i);const o=s=>`${s.toFixed(2)} د.أ`,a=i.taxInclusiveAmount;return console.log("💰 InvoiceTotalsSection - Final total (tax_inclusive_amount):",a),e.jsxs(fe,{className:"bg-gradient-to-r from-green-50 to-emerald-50 border-2 border-green-200",children:[e.jsx(De,{children:e.jsx($e,{className:"text-green-900 text-xl font-cairo text-center",children:"المجموع الكلي"})}),e.jsx(ve,{children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[e.jsx("div",{className:"space-y-4",children:e.jsxs("div",{className:"bg-white p-4 rounded-lg border border-green-200",children:[e.jsxs("div",{className:"flex justify-between items-center py-2 border-b",children:[e.jsx("span",{className:"font-semibold text-gray-700",children:"اجمالي الفاتورة قبل الخصم:"}),e.jsx("span",{className:"font-bold text-lg",children:o(i.taxExclusiveAmount+i.allowanceChargeAmount)})]}),e.jsxs("div",{className:"flex justify-between items-center py-2 border-b",children:[e.jsx("span",{className:"font-semibold text-gray-700",children:"مجموع قيمة الخصم:"}),e.jsx("span",{className:"font-bold text-red-600",children:o(i.allowanceChargeAmount)})]}),e.jsxs("div",{className:"flex justify-between items-center py-2 border-b",children:[e.jsx("span",{className:"font-semibold text-gray-700",children:"المبلغ قبل الضريبة:"}),e.jsx("span",{className:"font-bold",children:o(i.taxExclusiveAmount)})]}),e.jsxs("div",{className:"flex justify-between items-center py-2 border-b",children:[e.jsx("span",{className:"font-semibold text-gray-700",children:"مجموع قيمة الضريبة العامة:"}),e.jsx("span",{className:"font-bold text-blue-600",children:o(i.totalTaxAmount)})]}),e.jsxs("div",{className:"flex justify-between items-center py-3 border-t-2 border-green-300 mt-2",children:[e.jsx("span",{className:"font-bold text-lg text-green-800",children:"اجمالي الفاتورة:"}),e.jsx("span",{className:"font-bold text-xl text-green-800",children:o(a)})]})]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"bg-white p-4 rounded-lg border border-green-200",children:[e.jsx("h4",{className:"font-bold text-gray-800 mb-3 font-cairo",children:"تفاصيل الحساب:"}),e.jsxs("div",{className:"space-y-2 text-sm",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{children:"عدد البنود:"}),e.jsx("span",{className:"font-semibold",children:t.length})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{children:"إجمالي الكمية:"}),e.jsx("span",{className:"font-semibold",children:t.reduce((s,c)=>s+(c.quantity||0),0)})]}),e.jsx("div",{className:"flex justify-between",children:e.jsx("span",{})}),e.jsx("div",{className:"flex justify-between"})]})]}),e.jsxs("div",{className:"bg-blue-50 p-4 rounded-lg border border-blue-200",children:[e.jsx("h4",{className:"font-bold text-blue-800 mb-2 font-cairo",children:"المبلغ كتابة:"}),e.jsx("p",{className:"text-sm text-blue-700 leading-relaxed",children:jl(a)})]})]})]})})]})},Wx=({onInvoiceSaved:t,onCancel:r})=>{const[n,i]=v.useState(null),[o,a]=v.useState(!1),[s,c]=v.useState("income"),[l,m]=v.useState("tax_exclusive"),[u,d]=v.useState(!0),{toast:h}=et(),{customers:p=[],isLoading:f}=Vx();Gx();const{currentShift:x}=$n(),{currentEmployee:g}=lt(),{checkPermission:b}=Kn(),{isOnline:y}=jr(),[_,j]=v.useState({customer_id:"",customer_name:"",customer_number:"0000000000",customer_type:"NIN",phone_number:"",city:"",payment_method:"نقدي",invoice_date:new Date().toISOString().split("T")[0]}),[I,w]=v.useState(""),[N,C]=v.useState([{id:"1",product_id:"",item_name:"",quantity:1,unit_price:0,line_total:0,discount_amount:0,tax_percent:0,line_extension_amount:0,tax_amount:0,rounding_amount:0,price_after_tax:0,price_before_tax:0,tax_category_code:null}]),A=Mt();v.useEffect(()=>{A&&F()},[A]),v.useEffect(()=>{if(!u){const S=s==="general_tax"?16:0;console.log("🔄 CreateInvoice - Updating items tax percent to:",S,"for invoice type:",s),C(E=>E.map(O=>{if(!O.item_name||O.tax_percent===0&&s==="general_tax"){const R=S,D=s==="general_tax"?Ut(R):null;return{...O,tax_percent:R,tax_category_code:D}}return O}))}},[s,u]);const F=async()=>{if(!A){console.error("❌ CreateInvoice - No seller_id available for fetching seller data"),d(!1);return}try{d(!0),console.log("🔍 CreateInvoice - Fetching seller data for seller_id:",A);const S=localStorage.getItem(xe),E=`${nt}${W.GET_BY_ID("sellers",A)}&token=${S||""}`,R=await(await fetch(E)).json();if(!R.success||!R.data){console.error("❌ CreateInvoice - Error fetching seller data"),h({title:"خطأ",description:"فشل في تحميل بيانات البائع",variant:"destructive"});return}const D=R.data;i(D);const $=D.invoice_type==="ضريبة عامة"||D.invoice_type==="مبيعات عامة"?"general_tax":"income";c($),console.log("✅ CreateInvoice - Seller data fetched for seller_id:",A),console.log("📊 CreateInvoice - Seller data:",D),console.log("🏷️ CreateInvoice - Invoice type set to:",$,"based on seller invoice_type:",D.invoice_type)}catch(S){console.error("❌ CreateInvoice - Error fetching seller data:",S),h({title:"خطأ",description:"حدث خطأ في تحميل بيانات البائع",variant:"destructive"})}finally{d(!1)}},T=async()=>{var S;try{const E=localStorage.getItem(xe),O=`${nt}${W.GET_BY_ID("sellers",A)}&token=${E||""}`,M=(((S=(await(await fetch(O)).json()).data)==null?void 0:S.current_icv_counter)||0)+1;return await fetch(`${nt}${W.UPDATE("sellers",A)}&token=${E||""}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({current_icv_counter:M})}),M}catch(E){return console.error("Error generating ICV:",E),1}},k=()=>{console.log("🧮 CreateInvoice - Calculating total using government calculations for all modes");const S=N.map(O=>xt({quantity:O.quantity,unitPrice:O.unit_price,discountAmount:O.discount_amount||0,taxPercent:O.tax_percent||0,taxCalculationMode:l})),E=lr(S);return console.log("✅ CreateInvoice - Government calculation totals:",E),console.log("💰 CreateInvoice - Final total (tax_inclusive_amount):",E.taxInclusiveAmount),E.taxInclusiveAmount},P=async(S="فاتورة جديدة - غير مرسلة")=>{if(b("can_create_invoices","ليس لديك صلاحية إنشاء الفواتير")){if(!y){h({title:"⚠️ لا يوجد اتصال بالإنترنت",description:"يجب الاتصال بالإنترنت لحفظ الفاتورة. يرجى التحقق من اتصالك والمحاولة مرة أخرى.",variant:"destructive",duration:5e3});return}if(console.log("💾 Starting saveInvoice with status:",S),console.log("📋 Invoice data:",_),console.log("📝 Items with tax categories:",N),console.log("🏢 Seller:",n),console.log("🆔 Seller ID:",A),console.log("🔢 Tax calculation mode:",l),console.log("📄 Notes to include in XML:",I),s==="general_tax"){const E=N.filter(O=>{const R=Ut(O.tax_percent||16);return O.tax_category_code!==R});E.length>0&&(console.warn("⚠️ Tax category inconsistencies detected, auto-correcting:",E),C(O=>O.map(R=>({...R,tax_category_code:Ut(R.tax_percent||16)}))))}if(!_.customer_name||N.some(E=>!E.item_name)){console.error("❌ Validation failed - missing required fields"),h({title:"خطأ",description:"يرجى ملء جميع الحقول المطلوبة",variant:"destructive"});return}if(!n){console.error("❌ No seller data available"),h({title:"خطأ",description:"لم يتم العثور على بيانات البائع",variant:"destructive"});return}if(!A){console.error("❌ No seller_id available"),h({title:"خطأ",description:"معرف البائع غير متوفر",variant:"destructive"});return}try{a(!0),console.log("🔢 Generating invoice number...");const E=await bx(A);console.log("✅ Generated invoice number:",E),console.log("🔢 Generating ICV...");const O=await T();console.log("✅ Generated ICV:",O);const R=k();console.log("💰 Calculated total using standardized method:",R);const D=N.map(be=>xt({quantity:be.quantity,unitPrice:be.unit_price,discountAmount:be.discount_amount||0,taxPercent:be.tax_percent||0,taxCalculationMode:l})),$=lr(D);console.log("📊 Invoice totals:",$);const M=Ke($.taxExclusiveAmount),X=Ke($.taxInclusiveAmount),U=Ke($.totalTaxAmount),Q=Ke($.allowanceChargeAmount);console.log("💾 Saving invoice with properly formatted XML values:",{xmlTaxExclusiveAmount:M,xmlTaxInclusiveAmount:X,xmlTotalTaxAmount:U,xmlAllowanceChargeAmount:Q});const B={..._,invoice_type:s,tax_calculation_mode:l,notes:I};console.log("🔄 Generating XML content with notes and tax categories...");const z=await Bs(E,R,B,N,n,O,A),H=Jn(z);console.log("✅ XML content generated and encoded with notes and tax category support"),console.log("💾 Inserting invoice into database...");const Y=localStorage.getItem(xe),J={invoice_number:E,invoice_sequence:E,invoice_counter:O,invoice_date:_.invoice_date,customer_name:_.customer_name,customer_number:_.customer_number,customer_type:_.customer_type,phone_number:_.phone_number,city:_.city,payment_method:_.payment_method,subtotal:$.taxExclusiveAmount,total_amount:$.taxInclusiveAmount,allowance_charge_amount:$.allowanceChargeAmount,tax_exclusive_amount:$.taxExclusiveAmount,tax_inclusive_amount:$.taxInclusiveAmount,total_tax_amount:$.totalTaxAmount,xml_tax_exclusive_amount:M,xml_tax_inclusive_amount:X,xml_total_tax_amount:U,xml_allowance_charge_amount:Q,status:S,xml_file:z,xml_base64:H,encoded_xml:H,notes:I||null,seller_id:A};g!=null&&g.id&&(J.created_by=g.id),x!=null&&x.id&&(J.shift_id=x.id);const ce=await(await fetch(`${nt}${W.CREATE("invoices")}&token=${Y||""}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(J)})).json();if(!ce.success)throw console.error("❌ Error inserting invoice:",ce.message),new Error(`Invoice insertion failed: ${ce.message}`);const ke=ce.data;console.log("✅ Invoice saved successfully:",ke);for(let be=0;be<N.length;be++){const Se=N[be],je=D[be],Re=Ke(Se.quantity),We=Ke(Se.unit_price),se=Ke(je.roundingAmount),q={invoice_id:ke.id,product_id:Se.product_id||null,item_name:Se.item_name,quantity:Se.quantity,unit_price:Se.unit_price,discount_amount:Se.discount_amount||0,tax_percent:Se.tax_percent||0,line_extension_amount:je.lineExtensionAmount,tax_amount:je.taxAmount,rounding_amount:je.roundingAmount,line_total:je.roundingAmount,line_number:be+1,xml_quantity:Re,xml_unit_price:We,xml_line_total:se,price_before_tax:je.unitPriceBeforeTax,price_after_tax:je.unitPriceAfterTax,tax_category_code:Se.tax_category_code,tax_calculation_mode:l};await fetch(`${nt}${W.CREATE("invoice_items")}&token=${Y||""}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(q)})}return console.log("✅ Invoice items saved successfully with tax categories"),h({title:"تم الحفظ",description:`تم حفظ الفاتورة ${E} بنجاح`}),j({customer_id:"",customer_name:"",customer_number:"",customer_type:"NIN",phone_number:"",city:"",payment_method:"نقدي",invoice_date:new Date().toISOString().split("T")[0]}),C([{id:"1",product_id:"",item_name:"",quantity:1,unit_price:0,line_total:0,discount_amount:0,tax_percent:s==="general_tax"?16:0,line_extension_amount:0,tax_amount:0,rounding_amount:0,price_after_tax:0,price_before_tax:0,tax_category_code:s==="general_tax"?Ut(16):null}]),w(""),t&&t(),ke}catch(E){console.error("❌ Error saving invoice:",E);let O="فشل في حفظ الفاتورة";E instanceof Error&&(console.error("❌ Detailed error:",E.message),O=`فشل في حفظ الفاتورة: ${E.message}`),h({title:"خطأ",description:O,variant:"destructive"})}finally{a(!1)}}};return console.log("🎨 CreateInvoice - Rendering with:",{seller_id:A,invoiceType:s,taxCalculationMode:l,sellerLoading:u,sellerInvoiceType:n==null?void 0:n.invoice_type,itemsCount:N.length}),u?e.jsxs("div",{className:"flex flex-col items-center justify-center h-64 space-y-4",children:[e.jsx(ct,{className:"h-12 w-12 animate-spin text-blue-600"}),e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"text-lg font-bold text-gray-700 font-cairo",children:"جاري تحميل بيانات البائع..."}),e.jsx("p",{className:"text-sm text-gray-500 font-cairo",children:"يرجى الانتظار لتحديد نوع الفاتورة"})]})]}):A?e.jsxs("div",{className:"space-y-4 md:space-y-6 font-cairo",dir:"rtl",children:[!y&&e.jsxs("div",{className:"bg-destructive/10 border border-destructive/30 rounded-lg p-4 flex items-center gap-3",children:[e.jsx(tn,{className:"h-6 w-6 text-destructive flex-shrink-0"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold text-destructive",children:"لا يوجد اتصال بالإنترنت"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"لا يمكن حفظ الفاتورة حالياً. يرجى التحقق من اتصالك بالإنترنت."})]})]}),r&&e.jsx("div",{className:"flex justify-start mb-4",children:e.jsxs(V,{onClick:r,variant:"outline",className:"flex items-center gap-2",children:[e.jsx(at,{className:"h-4 w-4"}),"إغلاق"]})}),e.jsxs(fe,{className:"bg-gradient-to-r from-blue-50 to-indigo-50 border-2 border-blue-200",children:[e.jsx(De,{children:e.jsxs($e,{className:"flex items-center gap-2 text-blue-900 text-lg md:text-xl font-cairo",children:[e.jsx(It,{className:"h-5 w-5 md:h-6 md:w-6"}),"معلومات الفاتورة",s==="general_tax"&&e.jsx("span",{className:"text-sm bg-red-100 px-2 py-1 rounded text-red-800",children:"مبيعات عامة - ضريبة 16%"}),s==="income"&&e.jsx("span",{className:"text-sm bg-green-100 px-2 py-1 rounded text-green-800",children:"دخل - بدون ضريبة"})]})}),e.jsx(ve,{children:e.jsx(cl,{customers:p,invoiceData:_,setInvoiceData:j})})]}),e.jsxs(fe,{className:"bg-gradient-to-r from-purple-50 to-pink-50 border-2 border-purple-200",children:[e.jsx(De,{children:e.jsx("div",{className:"flex items-center justify-between flex-wrap gap-4",children:e.jsxs($e,{className:"flex items-center gap-2 text-purple-900 text-lg md:text-xl font-cairo",children:[e.jsx(gr,{className:"h-5 w-5 md:h-6 md:w-6"}),"عناصر الفاتورة"]})})}),e.jsx(ve,{children:e.jsx(wl,{items:N,onItemsChange:C,isGeneralTax:s==="general_tax",taxCalculationMode:l})})]}),e.jsx(Hx,{items:N,taxCalculationMode:l}),e.jsxs(fe,{className:"bg-gradient-to-r from-yellow-50 to-amber-50 border-2 border-yellow-200",children:[e.jsx(De,{children:e.jsxs($e,{className:"flex items-center gap-2 text-yellow-900 text-lg md:text-xl font-cairo",children:[e.jsx(It,{className:"h-5 w-5 md:h-6 md:w-6"}),"ملاحظات الفاتورة"]})}),e.jsx(ve,{children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{htmlFor:"notes",className:"block text-sm font-medium text-gray-700 font-cairo",children:"أضف ملاحظات للفاتورة (اختياري)"}),e.jsx("textarea",{id:"notes",value:I,onChange:S=>w(S.target.value),placeholder:"أدخل أي ملاحظات إضافية للفاتورة هنا...",className:"w-full min-h-[100px] p-3 border border-gray-300 rounded-md focus:ring-2 focus:ring-yellow-500 focus:border-yellow-500 resize-y font-cairo",dir:"rtl"}),e.jsx("p",{className:"text-xs text-gray-500 font-cairo",children:"ستظهر هذه الملاحظات في الفاتورة المطبوعة وملف XML"})]})})]}),e.jsx("div",{className:"flex justify-center gap-4",children:e.jsxs(gt,{children:[e.jsx(mn,{asChild:!0,children:e.jsxs(V,{variant:"outline",className:"flex items-center gap-2",children:[e.jsx(fo,{className:"h-4 w-4"}),"معاينة الفاتورة"]})}),e.jsxs(bt,{className:"max-w-4xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Tt,{children:e.jsx(At,{className:"font-cairo",children:"معاينة الفاتورة"})}),e.jsx(Fx,{invoiceData:_,items:N,total:k(),invoiceNumber:"",sellerData:n})]})]})}),e.jsx(Cl,{invoiceData:_,items:N,total:k(),loading:o,sellerLoading:u,sellerData:n,onSave:P})]}):e.jsx("div",{className:"flex items-center justify-center h-64",children:e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"text-red-600 font-cairo",children:"لم يتم العثور على معرف البائع"}),e.jsx("p",{className:"text-gray-500 font-cairo",children:"يرجى إعادة تسجيل الدخول"})]})})},Xx=({invoiceId:t,onBack:r})=>{const[n,i]=v.useState([]),[o,a]=v.useState([]),[s,c]=v.useState(null),[l,m]=v.useState(!1),[u,d]=v.useState(!0),[h,p]=v.useState("income"),[f,x]=v.useState(!0),[g,b]=v.useState(""),{toast:y}=et(),{hasPermission:_}=lt();v.useEffect(()=>{_("can_edit_invoices")||(y({title:"غير مصرح",description:"ليس لديك صلاحية تعديل الفواتير",variant:"destructive"}),r())},[_,r,y]);const[j,I]=v.useState({customer_id:"",customer_name:"",customer_number:"0000000000",customer_type:"NIN",phone_number:"",city:"",payment_method:"نقدي",invoice_date:new Date().toISOString().split("T")[0]}),[w,N]=v.useState([{id:"1",product_id:"",item_name:"",quantity:1,unit_price:0,line_total:0,discount_amount:0,tax_percent:0,line_extension_amount:0,tax_amount:0,rounding_amount:0,price_after_tax:0}]),C=Mt();v.useEffect(()=>{C&&(T(),k(),F(),A())},[t,C]);const A=async()=>{try{d(!0);const E=localStorage.getItem(xe),O=`${oe()}${W.GET_BY_ID("invoices",t)}&token=${E||""}`,D=await(await fetch(O)).json();if(!D.success||!D.data)throw new Error("Invoice not found");const $=D.data;if(["مرسلة للحكومة","مرسلة إلى فوترة","مرسلة"].includes($.status)){y({title:"تحذير",description:"لا يمكن تعديل الفاتورة بعد إرسالها",variant:"destructive"}),r();return}I({customer_id:$.customer_id||"",customer_name:$.customer_name||"",customer_number:$.customer_number||"",customer_type:$.customer_type||"NIN",phone_number:$.phone_number||"",city:$.city||"",payment_method:$.payment_method||"نقدي",invoice_date:$.invoice_date||new Date().toISOString().split("T")[0],is_return:$.is_return||!1,return_reason:$.return_reason||"",return_payment_type:$.return_payment_type||"",original_invoice_number:$.original_invoice_number||""}),b($.notes||"");const M=`${oe()}${W.GET_ALL("invoice_items")}&token=${E||""}`,U=await(await fetch(M)).json();if(U.success&&U.data){const Q=U.data.filter(B=>B.invoice_id===t).sort((B,z)=>(B.line_number||0)-(z.line_number||0));if(Q.length>0){const B=Q.map((z,H)=>({id:(H+1).toString(),product_id:z.product_id||"",item_name:z.item_name||"",quantity:Number(z.quantity)||1,unit_price:Number(z.unit_price)||0,line_total:Number(z.line_total)||0,discount_amount:Number(z.discount_amount)||0,tax_percent:Number(z.tax_percent)||0,line_extension_amount:Number(z.line_extension_amount)||0,tax_amount:Number(z.tax_amount)||0,rounding_amount:Number(z.rounding_amount)||0,price_after_tax:Number(z.price_after_tax)||0}));N(B)}}}catch(E){console.error("Error loading invoice data:",E),y({title:"خطأ",description:"فشل في تحميل بيانات الفاتورة",variant:"destructive"}),r()}finally{d(!1)}},F=async()=>{if(!C){console.error("❌ EditInvoice - No seller_id available for fetching seller data"),x(!1);return}try{x(!0),console.log("🔍 EditInvoice - Fetching seller data for seller_id:",C);const E=localStorage.getItem(xe),O=`${oe()}${W.GET_BY_ID("sellers",C)}&token=${E||""}`,D=await(await fetch(O)).json();if(!D.success||!D.data){console.error("❌ EditInvoice - Error fetching seller data"),y({title:"خطأ",description:"فشل في تحميل بيانات البائع",variant:"destructive"});return}const $=D.data;c($);const M=$.invoice_type==="ضريبة عامة"||$.invoice_type==="مبيعات عامة"?"general_tax":"income";p(M),console.log("✅ EditInvoice - Seller data fetched for seller_id:",C)}catch(E){console.error("❌ EditInvoice - Error fetching seller data:",E),y({title:"خطأ",description:"حدث خطأ في تحميل بيانات البائع",variant:"destructive"})}finally{x(!1)}},T=async()=>{try{const E=localStorage.getItem(xe),O=`${oe()}${W.GET_ALL("customers")}&token=${E||""}`,D=await(await fetch(O)).json();if(D.success&&D.data){const $=D.data.filter(M=>M.seller_id===C);i($)}}catch(E){console.error("Error fetching customers:",E)}},k=async()=>{if(C)try{const E=localStorage.getItem(xe),O=JSON.stringify({seller_id:C}),R=`${oe()}${W.GET_ALL("products")}&filters=${encodeURIComponent(O)}&limit=500&token=${E||""}`,$=await(await fetch(R)).json();$.success&&$.data&&(console.log("EditInvoice - fetched products:",$.data.length),a($.data))}catch(E){console.error("Error fetching products:",E)}},P=()=>{console.log("🧮 EditInvoice - Calculating total using government calculations");const E=w.map(R=>xt({quantity:R.quantity,unitPrice:R.unit_price,discountAmount:R.discount_amount||0,taxPercent:R.tax_percent||0})),O=lr(E);return console.log("✅ EditInvoice - Government calculation totals:",O),O.taxInclusiveAmount},S=async(E="فاتورة جديدة - غير مرسلة")=>{var O,R;if(!j.customer_name||w.some(D=>!D.item_name)){y({title:"خطأ",description:"يرجى ملء جميع الحقول المطلوبة",variant:"destructive"});return}if(!s){y({title:"خطأ",description:"لم يتم العثور على بيانات البائع",variant:"destructive"});return}try{m(!0);const D=P(),$=w.map(re=>xt({quantity:re.quantity,unitPrice:re.unit_price,discountAmount:re.discount_amount||0,taxPercent:re.tax_percent||0})),M=lr($),X=Ke(M.taxExclusiveAmount),U=Ke(M.taxInclusiveAmount),Q=Ke(M.totalTaxAmount),B=Ke(M.allowanceChargeAmount),z=localStorage.getItem(xe),H=`${oe()}${W.GET_BY_ID("invoices",t)}&token=${z||""}`,J=await(await fetch(H)).json(),ie=((O=J.data)==null?void 0:O.invoice_number)||"INV-ERROR",ce=((R=J.data)==null?void 0:R.invoice_counter)||1,ke={...j,invoice_type:h},be=await Bs(ie,D,ke,w,s,ce,C),Se=Jn(be),je={invoice_date:j.invoice_date,customer_name:j.customer_name,customer_number:j.customer_number,customer_type:j.customer_type,phone_number:j.phone_number,city:j.city,payment_method:j.payment_method,subtotal:M.taxExclusiveAmount,total_amount:M.taxInclusiveAmount,allowance_charge_amount:M.allowanceChargeAmount,tax_exclusive_amount:M.taxExclusiveAmount,tax_inclusive_amount:M.taxInclusiveAmount,total_tax_amount:M.totalTaxAmount,xml_tax_exclusive_amount:X,xml_tax_inclusive_amount:U,xml_total_tax_amount:Q,xml_allowance_charge_amount:B,status:E,xml_file:be,xml_base64:Se,encoded_xml:Se,return_reason:j.return_reason,return_payment_type:j.return_payment_type,original_invoice_number:j.original_invoice_number,notes:g||null},We=await(await fetch(`${oe()}${W.UPDATE("invoices",t)}&token=${z||""}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(je)})).json();if(!We.success)throw new Error(We.message);const se=`${oe()}${W.GET_ALL("invoice_items")}&token=${z||""}`,ne=await(await fetch(se)).json();if(ne.success&&ne.data){const re=ne.data.filter(de=>de.invoice_id===t);for(const de of re)await fetch(`${oe()}${W.DELETE("invoice_items",de.id)}&token=${z||""}`,{method:"POST"})}for(let re=0;re<w.length;re++){const de=w[re],ze=$[re],Ce=Ke(de.quantity),st=Ke(de.unit_price),ot=Ke(ze.roundingAmount),dt={invoice_id:t,product_id:de.product_id||null,item_name:de.item_name,quantity:de.quantity,unit_price:de.unit_price,discount_amount:de.discount_amount||0,tax_percent:de.tax_percent||0,line_extension_amount:ze.lineExtensionAmount,tax_amount:ze.taxAmount,rounding_amount:ze.roundingAmount,line_total:ze.roundingAmount,line_number:re+1,xml_quantity:Ce,xml_unit_price:st,xml_line_total:ot,price_before_tax:h==="general_tax"?de.unit_price:0,price_after_tax:h==="general_tax"?de.unit_price*(1+(de.tax_percent||0)/100):de.unit_price,tax_category_code:h==="general_tax"?"S":null,tax_calculation_mode:h==="general_tax"?"before_tax":null};await fetch(`${oe()}${W.CREATE("invoice_items")}&token=${z||""}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(dt)})}y({title:"تم التحديث",description:`تم تحديث الفاتورة ${ie} بنجاح`}),r()}catch(D){console.error("Error updating invoice:",D),y({title:"خطأ",description:"فشل في تحديث الفاتورة",variant:"destructive"})}finally{m(!1)}};return u||f?e.jsx("div",{className:"flex items-center justify-center h-64",children:e.jsx("div",{className:"animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600"})}):C?e.jsxs("div",{className:"space-y-4 md:space-y-6 font-cairo",dir:"rtl",children:[e.jsxs("div",{className:"flex items-center justify-between mb-6",children:[e.jsxs(V,{onClick:r,variant:"outline",className:"flex items-center gap-2",children:[e.jsx(qo,{className:"h-4 w-4"}),"العودة للرئيسية"]}),e.jsx("h1",{className:"text-2xl font-bold text-blue-900",children:"تعديل الفاتورة"})]}),e.jsxs(fe,{className:"bg-gradient-to-r from-blue-50 to-indigo-50 border-2 border-blue-200",children:[e.jsx(De,{children:e.jsxs($e,{className:"flex items-center gap-2 text-blue-900 text-lg md:text-xl font-cairo",children:[e.jsx(It,{className:"h-5 w-5 md:h-6 md:w-6"}),"معلومات الفاتورة",h==="general_tax"&&e.jsx("span",{className:"text-sm bg-red-100 px-2 py-1 rounded text-red-800",children:"مبيعات عامة "}),h==="income"&&e.jsx("span",{className:"text-sm bg-green-100 px-2 py-1 rounded text-green-800",children:"دخل - بدون ضريبة"})]})}),e.jsx(ve,{children:e.jsx(cl,{customers:n,invoiceData:j,setInvoiceData:I})})]}),e.jsxs(fe,{className:"bg-gradient-to-r from-purple-50 to-pink-50 border-2 border-purple-200",children:[e.jsx(De,{children:e.jsxs($e,{className:"flex items-center gap-2 text-purple-900 text-lg md:text-xl font-cairo",children:[e.jsx(gr,{className:"h-5 w-5 md:h-6 md:w-6"}),"عناصر الفاتورة"]})}),e.jsx(ve,{children:e.jsx(wl,{items:w,onItemsChange:N,isGeneralTax:h==="general_tax"})})]}),e.jsxs(fe,{className:"bg-gradient-to-r from-yellow-50 to-amber-50 border-2 border-yellow-200",children:[e.jsx(De,{children:e.jsxs($e,{className:"flex items-center gap-2 text-yellow-900 text-lg md:text-xl font-cairo",children:[e.jsx(It,{className:"h-5 w-5 md:h-6 md:w-6"}),"ملاحظات الفاتورة"]})}),e.jsx(ve,{children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{htmlFor:"notes",className:"block text-sm font-medium text-gray-700 font-cairo",children:"أضف ملاحظات للفاتورة (اختياري)"}),e.jsx("textarea",{id:"notes",value:g,onChange:E=>b(E.target.value),placeholder:"أدخل أي ملاحظات إضافية للفاتورة هنا...",className:"w-full min-h-[100px] p-3 border border-gray-300 rounded-md focus:ring-2 focus:ring-yellow-500 focus:border-yellow-500 resize-y font-cairo",dir:"rtl"}),e.jsx("p",{className:"text-xs text-gray-500 font-cairo",children:"ستظهر هذه الملاحظات في الفاتورة المطبوعة وملف XML"})]})})]}),e.jsx(Cl,{invoiceData:j,items:w,total:P(),loading:l,sellerLoading:f,sellerData:s,onSave:S,isEdit:!0})]}):e.jsx("div",{className:"flex items-center justify-center h-64",children:e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"text-red-600 font-cairo",children:"لم يتم العثور على معرف البائع"}),e.jsx("p",{className:"text-gray-500 font-cairo",children:"يرجى إعادة تسجيل الدخول"})]})})},El=({open:t,onOpenChange:r,htmlContent:n,invoiceNumber:i,invoice:o,onBackToHome:a})=>{const s=v.useRef(null),c=v.useCallback(async()=>{if(!window.html2pdf){alert("لم يتم تحميل مكتبة PDF. تأكد من توفر الإنترنت.");return}document.fonts&&document.fonts.ready?await document.fonts.ready:await new Promise(p=>setTimeout(p,1200));const d=s.current;if(!d)return;const h=d.cloneNode(!0);Array.from(h.querySelectorAll(".custom-button")).forEach(p=>p.style.display="none"),window.html2pdf().set({margin:0,filename:(i||"فاتورة")+".pdf",image:{type:"jpeg",quality:.98},html2canvas:{scale:3,backgroundColor:"#fff",useCORS:!0,logging:!1,delay:1800,letterRendering:!0},jsPDF:{unit:"mm",format:"a4",orientation:"portrait"}}).from(h).save()},[i]),l=v.useCallback(async()=>{document.fonts&&document.fonts.ready?await document.fonts.ready:await new Promise(x=>setTimeout(x,800));const d=s.current;if(!d)return;const h=d.cloneNode(!0);Array.from(h.querySelectorAll(".custom-button")).forEach(x=>x.style.display="none");const p=h.innerHTML,f=window.open("","_blank","width=850,height=1200");f&&(f.document.open(),f.document.write(`
      <html lang="ar" dir="rtl">
      <head>
        <title>طباعة الفاتورة</title>
        <link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;700&display=swap" rel="stylesheet">
        <style>
            /* Just copy high-level style so invoice looks correct */
            body { background: #fff !important; font-family: 'Cairo', Arial, sans-serif; margin:0; padding:0; }
        </style>
      </head>
      <body>
        <div>${p}</div>
        <script>
          function allImagesLoaded() {
            var imgs = document.images;
            var loaded = 0, total = imgs.length;
            if(total===0){ window.print(); window.close(); return;}
            for(var i=0;i<total;i++){
              if(imgs[i].complete) loaded++;
              else {
                imgs[i].addEventListener('load', function(){ loaded++; if(loaded===total){window.print();window.close();}});
                imgs[i].addEventListener('error', function(){ loaded++; if(loaded===total){window.print();window.close();}});
              }
            }
            if(loaded===total){window.print();window.close();}
          }
          window.onload = allImagesLoaded;
        <\/script>
      </body>
      </html>`),f.document.close())},[]),m=`
    .custom-button { display: none !important; }
  `;we.useEffect(()=>{if(!window.html2pdf){const d="html2pdf-react-runtime";if(!document.getElementById(d)){const h=document.createElement("script");h.id=d,h.src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js",h.async=!0,document.body.appendChild(h)}}},[]);const u=v.useCallback(()=>{r(!1),a&&a()},[r,a]);return e.jsx(gt,{open:t,onOpenChange:r,children:e.jsxs(bt,{className:"max-w-5xl max-h-[95vh] overflow-auto p-0",style:{direction:"rtl"},children:[e.jsx(Tt,{className:"p-4 pb-2",children:e.jsxs(At,{className:"text-right",children:["معاينة الفاتورة ",i?`(${i})`:""]})}),e.jsxs("div",{className:"flex gap-3 px-4 pb-4 justify-start flex-wrap",children:[e.jsxs(V,{onClick:u,className:"bg-gradient-to-r from-red-500 to-orange-600 hover:from-red-600 hover:to-orange-700 text-white shadow-lg transition-all duration-200 flex items-center gap-2",children:[e.jsx(ys,{className:"h-4 w-4"}),"🏠 العودة الى الصفحة الرئيسية"]}),e.jsxs(V,{onClick:c,className:"bg-gradient-to-r from-blue-500 to-indigo-600 hover:from-blue-600 hover:to-indigo-700 text-white shadow-lg transition-all duration-200 flex items-center gap-2",children:[e.jsx(Rs,{className:"h-4 w-4"}),"📥 تحميل PDF"]}),e.jsxs(V,{onClick:l,className:"bg-gradient-to-r from-green-500 to-emerald-600 hover:from-green-600 hover:to-emerald-700 text-white shadow-lg transition-all duration-200 flex items-center gap-2",children:[e.jsx(Zr,{className:"h-4 w-4"}),"🖨️ طباعة الفاتورة A4"]})]}),e.jsx("div",{ref:s,className:"w-full rounded-b-lg overflow-auto bg-white min-h-[70vh] border-t border-gray-200",style:{padding:0,position:"relative"},dangerouslySetInnerHTML:{__html:(n||"<div class='p-8 text-center'>لا يوجد محتوى</div>")+`<style>${m}</style>`}})]})})},Jx={show_company_name:!0,show_company_logo:!0,show_tax_number:!0,show_income_number:!0,show_invoice_type_badge:!0,show_invoice_number:!0,show_invoice_date:!0,show_payment_method:!0,show_cashier_name:!1,show_currency:!0,show_customer_name:!0,show_customer_number:!0,show_customer_phone:!0,show_customer_city:!0,show_item_number:!0,show_item_description:!0,show_item_quantity:!0,show_item_unit_price:!0,show_item_amount:!0,show_item_discount:!0,show_item_tax_percent:!0,show_item_tax_amount:!0,show_item_total:!0,show_subtotal:!0,show_total_before_tax:!0,show_total_tax:!0,show_total_discount:!0,show_final_total:!0,show_amount_in_words:!0,show_payment_info:!0,show_notes:!0,show_qr_code:!0,show_footer_text:!0,show_thank_you_message:!0,custom_thank_you_message:"شكراً لتعاملكم معنا",custom_footer_text:"",custom_invoice_title:"فاتورة ضريبية",custom_return_title:"فاتورة إرجاع"},Ie=t=>t===!0||t===1||t==="1",Kx=t=>`https://api.qrserver.com/v1/create-qr-code/?size=150x150&data=${encodeURIComponent(t)}`,Sl=(t,r,n,i,o,a,s,c,l,m,u,d,h)=>{const p={...Jx,...h},f=m==="income"||(s==null?void 0:s.invoice_type)==="دخل"||(s==null?void 0:s.invoice_type)==="income",x=(s==null?void 0:s.enable_fawatrah)===!0||(s==null?void 0:s.enable_fawatrah)==1||(s==null?void 0:s.enable_fawatrah)==="1";(s==null?void 0:s.enable_bw_print)===!0||(s==null?void 0:s.enable_bw_print)==1||(s==null?void 0:s.enable_bw_print)==="1"||(s==null||s.enable_bw_print);const g=Number(l==null?void 0:l.tax_exclusive_amount)||i.reduce((T,k)=>T+(Number(k.quantity)*Number(k.unit_price)-Number(k.discount_amount||0)),0),b=f?0:Number((l==null?void 0:l.total_tax_amount)||0),y=Math.abs(Number(r)),_=Number((l==null?void 0:l.allowance_charge_amount)||0),j=(s==null?void 0:s.thermal_paper_width)||"80mm",w=parseInt(j)-20,N=a!=null&&a.is_return?p.custom_return_title||"فاتورة إرجاع":x?p.custom_invoice_title||"فاتورة ضريبية":"فاتورة",C=()=>{let T="";return Ie(p.show_item_number)&&(T+="<th>#</th>"),Ie(p.show_item_description)&&(T+="<th>المنتج</th>"),Ie(p.show_item_quantity)&&(T+="<th>الكمية</th>"),Ie(p.show_item_unit_price)&&(T+="<th>السعر</th>"),Ie(p.show_item_discount)&&(T+="<th>الخصم</th>"),!f&&Ie(p.show_item_tax_amount)&&(T+="<th>الضريبة</th>"),Ie(p.show_item_total)&&(T+="<th>المجموع</th>"),T},A=()=>i.map((T,k)=>{const P=Number(T.line_total)||Number(T.rounding_amount)||Number(T.quantity)*Number(T.unit_price)-Number(T.discount_amount||0);let S="";return Ie(p.show_item_number)&&(S+=`<td>${k+1}</td>`),Ie(p.show_item_description)&&(S+=`<td class="item-name">${T.item_name}</td>`),Ie(p.show_item_quantity)&&(S+=`<td>${T.quantity}</td>`),Ie(p.show_item_unit_price)&&(S+=`<td>${Number(T.unit_price||0).toFixed(2)}</td>`),Ie(p.show_item_discount)&&(S+=`<td>${Number(T.discount_amount||0).toFixed(2)}</td>`),!f&&Ie(p.show_item_tax_amount)&&(S+=`<td>${Number(T.tax_amount||0).toFixed(2)}</td>`),Ie(p.show_item_total)&&(S+=`<td>${Number(P||0).toFixed(2)}</td>`),`<tr>${S}</tr>`}).join("");return`
    <!DOCTYPE html>
    <html dir="rtl" lang="ar">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>${N} - ${t}</title>
      <style>
        @page {
          size: ${j} auto;
          margin: 3mm;
        }
        
        * {
          margin: 0;
          padding: 0;
          box-sizing: border-box;
        }
        
        body {
          font-family: 'Tahoma', 'Arial', 'Segoe UI', sans-serif;
          font-size: 10px;
          line-height: 1.3;
          color: #000;
          background: #fff;
          padding: 3mm;
          width: ${j};
          margin: 0 auto;
          font-weight: 600;
          -webkit-font-smoothing: antialiased;
          -moz-osx-font-smoothing: grayscale;
        }
        
        @media print {
          body {
            padding: 2mm;
            font-size: 9px;
          }
        }
        
        .header {
          text-align: center;
          margin-bottom: 10px;
          padding: 6px;
          background: #fff;
          border: 1px solid #000;
          border-radius: 4px;
        }
        
        .company-name {
          font-size: 14px;
          font-weight: bold;
          margin-bottom: 3px;
          color: #000;
        }
        
        .tax-number {
          font-size: 9px;
          color: #000;
          margin-bottom: 2px;
          font-weight: 600;
        }
        
        .invoice-type {
          background: #000;
          color: white;
          padding: 4px 8px;
          border-radius: 12px;
          font-size: 10px;
          font-weight: bold;
          margin: 6px 0;
          display: inline-block;
        }
        
        .section {
          margin-bottom: 8px;
          border: 1px solid #000;
          border-radius: 3px;
          overflow: hidden;
        }
        
        .section-header {
          background: #fff;
          padding: 4px;
          font-weight: bold;
          border-bottom: 1px solid #000;
          font-size: 10px;
          color: #000;
        }
        
        .section-content {
          padding: 4px;
        }
        
        .info-table {
          width: 100%;
          border-collapse: collapse;
        }
        
        .info-table td {
          padding: 2px 4px;
          border-bottom: 1px dotted #000;
          font-size: 9px;
          color: #000;
          font-weight: 600;
        }
        
        .info-table td:first-child {
          font-weight: bold;
          width: 40%;
          color: #000;
        }
        
        .items-table {
          width: 100%;
          border-collapse: collapse;
          margin-top: 3px;
        }
        
        .items-table th {
          background: #fff;
          padding: 3px 2px;
          border: 1px solid #000;
          font-size: 8px;
          font-weight: bold;
          text-align: center;
          color: #000;
        }
        
        .items-table td {
          padding: 3px 2px;
          border: 1px solid #000;
          font-size: 8px;
          text-align: center;
          color: #000;
          font-weight: 600;
        }
        
        .item-name {
          text-align: right !important;
          font-weight: bold;
        }
        
        .totals-table {
          width: 100%;
          border-collapse: collapse;
          margin-top: 3px;
        }
        
        .totals-table td {
          padding: 3px 4px;
          border-bottom: 1px dotted #000;
          font-size: 9px;
          color: #000;
          font-weight: 600;
        }
        
        .totals-table td:first-child {
          font-weight: bold;
          color: #000;
        }
        
        .totals-table td:last-child {
          text-align: left;
          font-weight: bold;
        }
        
        .final-total {
          background: #000;
          color: white;
          font-size: 10px;
          font-weight: bold;
        }
        
        .return-info {
          background: #fff;
          border: 1px solid #000;
          padding: 4px;
          margin-bottom: 6px;
          border-radius: 3px;
          font-size: 9px;
        }
        
        .return-info strong {
          color: #000;
        }
        
        .qr-section {
          text-align: center;
          margin-top: 8px;
          padding: 6px;
          border: 1px solid #000;
          border-radius: 3px;
          background: #fff;
        }
        
        .qr-code {
          max-width: ${w}mm;
          height: auto;
          margin: 4px auto;
          filter: contrast(1.3);
          background: #fff;
          padding: 4px;
          border: 2px solid #000;
          border-radius: 2px;
        }
        
        .footer {
          text-align: center;
          font-size: 8px;
          margin-top: 8px;
          padding-top: 6px;
          border-top: 1px dashed #000;
          color: #000;
          font-weight: 600;
        }
        
        .notes-section {
          background: #fff;
          padding: 4px;
          margin-top: 6px;
          border-radius: 3px;
          border: 1px solid #000;
          font-size: 8px;
          color: #000;
          font-weight: 600;
        }
        
        .divider {
          border-top: 1px dashed #000;
          margin: 6px 0;
        }
        
        .payment-info {
          background: #fff;
          border: 1px solid #000;
          padding: 6px;
          margin: 8px 0;
          border-radius: 3px;
        }
        
        .payment-info-title {
          text-align: center;
          font-size: 9px;
          font-weight: bold;
          color: #000;
          margin-bottom: 4px;
          border-bottom: 1px solid #000;
          padding-bottom: 3px;
        }
        
        .payment-row {
          display: flex;
          justify-content: space-between;
          padding: 3px 2px;
          margin: 2px 0;
          border-radius: 2px;
        }
        
        .payment-label {
          font-size: 9px;
          font-weight: bold;
          color: #000;
        }
        
        .payment-value {
          font-size: 10px;
          font-weight: bold;
          color: #000;
        }
        
        .paid-amount {
          background: #fff;
          border: 1px solid #000;
        }
        
        .change-amount {
          background: #fff;
          border: 1px solid #000;
        }
        
        .change-amount .payment-value {
          font-size: 10px;
          color: #000;
        }
        
        /* Print optimization */
        @media print {
          body {
            padding: 2mm;
            font-size: 9px;
            font-weight: 600;
          }
          
          * {
            -webkit-print-color-adjust: exact !important;
            print-color-adjust: exact !important;
          }
        }
        
      </style>
    </head>
    <body>
      <!-- Header Section -->
      <div class="header">
        ${Ie(p.show_company_name)?`<div class="company-name">${(s==null?void 0:s.seller_name)||"اسم الشركة"}</div>`:""}
        ${x&&Ie(p.show_tax_number)&&(s!=null&&s.tax_number)?`<div class="tax-number">الرقم الضريبي: ${s.tax_number}</div>`:""}
        ${x&&Ie(p.show_income_number)&&(s!=null&&s.income_number)?`<div class="tax-number">رقم الدخل: ${s.income_number}</div>`:""}
        ${Ie(p.show_invoice_type_badge)?`
          <div class="invoice-type">${N}</div>
        `:""}
      </div>
      
      <!-- Return Information -->
      ${a!=null&&a.is_return?`
        <div class="return-info">
          <div><strong>سبب الإرجاع:</strong> ${a.return_reason||"غير محدد"}</div>
          ${a.original_invoice_number?`<div><strong>الفاتورة الأصلية:</strong> ${a.original_invoice_number}</div>`:""}
          ${a.original_invoice_total?`<div><strong>مبلغ الفاتورة الأصلية:</strong> ${Number(a.original_invoice_total).toFixed(2)}</div>`:""}
        </div>
      `:""}
      
      <!-- Invoice Information Section -->
      <div class="section">
        <div class="section-header">معلومات الفاتورة</div>
        <div class="section-content">
          <table class="info-table">
            ${Ie(p.show_invoice_number)?`
            <tr>
              <td>رقم الفاتورة:</td>
              <td>${t}</td>
            </tr>
            `:""}
            ${Ie(p.show_invoice_date)?`
            <tr>
              <td>التاريخ:</td>
              <td>${n!=null&&n.invoice_date?n.invoice_date:new Date().toLocaleString("ar",{dateStyle:"short",timeStyle:"short"})}</td>
            </tr>
            `:""}
            ${Ie(p.show_customer_name)?`
            <tr>
              <td>العميل:</td>
              <td>${(n==null?void 0:n.customer_name)||"عميل عام"}</td>
            </tr>
            `:""}
            ${Ie(p.show_customer_number)&&(n!=null&&n.customer_number)?`
            <tr>
              <td>رقم العميل:</td>
              <td>${n.customer_number}</td>
            </tr>
            `:""}
            ${Ie(p.show_customer_phone)&&(n!=null&&n.customer_phone)?`
            <tr>
              <td>الهاتف:</td>
              <td>${n.customer_phone}</td>
            </tr>
            `:""}
            ${Ie(p.show_customer_city)&&(n!=null&&n.customer_city)?`
            <tr>
              <td>المدينة:</td>
              <td>${n.customer_city}</td>
            </tr>
            `:""}
            ${Ie(p.show_payment_method)?`
            <tr>
              <td>طريقة الدفع:</td>
              <td>${(n==null?void 0:n.payment_method)||"نقدي"}</td>
            </tr>
            `:""}
            ${Ie(p.show_currency)?`
            <tr>
              <td>العملة:</td>
              <td>${(n==null?void 0:n.currency)||(s==null?void 0:s.currency)||"JOD"}</td>
            </tr>
            `:""}
            ${d&&Ie(p.show_cashier_name)?`
            <tr>
              <td>الموظف:</td>
              <td>${d}</td>
            </tr>
            `:""}
          </table>
        </div>
      </div>
      
      <!-- Items Section -->
      <div class="section">
        <div class="section-header">تفاصيل المواد</div>
        <div class="section-content">
          <table class="items-table">
            <thead>
              <tr>
                ${C()}
              </tr>
            </thead>
            <tbody>
              ${A()}
            </tbody>
          </table>
        </div>
      </div>
      
      <!-- Totals Section -->
      <div class="section">
        <div class="section-header">المجموع</div>
        <div class="section-content">
          <table class="totals-table">
            ${Ie(p.show_subtotal)?`
            <tr>
              <td>المجموع الفرعي:</td>
              <td>${g.toFixed(2)}</td>
            </tr>
            `:""}
            ${!f&&b>0&&Ie(p.show_total_tax)?`
            <tr>
              <td>الضريبة:</td>
              <td>${Number(b).toFixed(2)}</td>
            </tr>
            `:""}
            ${_>0&&Ie(p.show_total_discount)?`
            <tr>
              <td>إجمالي الخصومات:</td>
              <td>${_.toFixed(2)}</td>
            </tr>
            `:""}
            ${Ie(p.show_final_total)?`
            <tr class="final-total">
              <td>المجموع الكلي:</td>
              <td>${Number(y).toFixed(2)}</td>
            </tr>
            `:""}
          </table>
        </div>
      </div>
      
      <!-- Payment Information Section -->
      ${Ie(p.show_payment_info)&&u&&(u.paidAmount!==void 0||u.changeAmount!==void 0)?`
      <div class="payment-info">
        <div class="payment-info-title">معلومات الدفع</div>
        ${u.paidAmount!==void 0?`
        <div class="payment-row paid-amount">
          <span class="payment-label">المبلغ المدفوع:</span>
          <span class="payment-value">${Number(u.paidAmount).toFixed(2)}</span>
        </div>
        `:""}
        ${u.changeAmount!==void 0&&Number(u.changeAmount)>0?`
        <div class="payment-row change-amount">
          <span class="payment-label">الباقي للعميل:</span>
          <span class="payment-value">${Number(u.changeAmount).toFixed(2)}</span>
        </div>
        `:""}
        ${u.changeAmount!==void 0&&Number(u.changeAmount)===0?`
        <div class="payment-row change-amount">
          <span class="payment-label">✓ دفع بالضبط</span>
          <span class="payment-value">0.00</span>
        </div>
        `:""}
      </div>
      `:""}
      
      <!-- Notes Section -->
      ${Ie(p.show_notes)&&c?`
      <div class="notes-section">
        <strong>ملاحظات:</strong><br>
        ${c}
      </div>
      `:""}
      
      <!-- QR Code Section -->
      ${Ie(p.show_qr_code)&&o?`
      <div class="qr-section">
        <img src="${o.startsWith("data:")||o.startsWith("http")?o:Kx(o)}" 
          alt="QR Code" class="qr-code">
      </div>
      `:""}
      
      <!-- Footer -->
      <div class="footer">
        ${Ie(p.show_thank_you_message)?`
          <div style="font-weight: bold; margin-bottom: 5px;">${p.custom_thank_you_message||"شكراً لتعاملكم معنا"}</div>
        `:""}
        <div>هذه الفاتورة صادرة إلكترونياً</div>
        ${Ie(p.show_footer_text)&&(p.custom_footer_text||s!=null&&s.footer_text)?`
          <div style="margin-top: 5px;">${p.custom_footer_text||s.footer_text}</div>
        `:""}
      </div>
    </body>
    </html>
  `},Ei=({invoice:t,variant:r="outline",size:n="sm",className:i=""})=>{const{seller:o}=Ot(),{currentEmployee:a}=lt(),{toast:s}=et(),[c,l]=v.useState(!1);if(!o||!o.enable_thermal_printing)return null;const m=async()=>{l(!0);try{console.log("🖨️ Starting thermal print for invoice:",t.invoice_number);const u=localStorage.getItem(xe),d=await fetch(`${nt}${W.GET_ALL("invoice_items")}&token=${u}&invoice_id=${t.id}`,{method:"GET"});if(!d.ok)throw new Error("Failed to fetch items");const p=(await d.json()).data||[],f=p.filter(k=>k.invoice_id===t.id);console.log("📄 Items fetched:",p.length,"→ Filtered for invoice:",f.length);const x=t.seller_id||o.id,g=await fetch(`${nt}${W.GET_BY_ID("sellers",x)}&token=${u}`,{method:"GET"});if(!g.ok)throw new Error("Failed to fetch seller");const y=(await g.json()).data;y&&(y.enable_bw_print=y.enable_bw_print==1||y.enable_bw_print===!0||y.enable_bw_print==="1",y.enable_fawatrah=y.enable_fawatrah==1||y.enable_fawatrah===!0||y.enable_fawatrah==="1"),console.log("🏢 Seller data fetched:",y==null?void 0:y.seller_name,"B&W Print:",y==null?void 0:y.enable_bw_print);const _={customer_id:t.id,customer_name:t.customer_name,customer_number:t.customer_number,customer_type:t.customer_type,phone_number:t.phone_number||"",city:t.city||"",payment_method:t.payment_method,invoice_date:t.invoice_date,is_return:t.is_return,return_reason:t.return_reason,return_payment_type:t.return_payment_type,original_invoice_number:t.original_invoice_number};let j=t.qr_code;!j&&t.api_response&&(j=qt(t.api_response)),!j&&t.qr_code_image&&(j=t.qr_code_image),console.log("🔍 QR Data available:",!!j);const w=(y==null?void 0:y.invoice_type)==="دخل"||(y==null?void 0:y.invoice_type)==="income"?"income":"general_tax",N={tax_exclusive_amount:t.tax_exclusive_amount||0,total_tax_amount:t.total_tax_amount||0,tax_inclusive_amount:t.tax_inclusive_amount||t.total_amount||0,allowance_charge_amount:t.allowance_charge_amount||0},C=await Ao(x);console.log("⚙️ Display settings fetched:",C?"yes":"using defaults");const A=y!=null&&y.show_cashier_name&&a?a.employee_name:void 0,F=Sl(t.invoice_number,t.total_amount,_,f,j,{is_return:t.is_return,return_reason:t.return_reason,original_invoice_number:t.original_invoice_number,original_invoice_total:t.total_amount},y,t.notes,N,w,void 0,A,C),T=window.open("","_blank","width=400,height=600");if(T)T.document.write(F),T.document.close(),T.onload=()=>{setTimeout(()=>{try{T.focus(),T.print()}catch(k){console.error("❌ Print error:",k),s({title:"تحذير",description:"تم فتح النافذة، يرجى الطباعة يدوياً",variant:"destructive"})}},500)},setTimeout(()=>{if(T&&!T.closed)try{T.focus(),T.print()}catch(k){console.warn("Fallback print attempt failed:",k)}},1e3);else throw new Error("فشل في فتح نافذة الطباعة");s({title:"تم فتح الإيصال الحراري",description:"تم فتح نافذة الطباعة الحرارية"})}catch(u){console.error("❌ Error generating thermal receipt:",u),s({title:"خطأ",description:"فشل في إنشاء الإيصال الحراري",variant:"destructive"})}finally{l(!1)}};return e.jsxs(V,{variant:r,size:n,className:`text-orange-600 border-orange-300 hover:bg-orange-50 ${i}`,onClick:m,disabled:c,title:"طباعة إيصال حراري",children:[c?e.jsx(ct,{className:"h-4 w-4 animate-spin"}):e.jsx(Zr,{className:"h-4 w-4"}),"طباعة حرارية"]})},Yx=({invoiceId:t,onBack:r})=>{const[n,i]=v.useState(null),[o,a]=v.useState([]),[s,c]=v.useState(null),[l,m]=v.useState(!0),{toast:u}=et(),[d,h]=v.useState(void 0),p=Dr(),[f,x]=v.useState(!1),[g,b]=v.useState(null);v.useEffect(()=>{window.scrollTo({top:0,behavior:"smooth"}),y()},[t]);const y=async()=>{try{m(!0);const F=localStorage.getItem(xe),T=`${oe()}${W.GET_BY_ID("invoices",t)}&token=${F||""}`,P=await(await fetch(T)).json();if(!P.success||!P.data)throw new Error("Invoice not found");const S=P.data;i(S);const E=S.seller_id;if(E){const M=`${oe()}${W.GET_BY_ID("sellers",E)}&token=${F||""}`,U=await(await fetch(M)).json();U.success&&U.data&&(console.log("Fetched seller data with logos:",U.data),c(U.data))}let O;S&&S.api_response?O=qt(S.api_response)||void 0:S&&S.qr_code_image?O=S.qr_code_image:O=void 0,h(O);const R=`${oe()}${W.GET_ALL("invoice_items")}&token=${F||""}`,$=await(await fetch(R)).json();if($.success&&$.data){const X=$.data.filter(U=>U.invoice_id===t).sort((U,Q)=>(U.line_number||0)-(Q.line_number||0)).map(U=>({id:U.id,product_id:U.product_id||"",item_name:U.item_name,quantity:U.quantity,unit_price:U.unit_price,xml_unit_price:U.xml_unit_price,discount_amount:U.discount_amount||0,tax_percent:U.tax_percent||0,line_total:U.line_total,line_extension_amount:U.line_extension_amount||0,tax_amount:U.tax_amount||0,rounding_amount:U.rounding_amount||0,price_before_tax:U.price_before_tax||0,price_after_tax:U.price_after_tax||0,tax_calculation_mode:U.tax_calculation_mode||"tax_exclusive"}));a(X)}}catch(F){console.error("Error loading invoice data:",F),u({title:"خطأ",description:"فشل في تحميل بيانات الفاتورة",variant:"destructive"}),r()}finally{m(!1)}},_=async()=>{if(!(!n||!s))try{const F={customer_id:n.id,customer_name:n.customer_name,customer_number:n.customer_number,customer_type:n.customer_type,phone_number:n.phone_number||"",city:n.city||"",payment_method:n.payment_method,invoice_date:n.invoice_date,is_return:n.is_return,return_reason:n.return_reason,return_payment_type:n.return_payment_type,original_invoice_number:n.original_invoice_number},T={...s,seller_logo_url:s.seller_logo_url||null,fawtra_logo_url:s.fawtra_logo_url||"/fawtra-logo.png",show_company_logo:s.show_company_logo!==!1},k={tax_exclusive_amount:n.tax_exclusive_amount,total_tax_amount:n.total_tax_amount,tax_inclusive_amount:n.tax_inclusive_amount,allowance_charge_amount:n.allowance_charge_amount},P=await Ao(n.seller_id||(s==null?void 0:s.id)),S=$x(n.invoice_number,n.total_amount,F,o,d,{is_return:n.is_return,return_reason:n.return_reason,original_invoice_number:n.original_invoice_number},T,n.notes||void 0,k,s.invoice_type,P);b(S),x(!0)}catch(F){console.error("Error generating HTML invoice:",F),u({title:"خطأ",description:"فشل في توليد الفاتورة",variant:"destructive"})}},{seller:j}=Ot(),I=(j==null?void 0:j.enable_fawatrah)===!0||(j==null?void 0:j.enable_fawatrah)==1,w=(F,T)=>{if(T)return e.jsx(Ae,{className:"bg-orange-100 text-orange-800 border-orange-300",children:"فاتورة إرجاع"});if(!I)return e.jsx(Ae,{className:"bg-blue-100 text-blue-800 border-blue-300",children:"فاتورة"});switch(F){case"فاتورة جديدة - غير مرسلة":return e.jsx(Ae,{className:"bg-blue-100 text-blue-800 border-blue-300",children:"جديدة - غير مرسلة"});case"مرسلة إلى فوترة":return e.jsx(Ae,{className:"bg-green-100 text-green-800 border-green-300",children:"مرسلة إلى فوترة"});case"مرسلة للحكومة":return e.jsx(Ae,{className:"bg-blue-100 text-blue-800 border-blue-300",children:"مرسلة للحكومة"});case"مرسلة":return e.jsx(Ae,{className:"bg-green-100 text-green-800 border-green-300",children:"مرسلة"});case"مسودة":return e.jsx(Ae,{className:"bg-yellow-100 text-yellow-800 border-yellow-300",children:"مسودة"});default:return e.jsx(Ae,{variant:"secondary",children:F})}},N=(s==null?void 0:s.invoice_type)==="income"||(s==null?void 0:s.invoice_type)==="دخل",C=()=>n?{subtotal:Number(n.tax_exclusive_amount||0),totalTax:Number(n.total_tax_amount||0),total:Number(n.tax_inclusive_amount||n.total_amount||0)}:{subtotal:0,totalTax:0,total:0};if(l)return e.jsx("div",{className:"flex items-center justify-center h-64",children:e.jsx("div",{className:"animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600"})});if(!n)return e.jsxs("div",{className:"text-center p-8",children:[e.jsx("p",{className:"text-red-500",children:"لم يتم العثور على الفاتورة"}),e.jsx(V,{onClick:r,className:"mt-4",children:"العودة"})]});const A=C();return e.jsxs("div",{className:"space-y-4 md:space-y-6 font-cairo",dir:"rtl",children:[e.jsxs("div",{className:`mb-6 ${p?"space-y-4":"flex items-center justify-between"}`,children:[e.jsxs(V,{onClick:r,variant:"outline",className:`flex items-center gap-2 ${p?"w-full justify-center py-3":""}`,children:[e.jsx(qo,{className:"h-4 w-4"}),"العودة للرئيسية"]}),p?e.jsxs("div",{className:"space-y-3",children:[e.jsx("h1",{className:"text-xl font-bold text-blue-900 text-center",children:"عرض الفاتورة"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(V,{onClick:_,className:"flex-1 bg-gradient-to-r from-green-500 to-emerald-600 hover:from-green-600 hover:to-emerald-700 text-white shadow-lg transition-all duration-200 py-3",children:[e.jsx(fo,{className:"h-5 w-5 ml-2"}),"معاينة A4"]}),e.jsx(Ei,{invoice:n,variant:"default",size:"default",className:"flex-1 bg-gradient-to-r from-blue-500 to-blue-600 hover:from-blue-600 hover:to-blue-700 text-white shadow-lg transition-all duration-200 py-3"})]})]}):e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("h1",{className:"text-2xl font-bold text-blue-900",children:"عرض الفاتورة"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(V,{onClick:_,className:"bg-gradient-to-r from-green-500 to-emerald-600 hover:from-green-600 hover:to-emerald-700 text-white shadow-lg transition-all duration-200 px-6 py-3",children:[e.jsx(fo,{className:"h-5 w-5 ml-2"}),"معاينة A4"]}),e.jsx(Ei,{invoice:n,variant:"default",size:"default",className:"bg-gradient-to-r from-blue-500 to-blue-600 hover:from-blue-600 hover:to-blue-700 text-white shadow-lg transition-all duration-200 px-6 py-3"})]})]})]}),e.jsxs(fe,{className:"bg-gradient-to-r from-blue-50 to-indigo-50 border-2 border-blue-200",children:[e.jsx(De,{children:e.jsxs($e,{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2 text-blue-900",children:[e.jsx(It,{className:"h-6 w-6"}),"فاتورة رقم: ",n.invoice_number]}),w(n.status,n.is_return)]})}),e.jsx(ve,{children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-gray-600",children:"تاريخ الفاتورة"}),e.jsx("p",{className:"font-medium",children:new Date(n.invoice_date).toLocaleDateString("ar",{calendar:"gregory"})})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-gray-600",children:"اسم العميل"}),e.jsx("p",{className:"font-medium",children:n.customer_name})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-gray-600",children:"رقم العميل"}),e.jsx("p",{className:"font-medium",children:n.customer_number})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-gray-600",children:"نوع العميل"}),e.jsx("p",{className:"font-medium",children:n.customer_type})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-gray-600",children:"رقم الهاتف"}),e.jsx("p",{className:"font-medium",children:n.phone_number||"غير محدد"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-gray-600",children:"المدينة"}),e.jsx("p",{className:"font-medium",children:n.city||"غير محدد"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-gray-600",children:"طريقة الدفع"}),e.jsx("p",{className:"font-medium",children:n.payment_method})]}),n.is_return&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-gray-600",children:"سبب الإرجاع"}),e.jsx("p",{className:"font-medium text-orange-600",children:n.return_reason})]}),n.original_invoice_number&&e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-gray-600",children:"الفاتورة الأصلية"}),e.jsx("p",{className:"font-medium",children:n.original_invoice_number})]})]})]})})]}),e.jsxs(fe,{className:"bg-gradient-to-r from-purple-50 to-pink-50 border-2 border-purple-200",children:[e.jsx(De,{children:e.jsx($e,{className:"text-purple-900",children:"عناصر الفاتورة"})}),e.jsx(ve,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full border-collapse",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b-2 border-purple-200",children:[e.jsx("th",{className:"text-right p-2 font-semibold",children:"المنتج"}),e.jsx("th",{className:"text-right p-2 font-semibold",children:"الكمية"}),e.jsx("th",{className:"text-right p-2 font-semibold",children:"السعر"}),!N&&e.jsx("th",{className:"text-right p-2 font-semibold",children:"الضريبة"}),e.jsx("th",{className:"text-right p-2 font-semibold",children:"المجموع"})]})}),e.jsx("tbody",{children:o.map((F,T)=>{const k=Number(parseFloat(F.xml_unit_price||"0")||F.unit_price||0),P=Number(F.discount_amount||0),S=Number(F.tax_amount||0),E=Number(F.rounding_amount||F.price_after_tax||0),O=N?4:5;return e.jsxs(we.Fragment,{children:[e.jsxs("tr",{className:"border-b border-purple-100",children:[e.jsx("td",{className:"p-2",children:F.item_name}),e.jsx("td",{className:"p-2",children:F.quantity}),e.jsxs("td",{className:"p-2",children:[k.toFixed(2)," د.أ"]}),!N&&e.jsxs("td",{className:"p-2",children:[F.tax_percent,"%"]}),e.jsxs("td",{className:"p-2 font-semibold",children:[E.toFixed(2)," د.أ"]})]}),P>0&&e.jsx("tr",{className:"bg-amber-50 text-amber-800 text-sm",children:e.jsxs("td",{colSpan:O,className:"p-2 pr-8",children:["↳ خصم: -",P.toFixed(2)," د.أ"]})}),!N&&S>0&&e.jsx("tr",{className:"bg-blue-50 text-blue-800 text-sm",children:e.jsxs("td",{colSpan:O,className:"p-2 pr-8",children:["↳ ضريبة (",F.tax_percent,"%): ",S.toFixed(2)," د.أ"]})})]},T)})})]})})})]}),e.jsxs(fe,{className:"bg-gradient-to-r from-green-50 to-emerald-50 border-2 border-green-200",children:[e.jsx(De,{children:e.jsx($e,{className:"text-green-900",children:"ملخص الفاتورة"})}),e.jsx(ve,{children:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{children:"المجموع قبل الضريبة:"}),e.jsxs("span",{className:"font-medium",children:[A.subtotal.toFixed(2)," د.أ"]})]}),!N&&e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{children:"مجموع الضريبة:"}),e.jsxs("span",{className:"font-medium",children:[A.totalTax.toFixed(2)," د.أ"]})]}),e.jsxs("div",{className:"flex justify-between text-lg font-bold border-t pt-2",children:[e.jsx("span",{children:"المجموع الإجمالي:"}),e.jsxs("span",{className:"text-green-700",children:[A.total.toFixed(2)," د.أ"]})]})]})})]}),n.notes&&e.jsxs(fe,{className:"bg-gradient-to-r from-yellow-50 to-amber-50 border-2 border-yellow-200",children:[e.jsx(De,{children:e.jsx($e,{className:"text-yellow-900",children:"ملاحظات الفاتورة"})}),e.jsx(ve,{children:e.jsx("p",{className:"whitespace-pre-wrap",children:n.notes})})]}),e.jsx(El,{open:f,onOpenChange:x,htmlContent:g||"",invoiceNumber:n.invoice_number})]})};function kl(){const{user:t,sellerData:r}=tr(),n=dn(),i=(r==null?void 0:r.id)||(t==null?void 0:t.seller_id)||(t==null?void 0:t.id),o=vr({queryKey:["customers",i],queryFn:async()=>{if(!i)return[];const l=localStorage.getItem(xe),m=Date.now(),u=`${oe()}${W.GET_ALL("customers")}&filters=${encodeURIComponent(JSON.stringify({seller_id:i}))}&orderBy=created_at&orderDir=DESC&_t=${m}`,d=await fetch(u,{headers:l?{Authorization:`Bearer ${l}`}:{}});if(!d.ok)throw new Error("Failed to fetch customers");return(await d.json()).data||[]},enabled:!!i}),a=$t({mutationFn:async l=>{const m=localStorage.getItem(xe),u=await fetch(`${oe()}${W.CREATE("customers")}`,{method:"POST",headers:{"Content-Type":"application/json",...m?{Authorization:`Bearer ${m}`}:{}},body:JSON.stringify({...l,seller_id:i})});if(!u.ok)throw new Error("Failed to create customer");return u.json()},onSuccess:()=>{n.invalidateQueries({queryKey:["customers",i]})}}),s=$t({mutationFn:async({id:l,...m})=>{const u=localStorage.getItem(xe),d=await fetch(`${oe()}${W.UPDATE("customers",l)}`,{method:"POST",headers:{"Content-Type":"application/json",...u?{Authorization:`Bearer ${u}`}:{}},body:JSON.stringify(m)});if(!d.ok)throw new Error("Failed to update customer");return d.json()},onSuccess:()=>{n.invalidateQueries({queryKey:["customers",i]})}}),c=$t({mutationFn:async l=>{const m=localStorage.getItem(xe),u=await fetch(`${oe()}${W.DELETE("customers",l)}`,{method:"POST",headers:m?{Authorization:`Bearer ${m}`}:{}});if(!u.ok)throw new Error("Failed to delete customer");return u.json()},onSuccess:()=>{n.invalidateQueries({queryKey:["customers",i]})}});return{...o,data:o.data||[],customers:o.data||[],createCustomer:a.mutateAsync,updateCustomer:s.mutateAsync,deleteCustomer:c.mutateAsync}}const Kr=()=>{if(Rr())try{const t=new(window.AudioContext||window.webkitAudioContext),r=t.createOscillator(),n=t.createOscillator(),i=t.createGain();r.connect(i),n.connect(i),i.connect(t.destination),r.frequency.value=1800,n.frequency.value=2400,r.type="sine",n.type="sine",i.gain.setValueAtTime(.4,t.currentTime),i.gain.exponentialRampToValueAtTime(.01,t.currentTime+.15),r.start(t.currentTime),n.start(t.currentTime),r.stop(t.currentTime+.15),n.stop(t.currentTime+.15)}catch(t){console.warn("Sound play failed:",t)}},Eo=()=>{if(Rr())try{const t=new(window.AudioContext||window.webkitAudioContext),r=t.createOscillator(),n=t.createGain();r.connect(n),n.connect(t.destination),r.frequency.setValueAtTime(523.25,t.currentTime),r.frequency.setValueAtTime(659.25,t.currentTime+.1),r.type="sine",n.gain.setValueAtTime(.2,t.currentTime),n.gain.exponentialRampToValueAtTime(.01,t.currentTime+.3),r.start(t.currentTime),r.stop(t.currentTime+.3)}catch(t){console.warn("Sound play failed:",t)}},Et=()=>{if(Rr())try{const t=new(window.AudioContext||window.webkitAudioContext),r=t.createGain();r.connect(t.destination);const n=t.createOscillator();n.connect(r),n.frequency.value=400,n.type="square";const i=t.createOscillator();i.connect(r),i.frequency.value=250,i.type="square",r.gain.setValueAtTime(.35,t.currentTime),r.gain.setValueAtTime(.35,t.currentTime+.15),r.gain.exponentialRampToValueAtTime(.01,t.currentTime+.35),n.start(t.currentTime),n.stop(t.currentTime+.1),i.start(t.currentTime+.15),i.stop(t.currentTime+.3)}catch(t){console.warn("Sound play failed:",t)}},Qx=()=>{if(Rr())try{const t=new(window.AudioContext||window.webkitAudioContext),r=t.createOscillator(),n=t.createGain();r.connect(n),n.connect(t.destination),r.frequency.value=1e3,r.type="sine",n.gain.setValueAtTime(.1,t.currentTime),n.gain.exponentialRampToValueAtTime(.01,t.currentTime+.05),r.start(t.currentTime),r.stop(t.currentTime+.05)}catch(t){console.warn("Sound play failed:",t)}},Zx=t=>{localStorage.setItem("pos_sounds_enabled",t?"true":"false")},Rr=()=>{const t=localStorage.getItem("pos_sounds_enabled");return t===null?!0:t==="true"};Rr();const ua=({onRefresh:t,threshold:r=80,resistance:n=2.5,enabled:i=!0})=>{const[o,a]=v.useState({isPulling:!1,pullDistance:0,isRefreshing:!1,canRefresh:!1}),s=v.useRef(0),c=v.useRef(null),l=v.useCallback((h="medium")=>{if("vibrate"in navigator){const p={light:[10],medium:[20],heavy:[30,10,30]};navigator.vibrate(p[h])}},[]),m=v.useCallback(h=>{if(!i)return;const p=c.current;if(!p)return;(p.scrollTop||window.scrollY||document.documentElement.scrollTop)<=0&&(s.current=h.touches[0].clientY,a(x=>({...x,isPulling:!0})))},[i]),u=v.useCallback(h=>{if(!i||!o.isPulling||o.isRefreshing)return;const f=h.touches[0].clientY-s.current;if(f>0){const x=Math.min(f/n,r*1.5),g=x>=r;a(b=>({...b,pullDistance:x,canRefresh:g})),g&&!o.canRefresh&&l("medium")}},[i,o.isPulling,o.isRefreshing,o.canRefresh,n,r,l]),d=v.useCallback(async()=>{if(!(!i||!o.isPulling||o.isRefreshing))if(o.canRefresh){a(h=>({...h,isRefreshing:!0,isPulling:!1})),l("heavy");try{await t(),Kr()}catch(h){console.error("Refresh error:",h)}finally{a(h=>({...h,isRefreshing:!1,pullDistance:0,canRefresh:!1})),l("light")}}else a(h=>({...h,isPulling:!1,pullDistance:0,canRefresh:!1}))},[i,o.isPulling,o.isRefreshing,o.canRefresh,t,l]);return v.useEffect(()=>{const h=c.current||document.documentElement;return h.addEventListener("touchstart",m,{passive:!0}),h.addEventListener("touchmove",u,{passive:!0}),h.addEventListener("touchend",d,{passive:!0}),()=>{h.removeEventListener("touchstart",m),h.removeEventListener("touchmove",u),h.removeEventListener("touchend",d)}},[m,u,d]),{...o,containerRef:c,progress:Math.min(o.pullDistance/r*100,100)}},ma=({isPulling:t,pullDistance:r,isRefreshing:n,canRefresh:i,progress:o})=>!t&&!n?null:e.jsx("div",{className:Z("fixed top-0 left-0 right-0 z-50 flex items-center justify-center transition-all duration-300","bg-gradient-to-b from-blue-50/95 to-transparent dark:from-blue-950/95 backdrop-blur-sm"),style:{height:`${Math.max(r,n?80:0)}px`,opacity:t||n?1:0},children:e.jsxs("div",{className:"flex flex-col items-center gap-2 py-4",children:[e.jsx("div",{className:Z("transition-all duration-300",i&&"scale-110"),style:{transform:`rotate(${Math.min(o*3.6,360)}deg)`,transition:n?"none":"transform 0.1s linear"},children:n?e.jsx(ct,{className:"h-6 w-6 text-blue-600 animate-spin"}):i?e.jsx(_r,{className:"h-6 w-6 text-green-600"}):e.jsx(Bu,{className:"h-6 w-6 text-blue-600"})}),e.jsx("div",{className:"w-32 h-1 bg-gray-200 dark:bg-gray-700 rounded-full overflow-hidden",children:e.jsx("div",{className:Z("h-full transition-all duration-100 rounded-full",i?"bg-green-500":"bg-blue-500"),style:{width:`${o}%`}})}),e.jsx("p",{className:Z("text-xs font-medium transition-colors duration-200",n&&"text-blue-600 dark:text-blue-400",i&&!n&&"text-green-600 dark:text-green-400",!i&&!n&&"text-gray-600 dark:text-gray-400"),children:n?"جاري التحديث...":i?"اترك للتحديث":"اسحب للأسفل للتحديث"})]})}),eg=["البلقاء","معان","مادبا","المفرق","الكرك","جرش","إربد","الزرقاء","الطفيلة","العقبة","عمان","عجلون"],tg=()=>{const{toast:t}=et(),r=Mt(),{silentCheck:n,checkPermission:i}=Kn(),[o,a]=v.useState(null),[s,c]=v.useState(!1),[l,m]=v.useState(""),[u,d]=v.useState({customer_name:"",customer_number:"",customer_type:"NIN",phone_number:"",city:"",postal_code:""}),{data:h=[],isLoading:p,refetch:f}=kl(),x=Dr(),g=n("can_manage_customers"),b=n("can_delete_customers"),y=v.useCallback(async()=>{await f()},[f]),{isPulling:_,pullDistance:j,isRefreshing:I,canRefresh:w,progress:N}=ua({onRefresh:y,enabled:x}),C=async()=>{if(i("can_manage_customers","ليس لديك صلاحية إضافة أو تعديل العملاء")){if(!u.customer_name.trim()){t({title:"خطأ",description:"يرجى إدخال اسم العميل",variant:"destructive"});return}if(!r){t({title:"خطأ",description:"تعذر تحديد البائع الحالي. أعد تسجيل الدخول.",variant:"destructive"});return}try{const S=localStorage.getItem(xe),E={customer_name:u.customer_name,customer_number:u.customer_number,customer_type:u.customer_type,phone_number:u.phone_number,city:u.city,postal_code:u.postal_code,seller_id:r};if(o){if(!(await fetch(`${oe()}${W.UPDATE("customers",o.id)}`,{method:"POST",headers:{"Content-Type":"application/json",...S?{Authorization:`Bearer ${S}`}:{}},body:JSON.stringify(E)})).ok)throw new Error("Failed to update customer");t({title:"تم التحديث",description:"تم تحديث بيانات العميل بنجاح"})}else{if(!(await fetch(`${oe()}${W.CREATE("customers")}`,{method:"POST",headers:{"Content-Type":"application/json",...S?{Authorization:`Bearer ${S}`}:{}},body:JSON.stringify(E)})).ok)throw new Error("Failed to create customer");t({title:"تم الإضافة",description:"تم إضافة العميل بنجاح"})}c(!1),a(null),d({customer_name:"",customer_number:"",customer_type:"NIN",phone_number:"",city:"",postal_code:""}),await f()}catch(S){console.error("Error saving customer:",S),t({title:"خطأ",description:"فشل في حفظ بيانات العميل",variant:"destructive"})}}},A=S=>{a(S),d({customer_name:S.customer_name,customer_number:S.customer_number,customer_type:S.customer_type,phone_number:S.phone_number||"",city:S.city||"",postal_code:S.postal_code||""}),c(!0)},F=async S=>{if(i("can_delete_customers","ليس لديك صلاحية حذف العملاء")&&confirm("هل أنت متأكد من حذف هذا العميل؟"))try{const E=localStorage.getItem(xe);if(!(await fetch(`${oe()}${W.DELETE("customers",S)}`,{method:"POST",headers:E?{Authorization:`Bearer ${E}`}:{}})).ok)throw new Error("Failed to delete customer");t({title:"تم الحذف",description:"تم حذف العميل بنجاح"}),await f()}catch(E){console.error("Error deleting customer:",E),t({title:"خطأ",description:"فشل في حذف العميل",variant:"destructive"})}},T=S=>{switch(S){case"NIN":return"الرقم الوطني للمشتري";case"TN":return"الرقم الضريبي للمشتري";case"PASSPORT":return"الرقم الشخصي لغير الأردني";default:return S}},k=S=>{switch(S){case"NIN":return"bg-gradient-to-r from-blue-500 to-blue-600 text-white";case"TN":return"bg-gradient-to-r from-green-500 to-green-600 text-white";case"PASSPORT":return"bg-gradient-to-r from-purple-500 to-purple-600 text-white";default:return"bg-gradient-to-r from-gray-500 to-gray-600 text-white"}},P=v.useMemo(()=>{if(!h||h.length===0)return[];if(!l.trim())return h;const S=l.toLowerCase();return h.filter(E=>{var O;return E.customer_name.toLowerCase().includes(S)||E.customer_number.toLowerCase().includes(S)||((O=E.city)==null?void 0:O.toLowerCase().includes(S))||!1})},[h,l]);return v.useMemo(()=>({total:P.length,nin:P.filter(S=>S.customer_type==="NIN").length,tn:P.filter(S=>S.customer_type==="TN").length,passport:P.filter(S=>S.customer_type==="PASSPORT").length}),[P]),v.useCallback(S=>{A(S)},[]),v.useCallback(S=>{F(S)},[]),p?e.jsx("div",{className:"flex items-center justify-center h-64",children:e.jsx("div",{className:"animate-spin rounded-full h-12 w-12 border-b-2 border-indigo-600"})}):e.jsxs(e.Fragment,{children:[e.jsx(ma,{isPulling:_,pullDistance:j,isRefreshing:I,canRefresh:w,progress:N}),e.jsxs("div",{className:"space-y-4 md:space-y-6",dir:"rtl",children:[e.jsxs(fe,{className:"bg-gradient-to-r from-indigo-50 to-blue-50 border-2 border-indigo-200",children:[e.jsx(De,{className:"p-4 md:p-6",children:e.jsxs($e,{className:"flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3 text-indigo-900",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Rt,{className:"h-5 w-5 md:h-6 md:w-6"}),e.jsx("span",{className:"text-lg md:text-xl",children:"إدارة العملاء"})]}),g&&e.jsxs(gt,{open:s,onOpenChange:c,children:[e.jsx(mn,{asChild:!0,children:e.jsxs(V,{className:"w-full sm:w-auto min-h-[44px] bg-gradient-to-r from-indigo-500 to-indigo-600 hover:from-indigo-600 hover:to-indigo-700",onClick:()=>{a(null),d({customer_name:"",customer_number:"",customer_type:"NIN",phone_number:"",city:"",postal_code:""})},children:[e.jsx(kt,{className:"h-5 w-5 ml-1"}),"إضافة عميل جديد"]})}),e.jsxs(bt,{dir:"rtl",className:"max-w-[95vw] sm:max-w-md max-h-[90vh] overflow-y-auto p-4 sm:p-6",children:[e.jsxs(Tt,{children:[e.jsx(At,{children:o?"تعديل بيانات العميل":"إضافة عميل جديد"}),e.jsx(kn,{children:o?"قم بتعديل بيانات العميل":"أدخل بيانات العميل الجديد"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(_e,{htmlFor:"customer_name",className:"text-indigo-900 font-semibold",children:"اسم العميل *"}),e.jsx(Te,{id:"customer_name",value:u.customer_name,onChange:S=>d({...u,customer_name:S.target.value}),placeholder:"أدخل اسم العميل",className:"border-2 border-indigo-200 focus:border-indigo-400"})]}),e.jsxs("div",{children:[e.jsx(_e,{htmlFor:"customer_number",className:"text-indigo-900 font-semibold",children:"رقم العميل"}),e.jsx(Te,{id:"customer_number",value:u.customer_number,onChange:S=>d({...u,customer_number:S.target.value}),placeholder:"أدخل رقم العميل",className:"border-2 border-indigo-200 focus:border-indigo-400"})]}),e.jsxs("div",{children:[e.jsx(_e,{htmlFor:"customer_type",className:"text-indigo-900 font-semibold",children:"نوع الرقم"}),e.jsxs(vt,{value:u.customer_type,onValueChange:S=>d({...u,customer_type:S}),children:[e.jsx(_t,{className:"border-2 border-indigo-200 focus:border-indigo-400",children:e.jsx(wt,{})}),e.jsxs(jt,{children:[e.jsx(Je,{value:"NIN",children:"الرقم الوطني للمشتري"}),e.jsx(Je,{value:"TN",children:"الرقم الضريبي للمشتري"}),e.jsx(Je,{value:"PASSPORT",children:"الرقم الشخصي لغير الأردني"})]})]})]}),e.jsxs("div",{children:[e.jsx(_e,{htmlFor:"phone_number",className:"text-indigo-900 font-semibold",children:"رقم الهاتف"}),e.jsx(Te,{id:"phone_number",value:u.phone_number,onChange:S=>d({...u,phone_number:S.target.value}),placeholder:"+962791234567",className:"border-2 border-indigo-200 focus:border-indigo-400"})]}),e.jsxs("div",{children:[e.jsx(_e,{htmlFor:"city",className:"text-indigo-900 font-semibold",children:"المدينة"}),e.jsxs(vt,{value:u.city,onValueChange:S=>d({...u,city:S}),children:[e.jsx(_t,{className:"border-2 border-indigo-200 focus:border-indigo-400",children:e.jsx(wt,{placeholder:"اختر المدينة"})}),e.jsx(jt,{className:"bg-white z-50",children:eg.map(S=>e.jsx(Je,{value:S,children:S},S))})]})]}),e.jsxs("div",{children:[e.jsx(_e,{htmlFor:"postal_code",className:"text-indigo-900 font-semibold",children:"الرمز البريدي"}),e.jsx(Te,{id:"postal_code",value:u.postal_code,onChange:S=>d({...u,postal_code:S.target.value}),placeholder:"11195",className:"border-2 border-indigo-200 focus:border-indigo-400"})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsxs(V,{onClick:C,className:"flex-1 min-h-[44px] bg-gradient-to-r from-green-500 to-green-600 hover:from-green-600 hover:to-green-700",children:[e.jsx(Dn,{className:"h-5 w-5 ml-1"}),o?"تحديث":"حفظ"]}),e.jsxs(V,{variant:"outline",onClick:()=>c(!1),className:"flex-1 min-h-[44px] border-2 border-gray-300",children:[e.jsx(at,{className:"h-5 w-5 ml-1"}),"إلغاء"]})]})]})]})]})]})}),e.jsx(ve,{className:"p-4 md:p-6 pt-0",children:e.jsxs("div",{className:"relative",children:[e.jsx(zt,{className:"absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 h-5 w-5"}),e.jsx(Te,{placeholder:"البحث في العملاء...",value:l,onChange:S=>m(S.target.value),className:"pr-10 h-11 md:h-10 border-2 border-indigo-200 focus:border-indigo-400"})]})})]}),e.jsxs("div",{className:"grid grid-cols-2 lg:grid-cols-4 gap-3 md:gap-4",children:[e.jsx(fe,{className:"bg-gradient-to-r from-blue-500 to-blue-600 text-white",children:e.jsx(ve,{className:"p-3 md:p-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs md:text-sm opacity-90",children:"إجمالي العملاء"}),e.jsx("p",{className:"text-xl md:text-2xl font-bold",children:P.length})]}),e.jsx(Rt,{className:"h-6 w-6 md:h-8 md:w-8 opacity-80"})]})})}),e.jsx(fe,{className:"bg-gradient-to-r from-green-500 to-green-600 text-white",children:e.jsx(ve,{className:"p-3 md:p-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs md:text-sm opacity-90",children:"رقم وطني"}),e.jsx("p",{className:"text-xl md:text-2xl font-bold",children:P.filter(S=>S.customer_type==="NIN").length})]}),e.jsx(Rt,{className:"h-6 w-6 md:h-8 md:w-8 opacity-80"})]})})}),e.jsx(fe,{className:"bg-gradient-to-r from-purple-500 to-purple-600 text-white",children:e.jsx(ve,{className:"p-3 md:p-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs md:text-sm opacity-90",children:"رقم ضريبي"}),e.jsx("p",{className:"text-xl md:text-2xl font-bold",children:P.filter(S=>S.customer_type==="TN").length})]}),e.jsx(Rt,{className:"h-6 w-6 md:h-8 md:w-8 opacity-80"})]})})}),e.jsx(fe,{className:"bg-gradient-to-r from-orange-500 to-orange-600 text-white",children:e.jsx(ve,{className:"p-3 md:p-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs md:text-sm opacity-90",children:"جواز سفر"}),e.jsx("p",{className:"text-xl md:text-2xl font-bold",children:P.filter(S=>S.customer_type==="PASSPORT").length})]}),e.jsx(Rt,{className:"h-6 w-6 md:h-8 md:w-8 opacity-80"})]})})})]}),e.jsx(fe,{className:"shadow-xl border-2 border-gray-200",children:e.jsx(ve,{className:"p-0",children:e.jsxs("div",{className:"overflow-x-auto",children:[e.jsx("div",{className:"hidden md:block",children:e.jsxs(Io,{children:[e.jsx(Oo,{children:e.jsxs(ar,{className:"bg-gradient-to-r from-indigo-50 to-blue-50",children:[e.jsx(rt,{className:"text-right font-bold text-indigo-900",children:"اسم العميل"}),e.jsx(rt,{className:"text-right font-bold text-indigo-900",children:"رقم العميل"}),e.jsx(rt,{className:"text-right font-bold text-indigo-900",children:"نوع الرقم"}),e.jsx(rt,{className:"text-right font-bold text-indigo-900",children:"الهاتف"}),e.jsx(rt,{className:"text-right font-bold text-indigo-900",children:"المدينة"}),e.jsx(rt,{className:"text-right font-bold text-indigo-900",children:"تاريخ الإضافة"}),e.jsx(rt,{className:"text-right font-bold text-indigo-900",children:"الإجراءات"})]})}),e.jsx(Ro,{children:P.length===0?e.jsx(ar,{children:e.jsx(Qe,{colSpan:7,className:"text-center py-8 text-gray-500",children:"لا يوجد عملاء"})}):P.map(S=>e.jsxs(ar,{className:"hover:bg-gray-50",children:[e.jsx(Qe,{className:"font-medium",children:S.customer_name}),e.jsx(Qe,{children:S.customer_number||"-"}),e.jsx(Qe,{children:e.jsx(Ae,{className:k(S.customer_type),children:T(S.customer_type)})}),e.jsx(Qe,{children:S.phone_number?e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx($a,{className:"h-3 w-3 text-gray-400"}),S.phone_number]}):"-"}),e.jsx(Qe,{children:S.city?e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Da,{className:"h-3 w-3 text-gray-400"}),S.city]}):"-"}),e.jsx(Qe,{className:"text-gray-500",children:new Date(S.created_at).toLocaleDateString("ar-JO")}),e.jsx(Qe,{children:e.jsxs("div",{className:"flex gap-2",children:[g&&e.jsx(V,{variant:"outline",size:"sm",onClick:()=>A(S),className:"border-blue-300 text-blue-600 hover:bg-blue-50",children:e.jsx(en,{className:"h-4 w-4"})}),b&&e.jsx(V,{variant:"outline",size:"sm",onClick:()=>F(S.id),className:"border-red-300 text-red-600 hover:bg-red-50",children:e.jsx(Ar,{className:"h-4 w-4"})})]})})]},S.id))})]})}),e.jsx("div",{className:"md:hidden space-y-3 p-3",children:P.length===0?e.jsx("div",{className:"text-center py-8 text-gray-500",children:"لا يوجد عملاء"}):P.map(S=>e.jsx(fe,{className:"border-2 border-gray-200 shadow-sm hover:shadow-md transition-shadow",children:e.jsxs(ve,{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-1",children:[e.jsx("div",{className:"h-10 w-10 rounded-full bg-gradient-to-br from-indigo-100 to-blue-100 flex items-center justify-center flex-shrink-0",children:e.jsx(Rt,{className:"h-5 w-5 text-indigo-600"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("h3",{className:"font-bold text-base truncate",children:S.customer_name}),e.jsx("p",{className:"text-sm text-gray-500 truncate",children:S.customer_number||"-"})]})]}),e.jsx(Ae,{className:`${k(S.customer_type)} text-xs flex-shrink-0`,children:S.customer_type})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 text-sm bg-gray-50 rounded-lg p-2",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx($a,{className:"h-4 w-4 text-gray-400 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:S.phone_number||"-"})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Da,{className:"h-4 w-4 text-gray-400 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:S.city||"-"})]})]}),e.jsxs("div",{className:"flex gap-2 pt-2 border-t",children:[g&&e.jsxs(V,{variant:"outline",onClick:()=>A(S),className:"flex-1 min-h-[44px] border-blue-300 text-blue-600 hover:bg-blue-50",children:[e.jsx(en,{className:"h-4 w-4 ml-1"}),"تعديل"]}),b&&e.jsxs(V,{variant:"outline",onClick:()=>F(S.id),className:"flex-1 min-h-[44px] border-red-300 text-red-600 hover:bg-red-50",children:[e.jsx(Ar,{className:"h-4 w-4 ml-1"}),"حذف"]})]})]})},S.id))})]})})})]})]})};var Tl={exports:{}};(function(t,r){(function(n,i){t.exports=i(i.toString()).default})(Li,function(n){return function(i){function o(s){if(a[s])return a[s].exports;var c=a[s]={i:s,l:!1,exports:{}};return i[s].call(c.exports,c,c.exports,o),c.l=!0,c.exports}var a={};return o.m=i,o.c=a,o.i=function(s){return s},o.d=function(s,c,l){o.o(s,c)||Object.defineProperty(s,c,{configurable:!1,enumerable:!0,get:l})},o.n=function(s){var c=s&&s.__esModule?function(){return s.default}:function(){return s};return o.d(c,"a",c),c},o.o=function(s,c){return Object.prototype.hasOwnProperty.call(s,c)},o.p="/",o(o.s=166)}([function(i,o){function a(s){var c=typeof s;return s!=null&&(c=="object"||c=="function")}i.exports=a},function(i,o,a){function s(l,m){return this._row=[],this.config=l||{},this.supplements=m,this}var c=a(3);s.prototype._nextUnset=function(l,m){var u;for(m===void 0&&(m=0),u=m;u<l.length;u++)if(!l[u])return u;return l.length},s.prototype._matchPattern=function(l,m,u){var d,h,p,f,x=0,g=0,b=0,y=0;for(u=u||this.SINGLE_CODE_ERROR||1,d=0;d<l.length;d++)b+=l[d],y+=m[d];if(b<y)return Number.MAX_VALUE;for(h=b/y,u*=h,d=0;d<l.length;d++){if(p=l[d],f=m[d]*h,(g=Math.abs(p-f)/f)>u)return Number.MAX_VALUE;x+=g}return x/y},s.prototype._nextSet=function(l,m){var u;for(m=m||0,u=m;u<l.length;u++)if(l[u])return u;return l.length},s.prototype._correctBars=function(l,m,u){for(var d=u.length,h=0;d--;)(h=l[u[d]]*(1-(1-m)/2))>1&&(l[u[d]]=h)},s.prototype._matchTrace=function(l,m){var u,d,h=[],p=this,f=p._nextSet(p._row),x=!p._row[f],g=0,b={error:Number.MAX_VALUE,code:-1,start:0};if(l){for(u=0;u<l.length;u++)h.push(0);for(u=f;u<p._row.length;u++)if(p._row[u]^x)h[g]++;else{if(g===h.length-1)return d=p._matchPattern(h,l),d<m?(b.start=u-f,b.end=u,b.counter=h,b):null;g++,h[g]=1,x=!x}}else for(h.push(0),u=f;u<p._row.length;u++)p._row[u]^x?h[g]++:(g++,h.push(0),h[g]=1,x=!x);return b.start=f,b.end=p._row.length-1,b.counter=h,b},s.prototype.decodePattern=function(l){var m,u=this;return u._row=l,m=u._decode(),m===null?(u._row.reverse(),(m=u._decode())&&(m.direction=s.DIRECTION.REVERSE,m.start=u._row.length-m.start,m.end=u._row.length-m.end)):m.direction=s.DIRECTION.FORWARD,m&&(m.format=u.FORMAT),m},s.prototype._matchRange=function(l,m,u){var d;for(l=l<0?0:l,d=l;d<m;d++)if(this._row[d]!==u)return!1;return!0},s.prototype._fillCounters=function(l,m,u){var d,h=this,p=0,f=[];for(u=u===void 0||u,l=l!==void 0?l:h._nextUnset(h._row),m=m||h._row.length,f[p]=0,d=l;d<m;d++)h._row[d]^u?f[p]++:(p++,f[p]=1,u=!u);return f},s.prototype._toCounters=function(l,m){var u,d=this,h=m.length,p=d._row.length,f=!d._row[l],x=0;for(c.a.init(m,0),u=l;u<p;u++)if(d._row[u]^f)m[x]++;else{if(++x===h)break;m[x]=1,f=!f}return m},Object.defineProperty(s.prototype,"FORMAT",{value:"unknown",writeable:!1}),s.DIRECTION={FORWARD:1,REVERSE:-1},s.Exception={StartNotFoundException:"Start-Info was not found!",CodeNotFoundException:"Code could not be found!",PatternNotFoundException:"Pattern could not be found!"},s.CONFIG_KEYS={},o.a=s},function(i,o){var a=Array.isArray;i.exports=a},function(i,o,a){o.a={init:function(s,c){for(var l=s.length;l--;)s[l]=c},shuffle:function(s){var c,l,m=s.length-1;for(m;m>=0;m--)c=Math.floor(Math.random()*m),l=s[m],s[m]=s[c],s[c]=l;return s},toPointList:function(s){var c,l,m=[],u=[];for(c=0;c<s.length;c++){for(m=[],l=0;l<s[c].length;l++)m[l]=s[c][l];u[c]="["+m.join(",")+"]"}return"["+u.join(`,\r
`)+"]"},threshold:function(s,c,l){var m,u=[];for(m=0;m<s.length;m++)l.apply(s,[s[m]])>=c&&u.push(s[m]);return u},maxIndex:function(s){var c,l=0;for(c=0;c<s.length;c++)s[c]>s[l]&&(l=c);return l},max:function(c){var l,m=0;for(l=0;l<c.length;l++)c[l]>m&&(m=c[l]);return m},sum:function(c){for(var l=c.length,m=0;l--;)m+=c[l];return m}}},function(i,o,a){function s(p,f){p=m()(c(),p),u.a.call(this,p,f)}function c(){var p={};return Object.keys(s.CONFIG_KEYS).forEach(function(f){p[f]=s.CONFIG_KEYS[f].default}),p}var l=a(28),m=a.n(l),u=a(1),d=Object.assign||function(p){for(var f=1;f<arguments.length;f++){var x=arguments[f];for(var g in x)Object.prototype.hasOwnProperty.call(x,g)&&(p[g]=x[g])}return p},h={CODE_L_START:{value:0},CODE_G_START:{value:10},START_PATTERN:{value:[1,1,1]},STOP_PATTERN:{value:[1,1,1]},MIDDLE_PATTERN:{value:[1,1,1,1,1]},EXTENSION_START_PATTERN:{value:[1,1,2]},CODE_PATTERN:{value:[[3,2,1,1],[2,2,2,1],[2,1,2,2],[1,4,1,1],[1,1,3,2],[1,2,3,1],[1,1,1,4],[1,3,1,2],[1,2,1,3],[3,1,1,2],[1,1,2,3],[1,2,2,2],[2,2,1,2],[1,1,4,1],[2,3,1,1],[1,3,2,1],[4,1,1,1],[2,1,3,1],[3,1,2,1],[2,1,1,3]]},CODE_FREQUENCY:{value:[0,11,13,14,19,25,28,21,22,26]},SINGLE_CODE_ERROR:{value:.7},AVG_CODE_ERROR:{value:.48},FORMAT:{value:"ean_13",writeable:!1}};s.prototype=Object.create(u.a.prototype,h),s.prototype.constructor=s,s.prototype._decodeCode=function(p,f){var x,g,b,y=[0,0,0,0],_=this,j=p,I=!_._row[j],w=0,N={error:Number.MAX_VALUE,code:-1,start:p,end:p};for(f||(f=_.CODE_PATTERN.length),x=j;x<_._row.length;x++)if(_._row[x]^I)y[w]++;else{if(w===y.length-1){for(g=0;g<f;g++)(b=_._matchPattern(y,_.CODE_PATTERN[g]))<N.error&&(N.code=g,N.error=b);return N.end=x,N.error>_.AVG_CODE_ERROR?null:N}w++,y[w]=1,I=!I}return null},s.prototype._findPattern=function(p,f,x,g,b){var y,_,j,I,w=[],N=this,C=0,A={error:Number.MAX_VALUE,code:-1,start:0,end:0};for(f||(f=N._nextSet(N._row)),x===void 0&&(x=!1),g===void 0&&(g=!0),b===void 0&&(b=N.AVG_CODE_ERROR),y=0;y<p.length;y++)w[y]=0;for(y=f;y<N._row.length;y++)if(N._row[y]^x)w[C]++;else{if(C===w.length-1){for(I=0,j=0;j<w.length;j++)I+=w[j];if((_=N._matchPattern(w,p))<b)return A.error=_,A.start=y-I,A.end=y,A;if(!g)return null;for(j=0;j<w.length-2;j++)w[j]=w[j+2];w[w.length-2]=0,w[w.length-1]=0,C--}else C++;w[C]=1,x=!x}return null},s.prototype._findStart=function(){for(var p,f,x=this,g=x._nextSet(x._row);!f;){if(!(f=x._findPattern(x.START_PATTERN,g)))return null;if((p=f.start-(f.end-f.start))>=0&&x._matchRange(p,f.start,0))return f;g=f.end,f=null}},s.prototype._verifyTrailingWhitespace=function(p){var f,x=this;return f=p.end+(p.end-p.start),f<x._row.length&&x._matchRange(p.end,f,0)?p:null},s.prototype._findEnd=function(p,f){var x=this,g=x._findPattern(x.STOP_PATTERN,p,f,!1);return g!==null?x._verifyTrailingWhitespace(g):null},s.prototype._calculateFirstDigit=function(p){var f,x=this;for(f=0;f<x.CODE_FREQUENCY.length;f++)if(p===x.CODE_FREQUENCY[f])return f;return null},s.prototype._decodePayload=function(p,f,x){var g,b,y=this,_=0;for(g=0;g<6;g++){if(!(p=y._decodeCode(p.end)))return null;p.code>=y.CODE_G_START?(p.code=p.code-y.CODE_G_START,_|=1<<5-g):_|=0<<5-g,f.push(p.code),x.push(p)}if((b=y._calculateFirstDigit(_))===null||(f.unshift(b),(p=y._findPattern(y.MIDDLE_PATTERN,p.end,!0,!1))===null))return null;for(x.push(p),g=0;g<6;g++){if(!(p=y._decodeCode(p.end,y.CODE_G_START)))return null;x.push(p),f.push(p.code)}return p},s.prototype._decode=function(){var p,f,x=this,g=[],b=[],y={};if(!(p=x._findStart())||(f={code:p.code,start:p.start,end:p.end},b.push(f),!(f=x._decodePayload(f,g,b)))||!(f=x._findEnd(f.end,!1))||(b.push(f),!x._checksum(g)))return null;if(this.supplements.length>0){var _=this._decodeExtensions(f.end);if(!_)return null;var j=_.decodedCodes[_.decodedCodes.length-1],I={start:j.start+((j.end-j.start)/2|0),end:j.end};if(!x._verifyTrailingWhitespace(I))return null;y={supplement:_,code:g.join("")+_.code}}return d({code:g.join(""),start:p.start,end:f.end,codeset:"",startInfo:p,decodedCodes:b},y)},s.prototype._decodeExtensions=function(p){var f,x,g=this._nextSet(this._row,p),b=this._findPattern(this.EXTENSION_START_PATTERN,g,!1,!1);if(b===null)return null;for(f=0;f<this.supplements.length;f++)if((x=this.supplements[f].decode(this._row,b.end))!==null)return{code:x.code,start:g,startInfo:b,end:x.end,codeset:"",decodedCodes:x.decodedCodes};return null},s.prototype._checksum=function(p){var f,x=0;for(f=p.length-2;f>=0;f-=2)x+=p[f];for(x*=3,f=p.length-1;f>=0;f-=2)x+=p[f];return x%10==0},s.CONFIG_KEYS={supplements:{type:"arrayOf(string)",default:[],description:"Allowed extensions to be decoded (2 and/or 5)"}},o.a=s},function(i,o,a){var s=a(38),c=typeof self=="object"&&self&&self.Object===Object&&self,l=s||c||Function("return this")();i.exports=l},function(i,o){function a(s){return s!=null&&typeof s=="object"}i.exports=a},function(i,o){function a(s){var c=new Float32Array(2);return c[0]=s[0],c[1]=s[1],c}i.exports=a},function(i,o,a){function s(p){return p==null?p===void 0?d:u:h&&h in Object(p)?l(p):m(p)}var c=a(11),l=a(119),m=a(146),u="[object Null]",d="[object Undefined]",h=c?c.toStringTag:void 0;i.exports=s},function(i,o,a){o.a={drawRect:function(s,c,l,m){l.strokeStyle=m.color,l.fillStyle=m.color,l.lineWidth=1,l.beginPath(),l.strokeRect(s.x,s.y,c.x,c.y)},drawPath:function(s,c,l,m){l.strokeStyle=m.color,l.fillStyle=m.color,l.lineWidth=m.lineWidth,l.beginPath(),l.moveTo(s[0][c.x],s[0][c.y]);for(var u=1;u<s.length;u++)l.lineTo(s[u][c.x],s[u][c.y]);l.closePath(),l.stroke()},drawImage:function(s,c,l){var m,u=l.getImageData(0,0,c.x,c.y),d=u.data,h=s.length,p=d.length;if(p/h!=4)return!1;for(;h--;)m=s[h],d[--p]=255,d[--p]=m,d[--p]=m,d[--p]=m;return l.putImageData(u,0,0),!0}}},function(i,o,a){function s(h){var p=-1,f=h==null?0:h.length;for(this.clear();++p<f;){var x=h[p];this.set(x[0],x[1])}}var c=a(133),l=a(134),m=a(135),u=a(136),d=a(137);s.prototype.clear=c,s.prototype.delete=l,s.prototype.get=m,s.prototype.has=u,s.prototype.set=d,i.exports=s},function(i,o,a){var s=a(5),c=s.Symbol;i.exports=c},function(i,o,a){function s(l,m){for(var u=l.length;u--;)if(c(l[u][0],m))return u;return-1}var c=a(17);i.exports=s},function(i,o,a){function s(d,h){return c(d)?d:l(d,h)?[d]:m(u(d))}var c=a(2),l=a(130),m=a(154),u=a(165);i.exports=s},function(i,o,a){function s(l,m){var u=l.__data__;return c(m)?u[typeof m=="string"?"string":"hash"]:u.map}var c=a(131);i.exports=s},function(i,o){function a(l,m){return!!(m=m??s)&&(typeof l=="number"||c.test(l))&&l>-1&&l%1==0&&l<m}var s=9007199254740991,c=/^(?:0|[1-9]\d*)$/;i.exports=a},function(i,o,a){var s=a(22),c=s(Object,"create");i.exports=c},function(i,o){function a(s,c){return s===c||s!==s&&c!==c}i.exports=a},function(i,o,a){var s=a(96),c=a(6),l=Object.prototype,m=l.hasOwnProperty,u=l.propertyIsEnumerable,d=s(function(){return arguments}())?s:function(h){return c(h)&&m.call(h,"callee")&&!u.call(h,"callee")};i.exports=d},function(i,o,a){function s(T,k){return{x:T,y:k,toVec2:function(){return C.clone([this.x,this.y])},toVec3:function(){return A.clone([this.x,this.y,1])},round:function(){return this.x=this.x>0?Math.floor(this.x+.5):Math.floor(this.x-.5),this.y=this.y>0?Math.floor(this.y+.5):Math.floor(this.y-.5),this}}}function c(T,k,P){P||(P=T);for(var S=T.data,E=S.length,O=P.data;E--;)O[E]=S[E]<k?1:0}function l(T,k){k||(k=8);for(var P=T.data,S=P.length,E=8-k,O=1<<k,R=new Int32Array(O);S--;)R[P[S]>>E]++;return R}function m(T,k){function P(D,$){var M,X=0;for(M=D;M<=$;M++)X+=O[M];return X}function S(D,$){var M,X=0;for(M=D;M<=$;M++)X+=M*O[M];return X}function E(){var D,$,M,X,U,Q,B,z=[0],H=(1<<k)-1;for(O=l(T,k),X=1;X<H;X++)D=P(0,X),$=P(X+1,H),M=D*$,M===0&&(M=1),U=S(0,X)*$,Q=S(X+1,H)*D,B=U-Q,z[X]=B*B/M;return N.a.maxIndex(z)}k||(k=8);var O,R=8-k;return E()<<R}function u(T,k){var P=m(T);return c(T,P,k),P}function d(T,k,P){function S(M){var X=!1;for(O=0;O<$.length;O++)R=$[O],R.fits(M)&&(R.add(M),X=!0);return X}var E,O,R,D,$=[];for(P||(P="rad"),E=0;E<T.length;E++)D=w.a.createPoint(T[E],E,P),S(D)||$.push(w.a.create(D,k));return $}function h(T,k,P){var S,E,O,R,D=0,$=0,M=[];for(S=0;S<k;S++)M[S]={score:0,item:null};for(S=0;S<T.length;S++)if((E=P.apply(this,[T[S]]))>$)for(O=M[D],O.score=E,O.item=T[S],$=Number.MAX_VALUE,R=0;R<k;R++)M[R].score<$&&($=M[R].score,D=R);return M}function p(T,k,P){for(var S,E=0,O=k.x,R=Math.floor(T.length/4),D=k.x/2,$=0,M=k.x;O<R;){for(S=0;S<D;S++)P[$]=(.299*T[4*E+0]+.587*T[4*E+1]+.114*T[4*E+2]+(.299*T[4*(E+1)+0]+.587*T[4*(E+1)+1]+.114*T[4*(E+1)+2])+(.299*T[4*O+0]+.587*T[4*O+1]+.114*T[4*O+2])+(.299*T[4*(O+1)+0]+.587*T[4*(O+1)+1]+.114*T[4*(O+1)+2]))/4,$++,E+=2,O+=2;E+=M,O+=M}}function f(T,k,P){var S,E=T.length/4|0;if(P&&P.singleChannel===!0)for(S=0;S<E;S++)k[S]=T[4*S+0];else for(S=0;S<E;S++)k[S]=.299*T[4*S+0]+.587*T[4*S+1]+.114*T[4*S+2]}function x(T,k){for(var P=T.data,S=T.size.x,E=k.data,O=0,R=S,D=P.length,$=S/2,M=0;R<D;){for(var X=0;X<$;X++)E[M]=Math.floor((P[O]+P[O+1]+P[R]+P[R+1])/4),M++,O+=2,R+=2;O+=S,R+=S}}function g(T,k){var P=T[0],S=T[1],E=T[2],O=E*S,R=O*(1-Math.abs(P/60%2-1)),D=E-O,$=0,M=0,X=0;return k=k||[0,0,0],P<60?($=O,M=R):P<120?($=R,M=O):P<180?(M=O,X=R):P<240?(M=R,X=O):P<300?($=R,X=O):P<360&&($=O,X=R),k[0]=255*($+D)|0,k[1]=255*(M+D)|0,k[2]=255*(X+D)|0,k}function b(T){var k,P=[],S=[];for(k=1;k<Math.sqrt(T)+1;k++)T%k==0&&(S.push(k),k!==T/k&&P.unshift(Math.floor(T/k)));return S.concat(P)}function y(T,k){for(var P=0,S=0,E=[];P<T.length&&S<k.length;)T[P]===k[S]?(E.push(T[P]),P++,S++):T[P]>k[S]?S++:P++;return E}function _(T,k){function P(B){for(var z=0,H=B[Math.floor(B.length/2)];z<B.length-1&&B[z]<Q;)z++;return z>0&&(H=Math.abs(B[z]-Q)>Math.abs(B[z-1]-Q)?B[z-1]:B[z]),Q/H<$[X+1]/$[X]&&Q/H>$[X-1]/$[X]?{x:H,y:H}:null}var S,E=b(k.x),O=b(k.y),R=Math.max(k.x,k.y),D=y(E,O),$=[8,10,15,20,32,60,80],M={"x-small":5,small:4,medium:3,large:2,"x-large":1},X=M[T]||M.medium,U=$[X],Q=Math.floor(R/U);return S=P(D),S||(S=P(b(R)))||(S=P(b(Q*U))),S}function j(T){return{value:parseFloat(T),unit:(T.indexOf("%"),T.length,"%")}}function I(T,k,P){var S={width:T,height:k},E=Object.keys(P).reduce(function(O,R){var D=P[R],$=j(D),M=F[R]($,S);return O[R]=M,O},{});return{sx:E.left,sy:E.top,sw:E.right-E.left,sh:E.bottom-E.top}}var w=a(50),N=a(3);o.b=s,o.f=u,o.g=d,o.h=h,o.c=p,o.d=f,o.i=x,o.a=g,o.e=_,o.j=I;var C={clone:a(7)},A={clone:a(83)},F={top:function(T,k){if(T.unit==="%")return Math.floor(k.height*(T.value/100))},right:function(T,k){if(T.unit==="%")return Math.floor(k.width-k.width*(T.value/100))},bottom:function(T,k){if(T.unit==="%")return Math.floor(k.height-k.height*(T.value/100))},left:function(T,k){if(T.unit==="%")return Math.floor(k.width*(T.value/100))}}},function(i,o,a){function s(d,h,p,f){h?this.data=h:p?(this.data=new p(d.x*d.y),p===Array&&f&&m.a.init(this.data,0)):(this.data=new Uint8Array(d.x*d.y),Uint8Array===Array&&f&&m.a.init(this.data,0)),this.size=d}var c=a(53),l=a(19),m=a(3),u={clone:a(7)};s.prototype.inImageWithBorder=function(d,h){return d.x>=h&&d.y>=h&&d.x<this.size.x-h&&d.y<this.size.y-h},s.sample=function(d,h,p){var f=Math.floor(h),x=Math.floor(p),g=d.size.x,b=x*d.size.x+f,y=d.data[b+0],_=d.data[b+1],j=d.data[b+g],I=d.data[b+g+1],w=y-_;return h-=f,p-=x,Math.floor(h*(p*(w-j+I)-w)+p*(j-y)+y)},s.clearArray=function(d){for(var h=d.length;h--;)d[h]=0},s.prototype.subImage=function(d,h){return new c.a(d,h,this)},s.prototype.subImageAsCopy=function(d,h){var p,f,x=d.size.y,g=d.size.x;for(p=0;p<g;p++)for(f=0;f<x;f++)d.data[f*g+p]=this.data[(h.y+f)*this.size.x+h.x+p]},s.prototype.copyTo=function(d){for(var h=this.data.length,p=this.data,f=d.data;h--;)f[h]=p[h]},s.prototype.get=function(d,h){return this.data[h*this.size.x+d]},s.prototype.getSafe=function(d,h){var p;if(!this.indexMapping){for(this.indexMapping={x:[],y:[]},p=0;p<this.size.x;p++)this.indexMapping.x[p]=p,this.indexMapping.x[p+this.size.x]=p;for(p=0;p<this.size.y;p++)this.indexMapping.y[p]=p,this.indexMapping.y[p+this.size.y]=p}return this.data[this.indexMapping.y[h+this.size.y]*this.size.x+this.indexMapping.x[d+this.size.x]]},s.prototype.set=function(d,h,p){return this.data[h*this.size.x+d]=p,this},s.prototype.zeroBorder=function(){var d,h=this.size.x,p=this.size.y,f=this.data;for(d=0;d<h;d++)f[d]=f[(p-1)*h+d]=0;for(d=1;d<p-1;d++)f[d*h]=f[d*h+(h-1)]=0},s.prototype.invert=function(){for(var d=this.data,h=d.length;h--;)d[h]=d[h]?0:1},s.prototype.convolve=function(d){var h,p,f,x,g=d.length/2|0,b=0;for(p=0;p<this.size.y;p++)for(h=0;h<this.size.x;h++){for(b=0,x=-g;x<=g;x++)for(f=-g;f<=g;f++)b+=d[x+g][f+g]*this.getSafe(h+f,p+x);this.data[p*this.size.x+h]=b}},s.prototype.moments=function(d){var h,p,f,x,g,b,y,_,j,I,w,N,C=this.data,A=this.size.y,F=this.size.x,T=[],k=[],P=Math.PI,S=P/4;if(d<=0)return k;for(g=0;g<d;g++)T[g]={m00:0,m01:0,m10:0,m11:0,m02:0,m20:0,theta:0,rad:0};for(p=0;p<A;p++)for(x=p*p,h=0;h<F;h++)(f=C[p*F+h])>0&&(b=T[f-1],b.m00+=1,b.m01+=p,b.m10+=h,b.m11+=h*p,b.m02+=x,b.m20+=h*h);for(g=0;g<d;g++)b=T[g],isNaN(b.m00)||b.m00===0||(I=b.m10/b.m00,w=b.m01/b.m00,y=b.m11/b.m00-I*w,_=b.m02/b.m00-w*w,j=b.m20/b.m00-I*I,N=(_-j)/(2*y),N=.5*Math.atan(N)+(y>=0?S:-S)+P,b.theta=(180*N/P+90)%180-90,b.theta<0&&(b.theta+=180),b.rad=N>P?N-P:N,b.vec=u.clone([Math.cos(N),Math.sin(N)]),k.push(b));return k},s.prototype.show=function(d,h){var p,f,x,g,b,y,_;for(h||(h=1),p=d.getContext("2d"),d.width=this.size.x,d.height=this.size.y,f=p.getImageData(0,0,d.width,d.height),x=f.data,g=0,_=0;_<this.size.y;_++)for(y=0;y<this.size.x;y++)b=_*this.size.x+y,g=this.get(y,_)*h,x[4*b+0]=g,x[4*b+1]=g,x[4*b+2]=g,x[4*b+3]=255;p.putImageData(f,0,0)},s.prototype.overlay=function(d,h,p){(!h||h<0||h>360)&&(h=360);for(var f=[0,1,1],x=[0,0,0],g=[255,255,255],b=[0,0,0],y=[],_=d.getContext("2d"),j=_.getImageData(p.x,p.y,this.size.x,this.size.y),I=j.data,w=this.data.length;w--;)f[0]=this.data[w]*h,y=f[0]<=0?g:f[0]>=360?b:a.i(l.a)(f,x),I[4*w+0]=y[0],I[4*w+1]=y[1],I[4*w+2]=y[2],I[4*w+3]=255;_.putImageData(j,p.x,p.y)},o.a=s},function(i,o,a){function s(l,m,u){m=="__proto__"&&c?c(l,m,{configurable:!0,enumerable:!0,value:u,writable:!0}):l[m]=u}var c=a(37);i.exports=s},function(i,o,a){function s(m,u){var d=l(m,u);return c(d)?d:void 0}var c=a(97),l=a(120);i.exports=s},function(i,o,a){function s(m){if(typeof m=="string"||c(m))return m;var u=m+"";return u=="0"&&1/m==-l?"-0":u}var c=a(27),l=1/0;i.exports=s},function(i,o,a){function s(m){return m!=null&&l(m.length)&&!c(m)}var c=a(25),l=a(26);i.exports=s},function(i,o,a){function s(p){if(!l(p))return!1;var f=c(p);return f==u||f==d||f==m||f==h}var c=a(8),l=a(0),m="[object AsyncFunction]",u="[object Function]",d="[object GeneratorFunction]",h="[object Proxy]";i.exports=s},function(i,o){function a(c){return typeof c=="number"&&c>-1&&c%1==0&&c<=s}var s=9007199254740991;i.exports=a},function(i,o,a){function s(u){return typeof u=="symbol"||l(u)&&c(u)==m}var c=a(8),l=a(6),m="[object Symbol]";i.exports=s},function(i,o,a){var s=a(100),c=a(116),l=c(function(m,u,d){s(m,u,d)});i.exports=l},function(i,o){i.exports=function(a){return a.webpackPolyfill||(a.deprecate=function(){},a.paths=[],a.children||(a.children=[]),Object.defineProperty(a,"loaded",{enumerable:!0,get:function(){return a.l}}),Object.defineProperty(a,"id",{enumerable:!0,get:function(){return a.i}}),a.webpackPolyfill=1),a}},function(i,o,a){var s={searchDirections:[[0,1],[1,1],[1,0],[1,-1],[0,-1],[-1,-1],[-1,0],[-1,1]],create:function(c,l){function m(b,y,_,j){var I,w,N;for(I=0;I<7;I++){if(w=b.cy+x[b.dir][0],N=b.cx+x[b.dir][1],h=w*g+N,p[h]===y&&(f[h]===0||f[h]===_))return f[h]=_,b.cy=w,b.cx=N,!0;f[h]===0&&(f[h]=j),b.dir=(b.dir+1)%8}return!1}function u(b,y,_){return{dir:_,x:b,y,next:null,prev:null}}function d(b,y,_,j,I){var w,N,C,A=null,F={cx:y,cy:b,dir:0};if(m(F,j,_,I)){A=u(y,b,F.dir),w=A,C=F.dir,N=u(F.cx,F.cy,0),N.prev=w,w.next=N,N.next=null,w=N;do F.dir=(F.dir+6)%8,m(F,j,_,I),C!==F.dir?(w.dir=F.dir,N=u(F.cx,F.cy,0),N.prev=w,w.next=N,N.next=null,w=N):(w.dir=C,w.x=F.cx,w.y=F.cy),C=F.dir;while(F.cx!==y||F.cy!==b);A.prev=w.prev,w.prev.next=A}return A}var h,p=c.data,f=l.data,x=this.searchDirections,g=c.size.x;return{trace:function(b,y,_,j){return m(b,y,_,j)},contourTracing:function(b,y,_,j,I){return d(b,y,_,j,I)}}}};o.a=s},function(i,o,a){function s(){c.a.call(this)}var c=a(1),l=a(3),m={ALPHABETH_STRING:{value:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. *$/+%"},ALPHABET:{value:[48,49,50,51,52,53,54,55,56,57,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,45,46,32,42,36,47,43,37]},CHARACTER_ENCODINGS:{value:[52,289,97,352,49,304,112,37,292,100,265,73,328,25,280,88,13,268,76,28,259,67,322,19,274,82,7,262,70,22,385,193,448,145,400,208,133,388,196,148,168,162,138,42]},ASTERISK:{value:148},FORMAT:{value:"code_39",writeable:!1}};s.prototype=Object.create(c.a.prototype,m),s.prototype.constructor=s,s.prototype._decode=function(){var u,d,h,p,f=this,x=[0,0,0,0,0,0,0,0,0],g=[],b=f._findStart();if(!b)return null;p=f._nextSet(f._row,b.end);do{if(x=f._toCounters(p,x),(h=f._toPattern(x))<0||(u=f._patternToChar(h))<0)return null;g.push(u),d=p,p+=l.a.sum(x),p=f._nextSet(f._row,p)}while(u!=="*");return g.pop(),g.length&&f._verifyTrailingWhitespace(d,p,x)?{code:g.join(""),start:b.start,end:p,startInfo:b,decodedCodes:g}:null},s.prototype._verifyTrailingWhitespace=function(u,d,h){var p=l.a.sum(h);return 3*(d-u-p)>=p},s.prototype._patternToChar=function(u){var d,h=this;for(d=0;d<h.CHARACTER_ENCODINGS.length;d++)if(h.CHARACTER_ENCODINGS[d]===u)return String.fromCharCode(h.ALPHABET[d]);return-1},s.prototype._findNextWidth=function(u,d){var h,p=Number.MAX_VALUE;for(h=0;h<u.length;h++)u[h]<p&&u[h]>d&&(p=u[h]);return p},s.prototype._toPattern=function(u){for(var d,h,p=u.length,f=0,x=p,g=0,b=this;x>3;){for(f=b._findNextWidth(u,f),x=0,d=0,h=0;h<p;h++)u[h]>f&&(d|=1<<p-1-h,x++,g+=u[h]);if(x===3){for(h=0;h<p&&x>0;h++)if(u[h]>f&&(x--,2*u[h]>=g))return-1;return d}}return-1},s.prototype._findStart=function(){var u,d,h,p=this,f=p._nextSet(p._row),x=f,g=[0,0,0,0,0,0,0,0,0],b=0,y=!1;for(u=f;u<p._row.length;u++)if(p._row[u]^y)g[b]++;else{if(b===g.length-1){if(p._toPattern(g)===p.ASTERISK&&(h=Math.floor(Math.max(0,x-(u-x)/4)),p._matchRange(h,x,0)))return{start:x,end:u};for(x+=g[0]+g[1],d=0;d<7;d++)g[d]=g[d+2];g[7]=0,g[8]=0,b--}else b++;g[b]=1,y=!y}return null},o.a=s},function(i,o){function a(s,c){return s[0]*c[0]+s[1]*c[1]}i.exports=a},function(i,o,a){var s=a(22),c=a(5),l=s(c,"Map");i.exports=l},function(i,o,a){function s(h){var p=-1,f=h==null?0:h.length;for(this.clear();++p<f;){var x=h[p];this.set(x[0],x[1])}}var c=a(138),l=a(139),m=a(140),u=a(141),d=a(142);s.prototype.clear=c,s.prototype.delete=l,s.prototype.get=m,s.prototype.has=u,s.prototype.set=d,i.exports=s},function(i,o,a){function s(m,u,d){(d===void 0||l(m[u],d))&&(d!==void 0||u in m)||c(m,u,d)}var c=a(21),l=a(17);i.exports=s},function(i,o,a){function s(d,h,p){var f=d[h];u.call(d,h)&&l(f,p)&&(p!==void 0||h in d)||c(d,h,p)}var c=a(21),l=a(17),m=Object.prototype,u=m.hasOwnProperty;i.exports=s},function(i,o,a){var s=a(22),c=function(){try{var l=s(Object,"defineProperty");return l({},"",{}),l}catch{}}();i.exports=c},function(i,o,a){(function(s){var c=typeof s=="object"&&s&&s.Object===Object&&s;i.exports=c}).call(o,a(47))},function(i,o,a){var s=a(147),c=s(Object.getPrototypeOf,Object);i.exports=c},function(i,o){function a(c){var l=c&&c.constructor;return c===(typeof l=="function"&&l.prototype||s)}var s=Object.prototype;i.exports=a},function(i,o,a){function s(m,u,d){return u=l(u===void 0?m.length-1:u,0),function(){for(var h=arguments,p=-1,f=l(h.length-u,0),x=Array(f);++p<f;)x[p]=h[u+p];p=-1;for(var g=Array(u+1);++p<u;)g[p]=h[p];return g[u]=d(x),c(m,this,g)}}var c=a(87),l=Math.max;i.exports=s},function(i,o,a){var s=a(106),c=a(148),l=c(s);i.exports=l},function(i,o){function a(s){return s}i.exports=a},function(i,o,a){(function(s){var c=a(5),l=a(163),m=typeof o=="object"&&o&&!o.nodeType&&o,u=m&&typeof s=="object"&&s&&!s.nodeType&&s,d=u&&u.exports===m,h=d?c.Buffer:void 0,p=h?h.isBuffer:void 0,f=p||l;s.exports=f}).call(o,a(29)(i))},function(i,o,a){var s=a(98),c=a(109),l=a(145),m=l&&l.isTypedArray,u=m?c(m):s;i.exports=u},function(i,o,a){function s(u){return m(u)?c(u,!0):l(u)}var c=a(88),l=a(99),m=a(24);i.exports=s},function(i,o){var a;a=function(){return this}();try{a=a||Function("return this")()||(0,eval)("this")}catch{typeof window=="object"&&(a=window)}i.exports=a},function(i,o,a){function s(q){h(q),R=B.a.create(se.decoder,E)}function c(q){var ne;if(se.inputStream.type==="VideoStream")ne=document.createElement("video"),k=ce.a.createVideoStream(ne);else if(se.inputStream.type==="ImageStream")k=ce.a.createImageStream();else if(se.inputStream.type==="LiveStream"){var re=l();re&&((ne=re.querySelector("video"))||(ne=document.createElement("video"),re.appendChild(ne))),k=ce.a.createLiveStream(ne),H.a.request(ne,se.inputStream.constraints).then(function(){k.trigger("canrecord")}).catch(function(de){return q(de)})}k.setAttribute("preload","auto"),k.setInputStream(se.inputStream),k.addEventListener("canrecord",m.bind(void 0,q))}function l(){var q=se.inputStream.target;if(q&&q.nodeName&&q.nodeType===1)return q;var ne=typeof q=="string"?q:"#interactive.viewport";return document.querySelector(ne)}function m(q){Q.a.checkImageConstraints(k,se.locator),d(),P=ke.a.create(k,je.dom.image),T(se.numOfWorkers,function(){se.numOfWorkers===0&&s(),u(q)})}function u(q){k.play(),q()}function d(){if(typeof document<"u"){var q=l();if(je.dom.image=document.querySelector("canvas.imgBuffer"),je.dom.image||(je.dom.image=document.createElement("canvas"),je.dom.image.className="imgBuffer",q&&se.inputStream.type==="ImageStream"&&q.appendChild(je.dom.image)),je.ctx.image=je.dom.image.getContext("2d"),je.dom.image.width=k.getCanvasSize().x,je.dom.image.height=k.getCanvasSize().y,je.dom.overlay=document.querySelector("canvas.drawingBuffer"),!je.dom.overlay){je.dom.overlay=document.createElement("canvas"),je.dom.overlay.className="drawingBuffer",q&&q.appendChild(je.dom.overlay);var ne=document.createElement("br");ne.setAttribute("clear","all"),q&&q.appendChild(ne)}je.ctx.overlay=je.dom.overlay.getContext("2d"),je.dom.overlay.width=k.getCanvasSize().x,je.dom.overlay.height=k.getCanvasSize().y}}function h(q){E=q||new U.a({x:k.getWidth(),y:k.getHeight()}),O=[Se.clone([0,0]),Se.clone([0,E.size.y]),Se.clone([E.size.x,E.size.y]),Se.clone([E.size.x,0])],Q.a.init(E,se.locator)}function p(){return se.locate?Q.a.locate():[[Se.clone(O[0]),Se.clone(O[1]),Se.clone(O[2]),Se.clone(O[3])]]}function f(q){function ne(ot){for(var dt=ot.length;dt--;)ot[dt][0]+=Ce,ot[dt][1]+=st}function re(ot){ot[0].x+=Ce,ot[0].y+=st,ot[1].x+=Ce,ot[1].y+=st}var de,ze=k.getTopRight(),Ce=ze.x,st=ze.y;if(Ce!==0||st!==0){if(q.barcodes)for(de=0;de<q.barcodes.length;de++)f(q.barcodes[de]);if(q.line&&q.line.length===2&&re(q.line),q.box&&ne(q.box),q.boxes&&q.boxes.length>0)for(de=0;de<q.boxes.length;de++)ne(q.boxes[de])}}function x(q,ne){ne&&D&&(q.barcodes?q.barcodes.filter(function(re){return re.codeResult}).forEach(function(re){return x(re,ne)}):q.codeResult&&D.addResult(ne,k.getCanvasSize(),q.codeResult))}function g(q){return q&&(q.barcodes?q.barcodes.some(function(ne){return ne.codeResult}):q.codeResult)}function b(q,ne){var re=q;q&&We&&(f(q),x(q,ne),re=q.barcodes||q),z.a.publish("processed",re),g(q)&&z.a.publish("detected",re)}function y(){var q,ne;ne=p(),ne?(q=R.decodeFromBoundingBoxes(ne),q=q||{},q.boxes=ne,b(q,E.data)):b()}function _(){var q;if(We){if(Re.length>0){if(!(q=Re.filter(function(ne){return!ne.busy})[0]))return;P.attachData(q.imageData)}else P.attachData(E.data);P.grab()&&(q?(q.busy=!0,q.worker.postMessage({cmd:"process",imageData:q.imageData},[q.imageData.buffer])):y())}else y()}function j(){var q=null,ne=1e3/(se.frequency||60);S=!1,function re(de){q=q||de,S||(de>=q&&(q+=ne,_()),window.requestAnimFrame(re))}(performance.now())}function I(){We&&se.inputStream.type==="LiveStream"?j():_()}function w(q){var ne,re={worker:void 0,imageData:new Uint8Array(k.getWidth()*k.getHeight()),busy:!0};ne=A(),re.worker=new Worker(ne),re.worker.onmessage=function(de){if(de.data.event==="initialized")return URL.revokeObjectURL(ne),re.busy=!1,re.imageData=new Uint8Array(de.data.imageData),q(re);de.data.event==="processed"?(re.imageData=new Uint8Array(de.data.imageData),re.busy=!1,b(de.data.result,re.imageData)):de.data.event},re.worker.postMessage({cmd:"init",size:{x:k.getWidth(),y:k.getHeight()},imageData:re.imageData,config:N(se)},[re.imageData.buffer])}function N(q){return be({},q,{inputStream:be({},q.inputStream,{target:null})})}function C(q){function ne(Ce){self.postMessage({event:"processed",imageData:ze.data,result:Ce},[ze.data.buffer])}function re(){self.postMessage({event:"initialized",imageData:ze.data},[ze.data.buffer])}if(q){var de=q().default;if(!de)return void self.postMessage({event:"error",message:"Quagga could not be created"})}var ze;self.onmessage=function(Ce){if(Ce.data.cmd==="init"){var st=Ce.data.config;st.numOfWorkers=0,ze=new de.ImageWrapper({x:Ce.data.size.x,y:Ce.data.size.y},new Uint8Array(Ce.data.imageData)),de.init(st,re,ze),de.onProcessed(ne)}else Ce.data.cmd==="process"?(ze.data=new Uint8Array(Ce.data.imageData),de.start()):Ce.data.cmd==="setReaders"&&de.setReaders(Ce.data.readers)}}function A(){var q,ne;return n!==void 0&&(ne=n),q=new Blob(["("+C.toString()+")("+ne+");"],{type:"text/javascript"}),window.URL.createObjectURL(q)}function F(q){R?R.setReaders(q):We&&Re.length>0&&Re.forEach(function(ne){ne.worker.postMessage({cmd:"setReaders",readers:q})})}function T(q,ne){var re=q-Re.length;if(re===0)return ne&&ne();if(re<0)return Re.slice(re).forEach(function(Ce){Ce.worker.terminate()}),Re=Re.slice(0,re),ne&&ne();for(var de=function(Ce){Re.push(Ce),Re.length>=q&&ne&&ne()},ze=0;ze<re;ze++)w(de)}Object.defineProperty(o,"__esModule",{value:!0});var k,P,S,E,O,R,D,$=a(28),M=a.n($),X=a(54),U=(a.n(X),a(20)),Q=a(64),B=a(57),z=a(51),H=a(59),Y=a(9),J=a(49),ie=a(55),ce=a(63),ke=a(61),be=Object.assign||function(q){for(var ne=1;ne<arguments.length;ne++){var re=arguments[ne];for(var de in re)Object.prototype.hasOwnProperty.call(re,de)&&(q[de]=re[de])}return q},Se={clone:a(7)},je={ctx:{image:null,overlay:null},dom:{image:null,overlay:null}},Re=[],We=!0,se={};o.default={init:function(q,ne,re){if(se=M()({},ie.a,q),re)return We=!1,s(re),ne();c(ne)},start:function(){I()},stop:function(){S=!0,T(0),se.inputStream.type==="LiveStream"&&(H.a.release(),k.clearEventHandlers())},pause:function(){S=!0},onDetected:function(q){z.a.subscribe("detected",q)},offDetected:function(q){z.a.unsubscribe("detected",q)},onProcessed:function(q){z.a.subscribe("processed",q)},offProcessed:function(q){z.a.unsubscribe("processed",q)},setReaders:function(q){F(q)},registerResultCollector:function(q){q&&typeof q.addResult=="function"&&(D=q)},canvas:je,decodeSingle:function(q,ne){var re=this;q=M()({inputStream:{type:"ImageStream",sequence:!1,size:800,src:q.src},numOfWorkers:1,locator:{halfSample:!1}},q),this.init(q,function(){z.a.once("processed",function(de){re.stop(),ne.call(null,de)},!0),I()})},ImageWrapper:U.a,ImageDebug:Y.a,ResultCollector:J.a,CameraAccess:H.a}},function(i,o,a){function s(m,u){return!!u&&u.some(function(d){return Object.keys(d).every(function(h){return d[h]===m[h]})})}function c(m,u){return typeof u!="function"||u(m)}var l=a(9);o.a={create:function(m){function u(g){return f&&g&&!s(g,m.blacklist)&&c(g,m.filter)}var d=document.createElement("canvas"),h=d.getContext("2d"),p=[],f=m.capacity||20,x=m.capture===!0;return{addResult:function(g,b,y){var _={};u(y)&&(f--,_.codeResult=y,x&&(d.width=b.x,d.height=b.y,l.a.drawImage(g,b,h),_.frame=d.toDataURL()),p.push(_))},getResults:function(){return p}}}}},function(i,o,a){var s={clone:a(7),dot:a(32)};o.a={create:function(c,l){function m(){u(c),d()}function u(x){f[x.id]=x,h.push(x)}function d(){var x,g=0;for(x=0;x<h.length;x++)g+=h[x].rad;p.rad=g/h.length,p.vec=s.clone([Math.cos(p.rad),Math.sin(p.rad)])}var h=[],p={rad:0,vec:s.clone([0,0])},f={};return m(),{add:function(x){f[x.id]||(u(x),d())},fits:function(x){return Math.abs(s.dot(x.point.vec,p.vec))>l},getPoints:function(){return h},getCenter:function(){return p}}},createPoint:function(c,l,m){return{rad:c[m],point:c,id:l}}}},function(i,o,a){o.a=function(){function s(d){return u[d]||(u[d]={subscribers:[]}),u[d]}function c(){u={}}function l(d,h){d.async?setTimeout(function(){d.callback(h)},4):d.callback(h)}function m(d,h,p){var f;if(typeof h=="function")f={callback:h,async:p};else if(f=h,!f.callback)throw"Callback was not specified on options";s(d).subscribers.push(f)}var u={};return{subscribe:function(d,h,p){return m(d,h,p)},publish:function(d,h){var p=s(d),f=p.subscribers;f.filter(function(x){return!!x.once}).forEach(function(x){l(x,h)}),p.subscribers=f.filter(function(x){return!x.once}),p.subscribers.forEach(function(x){l(x,h)})},once:function(d,h,p){m(d,{callback:h,async:p,once:!0})},unsubscribe:function(d,h){var p;d?(p=s(d),p.subscribers=p&&h?p.subscribers.filter(function(f){return f.callback!==h}):[]):c()}}}()},function(i,o,a){function s(){return navigator.mediaDevices&&typeof navigator.mediaDevices.enumerateDevices=="function"?navigator.mediaDevices.enumerateDevices():Promise.reject(new Error("enumerateDevices is not defined"))}function c(l){return navigator.mediaDevices&&typeof navigator.mediaDevices.getUserMedia=="function"?navigator.mediaDevices.getUserMedia(l):Promise.reject(new Error("getUserMedia is not defined"))}o.b=s,o.a=c},function(i,o,a){function s(c,l,m){m||(m={data:null,size:l}),this.data=m.data,this.originalSize=m.size,this.I=m,this.from=c,this.size=l}s.prototype.show=function(c,l){var m,u,d,h,p,f,x;for(l||(l=1),m=c.getContext("2d"),c.width=this.size.x,c.height=this.size.y,u=m.getImageData(0,0,c.width,c.height),d=u.data,h=0,p=0;p<this.size.y;p++)for(f=0;f<this.size.x;f++)x=p*this.size.x+f,h=this.get(f,p)*l,d[4*x+0]=h,d[4*x+1]=h,d[4*x+2]=h,d[4*x+3]=255;u.data=d,m.putImageData(u,0,0)},s.prototype.get=function(c,l){return this.data[(this.from.y+l)*this.originalSize.x+this.from.x+c]},s.prototype.updateData=function(c){this.originalSize=c.size,this.data=c.data},s.prototype.updateFrom=function(c){return this.from=c,this},o.a=s},function(i,o){typeof window<"u"&&(window.requestAnimFrame=function(){return window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.oRequestAnimationFrame||window.msRequestAnimationFrame||function(a){window.setTimeout(a,1e3/60)}}()),Math.imul=Math.imul||function(a,s){var c=a>>>16&65535,l=65535&a,m=s>>>16&65535,u=65535&s;return l*u+(c*u+l*m<<16>>>0)|0},typeof Object.assign!="function"&&(Object.assign=function(a){if(a===null)throw new TypeError("Cannot convert undefined or null to object");for(var s=Object(a),c=1;c<arguments.length;c++){var l=arguments[c];if(l!==null)for(var m in l)Object.prototype.hasOwnProperty.call(l,m)&&(s[m]=l[m])}return s})},function(i,o,a){var s=void 0;s=a(56),o.a=s},function(i,o){i.exports={inputStream:{name:"Live",type:"LiveStream",constraints:{width:640,height:480,facingMode:"environment"},area:{top:"0%",right:"0%",left:"0%",bottom:"0%"},singleChannel:!1},locate:!0,numOfWorkers:4,decoder:{readers:["code_128_reader"]},locator:{halfSample:!0,patchSize:"medium"}}},function(i,o,a){var s=a(58),c=(a(9),a(69)),l=a(4),m=a(31),u=a(70),d=a(68),h=a(77),p=a(74),f=a(72),x=a(73),g=a(76),b=a(75),y=a(67),_=a(71),j=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(w){return typeof w}:function(w){return w&&typeof Symbol=="function"&&w.constructor===Symbol&&w!==Symbol.prototype?"symbol":typeof w},I={code_128_reader:c.a,ean_reader:l.a,ean_5_reader:x.a,ean_2_reader:f.a,ean_8_reader:p.a,code_39_reader:m.a,code_39_vin_reader:u.a,codabar_reader:d.a,upc_reader:h.a,upc_e_reader:g.a,i2of5_reader:b.a,"2of5_reader":y.a,code_93_reader:_.a};o.a={create:function(w,N){function C(){w.readers.forEach(function(O){var R,D={},$=[];(O===void 0?"undefined":j(O))==="object"?(R=O.format,D=O.config):typeof O=="string"&&(R=O),D.supplements&&($=D.supplements.map(function(M){return new I[M]})),E.push(new I[R](D,$))})}function A(O,R,D){function $(M){var X={y:M*Math.sin(R),x:M*Math.cos(R)};O[0].y-=X.y,O[0].x-=X.x,O[1].y+=X.y,O[1].x+=X.x}for($(D);D>1&&(!N.inImageWithBorder(O[0],0)||!N.inImageWithBorder(O[1],0));)D-=Math.ceil(D/2),$(-D);return O}function F(O){return[{x:(O[1][0]-O[0][0])/2+O[0][0],y:(O[1][1]-O[0][1])/2+O[0][1]},{x:(O[3][0]-O[2][0])/2+O[2][0],y:(O[3][1]-O[2][1])/2+O[2][1]}]}function T(O){var R,D=null,$=s.a.getBarcodeLine(N,O[0],O[1]);for(s.a.toBinaryLine($),R=0;R<E.length&&D===null;R++)D=E[R].decodePattern($.line);return D===null?null:{codeResult:D,barcodeLine:$}}function k(O,R,D){var $,M,X,U=Math.sqrt(Math.pow(O[1][0]-O[0][0],2)+Math.pow(O[1][1]-O[0][1],2)),Q=16,B=null,z=Math.sin(D),H=Math.cos(D);for($=1;$<Q&&B===null;$++)M=U/Q*$*($%2==0?-1:1),X={y:M*z,x:M*H},R[0].y+=X.x,R[0].x-=X.y,R[1].y+=X.x,R[1].x-=X.y,B=T(R);return B}function P(O){return Math.sqrt(Math.pow(Math.abs(O[1].y-O[0].y),2)+Math.pow(Math.abs(O[1].x-O[0].x),2))}function S(O){var R,D,$,M;return R=F(O),M=P(R),D=Math.atan2(R[1].y-R[0].y,R[1].x-R[0].x),(R=A(R,D,Math.floor(.1*M)))===null?null:($=T(R),$===null&&($=k(O,R,D)),$===null?null:{codeResult:$.codeResult,line:R,angle:D,pattern:$.barcodeLine.line,threshold:$.barcodeLine.threshold})}var E=[];return C(),{decodeFromBoundingBox:function(O){return S(O)},decodeFromBoundingBoxes:function(O){var R,D,$=[],M=w.multiple;for(R=0;R<O.length;R++){var X=O[R];if(D=S(X)||{},D.box=X,M)$.push(D);else if(D.codeResult)return D}if(M)return{barcodes:$}},setReaders:function(O){w.readers=O,E.length=0,C()}}}}},function(i,o,a){var s=(a(20),{}),c={DIR:{UP:1,DOWN:-1}};s.getBarcodeLine=function(l,m,u){function d(S,E){_=F[E*T+S],k=_<k?_:k,P=_>P?_:P,A.push(_)}var h,p,f,x,g,b,y,_,j=0|m.x,I=0|m.y,w=0|u.x,N=0|u.y,C=Math.abs(N-I)>Math.abs(w-j),A=[],F=l.data,T=l.size.x,k=255,P=0;for(C&&(b=j,j=I,I=b,b=w,w=N,N=b),j>w&&(b=j,j=w,w=b,b=I,I=N,N=b),h=w-j,p=Math.abs(N-I),f=h/2|0,g=I,x=I<N?1:-1,y=j;y<w;y++)C?d(g,y):d(y,g),(f-=p)<0&&(g+=x,f+=h);return{line:A,min:k,max:P}},s.toBinaryLine=function(l){var m,u,d,h,p,f,x=l.min,g=l.max,b=l.line,y=x+(g-x)/2,_=[],j=(g-x)/12,I=-j;for(d=b[0]>y?c.DIR.UP:c.DIR.DOWN,_.push({pos:0,val:b[0]}),p=0;p<b.length-2;p++)m=b[p+1]-b[p],u=b[p+2]-b[p+1],h=m+u<I&&b[p+1]<1.5*y?c.DIR.DOWN:m+u>j&&b[p+1]>.5*y?c.DIR.UP:d,d!==h&&(_.push({pos:p,val:b[p]}),d=h);for(_.push({pos:b.length,val:b[b.length-1]}),f=_[0].pos;f<_[1].pos;f++)b[f]=b[f]>y?0:1;for(p=1;p<_.length-1;p++)for(j=_[p+1].val>_[p].val?_[p].val+(_[p+1].val-_[p].val)/3*2|0:_[p+1].val+(_[p].val-_[p+1].val)/3|0,f=_[p].pos;f<_[p+1].pos;f++)b[f]=b[f]>j?0:1;return{line:b,threshold:j}},s.debug={printFrequency:function(l,m){var u,d=m.getContext("2d");for(m.width=l.length,m.height=256,d.beginPath(),d.strokeStyle="blue",u=0;u<l.length;u++)d.moveTo(u,255),d.lineTo(u,255-l[u]);d.stroke(),d.closePath()},printPattern:function(l,m){var u,d=m.getContext("2d");for(m.width=l.length,d.fillColor="black",u=0;u<l.length;u++)l[u]===1&&d.fillRect(u,0,1,100)}},o.a=s},function(i,o,a){function s(g){return new Promise(function(b,y){function _(){j>0?g.videoWidth>10&&g.videoHeight>10?b():window.setTimeout(_,500):y("Unable to play video stream. Is webcam working?"),j--}var j=10;_()})}function c(g,b){return a.i(x.a)(b).then(function(y){return new Promise(function(_){h=y,g.setAttribute("autoplay",!0),g.setAttribute("muted",!0),g.setAttribute("playsinline",!0),g.srcObject=y,g.addEventListener("loadedmetadata",function(){g.play(),_()})})}).then(s.bind(null,g))}function l(g){var b=f()(g,["width","height","facingMode","aspectRatio","deviceId"]);return g.minAspectRatio!==void 0&&g.minAspectRatio>0&&(b.aspectRatio=g.minAspectRatio,console.log("WARNING: Constraint 'minAspectRatio' is deprecated; Use 'aspectRatio' instead")),g.facing!==void 0&&(b.facingMode=g.facing,console.log("WARNING: Constraint 'facing' is deprecated. Use 'facingMode' instead'")),b}function m(g){var b={audio:!1,video:l(g)};return b.video.deviceId&&b.video.facingMode&&delete b.video.facingMode,Promise.resolve(b)}function u(){return a.i(x.b)().then(function(g){return g.filter(function(b){return b.kind==="videoinput"})})}function d(){if(h){var g=h.getVideoTracks();if(g&&g.length)return g[0]}}var h,p=a(162),f=a.n(p),x=a(52);o.a={request:function(g,b){return m(b).then(c.bind(null,g))},release:function(){var g=h&&h.getVideoTracks();g&&g.length&&g[0].stop(),h=null},enumerateVideoDevices:u,getActiveStreamLabel:function(){var g=d();return g?g.label:""},getActiveTrack:d}},function(i,o,a){function s(g){var b=arguments.length>1&&arguments[1]!==void 0?arguments[1]:x;return/^blob\:/i.test(g)?l(g).then(c).then(function(y){return m(y,b)}):Promise.resolve(null)}function c(g){return new Promise(function(b){var y=new FileReader;y.onload=function(_){return b(_.target.result)},y.readAsArrayBuffer(g)})}function l(g){return new Promise(function(b,y){var _=new XMLHttpRequest;_.open("GET",g,!0),_.responseType="blob",_.onreadystatechange=function(){_.readyState!==XMLHttpRequest.DONE||_.status!==200&&_.status!==0||b(this.response)},_.onerror=y,_.send()})}function m(g){var b=arguments.length>1&&arguments[1]!==void 0?arguments[1]:x,y=new DataView(g),_=g.byteLength,j=b.reduce(function(w,N){var C=Object.keys(f).filter(function(A){return f[A]===N})[0];return C&&(w[C]=N),w},{}),I=2;if(y.getUint8(0)!==255||y.getUint8(1)!==216)return!1;for(;I<_;){if(y.getUint8(I)!==255)return!1;if(y.getUint8(I+1)===225)return u(y,I+4,j);I+=2+y.getUint16(I+2)}}function u(g,b,y){if(p(g,b,4)!=="Exif")return!1;var _=b+6,j=void 0;if(g.getUint16(_)===18761)j=!1;else{if(g.getUint16(_)!==19789)return!1;j=!0}if(g.getUint16(_+2,!j)!==42)return!1;var I=g.getUint32(_+4,!j);return!(I<8)&&d(g,_,_+I,y,j)}function d(g,b,y,_,j){for(var I=g.getUint16(y,!j),w={},N=0;N<I;N++){var C=y+12*N+2,A=_[g.getUint16(C,!j)];A&&(w[A]=h(g,C,b,y,j))}return w}function h(g,b,y,_,j){var I=g.getUint16(b+2,!j),w=g.getUint32(b+4,!j);switch(I){case 3:if(w===1)return g.getUint16(b+8,!j)}}function p(g,b,y){for(var _="",j=b;j<b+y;j++)_+=String.fromCharCode(g.getUint8(j));return _}o.a=s;var f={274:"orientation"},x=Object.keys(f).map(function(g){return f[g]})},function(i,o,a){function s(u,d){u.width!==d.x&&(u.width=d.x),u.height!==d.y&&(u.height=d.y)}var c=a(19),l=Math.PI/180,m={};m.create=function(u,d){var h,p={},f=u.getConfig(),x=(a.i(c.b)(u.getRealWidth(),u.getRealHeight()),u.getCanvasSize()),g=a.i(c.b)(u.getWidth(),u.getHeight()),b=u.getTopRight(),y=b.x,_=b.y,j=null,I=null;return h=d||document.createElement("canvas"),h.width=x.x,h.height=x.y,j=h.getContext("2d"),I=new Uint8Array(g.x*g.y),p.attachData=function(w){I=w},p.getData=function(){return I},p.grab=function(){var w,N=f.halfSample,C=u.getFrame(),A=C,F=0;if(A){if(s(h,x),f.type==="ImageStream"&&(A=C.img,C.tags&&C.tags.orientation))switch(C.tags.orientation){case 6:F=90*l;break;case 8:F=-90*l}return F!==0?(j.translate(x.x/2,x.y/2),j.rotate(F),j.drawImage(A,-x.y/2,-x.x/2,x.y,x.x),j.rotate(-F),j.translate(-x.x/2,-x.y/2)):j.drawImage(A,0,0,x.x,x.y),w=j.getImageData(y,_,g.x,g.y).data,N?a.i(c.c)(w,g,I):a.i(c.d)(w,I,f),!0}return!1},p.getSize=function(){return g},p},o.a=m},function(i,o,a){function s(m,u){m.onload=function(){u.loaded(this)}}var c=a(60),l={};l.load=function(m,u,d,h,p){var f,x,g,b=new Array(h),y=new Array(b.length);if(p===!1)b[0]=m;else for(f=0;f<b.length;f++)g=d+f,b[f]=m+"image-"+("00"+g).slice(-3)+".jpg";for(y.notLoaded=[],y.addImage=function(_){y.notLoaded.push(_)},y.loaded=function(_){for(var j=y.notLoaded,I=0;I<j.length;I++)if(j[I]===_){j.splice(I,1);for(var w=0;w<b.length;w++){var N=b[w].substr(b[w].lastIndexOf("/"));if(_.src.lastIndexOf(N)!==-1){y[w]={img:_};break}}break}j.length===0&&(p===!1?a.i(c.a)(m,["orientation"]).then(function(C){y[0].tags=C,u(y)}).catch(function(C){console.log(C),u(y)}):u(y))},f=0;f<b.length;f++)x=new Image,y.addImage(x),s(x,y),x.src=b[f]},o.a=l},function(i,o,a){var s=a(62),c={};c.createVideoStream=function(l){function m(){var y=l.videoWidth,_=l.videoHeight;u=p.size?y/_>1?p.size:Math.floor(y/_*p.size):y,d=p.size?y/_>1?Math.floor(_/y*p.size):p.size:_,b.x=u,b.y=d}var u,d,h={},p=null,f=["canrecord","ended"],x={},g={x:0,y:0},b={x:0,y:0};return h.getRealWidth=function(){return l.videoWidth},h.getRealHeight=function(){return l.videoHeight},h.getWidth=function(){return u},h.getHeight=function(){return d},h.setWidth=function(y){u=y},h.setHeight=function(y){d=y},h.setInputStream=function(y){p=y,l.src=y.src!==void 0?y.src:""},h.ended=function(){return l.ended},h.getConfig=function(){return p},h.setAttribute=function(y,_){l.setAttribute(y,_)},h.pause=function(){l.pause()},h.play=function(){l.play()},h.setCurrentTime=function(y){p.type!=="LiveStream"&&(l.currentTime=y)},h.addEventListener=function(y,_,j){f.indexOf(y)!==-1?(x[y]||(x[y]=[]),x[y].push(_)):l.addEventListener(y,_,j)},h.clearEventHandlers=function(){f.forEach(function(y){var _=x[y];_&&_.length>0&&_.forEach(function(j){l.removeEventListener(y,j)})})},h.trigger=function(y,_){var j,I=x[y];if(y==="canrecord"&&m(),I&&I.length>0)for(j=0;j<I.length;j++)I[j].apply(h,_)},h.setTopRight=function(y){g.x=y.x,g.y=y.y},h.getTopRight=function(){return g},h.setCanvasSize=function(y){b.x=y.x,b.y=y.y},h.getCanvasSize=function(){return b},h.getFrame=function(){return l},h},c.createLiveStream=function(l){l.setAttribute("autoplay",!0);var m=c.createVideoStream(l);return m.ended=function(){return!1},m},c.createImageStream=function(){function l(){y=!1,s.a.load(w,function(k){if(_=k,k[0].tags&&k[0].tags.orientation)switch(k[0].tags.orientation){case 6:case 8:f=k[0].img.height,x=k[0].img.width;break;default:f=k[0].img.width,x=k[0].img.height}else f=k[0].img.width,x=k[0].img.height;u=p.size?f/x>1?p.size:Math.floor(f/x*p.size):f,d=p.size?f/x>1?Math.floor(x/f*p.size):p.size:x,T.x=u,T.y=d,y=!0,g=0,setTimeout(function(){m("canrecord",[])},0)},I,j,p.sequence)}function m(k,P){var S,E=A[k];if(E&&E.length>0)for(S=0;S<E.length;S++)E[S].apply(h,P)}var u,d,h={},p=null,f=0,x=0,g=0,b=!0,y=!1,_=null,j=0,I=1,w=null,N=!1,C=["canrecord","ended"],A={},F={x:0,y:0},T={x:0,y:0};return h.trigger=m,h.getWidth=function(){return u},h.getHeight=function(){return d},h.setWidth=function(k){u=k},h.setHeight=function(k){d=k},h.getRealWidth=function(){return f},h.getRealHeight=function(){return x},h.setInputStream=function(k){p=k,k.sequence===!1?(w=k.src,j=1):(w=k.src,j=k.length),l()},h.ended=function(){return N},h.setAttribute=function(){},h.getConfig=function(){return p},h.pause=function(){b=!0},h.play=function(){b=!1},h.setCurrentTime=function(k){g=k},h.addEventListener=function(k,P){C.indexOf(k)!==-1&&(A[k]||(A[k]=[]),A[k].push(P))},h.setTopRight=function(k){F.x=k.x,F.y=k.y},h.getTopRight=function(){return F},h.setCanvasSize=function(k){T.x=k.x,T.y=k.y},h.getCanvasSize=function(){return T},h.getFrame=function(){var k;return y?(b||(k=_[g],g<j-1?g++:setTimeout(function(){N=!0,m("ended",[])},0)),k):null},h},o.a=c},function(i,o,a){(function(s){function c(){var B;_=y.halfSample?new S.a({x:k.size.x/2|0,y:k.size.y/2|0}):k,T=a.i(E.e)(y.patchSize,_.size),Q.x=_.size.x/T.x|0,Q.y=_.size.y/T.y|0,F=new S.a(_.size,void 0,Uint8Array,!1),w=new S.a(T,void 0,Array,!0),B=new ArrayBuffer(65536),I=new S.a(T,new Uint8Array(B,0,T.x*T.y)),j=new S.a(T,new Uint8Array(B,T.x*T.y*3,T.x*T.y),void 0,!0),P=a.i($.a)(typeof window<"u"?window:typeof self<"u"?self:s,{size:T.x},B),A=new S.a({x:_.size.x/I.size.x|0,y:_.size.y/I.size.y|0},void 0,Array,!0),N=new S.a(A.size,void 0,void 0,!0),C=new S.a(A.size,void 0,Int32Array,!0)}function l(){y.useWorker||typeof document>"u"||(U.dom.binary=document.createElement("canvas"),U.dom.binary.className="binaryBuffer",U.ctx.binary=U.dom.binary.getContext("2d"),U.dom.binary.width=F.size.x,U.dom.binary.height=F.size.y)}function m(B){var z,H,Y,J,ie,ce,ke,be=F.size.x,Se=F.size.y,je=-F.size.x,Re=-F.size.y;for(z=0,H=0;H<B.length;H++)J=B[H],z+=J.rad;for(z/=B.length,z=(180*z/Math.PI+90)%180-90,z<0&&(z+=180),z=(180-z)*Math.PI/180,ie=X.copy(X.create(),[Math.cos(z),Math.sin(z),-Math.sin(z),Math.cos(z)]),H=0;H<B.length;H++)for(J=B[H],Y=0;Y<4;Y++)M.transformMat2(J.box[Y],J.box[Y],ie);for(H=0;H<B.length;H++)for(J=B[H],Y=0;Y<4;Y++)J.box[Y][0]<be&&(be=J.box[Y][0]),J.box[Y][0]>je&&(je=J.box[Y][0]),J.box[Y][1]<Se&&(Se=J.box[Y][1]),J.box[Y][1]>Re&&(Re=J.box[Y][1]);for(ce=[[be,Se],[je,Se],[je,Re],[be,Re]],ke=y.halfSample?2:1,ie=X.invert(ie,ie),Y=0;Y<4;Y++)M.transformMat2(ce[Y],ce[Y],ie);for(Y=0;Y<4;Y++)M.scale(ce[Y],ce[Y],ke);return ce}function u(){a.i(E.f)(_,F),F.zeroBorder()}function d(){var B,z,H,Y,J,ie,ce,ke=[];for(B=0;B<Q.x;B++)for(z=0;z<Q.y;z++)H=I.size.x*B,Y=I.size.y*z,x(H,Y),j.zeroBorder(),O.a.init(w.data,0),ie=R.a.create(j,w),ce=ie.rasterize(0),J=w.moments(ce.count),ke=ke.concat(g(J,[B,z],H,Y));return ke}function h(B){var z,H,Y=[];for(z=0;z<B;z++)Y.push(0);for(H=C.data.length;H--;)C.data[H]>0&&Y[C.data[H]-1]++;return Y=Y.map(function(J,ie){return{val:J,label:ie+1}}),Y.sort(function(J,ie){return ie.val-J.val}),Y.filter(function(J){return J.val>=5})}function p(B,z){var H,Y,J,ie,ce=[],ke=[];for(H=0;H<B.length;H++){for(Y=C.data.length,ce.length=0;Y--;)C.data[Y]===B[H].label&&(J=A.data[Y],ce.push(J));ie=m(ce),ie&&ke.push(ie)}return ke}function f(B){var z=a.i(E.g)(B,.9),H=a.i(E.h)(z,1,function(ce){return ce.getPoints().length}),Y=[],J=[];if(H.length===1){Y=H[0].item.getPoints();for(var ie=0;ie<Y.length;ie++)J.push(Y[ie].point)}return J}function x(B,z){F.subImageAsCopy(I,a.i(E.b)(B,z)),P.skeletonize()}function g(B,z,H,Y){var J,ie,ce,ke,be=[],Se=[],je=Math.ceil(T.x/3);if(B.length>=2){for(J=0;J<B.length;J++)B[J].m00>je&&be.push(B[J]);if(be.length>=2){for(ce=f(be),ie=0,J=0;J<ce.length;J++)ie+=ce[J].rad;ce.length>1&&ce.length>=be.length/4*3&&ce.length>B.length/4&&(ie/=ce.length,ke={index:z[1]*Q.x+z[0],pos:{x:H,y:Y},box:[M.clone([H,Y]),M.clone([H+I.size.x,Y]),M.clone([H+I.size.x,Y+I.size.y]),M.clone([H,Y+I.size.y])],moments:ce,rad:ie,vec:M.clone([Math.cos(ie),Math.sin(ie)])},Se.push(ke))}}return Se}function b(B){function z(){var be;for(be=0;be<C.data.length;be++)if(C.data[be]===0&&N.data[be]===1)return be;return C.length}function H(be){var Se,je,Re,We,se,q={x:be%C.size.x,y:be/C.size.x|0};if(be<C.data.length)for(Re=A.data[be],C.data[be]=ie,se=0;se<D.a.searchDirections.length;se++)je=q.y+D.a.searchDirections[se][0],Se=q.x+D.a.searchDirections[se][1],We=je*C.size.x+Se,N.data[We]!==0?C.data[We]===0&&Math.abs(M.dot(A.data[We].vec,Re.vec))>ce&&H(We):C.data[We]=Number.MAX_VALUE}var Y,J,ie=0,ce=.95,ke=0;for(O.a.init(N.data,0),O.a.init(C.data,0),O.a.init(A.data,null),Y=0;Y<B.length;Y++)J=B[Y],A.data[J.index]=J,N.data[J.index]=1;for(N.zeroBorder();(ke=z())<C.data.length;)ie++,H(ke);return ie}var y,_,j,I,w,N,C,A,F,T,k,P,S=a(20),E=a(19),O=a(3),R=(a(9),a(65)),D=a(30),$=a(66),M={clone:a(7),dot:a(32),scale:a(81),transformMat2:a(82)},X={copy:a(78),create:a(79),invert:a(80)},U={ctx:{binary:null},dom:{binary:null}},Q={x:0,y:0};o.a={init:function(B,z){y=z,k=B,c(),l()},locate:function(){var B,z;if(y.halfSample&&a.i(E.i)(k,_),u(),B=d(),B.length<Q.x*Q.y*.05)return null;var H=b(B);return H<1?null:(z=h(H),z.length===0?null:p(z))},checkImageConstraints:function(B,z){var H,Y,J,ie=B.getWidth(),ce=B.getHeight(),ke=z.halfSample?.5:1;if(B.getConfig().area&&(J=a.i(E.j)(ie,ce,B.getConfig().area),B.setTopRight({x:J.sx,y:J.sy}),B.setCanvasSize({x:ie,y:ce}),ie=J.sw,ce=J.sh),Y={x:Math.floor(ie*ke),y:Math.floor(ce*ke)},H=a.i(E.e)(z.patchSize,Y),B.setWidth(Math.floor(Math.floor(Y.x/H.x)*(1/ke)*H.x)),B.setHeight(Math.floor(Math.floor(Y.y/H.y)*(1/ke)*H.y)),B.getWidth()%H.x==0&&B.getHeight()%H.y==0)return!0;throw new Error("Image dimensions do not comply with the current settings: Width ("+ie+" )and height ("+ce+") must a multiple of "+H.x)}}}).call(o,a(47))},function(i,o,a){var s=a(30),c={createContour2D:function(){return{dir:null,index:null,firstVertex:null,insideContours:null,nextpeer:null,prevpeer:null}},CONTOUR_DIR:{CW_DIR:0,CCW_DIR:1,UNKNOWN_DIR:2},DIR:{OUTSIDE_EDGE:-32767,INSIDE_EDGE:-32766},create:function(l,m){var u=l.data,d=m.data,h=l.size.x,p=l.size.y,f=s.a.create(l,m);return{rasterize:function(x){var g,b,y,_,j,I,w,N,C,A,F,T,k=[],P=0;for(T=0;T<400;T++)k[T]=0;for(k[0]=u[0],C=null,I=1;I<p-1;I++)for(_=0,b=k[0],j=1;j<h-1;j++)if(F=I*h+j,d[F]===0)if((g=u[F])!==b){if(_===0)y=P+1,k[y]=g,b=g,(w=f.contourTracing(I,j,y,g,c.DIR.OUTSIDE_EDGE))!==null&&(P++,_=y,N=c.createContour2D(),N.dir=c.CONTOUR_DIR.CW_DIR,N.index=_,N.firstVertex=w,N.nextpeer=C,N.insideContours=null,C!==null&&(C.prevpeer=N),C=N);else if((w=f.contourTracing(I,j,c.DIR.INSIDE_EDGE,g,_))!==null){for(N=c.createContour2D(),N.firstVertex=w,N.insideContours=null,N.dir=x===0?c.CONTOUR_DIR.CCW_DIR:c.CONTOUR_DIR.CW_DIR,N.index=x,A=C;A!==null&&A.index!==_;)A=A.nextpeer;A!==null&&(N.nextpeer=A.insideContours,A.insideContours!==null&&(A.insideContours.prevpeer=N),A.insideContours=N)}}else d[F]=_;else d[F]===c.DIR.OUTSIDE_EDGE||d[F]===c.DIR.INSIDE_EDGE?(_=0,b=d[F]===c.DIR.INSIDE_EDGE?u[F]:k[0]):(_=d[F],b=k[_]);for(A=C;A!==null;)A.index=x,A=A.nextpeer;return{cc:C,count:P}},debug:{drawContour:function(x,g){var b,y,_,j=x.getContext("2d"),I=g;for(j.strokeStyle="red",j.fillStyle="red",j.lineWidth=1,b=I!==null?I.insideContours:null;I!==null;){switch(b!==null?(y=b,b=b.nextpeer):(y=I,I=I.nextpeer,b=I!==null?I.insideContours:null),y.dir){case c.CONTOUR_DIR.CW_DIR:j.strokeStyle="red";break;case c.CONTOUR_DIR.CCW_DIR:j.strokeStyle="blue";break;case c.CONTOUR_DIR.UNKNOWN_DIR:j.strokeStyle="green"}_=y.firstVertex,j.beginPath(),j.moveTo(_.x,_.y);do _=_.next,j.lineTo(_.x,_.y);while(_!==y.firstVertex);j.stroke()}}}}}};o.a=c},function(i,o,a){function s(c,l,m){var u=new c.Uint8Array(m),d=l.size|0,h=c.Math.imul;function p(w,N){w=w|0,N=N|0;var C=0,A=0,F=0,T=0,k=0,P=0,S=0,E=0;for(C=1;(C|0)<(d-1|0);C=C+1|0)for(E=E+d|0,A=1;(A|0)<(d-1|0);A=A+1|0)T=E-d|0,k=E+d|0,P=A-1|0,S=A+1|0,F=(u[w+T+P|0]|0)+(u[w+T+S|0]|0)+(u[w+E+A|0]|0)+(u[w+k+P|0]|0)+(u[w+k+S|0]|0)|0,(F|0)==5?u[N+E+A|0]=1:u[N+E+A|0]=0}function f(w,N,C){w=w|0,N=N|0,C=C|0;var A=0;for(A=h(d,d)|0;(A|0)>0;)A=A-1|0,u[C+A|0]=(u[w+A|0]|0)-(u[N+A|0]|0)|0}function x(w,N,C){w=w|0,N=N|0,C=C|0;var A=0;for(A=h(d,d)|0;(A|0)>0;)A=A-1|0,u[C+A|0]=u[w+A|0]|0|(u[N+A|0]|0)|0}function g(w){w=w|0;var N=0,C=0;for(C=h(d,d)|0;(C|0)>0;)C=C-1|0,N=(N|0)+(u[w+C|0]|0)|0;return N|0}function b(w,N){w=w|0,N=N|0;var C=0;for(C=h(d,d)|0;(C|0)>0;)C=C-1|0,u[w+C|0]=N}function y(w,N){w=w|0,N=N|0;var C=0,A=0,F=0,T=0,k=0,P=0,S=0,E=0;for(C=1;(C|0)<(d-1|0);C=C+1|0)for(E=E+d|0,A=1;(A|0)<(d-1|0);A=A+1|0)T=E-d|0,k=E+d|0,P=A-1|0,S=A+1|0,F=(u[w+T+P|0]|0)+(u[w+T+S|0]|0)+(u[w+E+A|0]|0)+(u[w+k+P|0]|0)+(u[w+k+S|0]|0)|0,(F|0)>0?u[N+E+A|0]=1:u[N+E+A|0]=0}function _(w,N){w=w|0,N=N|0;var C=0;for(C=h(d,d)|0;(C|0)>0;)C=C-1|0,u[N+C|0]=u[w+C|0]|0}function j(w){w=w|0;var N=0,C=0;for(N=0;(N|0)<(d-1|0);N=N+1|0)u[w+N|0]=0,u[w+C|0]=0,C=C+d-1|0,u[w+C|0]=0,C=C+1|0;for(N=0;(N|0)<(d|0);N=N+1|0)u[w+C|0]=0,C=C+1|0}function I(){var w=0,N=0,C=0,A=0,F=0,T=0;N=h(d,d)|0,C=N+N|0,A=C+N|0,b(A,0),j(w);do p(w,N),y(N,C),f(w,C,C),x(A,C,A),_(N,w),F=g(w)|0,T=(F|0)==0|0;while(!T)}return{skeletonize:I}}o.a=s},function(i,o,a){function s(h){c.a.call(this,h),this.barSpaceRatio=[1,1]}var c=a(1),l=1,m=3,u={START_PATTERN:{value:[m,l,m,l,l,l]},STOP_PATTERN:{value:[m,l,l,l,m]},CODE_PATTERN:{value:[[l,l,m,m,l],[m,l,l,l,m],[l,m,l,l,m],[m,m,l,l,l],[l,l,m,l,m],[m,l,m,l,l],[l,m,m,l,l],[l,l,l,m,m],[m,l,l,m,l],[l,m,l,m,l]]},SINGLE_CODE_ERROR:{value:.78,writable:!0},AVG_CODE_ERROR:{value:.3,writable:!0},FORMAT:{value:"2of5"}},d=u.START_PATTERN.value.reduce(function(h,p){return h+p},0);s.prototype=Object.create(c.a.prototype,u),s.prototype.constructor=s,s.prototype._findPattern=function(h,p,f,x){var g,b,y,_,j=[],I=this,w=0,N={error:Number.MAX_VALUE,code:-1,start:0,end:0},C=I.AVG_CODE_ERROR;for(f=f||!1,x=x||!1,p||(p=I._nextSet(I._row)),g=0;g<h.length;g++)j[g]=0;for(g=p;g<I._row.length;g++)if(I._row[g]^f)j[w]++;else{if(w===j.length-1){for(_=0,y=0;y<j.length;y++)_+=j[y];if((b=I._matchPattern(j,h))<C)return N.error=b,N.start=g-_,N.end=g,N;if(!x)return null;for(y=0;y<j.length-2;y++)j[y]=j[y+2];j[j.length-2]=0,j[j.length-1]=0,w--}else w++;j[w]=1,f=!f}return null},s.prototype._findStart=function(){for(var h,p,f=this,x=f._nextSet(f._row),g=1;!p;){if(!(p=f._findPattern(f.START_PATTERN,x,!1,!0)))return null;if(g=Math.floor((p.end-p.start)/d),(h=p.start-5*g)>=0&&f._matchRange(h,p.start,0))return p;x=p.end,p=null}},s.prototype._verifyTrailingWhitespace=function(h){var p,f=this;return p=h.end+(h.end-h.start)/2,p<f._row.length&&f._matchRange(h.end,p,0)?h:null},s.prototype._findEnd=function(){var h,p,f,x=this;return x._row.reverse(),f=x._nextSet(x._row),h=x._findPattern(x.STOP_PATTERN,f,!1,!0),x._row.reverse(),h===null?null:(p=h.start,h.start=x._row.length-h.end,h.end=x._row.length-p,h!==null?x._verifyTrailingWhitespace(h):null)},s.prototype._decodeCode=function(h){var p,f,x,g=this,b=0,y=g.AVG_CODE_ERROR,_={error:Number.MAX_VALUE,code:-1,start:0,end:0};for(p=0;p<h.length;p++)b+=h[p];for(x=0;x<g.CODE_PATTERN.length;x++)(f=g._matchPattern(h,g.CODE_PATTERN[x]))<_.error&&(_.code=x,_.error=f);if(_.error<y)return _},s.prototype._decodePayload=function(h,p,f){for(var x,g,b=this,y=0,_=h.length,j=[0,0,0,0,0];y<_;){for(x=0;x<5;x++)j[x]=h[y]*this.barSpaceRatio[0],y+=2;if(!(g=b._decodeCode(j)))return null;p.push(g.code+""),f.push(g)}return g},s.prototype._verifyCounterLength=function(h){return h.length%10==0},s.prototype._decode=function(){var h,p,f,x=this,g=[],b=[];return(h=x._findStart())?(b.push(h),(p=x._findEnd())?(f=x._fillCounters(h.end,p.start,!1),x._verifyCounterLength(f)&&x._decodePayload(f,g,b)?g.length<5?null:(b.push(p),{code:g.join(""),start:h.start,end:p.end,startInfo:h,decodedCodes:b}):null):null):null},o.a=s},function(i,o,a){function s(){c.a.call(this),this._counters=[]}var c=a(1),l={ALPHABETH_STRING:{value:"0123456789-$:/.+ABCD"},ALPHABET:{value:[48,49,50,51,52,53,54,55,56,57,45,36,58,47,46,43,65,66,67,68]},CHARACTER_ENCODINGS:{value:[3,6,9,96,18,66,33,36,48,72,12,24,69,81,84,21,26,41,11,14]},START_END:{value:[26,41,11,14]},MIN_ENCODED_CHARS:{value:4},MAX_ACCEPTABLE:{value:2},PADDING:{value:1.5},FORMAT:{value:"codabar",writeable:!1}};s.prototype=Object.create(c.a.prototype,l),s.prototype.constructor=s,s.prototype._decode=function(){var m,u,d,h,p,f=this,x=[];if(this._counters=f._fillCounters(),!(m=f._findStart()))return null;h=m.startCounter;do{if((d=f._toPattern(h))<0||(u=f._patternToChar(d))<0)return null;if(x.push(u),h+=8,x.length>1&&f._isStartEnd(d))break}while(h<f._counters.length);return x.length-2<f.MIN_ENCODED_CHARS||!f._isStartEnd(d)?null:f._verifyWhitespace(m.startCounter,h-8)&&f._validateResult(x,m.startCounter)?(h=h>f._counters.length?f._counters.length:h,p=m.start+f._sumCounters(m.startCounter,h-8),{code:x.join(""),start:m.start,end:p,startInfo:m,decodedCodes:x}):null},s.prototype._verifyWhitespace=function(m,u){return(m-1<=0||this._counters[m-1]>=this._calculatePatternLength(m)/2)&&(u+8>=this._counters.length||this._counters[u+7]>=this._calculatePatternLength(u)/2)},s.prototype._calculatePatternLength=function(m){var u,d=0;for(u=m;u<m+7;u++)d+=this._counters[u];return d},s.prototype._thresholdResultPattern=function(m,u){var d,h,p,f,x,g=this,b={space:{narrow:{size:0,counts:0,min:0,max:Number.MAX_VALUE},wide:{size:0,counts:0,min:0,max:Number.MAX_VALUE}},bar:{narrow:{size:0,counts:0,min:0,max:Number.MAX_VALUE},wide:{size:0,counts:0,min:0,max:Number.MAX_VALUE}}},y=u;for(p=0;p<m.length;p++){for(x=g._charToPattern(m[p]),f=6;f>=0;f--)d=(1&f)==2?b.bar:b.space,h=(1&x)==1?d.wide:d.narrow,h.size+=g._counters[y+f],h.counts++,x>>=1;y+=8}return["space","bar"].forEach(function(_){var j=b[_];j.wide.min=Math.floor((j.narrow.size/j.narrow.counts+j.wide.size/j.wide.counts)/2),j.narrow.max=Math.ceil(j.wide.min),j.wide.max=Math.ceil((j.wide.size*g.MAX_ACCEPTABLE+g.PADDING)/j.wide.counts)}),b},s.prototype._charToPattern=function(m){var u,d=this,h=m.charCodeAt(0);for(u=0;u<d.ALPHABET.length;u++)if(d.ALPHABET[u]===h)return d.CHARACTER_ENCODINGS[u];return 0},s.prototype._validateResult=function(m,u){var d,h,p,f,x,g,b=this,y=b._thresholdResultPattern(m,u),_=u;for(d=0;d<m.length;d++){for(g=b._charToPattern(m[d]),h=6;h>=0;h--){if(p=1&h?y.space:y.bar,f=(1&g)==1?p.wide:p.narrow,(x=b._counters[_+h])<f.min||x>f.max)return!1;g>>=1}_+=8}return!0},s.prototype._patternToChar=function(m){var u,d=this;for(u=0;u<d.CHARACTER_ENCODINGS.length;u++)if(d.CHARACTER_ENCODINGS[u]===m)return String.fromCharCode(d.ALPHABET[u]);return-1},s.prototype._computeAlternatingThreshold=function(m,u){var d,h,p=Number.MAX_VALUE,f=0;for(d=m;d<u;d+=2)h=this._counters[d],h>f&&(f=h),h<p&&(p=h);return(p+f)/2|0},s.prototype._toPattern=function(m){var u,d,h,p,f=7,x=m+f,g=1<<f-1,b=0;if(x>this._counters.length)return-1;for(u=this._computeAlternatingThreshold(m,x),d=this._computeAlternatingThreshold(m+1,x),h=0;h<f;h++)p=1&h?d:u,this._counters[m+h]>p&&(b|=g),g>>=1;return b},s.prototype._isStartEnd=function(m){var u;for(u=0;u<this.START_END.length;u++)if(this.START_END[u]===m)return!0;return!1},s.prototype._sumCounters=function(m,u){var d,h=0;for(d=m;d<u;d++)h+=this._counters[d];return h},s.prototype._findStart=function(){var m,u,d,h=this,p=h._nextUnset(h._row);for(m=1;m<this._counters.length;m++)if((u=h._toPattern(m))!==-1&&h._isStartEnd(u))return p+=h._sumCounters(0,m),d=p+h._sumCounters(m,m+8),{start:p,end:d,startCounter:m,endCounter:m+8}},o.a=s},function(i,o,a){function s(){l.a.call(this)}function c(u,d,h){for(var p=h.length,f=0,x=0;p--;)x+=u[h[p]],f+=d[h[p]];return x/f}var l=a(1),m={CODE_SHIFT:{value:98},CODE_C:{value:99},CODE_B:{value:100},CODE_A:{value:101},START_CODE_A:{value:103},START_CODE_B:{value:104},START_CODE_C:{value:105},STOP_CODE:{value:106},CODE_PATTERN:{value:[[2,1,2,2,2,2],[2,2,2,1,2,2],[2,2,2,2,2,1],[1,2,1,2,2,3],[1,2,1,3,2,2],[1,3,1,2,2,2],[1,2,2,2,1,3],[1,2,2,3,1,2],[1,3,2,2,1,2],[2,2,1,2,1,3],[2,2,1,3,1,2],[2,3,1,2,1,2],[1,1,2,2,3,2],[1,2,2,1,3,2],[1,2,2,2,3,1],[1,1,3,2,2,2],[1,2,3,1,2,2],[1,2,3,2,2,1],[2,2,3,2,1,1],[2,2,1,1,3,2],[2,2,1,2,3,1],[2,1,3,2,1,2],[2,2,3,1,1,2],[3,1,2,1,3,1],[3,1,1,2,2,2],[3,2,1,1,2,2],[3,2,1,2,2,1],[3,1,2,2,1,2],[3,2,2,1,1,2],[3,2,2,2,1,1],[2,1,2,1,2,3],[2,1,2,3,2,1],[2,3,2,1,2,1],[1,1,1,3,2,3],[1,3,1,1,2,3],[1,3,1,3,2,1],[1,1,2,3,1,3],[1,3,2,1,1,3],[1,3,2,3,1,1],[2,1,1,3,1,3],[2,3,1,1,1,3],[2,3,1,3,1,1],[1,1,2,1,3,3],[1,1,2,3,3,1],[1,3,2,1,3,1],[1,1,3,1,2,3],[1,1,3,3,2,1],[1,3,3,1,2,1],[3,1,3,1,2,1],[2,1,1,3,3,1],[2,3,1,1,3,1],[2,1,3,1,1,3],[2,1,3,3,1,1],[2,1,3,1,3,1],[3,1,1,1,2,3],[3,1,1,3,2,1],[3,3,1,1,2,1],[3,1,2,1,1,3],[3,1,2,3,1,1],[3,3,2,1,1,1],[3,1,4,1,1,1],[2,2,1,4,1,1],[4,3,1,1,1,1],[1,1,1,2,2,4],[1,1,1,4,2,2],[1,2,1,1,2,4],[1,2,1,4,2,1],[1,4,1,1,2,2],[1,4,1,2,2,1],[1,1,2,2,1,4],[1,1,2,4,1,2],[1,2,2,1,1,4],[1,2,2,4,1,1],[1,4,2,1,1,2],[1,4,2,2,1,1],[2,4,1,2,1,1],[2,2,1,1,1,4],[4,1,3,1,1,1],[2,4,1,1,1,2],[1,3,4,1,1,1],[1,1,1,2,4,2],[1,2,1,1,4,2],[1,2,1,2,4,1],[1,1,4,2,1,2],[1,2,4,1,1,2],[1,2,4,2,1,1],[4,1,1,2,1,2],[4,2,1,1,1,2],[4,2,1,2,1,1],[2,1,2,1,4,1],[2,1,4,1,2,1],[4,1,2,1,2,1],[1,1,1,1,4,3],[1,1,1,3,4,1],[1,3,1,1,4,1],[1,1,4,1,1,3],[1,1,4,3,1,1],[4,1,1,1,1,3],[4,1,1,3,1,1],[1,1,3,1,4,1],[1,1,4,1,3,1],[3,1,1,1,4,1],[4,1,1,1,3,1],[2,1,1,4,1,2],[2,1,1,2,1,4],[2,1,1,2,3,2],[2,3,3,1,1,1,2]]},SINGLE_CODE_ERROR:{value:.64},AVG_CODE_ERROR:{value:.3},FORMAT:{value:"code_128",writeable:!1},MODULE_INDICES:{value:{bar:[0,2,4],space:[1,3,5]}}};s.prototype=Object.create(l.a.prototype,m),s.prototype.constructor=s,s.prototype._decodeCode=function(u,d){var h,p,f,x=[0,0,0,0,0,0],g=this,b=u,y=!g._row[b],_=0,j={error:Number.MAX_VALUE,code:-1,start:u,end:u,correction:{bar:1,space:1}};for(h=b;h<g._row.length;h++)if(g._row[h]^y)x[_]++;else{if(_===x.length-1){for(d&&g._correct(x,d),p=0;p<g.CODE_PATTERN.length;p++)(f=g._matchPattern(x,g.CODE_PATTERN[p]))<j.error&&(j.code=p,j.error=f);return j.end=h,j.code===-1||j.error>g.AVG_CODE_ERROR?null:(g.CODE_PATTERN[j.code]&&(j.correction.bar=c(g.CODE_PATTERN[j.code],x,this.MODULE_INDICES.bar),j.correction.space=c(g.CODE_PATTERN[j.code],x,this.MODULE_INDICES.space)),j)}_++,x[_]=1,y=!y}return null},s.prototype._correct=function(u,d){this._correctBars(u,d.bar,this.MODULE_INDICES.bar),this._correctBars(u,d.space,this.MODULE_INDICES.space)},s.prototype._findStart=function(){var u,d,h,p,f,x=[0,0,0,0,0,0],g=this,b=g._nextSet(g._row),y=!1,_=0,j={error:Number.MAX_VALUE,code:-1,start:0,end:0,correction:{bar:1,space:1}};for(u=b;u<g._row.length;u++)if(g._row[u]^y)x[_]++;else{if(_===x.length-1){for(f=0,p=0;p<x.length;p++)f+=x[p];for(d=g.START_CODE_A;d<=g.START_CODE_C;d++)(h=g._matchPattern(x,g.CODE_PATTERN[d]))<j.error&&(j.code=d,j.error=h);if(j.error<g.AVG_CODE_ERROR)return j.start=u-f,j.end=u,j.correction.bar=c(g.CODE_PATTERN[j.code],x,this.MODULE_INDICES.bar),j.correction.space=c(g.CODE_PATTERN[j.code],x,this.MODULE_INDICES.space),j;for(p=0;p<4;p++)x[p]=x[p+2];x[4]=0,x[5]=0,_--}else _++;x[_]=1,y=!y}return null},s.prototype._decode=function(){var u,d,h=this,p=h._findStart(),f=null,x=!1,g=[],b=0,y=0,_=[],j=[],I=!1,w=!0;if(p===null)return null;switch(f={code:p.code,start:p.start,end:p.end,correction:{bar:p.correction.bar,space:p.correction.space}},j.push(f),y=f.code,f.code){case h.START_CODE_A:u=h.CODE_A;break;case h.START_CODE_B:u=h.CODE_B;break;case h.START_CODE_C:u=h.CODE_C;break;default:return null}for(;!x;){if(d=I,I=!1,(f=h._decodeCode(f.end,f.correction))!==null)switch(f.code!==h.STOP_CODE&&(w=!0),f.code!==h.STOP_CODE&&(_.push(f.code),b++,y+=b*f.code),j.push(f),u){case h.CODE_A:if(f.code<64)g.push(String.fromCharCode(32+f.code));else if(f.code<96)g.push(String.fromCharCode(f.code-64));else switch(f.code!==h.STOP_CODE&&(w=!1),f.code){case h.CODE_SHIFT:I=!0,u=h.CODE_B;break;case h.CODE_B:u=h.CODE_B;break;case h.CODE_C:u=h.CODE_C;break;case h.STOP_CODE:x=!0}break;case h.CODE_B:if(f.code<96)g.push(String.fromCharCode(32+f.code));else switch(f.code!==h.STOP_CODE&&(w=!1),f.code){case h.CODE_SHIFT:I=!0,u=h.CODE_A;break;case h.CODE_A:u=h.CODE_A;break;case h.CODE_C:u=h.CODE_C;break;case h.STOP_CODE:x=!0}break;case h.CODE_C:if(f.code<100)g.push(f.code<10?"0"+f.code:f.code);else switch(f.code!==h.STOP_CODE&&(w=!1),f.code){case h.CODE_A:u=h.CODE_A;break;case h.CODE_B:u=h.CODE_B;break;case h.STOP_CODE:x=!0}}else x=!0;d&&(u=u===h.CODE_A?h.CODE_B:h.CODE_A)}return f===null?null:(f.end=h._nextUnset(h._row,f.end),h._verifyTrailingWhitespace(f)?(y-=b*_[_.length-1])%103!==_[_.length-1]?null:g.length?(w&&g.splice(g.length-1,1),{code:g.join(""),start:p.start,end:f.end,codeset:u,startInfo:p,decodedCodes:j,endInfo:f}):null:null)},l.a.prototype._verifyTrailingWhitespace=function(u){var d,h=this;return d=u.end+(u.end-u.start)/2,d<h._row.length&&h._matchRange(u.end,d,0)?u:null},o.a=s},function(i,o,a){function s(){c.a.call(this)}var c=a(31),l={IOQ:/[IOQ]/g,AZ09:/[A-Z0-9]{17}/};s.prototype=Object.create(c.a.prototype),s.prototype.constructor=s,s.prototype._decode=function(){var m=c.a.prototype._decode.apply(this);if(!m)return null;var u=m.code;return u?(u=u.replace(l.IOQ,""),u.match(l.AZ09)&&this._checkChecksum(u)?(m.code=u,m):null):null},s.prototype._checkChecksum=function(m){return!!m},o.a=s},function(i,o,a){function s(){c.a.call(this)}var c=a(1),l=a(3),m="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. $/+%abcd*",u={ALPHABETH_STRING:{value:m},ALPHABET:{value:m.split("").map(function(d){return d.charCodeAt(0)})},CHARACTER_ENCODINGS:{value:[276,328,324,322,296,292,290,336,274,266,424,420,418,404,402,394,360,356,354,308,282,344,332,326,300,278,436,434,428,422,406,410,364,358,310,314,302,468,466,458,366,374,430,294,474,470,306,350]},ASTERISK:{value:350},FORMAT:{value:"code_93",writeable:!1}};s.prototype=Object.create(c.a.prototype,u),s.prototype.constructor=s,s.prototype._decode=function(){var d,h,p,f,x=this,g=[0,0,0,0,0,0],b=[],y=x._findStart();if(!y)return null;f=x._nextSet(x._row,y.end);do{if(g=x._toCounters(f,g),(p=x._toPattern(g))<0||(d=x._patternToChar(p))<0)return null;b.push(d),h=f,f+=l.a.sum(g),f=x._nextSet(x._row,f)}while(d!=="*");return b.pop(),b.length&&x._verifyEnd(h,f,g)&&x._verifyChecksums(b)?(b=b.slice(0,b.length-2),(b=x._decodeExtended(b))===null?null:{code:b.join(""),start:y.start,end:f,startInfo:y,decodedCodes:b}):null},s.prototype._verifyEnd=function(d,h){return!(d===h||!this._row[h])},s.prototype._patternToChar=function(d){var h,p=this;for(h=0;h<p.CHARACTER_ENCODINGS.length;h++)if(p.CHARACTER_ENCODINGS[h]===d)return String.fromCharCode(p.ALPHABET[h]);return-1},s.prototype._toPattern=function(d){for(var h=d.length,p=0,f=0,x=0;x<h;x++)f+=d[x];for(var g=0;g<h;g++){var b=Math.round(9*d[g]/f);if(b<1||b>4)return-1;if(1&g)p<<=b;else for(var y=0;y<b;y++)p=p<<1|1}return p},s.prototype._findStart=function(){var d,h,p,f=this,x=f._nextSet(f._row),g=x,b=[0,0,0,0,0,0],y=0,_=!1;for(d=x;d<f._row.length;d++)if(f._row[d]^_)b[y]++;else{if(y===b.length-1){if(f._toPattern(b)===f.ASTERISK&&(p=Math.floor(Math.max(0,g-(d-g)/4)),f._matchRange(p,g,0)))return{start:g,end:d};for(g+=b[0]+b[1],h=0;h<4;h++)b[h]=b[h+2];b[4]=0,b[5]=0,y--}else y++;b[y]=1,_=!_}return null},s.prototype._decodeExtended=function(d){for(var h=d.length,p=[],f=0;f<h;f++){var x=d[f];if(x>="a"&&x<="d"){if(f>h-2)return null;var g=d[++f],b=g.charCodeAt(0),y=void 0;switch(x){case"a":if(!(g>="A"&&g<="Z"))return null;y=String.fromCharCode(b-64);break;case"b":if(g>="A"&&g<="E")y=String.fromCharCode(b-38);else if(g>="F"&&g<="J")y=String.fromCharCode(b-11);else if(g>="K"&&g<="O")y=String.fromCharCode(b+16);else if(g>="P"&&g<="S")y=String.fromCharCode(b+43);else{if(!(g>="T"&&g<="Z"))return null;y=""}break;case"c":if(g>="A"&&g<="O")y=String.fromCharCode(b-32);else{if(g!=="Z")return null;y=":"}break;case"d":if(!(g>="A"&&g<="Z"))return null;y=String.fromCharCode(b+32)}p.push(y)}else p.push(x)}return p},s.prototype._verifyChecksums=function(d){return this._matchCheckChar(d,d.length-2,20)&&this._matchCheckChar(d,d.length-1,15)},s.prototype._matchCheckChar=function(d,h,p){var f=this,x=d.slice(0,h),g=x.length,b=x.reduce(function(y,_,j){return y+((j*-1+(g-1))%p+1)*f.ALPHABET.indexOf(_.charCodeAt(0))},0);return this.ALPHABET[b%47]===d[h].charCodeAt(0)},o.a=s},function(i,o,a){function s(){c.a.call(this)}var c=a(4),l={FORMAT:{value:"ean_2",writeable:!1}};s.prototype=Object.create(c.a.prototype,l),s.prototype.constructor=s,s.prototype.decode=function(m,u){this._row=m;var d,h=0,p=0,f=u,x=this._row.length,g=[],b=[];for(p=0;p<2&&f<x;p++){if(!(d=this._decodeCode(f)))return null;b.push(d),g.push(d.code%10),d.code>=this.CODE_G_START&&(h|=1<<1-p),p!=1&&(f=this._nextSet(this._row,d.end),f=this._nextUnset(this._row,f))}return g.length!=2||parseInt(g.join(""))%4!==h?null:{code:g.join(""),decodedCodes:b,end:d.end}},o.a=s},function(i,o,a){function s(){m.a.call(this)}function c(h){var p;for(p=0;p<10;p++)if(h===d[p])return p;return null}function l(h){var p,f=h.length,x=0;for(p=f-2;p>=0;p-=2)x+=h[p];for(x*=3,p=f-1;p>=0;p-=2)x+=h[p];return(x*=3)%10}var m=a(4),u={FORMAT:{value:"ean_5",writeable:!1}},d=[24,20,18,17,12,6,3,10,9,5];s.prototype=Object.create(m.a.prototype,u),s.prototype.constructor=s,s.prototype.decode=function(h,p){this._row=h;var f,x=0,g=0,b=p,y=this._row.length,_=[],j=[];for(g=0;g<5&&b<y;g++){if(!(f=this._decodeCode(b)))return null;j.push(f),_.push(f.code%10),f.code>=this.CODE_G_START&&(x|=1<<4-g),g!=4&&(b=this._nextSet(this._row,f.end),b=this._nextUnset(this._row,b))}return _.length!=5||l(_)!==c(x)?null:{code:_.join(""),decodedCodes:j,end:f.end}},o.a=s},function(i,o,a){function s(m,u){c.a.call(this,m,u)}var c=a(4),l={FORMAT:{value:"ean_8",writeable:!1}};s.prototype=Object.create(c.a.prototype,l),s.prototype.constructor=s,s.prototype._decodePayload=function(m,u,d){var h,p=this;for(h=0;h<4;h++){if(!(m=p._decodeCode(m.end,p.CODE_G_START)))return null;u.push(m.code),d.push(m)}if((m=p._findPattern(p.MIDDLE_PATTERN,m.end,!0,!1))===null)return null;for(d.push(m),h=0;h<4;h++){if(!(m=p._decodeCode(m.end,p.CODE_G_START)))return null;d.push(m),u.push(m.code)}return m},o.a=s},function(i,o,a){function s(f){f=m()(c(),f),u.a.call(this,f),this.barSpaceRatio=[1,1],f.normalizeBarSpaceWidth&&(this.SINGLE_CODE_ERROR=.38,this.AVG_CODE_ERROR=.09)}function c(){var f={};return Object.keys(s.CONFIG_KEYS).forEach(function(x){f[x]=s.CONFIG_KEYS[x].default}),f}var l=a(28),m=a.n(l),u=a(1),d=1,h=3,p={START_PATTERN:{value:[d,d,d,d]},STOP_PATTERN:{value:[d,d,h]},CODE_PATTERN:{value:[[d,d,h,h,d],[h,d,d,d,h],[d,h,d,d,h],[h,h,d,d,d],[d,d,h,d,h],[h,d,h,d,d],[d,h,h,d,d],[d,d,d,h,h],[h,d,d,h,d],[d,h,d,h,d]]},SINGLE_CODE_ERROR:{value:.78,writable:!0},AVG_CODE_ERROR:{value:.38,writable:!0},MAX_CORRECTION_FACTOR:{value:5},FORMAT:{value:"i2of5"}};s.prototype=Object.create(u.a.prototype,p),s.prototype.constructor=s,s.prototype._matchPattern=function(f,x){if(this.config.normalizeBarSpaceWidth){var g,b=[0,0],y=[0,0],_=[0,0],j=this.MAX_CORRECTION_FACTOR,I=1/j;for(g=0;g<f.length;g++)b[g%2]+=f[g],y[g%2]+=x[g];for(_[0]=y[0]/b[0],_[1]=y[1]/b[1],_[0]=Math.max(Math.min(_[0],j),I),_[1]=Math.max(Math.min(_[1],j),I),this.barSpaceRatio=_,g=0;g<f.length;g++)f[g]*=this.barSpaceRatio[g%2]}return u.a.prototype._matchPattern.call(this,f,x)},s.prototype._findPattern=function(f,x,g,b){var y,_,j,I,w=[],N=this,C=0,A={error:Number.MAX_VALUE,code:-1,start:0,end:0},F=N.AVG_CODE_ERROR;for(g=g||!1,b=b||!1,x||(x=N._nextSet(N._row)),y=0;y<f.length;y++)w[y]=0;for(y=x;y<N._row.length;y++)if(N._row[y]^g)w[C]++;else{if(C===w.length-1){for(I=0,j=0;j<w.length;j++)I+=w[j];if((_=N._matchPattern(w,f))<F)return A.error=_,A.start=y-I,A.end=y,A;if(!b)return null;for(j=0;j<w.length-2;j++)w[j]=w[j+2];w[w.length-2]=0,w[w.length-1]=0,C--}else C++;w[C]=1,g=!g}return null},s.prototype._findStart=function(){for(var f,x,g=this,b=g._nextSet(g._row),y=1;!x;){if(!(x=g._findPattern(g.START_PATTERN,b,!1,!0)))return null;if(y=Math.floor((x.end-x.start)/4),(f=x.start-10*y)>=0&&g._matchRange(f,x.start,0))return x;b=x.end,x=null}},s.prototype._verifyTrailingWhitespace=function(f){var x,g=this;return x=f.end+(f.end-f.start)/2,x<g._row.length&&g._matchRange(f.end,x,0)?f:null},s.prototype._findEnd=function(){var f,x,g=this;return g._row.reverse(),f=g._findPattern(g.STOP_PATTERN),g._row.reverse(),f===null?null:(x=f.start,f.start=g._row.length-f.end,f.end=g._row.length-x,f!==null?g._verifyTrailingWhitespace(f):null)},s.prototype._decodePair=function(f){var x,g,b=[],y=this;for(x=0;x<f.length;x++){if(!(g=y._decodeCode(f[x])))return null;b.push(g)}return b},s.prototype._decodeCode=function(f){var x,g,b,y=this,_=0,j=y.AVG_CODE_ERROR,I={error:Number.MAX_VALUE,code:-1,start:0,end:0};for(x=0;x<f.length;x++)_+=f[x];for(b=0;b<y.CODE_PATTERN.length;b++)(g=y._matchPattern(f,y.CODE_PATTERN[b]))<I.error&&(I.code=b,I.error=g);if(I.error<j)return I},s.prototype._decodePayload=function(f,x,g){for(var b,y,_=this,j=0,I=f.length,w=[[0,0,0,0,0],[0,0,0,0,0]];j<I;){for(b=0;b<5;b++)w[0][b]=f[j]*this.barSpaceRatio[0],w[1][b]=f[j+1]*this.barSpaceRatio[1],j+=2;if(!(y=_._decodePair(w)))return null;for(b=0;b<y.length;b++)x.push(y[b].code+""),g.push(y[b])}return y},s.prototype._verifyCounterLength=function(f){return f.length%10==0},s.prototype._decode=function(){var f,x,g,b=this,y=[],_=[];return(f=b._findStart())?(_.push(f),(x=b._findEnd())?(g=b._fillCounters(f.end,x.start,!1),b._verifyCounterLength(g)&&b._decodePayload(g,y,_)?y.length%2!=0||y.length<6?null:(_.push(x),{code:y.join(""),start:f.start,end:x.end,startInfo:f,decodedCodes:_}):null):null):null},s.CONFIG_KEYS={normalizeBarSpaceWidth:{type:"boolean",default:!1,description:"If true, the reader tries to normalize thewidth-difference between bars and spaces"}},o.a=s},function(i,o,a){function s(m,u){c.a.call(this,m,u)}var c=a(4),l={CODE_FREQUENCY:{value:[[56,52,50,49,44,38,35,42,41,37],[7,11,13,14,19,25,28,21,22,26]]},STOP_PATTERN:{value:[1/6*7,1/6*7,1/6*7,1/6*7,1/6*7,1/6*7]},FORMAT:{value:"upc_e",writeable:!1}};s.prototype=Object.create(c.a.prototype,l),s.prototype.constructor=s,s.prototype._decodePayload=function(m,u,d){var h,p=this,f=0;for(h=0;h<6;h++){if(!(m=p._decodeCode(m.end)))return null;m.code>=p.CODE_G_START&&(m.code=m.code-p.CODE_G_START,f|=1<<5-h),u.push(m.code),d.push(m)}return p._determineParity(f,u)?m:null},s.prototype._determineParity=function(m,u){var d,h;for(h=0;h<this.CODE_FREQUENCY.length;h++)for(d=0;d<this.CODE_FREQUENCY[h].length;d++)if(m===this.CODE_FREQUENCY[h][d])return u.unshift(h),u.push(d),!0;return!1},s.prototype._convertToUPCA=function(m){var u=[m[0]],d=m[m.length-2];return u=d<=2?u.concat(m.slice(1,3)).concat([d,0,0,0,0]).concat(m.slice(3,6)):d===3?u.concat(m.slice(1,4)).concat([0,0,0,0,0]).concat(m.slice(4,6)):d===4?u.concat(m.slice(1,5)).concat([0,0,0,0,0,m[5]]):u.concat(m.slice(1,6)).concat([0,0,0,0,d]),u.push(m[m.length-1]),u},s.prototype._checksum=function(m){return c.a.prototype._checksum.call(this,this._convertToUPCA(m))},s.prototype._findEnd=function(m,u){return u=!0,c.a.prototype._findEnd.call(this,m,u)},s.prototype._verifyTrailingWhitespace=function(m){var u,d=this;if((u=m.end+(m.end-m.start)/2)<d._row.length&&d._matchRange(m.end,u,0))return m},o.a=s},function(i,o,a){function s(m,u){c.a.call(this,m,u)}var c=a(4),l={FORMAT:{value:"upc_a",writeable:!1}};s.prototype=Object.create(c.a.prototype,l),s.prototype.constructor=s,s.prototype._decode=function(){var m=c.a.prototype._decode.call(this);return m&&m.code&&m.code.length===13&&m.code.charAt(0)==="0"?(m.code=m.code.substring(1),m):null},o.a=s},function(i,o){function a(s,c){return s[0]=c[0],s[1]=c[1],s[2]=c[2],s[3]=c[3],s}i.exports=a},function(i,o){function a(){var s=new Float32Array(4);return s[0]=1,s[1]=0,s[2]=0,s[3]=1,s}i.exports=a},function(i,o){function a(s,c){var l=c[0],m=c[1],u=c[2],d=c[3],h=l*d-u*m;return h?(h=1/h,s[0]=d*h,s[1]=-m*h,s[2]=-u*h,s[3]=l*h,s):null}i.exports=a},function(i,o){function a(s,c,l){return s[0]=c[0]*l,s[1]=c[1]*l,s}i.exports=a},function(i,o){function a(s,c,l){var m=c[0],u=c[1];return s[0]=l[0]*m+l[2]*u,s[1]=l[1]*m+l[3]*u,s}i.exports=a},function(i,o){function a(s){var c=new Float32Array(3);return c[0]=s[0],c[1]=s[1],c[2]=s[2],c}i.exports=a},function(i,o,a){function s(h){var p=-1,f=h==null?0:h.length;for(this.clear();++p<f;){var x=h[p];this.set(x[0],x[1])}}var c=a(122),l=a(123),m=a(124),u=a(125),d=a(126);s.prototype.clear=c,s.prototype.delete=l,s.prototype.get=m,s.prototype.has=u,s.prototype.set=d,i.exports=s},function(i,o,a){function s(p){var f=this.__data__=new c(p);this.size=f.size}var c=a(10),l=a(149),m=a(150),u=a(151),d=a(152),h=a(153);s.prototype.clear=l,s.prototype.delete=m,s.prototype.get=u,s.prototype.has=d,s.prototype.set=h,i.exports=s},function(i,o,a){var s=a(5),c=s.Uint8Array;i.exports=c},function(i,o){function a(s,c,l){switch(l.length){case 0:return s.call(c);case 1:return s.call(c,l[0]);case 2:return s.call(c,l[0],l[1]);case 3:return s.call(c,l[0],l[1],l[2])}return s.apply(c,l)}i.exports=a},function(i,o,a){function s(x,g){var b=m(x),y=!b&&l(x),_=!b&&!y&&u(x),j=!b&&!y&&!_&&h(x),I=b||y||_||j,w=I?c(x.length,String):[],N=w.length;for(var C in x)!g&&!f.call(x,C)||I&&(C=="length"||_&&(C=="offset"||C=="parent")||j&&(C=="buffer"||C=="byteLength"||C=="byteOffset")||d(C,N))||w.push(C);return w}var c=a(107),l=a(18),m=a(2),u=a(44),d=a(15),h=a(45),p=Object.prototype,f=p.hasOwnProperty;i.exports=s},function(i,o){function a(s,c){for(var l=-1,m=s==null?0:s.length,u=Array(m);++l<m;)u[l]=c(s[l],l,s);return u}i.exports=a},function(i,o){function a(s,c){for(var l=-1,m=c.length,u=s.length;++l<m;)s[u+l]=c[l];return s}i.exports=a},function(i,o,a){var s=a(0),c=Object.create,l=function(){function m(){}return function(u){if(!s(u))return{};if(c)return c(u);m.prototype=u;var d=new m;return m.prototype=void 0,d}}();i.exports=l},function(i,o,a){function s(m,u,d,h,p){var f=-1,x=m.length;for(d||(d=l),p||(p=[]);++f<x;){var g=m[f];u>0&&d(g)?u>1?s(g,u-1,d,h,p):c(p,g):h||(p[p.length]=g)}return p}var c=a(90),l=a(128);i.exports=s},function(i,o,a){var s=a(117),c=s();i.exports=c},function(i,o,a){function s(m,u){u=c(u,m);for(var d=0,h=u.length;m!=null&&d<h;)m=m[l(u[d++])];return d&&d==h?m:void 0}var c=a(13),l=a(23);i.exports=s},function(i,o){function a(s,c){return s!=null&&c in Object(s)}i.exports=a},function(i,o,a){function s(u){return l(u)&&c(u)==m}var c=a(8),l=a(6),m="[object Arguments]";i.exports=s},function(i,o,a){function s(y){return!(!m(y)||l(y))&&(c(y)?b:h).test(u(y))}var c=a(25),l=a(132),m=a(0),u=a(155),d=/[\\^$.*+?()[\]{}|]/g,h=/^\[object .+?Constructor\]$/,p=Function.prototype,f=Object.prototype,x=p.toString,g=f.hasOwnProperty,b=RegExp("^"+x.call(g).replace(d,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");i.exports=s},function(i,o,a){function s(d){return m(d)&&l(d.length)&&!!u[c(d)]}var c=a(8),l=a(26),m=a(6),u={};u["[object Float32Array]"]=u["[object Float64Array]"]=u["[object Int8Array]"]=u["[object Int16Array]"]=u["[object Int32Array]"]=u["[object Uint8Array]"]=u["[object Uint8ClampedArray]"]=u["[object Uint16Array]"]=u["[object Uint32Array]"]=!0,u["[object Arguments]"]=u["[object Array]"]=u["[object ArrayBuffer]"]=u["[object Boolean]"]=u["[object DataView]"]=u["[object Date]"]=u["[object Error]"]=u["[object Function]"]=u["[object Map]"]=u["[object Number]"]=u["[object Object]"]=u["[object RegExp]"]=u["[object Set]"]=u["[object String]"]=u["[object WeakMap]"]=!1,i.exports=s},function(i,o,a){function s(h){if(!c(h))return m(h);var p=l(h),f=[];for(var x in h)(x!="constructor"||!p&&d.call(h,x))&&f.push(x);return f}var c=a(0),l=a(40),m=a(144),u=Object.prototype,d=u.hasOwnProperty;i.exports=s},function(i,o,a){function s(p,f,x,g,b){p!==f&&m(f,function(y,_){if(d(y))b||(b=new c),u(p,f,_,x,s,g,b);else{var j=g?g(p[_],y,_+"",p,f,b):void 0;j===void 0&&(j=y),l(p,_,j)}},h)}var c=a(85),l=a(35),m=a(93),u=a(101),d=a(0),h=a(46);i.exports=s},function(i,o,a){function s(I,w,N,C,A,F,T){var k=I[N],P=w[N],S=T.get(P);if(S)return void c(I,N,S);var E=F?F(k,P,N+"",I,w,T):void 0,O=E===void 0;if(O){var R=p(P),D=!R&&x(P),$=!R&&!D&&_(P);E=P,R||D||$?p(k)?E=k:f(k)?E=u(k):D?(O=!1,E=l(P,!0)):$?(O=!1,E=m(P,!0)):E=[]:y(P)||h(P)?(E=k,h(k)?E=j(k):(!b(k)||C&&g(k))&&(E=d(P))):O=!1}O&&(T.set(P,E),A(E,P,C,F,T),T.delete(P)),c(I,N,E)}var c=a(35),l=a(111),m=a(112),u=a(113),d=a(127),h=a(18),p=a(2),f=a(159),x=a(44),g=a(25),b=a(0),y=a(160),_=a(45),j=a(164);i.exports=s},function(i,o,a){function s(m,u){return c(m,u,function(d,h){return l(m,h)})}var c=a(103),l=a(158);i.exports=s},function(i,o,a){function s(u,d,h){for(var p=-1,f=d.length,x={};++p<f;){var g=d[p],b=c(u,g);h(b,g)&&l(x,m(g,u),b)}return x}var c=a(94),l=a(105),m=a(13);i.exports=s},function(i,o,a){function s(u,d){return m(l(u,d,c),u+"")}var c=a(43),l=a(41),m=a(42);i.exports=s},function(i,o,a){function s(h,p,f,x){if(!u(h))return h;p=l(p,h);for(var g=-1,b=p.length,y=b-1,_=h;_!=null&&++g<b;){var j=d(p[g]),I=f;if(g!=y){var w=_[j];I=x?x(w,j,_):void 0,I===void 0&&(I=u(w)?w:m(p[g+1])?[]:{})}c(_,j,I),_=_[j]}return h}var c=a(36),l=a(13),m=a(15),u=a(0),d=a(23);i.exports=s},function(i,o,a){var s=a(156),c=a(37),l=a(43),m=c?function(u,d){return c(u,"toString",{configurable:!0,enumerable:!1,value:s(d),writable:!0})}:l;i.exports=m},function(i,o){function a(s,c){for(var l=-1,m=Array(s);++l<s;)m[l]=c(l);return m}i.exports=a},function(i,o,a){function s(f){if(typeof f=="string")return f;if(m(f))return l(f,s)+"";if(u(f))return p?p.call(f):"";var x=f+"";return x=="0"&&1/f==-d?"-0":x}var c=a(11),l=a(89),m=a(2),u=a(27),d=1/0,h=c?c.prototype:void 0,p=h?h.toString:void 0;i.exports=s},function(i,o){function a(s){return function(c){return s(c)}}i.exports=a},function(i,o,a){function s(l){var m=new l.constructor(l.byteLength);return new c(m).set(new c(l)),m}var c=a(86);i.exports=s},function(i,o,a){(function(s){function c(f,x){if(x)return f.slice();var g=f.length,b=p?p(g):new f.constructor(g);return f.copy(b),b}var l=a(5),m=typeof o=="object"&&o&&!o.nodeType&&o,u=m&&typeof s=="object"&&s&&!s.nodeType&&s,d=u&&u.exports===m,h=d?l.Buffer:void 0,p=h?h.allocUnsafe:void 0;s.exports=c}).call(o,a(29)(i))},function(i,o,a){function s(l,m){var u=m?c(l.buffer):l.buffer;return new l.constructor(u,l.byteOffset,l.length)}var c=a(110);i.exports=s},function(i,o){function a(s,c){var l=-1,m=s.length;for(c||(c=Array(m));++l<m;)c[l]=s[l];return c}i.exports=a},function(i,o,a){function s(m,u,d,h){var p=!d;d||(d={});for(var f=-1,x=u.length;++f<x;){var g=u[f],b=h?h(d[g],m[g],g,d,m):void 0;b===void 0&&(b=m[g]),p?l(d,g,b):c(d,g,b)}return d}var c=a(36),l=a(21);i.exports=s},function(i,o,a){var s=a(5),c=s["__core-js_shared__"];i.exports=c},function(i,o,a){function s(m){return c(function(u,d){var h=-1,p=d.length,f=p>1?d[p-1]:void 0,x=p>2?d[2]:void 0;for(f=m.length>3&&typeof f=="function"?(p--,f):void 0,x&&l(d[0],d[1],x)&&(f=p<3?void 0:f,p=1),u=Object(u);++h<p;){var g=d[h];g&&m(u,g,h,f)}return u})}var c=a(104),l=a(129);i.exports=s},function(i,o){function a(s){return function(c,l,m){for(var u=-1,d=Object(c),h=m(c),p=h.length;p--;){var f=h[s?p:++u];if(l(d[f],f,d)===!1)break}return c}}i.exports=a},function(i,o,a){function s(u){return m(l(u,void 0,c),u+"")}var c=a(157),l=a(41),m=a(42);i.exports=s},function(i,o,a){function s(h){var p=m.call(h,d),f=h[d];try{h[d]=void 0;var x=!0}catch{}var g=u.call(h);return x&&(p?h[d]=f:delete h[d]),g}var c=a(11),l=Object.prototype,m=l.hasOwnProperty,u=l.toString,d=c?c.toStringTag:void 0;i.exports=s},function(i,o){function a(s,c){return s==null?void 0:s[c]}i.exports=a},function(i,o,a){function s(p,f,x){f=c(f,p);for(var g=-1,b=f.length,y=!1;++g<b;){var _=h(f[g]);if(!(y=p!=null&&x(p,_)))break;p=p[_]}return y||++g!=b?y:!!(b=p==null?0:p.length)&&d(b)&&u(_,b)&&(m(p)||l(p))}var c=a(13),l=a(18),m=a(2),u=a(15),d=a(26),h=a(23);i.exports=s},function(i,o,a){function s(){this.__data__=c?c(null):{},this.size=0}var c=a(16);i.exports=s},function(i,o){function a(s){var c=this.has(s)&&delete this.__data__[s];return this.size-=c?1:0,c}i.exports=a},function(i,o,a){function s(d){var h=this.__data__;if(c){var p=h[d];return p===l?void 0:p}return u.call(h,d)?h[d]:void 0}var c=a(16),l="__lodash_hash_undefined__",m=Object.prototype,u=m.hasOwnProperty;i.exports=s},function(i,o,a){function s(u){var d=this.__data__;return c?d[u]!==void 0:m.call(d,u)}var c=a(16),l=Object.prototype,m=l.hasOwnProperty;i.exports=s},function(i,o,a){function s(m,u){var d=this.__data__;return this.size+=this.has(m)?0:1,d[m]=c&&u===void 0?l:u,this}var c=a(16),l="__lodash_hash_undefined__";i.exports=s},function(i,o,a){function s(u){return typeof u.constructor!="function"||m(u)?{}:c(l(u))}var c=a(91),l=a(39),m=a(40);i.exports=s},function(i,o,a){function s(d){return m(d)||l(d)||!!(u&&d&&d[u])}var c=a(11),l=a(18),m=a(2),u=c?c.isConcatSpreadable:void 0;i.exports=s},function(i,o,a){function s(d,h,p){if(!u(p))return!1;var f=typeof h;return!!(f=="number"?l(p)&&m(h,p.length):f=="string"&&h in p)&&c(p[h],d)}var c=a(17),l=a(24),m=a(15),u=a(0);i.exports=s},function(i,o,a){function s(d,h){if(c(d))return!1;var p=typeof d;return!(p!="number"&&p!="symbol"&&p!="boolean"&&d!=null&&!l(d))||u.test(d)||!m.test(d)||h!=null&&d in Object(h)}var c=a(2),l=a(27),m=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,u=/^\w*$/;i.exports=s},function(i,o){function a(s){var c=typeof s;return c=="string"||c=="number"||c=="symbol"||c=="boolean"?s!=="__proto__":s===null}i.exports=a},function(i,o,a){function s(m){return!!l&&l in m}var c=a(115),l=function(){var m=/[^.]+$/.exec(c&&c.keys&&c.keys.IE_PROTO||"");return m?"Symbol(src)_1."+m:""}();i.exports=s},function(i,o){function a(){this.__data__=[],this.size=0}i.exports=a},function(i,o,a){function s(u){var d=this.__data__,h=c(d,u);return!(h<0)&&(h==d.length-1?d.pop():m.call(d,h,1),--this.size,!0)}var c=a(12),l=Array.prototype,m=l.splice;i.exports=s},function(i,o,a){function s(l){var m=this.__data__,u=c(m,l);return u<0?void 0:m[u][1]}var c=a(12);i.exports=s},function(i,o,a){function s(l){return c(this.__data__,l)>-1}var c=a(12);i.exports=s},function(i,o,a){function s(l,m){var u=this.__data__,d=c(u,l);return d<0?(++this.size,u.push([l,m])):u[d][1]=m,this}var c=a(12);i.exports=s},function(i,o,a){function s(){this.size=0,this.__data__={hash:new c,map:new(m||l),string:new c}}var c=a(84),l=a(10),m=a(33);i.exports=s},function(i,o,a){function s(l){var m=c(this,l).delete(l);return this.size-=m?1:0,m}var c=a(14);i.exports=s},function(i,o,a){function s(l){return c(this,l).get(l)}var c=a(14);i.exports=s},function(i,o,a){function s(l){return c(this,l).has(l)}var c=a(14);i.exports=s},function(i,o,a){function s(l,m){var u=c(this,l),d=u.size;return u.set(l,m),this.size+=u.size==d?0:1,this}var c=a(14);i.exports=s},function(i,o,a){function s(m){var u=c(m,function(h){return d.size===l&&d.clear(),h}),d=u.cache;return u}var c=a(161),l=500;i.exports=s},function(i,o){function a(s){var c=[];if(s!=null)for(var l in Object(s))c.push(l);return c}i.exports=a},function(i,o,a){(function(s){var c=a(38),l=typeof o=="object"&&o&&!o.nodeType&&o,m=l&&typeof s=="object"&&s&&!s.nodeType&&s,u=m&&m.exports===l,d=u&&c.process,h=function(){try{return d&&d.binding&&d.binding("util")}catch{}}();s.exports=h}).call(o,a(29)(i))},function(i,o){function a(l){return c.call(l)}var s=Object.prototype,c=s.toString;i.exports=a},function(i,o){function a(s,c){return function(l){return s(c(l))}}i.exports=a},function(i,o){function a(m){var u=0,d=0;return function(){var h=l(),p=c-(h-d);if(d=h,p>0){if(++u>=s)return arguments[0]}else u=0;return m.apply(void 0,arguments)}}var s=800,c=16,l=Date.now;i.exports=a},function(i,o,a){function s(){this.__data__=new c,this.size=0}var c=a(10);i.exports=s},function(i,o){function a(s){var c=this.__data__,l=c.delete(s);return this.size=c.size,l}i.exports=a},function(i,o){function a(s){return this.__data__.get(s)}i.exports=a},function(i,o){function a(s){return this.__data__.has(s)}i.exports=a},function(i,o,a){function s(d,h){var p=this.__data__;if(p instanceof c){var f=p.__data__;if(!l||f.length<u-1)return f.push([d,h]),this.size=++p.size,this;p=this.__data__=new m(f)}return p.set(d,h),this.size=p.size,this}var c=a(10),l=a(33),m=a(34),u=200;i.exports=s},function(i,o,a){var s=a(143),c=/^\./,l=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,m=/\\(\\)?/g,u=s(function(d){var h=[];return c.test(d)&&h.push(""),d.replace(l,function(p,f,x,g){h.push(x?g.replace(m,"$1"):f||p)}),h});i.exports=u},function(i,o){function a(l){if(l!=null){try{return c.call(l)}catch{}try{return l+""}catch{}}return""}var s=Function.prototype,c=s.toString;i.exports=a},function(i,o){function a(s){return function(){return s}}i.exports=a},function(i,o,a){function s(l){return l!=null&&l.length?c(l,1):[]}var c=a(92);i.exports=s},function(i,o,a){function s(m,u){return m!=null&&l(m,u,c)}var c=a(95),l=a(121);i.exports=s},function(i,o,a){function s(m){return l(m)&&c(m)}var c=a(24),l=a(6);i.exports=s},function(i,o,a){function s(g){if(!m(g)||c(g)!=u)return!1;var b=l(g);if(b===null)return!0;var y=f.call(b,"constructor")&&b.constructor;return typeof y=="function"&&y instanceof y&&p.call(y)==x}var c=a(8),l=a(39),m=a(6),u="[object Object]",d=Function.prototype,h=Object.prototype,p=d.toString,f=h.hasOwnProperty,x=p.call(Object);i.exports=s},function(i,o,a){function s(m,u){if(typeof m!="function"||u!=null&&typeof u!="function")throw new TypeError(l);var d=function(){var h=arguments,p=u?u.apply(this,h):h[0],f=d.cache;if(f.has(p))return f.get(p);var x=m.apply(this,h);return d.cache=f.set(p,x)||f,x};return d.cache=new(s.Cache||c),d}var c=a(34),l="Expected a function";s.Cache=c,i.exports=s},function(i,o,a){var s=a(102),c=a(118),l=c(function(m,u){return m==null?{}:s(m,u)});i.exports=l},function(i,o){function a(){return!1}i.exports=a},function(i,o,a){function s(m){return c(m,l(m))}var c=a(114),l=a(46);i.exports=s},function(i,o,a){function s(l){return l==null?"":c(l)}var c=a(108);i.exports=s},function(i,o,a){i.exports=a(48)}])})})(Tl);var rg=Tl.exports;const Cn=Ln(rg),Al=({onDetected:t,onClose:r})=>{const n=v.useRef(null),[i,o]=v.useState(!1),[a,s]=v.useState(null);return v.useEffect(()=>(n.current&&(Cn.init({inputStream:{name:"Live",type:"LiveStream",target:n.current,constraints:{width:{min:640,ideal:1280,max:1920},height:{min:480,ideal:720,max:1080},facingMode:"environment",aspectRatio:{min:1,max:2}}},decoder:{readers:["ean_reader","ean_8_reader","code_128_reader","code_39_reader","upc_reader","upc_e_reader"],debug:{showCanvas:!0,showPatches:!1,showFoundPatches:!1,showSkeleton:!1,showLabels:!1,showPatchLabels:!1,showRemainingPatchLabels:!1,boxFromPatches:{showTransformed:!1,showTransformedBox:!1,showBB:!1}}},locate:!0,locator:{halfSample:!0,patchSize:"medium"},numOfWorkers:4,frequency:10},c=>{if(c){console.error("Quagga initialization failed:",c),s("فشل تشغيل الكاميرا. تأكد من منح الإذن للكاميرا."),Ge.error("فشل تشغيل الكاميرا",{description:"تأكد من منح الإذن للوصول إلى الكاميرا"});return}o(!0),Cn.start()}),Cn.onDetected(c=>{if(c.codeResult.code){const l=c.codeResult.code;console.log("Barcode detected:",l),t(l),Cn.stop()}})),()=>{Cn.stop()}),[t]),e.jsx("div",{className:"fixed inset-0 bg-black/95 z-50 flex items-center justify-center p-4",dir:"rtl",children:e.jsxs("div",{className:"bg-white rounded-xl max-w-3xl w-full shadow-2xl",children:[e.jsxs("div",{className:"flex justify-between items-center p-6 border-b bg-gradient-to-r from-blue-50 to-indigo-50",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Qu,{className:"h-6 w-6 text-blue-600"}),e.jsx("h2",{className:"text-2xl font-bold font-cairo text-gray-800",children:"مسح الباركود"})]}),e.jsx(V,{variant:"ghost",onClick:r,className:"hover:bg-red-100",children:e.jsx(at,{className:"h-6 w-6 text-gray-600"})})]}),e.jsx("div",{className:"p-6",children:a?e.jsxs("div",{className:"bg-red-50 border-2 border-red-200 rounded-lg p-8 text-center",children:[e.jsx("p",{className:"text-red-600 font-cairo text-lg",children:a}),e.jsx(V,{onClick:r,className:"mt-4",variant:"outline",children:"إغلاق"})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{ref:n,className:"w-full h-96 border-4 border-blue-500 rounded-lg overflow-hidden relative bg-black",children:!i&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-gray-900/50",children:e.jsxs("div",{className:"text-center text-white",children:[e.jsx("div",{className:"animate-spin rounded-full h-12 w-12 border-b-2 border-white mx-auto mb-4"}),e.jsx("p",{className:"font-cairo",children:"جاري تشغيل الكاميرا..."})]})})}),e.jsxs("div",{className:"mt-6 text-center space-y-2",children:[e.jsx("p",{className:"text-gray-700 font-cairo text-lg font-semibold",children:"وجّه الكاميرا نحو الباركود"}),e.jsx("p",{className:"text-gray-500 font-cairo text-sm",children:"سيتم المسح تلقائياً عند اكتشاف الباركود"})]}),e.jsxs("div",{className:"mt-4 bg-blue-50 rounded-lg p-4",children:[e.jsx("p",{className:"text-blue-800 font-cairo text-sm font-medium mb-2",children:"💡 نصائح:"}),e.jsxs("ul",{className:"text-blue-700 font-cairo text-sm space-y-1 list-disc list-inside",children:[e.jsx("li",{children:"تأكد من وجود إضاءة جيدة"}),e.jsx("li",{children:"ثبّت الهاتف أو الكاميرا"}),e.jsx("li",{children:"اجعل الباركود واضحاً في المربع"})]})]})]})})]})})};var ha="Avatar",[ng,$y]=Fn(ha),[sg,Il]=ng(ha),Ol=v.forwardRef((t,r)=>{const{__scopeAvatar:n,...i}=t,[o,a]=v.useState("idle");return e.jsx(sg,{scope:n,imageLoadingStatus:o,onImageLoadingStatusChange:a,children:e.jsx(Lt.span,{...i,ref:r})})});Ol.displayName=ha;var Rl="AvatarImage",Pl=v.forwardRef((t,r)=>{const{__scopeAvatar:n,src:i,onLoadingStatusChange:o=()=>{},...a}=t,s=Il(Rl,n),c=og(i,a.referrerPolicy),l=_u(m=>{o(m),s.onImageLoadingStatusChange(m)});return ec(()=>{c!=="idle"&&l(c)},[c,l]),c==="loaded"?e.jsx(Lt.img,{...a,ref:r,src:i}):null});Pl.displayName=Rl;var Ml="AvatarFallback",Ll=v.forwardRef((t,r)=>{const{__scopeAvatar:n,delayMs:i,...o}=t,a=Il(Ml,n),[s,c]=v.useState(i===void 0);return v.useEffect(()=>{if(i!==void 0){const l=window.setTimeout(()=>c(!0),i);return()=>window.clearTimeout(l)}},[i]),s&&a.imageLoadingStatus!=="loaded"?e.jsx(Lt.span,{...o,ref:r}):null});Ll.displayName=Ml;function og(t,r){const[n,i]=v.useState("idle");return ec(()=>{if(!t){i("error");return}let o=!0;const a=new window.Image,s=c=>()=>{o&&i(c)};return i("loading"),a.onload=s("loaded"),a.onerror=s("error"),a.src=t,r&&(a.referrerPolicy=r),()=>{o=!1}},[t,r]),n}var Dl=Ol,$l=Pl,Fl=Ll;const fr=v.forwardRef(({className:t,...r},n)=>e.jsx(Dl,{ref:n,className:Z("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",t),...r}));fr.displayName=Dl.displayName;const Yr=v.forwardRef(({className:t,...r},n)=>e.jsx($l,{ref:n,className:Z("aspect-square h-full w-full",t),...r}));Yr.displayName=$l.displayName;const pr=v.forwardRef(({className:t,...r},n)=>e.jsx(Fl,{ref:n,className:Z("flex h-full w-full items-center justify-center rounded-full bg-muted",t),...r}));pr.displayName=Fl.displayName;async function ag(t,r,n){const i=localStorage.getItem(xe),o=r.trim().toLowerCase(),a=`${oe()}${W.GET_ALL("product_categories")}&filters=${encodeURIComponent(JSON.stringify({seller_id:t,is_active:1}))}`,s=await fetch(a,{headers:i?{Authorization:`Bearer ${i}`}:{}});return s.ok?((await s.json()).data||[]).some(m=>m.category_name.trim().toLowerCase()===o&&m.id!==n):!1}function fa(t){const{toast:r}=et(),n=dn(),i=vr({queryKey:["categories",t],queryFn:async()=>{if(!t)return[];const l=localStorage.getItem(xe),m=Date.now(),u=`${oe()}${W.GET_ALL("product_categories")}&filters=${encodeURIComponent(JSON.stringify({seller_id:t,is_active:1}))}&orderBy=display_order&orderDir=ASC&_t=${m}`,d=await fetch(u,{headers:l?{Authorization:`Bearer ${l}`}:{}});if(!d.ok)throw new Error("Failed to fetch categories");return(await d.json()).data||[]},enabled:!!t}),o=$t({mutationFn:async l=>{if(!t)throw new Error("Seller ID is required");if(await ag(t,l.category_name))throw new Error("فئة بهذا الاسم موجودة بالفعل");const u=localStorage.getItem(xe),d=await fetch(`${oe()}${W.CREATE("product_categories")}`,{method:"POST",headers:{"Content-Type":"application/json",...u?{Authorization:`Bearer ${u}`}:{}},body:JSON.stringify({seller_id:t,...l})});if(!d.ok)throw new Error("Failed to create category");return d.json()},onSuccess:()=>{n.invalidateQueries({queryKey:["categories",t]}),r({title:"تم إضافة الفئة",description:"تم إضافة الفئة الجديدة بنجاح"})},onError:l=>{r({title:"خطأ",description:l.message||"فشل في إضافة الفئة",variant:"destructive"})}}),a=$t({mutationFn:async({id:l,updates:m})=>{const u=localStorage.getItem(xe),d=await fetch(`${oe()}${W.UPDATE("product_categories",l)}`,{method:"POST",headers:{"Content-Type":"application/json",...u?{Authorization:`Bearer ${u}`}:{}},body:JSON.stringify(m)});if(!d.ok)throw new Error("Failed to update category");return d.json()},onSuccess:()=>{n.invalidateQueries({queryKey:["categories",t]}),r({title:"تم التحديث",description:"تم تحديث الفئة بنجاح"})},onError:l=>{r({title:"خطأ",description:l.message||"فشل في تحديث الفئة",variant:"destructive"})}}),s=$t({mutationFn:async l=>{const m=localStorage.getItem(xe),u=await fetch(`${oe()}${W.UPDATE("product_categories",l)}`,{method:"POST",headers:{"Content-Type":"application/json",...m?{Authorization:`Bearer ${m}`}:{}},body:JSON.stringify({is_active:0})});if(!u.ok)throw new Error("Failed to delete category");return u.json()},onSuccess:()=>{n.invalidateQueries({queryKey:["categories",t]}),r({title:"تم الحذف",description:"تم حذف الفئة بنجاح"})},onError:l=>{r({title:"خطأ",description:l.message||"فشل في حذف الفئة",variant:"destructive"})}}),c=$t({mutationFn:async l=>{const m=localStorage.getItem(xe),u=l.map(d=>fetch(`${oe()}${W.UPDATE("product_categories",d.id)}`,{method:"POST",headers:{"Content-Type":"application/json",...m?{Authorization:`Bearer ${m}`}:{}},body:JSON.stringify({display_order:d.display_order})}));await Promise.all(u)},onSuccess:()=>{n.invalidateQueries({queryKey:["categories",t]}),r({title:"تم التحديث",description:"تم إعادة ترتيب الفئات بنجاح"})},onError:l=>{r({title:"خطأ",description:l.message||"فشل في إعادة الترتيب",variant:"destructive"})}});return{categories:i.data||[],isLoading:i.isLoading,error:i.error,refetch:i.refetch,createCategory:o.mutateAsync,updateCategory:a.mutateAsync,deleteCategory:s.mutateAsync,reorderCategories:c.mutateAsync}}const ig=(t,r)=>{const n="978",o=(parseInt(t.replace(/[^0-9]/g,"").substring(0,9))||Math.floor(Math.random()*999999999)).toString().padStart(9,"0"),a=n+o,s=cg(a);return a+s},cg=t=>{let r=0;for(let i=0;i<12;i++){const o=parseInt(t[i]);r+=i%2===0?o:o*3}return((10-r%10)%10).toString()},lg=t=>new Promise((r,n)=>{try{const i=document.createElement("canvas");Fu(i,t,{format:"EAN13",width:2,height:60,displayValue:!0,fontSize:14,margin:10,background:"#ffffff",lineColor:"#000000"}),r(i.toDataURL("image/png"))}catch(i){console.error("Error generating barcode:",i),n(i)}}),Si=async t=>{try{const r=await lg(t.barcode),n=window.open("","_blank","width=400,height=300");n&&(n.document.write(`
        <html dir="rtl">
          <head>
            <title>طباعة باركود - ${t.product_name}</title>
            <link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;700&display=swap" rel="stylesheet">
            <style>
              * {
                margin: 0;
                padding: 0;
                box-sizing: border-box;
              }
              body { 
                margin: 0; 
                padding: 20px; 
                font-family: 'Cairo', Arial, sans-serif;
                text-align: center;
                background: white;
              }
              .barcode-label {
                border: 2px solid #000;
                padding: 15px;
                display: inline-block;
                background: white;
                max-width: 300px;
              }
              .product-name {
                font-weight: bold;
                margin-bottom: 10px;
                font-size: 16px;
                color: #1a1a1a;
              }
              .barcode-image {
                margin: 10px 0;
              }
              .product-price {
                color: #2563eb;
                font-size: 20px;
                font-weight: bold;
                margin-top: 10px;
              }
              @media print {
                body {
                  padding: 0;
                }
                .barcode-label {
                  border: 2px solid #000;
                }
              }
            </style>
          </head>
          <body>
            <div class="barcode-label">
              <div class="product-name">${t.product_name}</div>
              <div class="barcode-image">
                <img src="${r}" alt="Barcode" />
              </div>
              <div class="product-price">${Number(t.unit_price||0).toFixed(2)} د.أ</div>
            </div>
            <script>
              window.onload = () => {
                setTimeout(() => {
                  window.print();
                  setTimeout(() => window.close(), 100);
                }, 500);
              };
            <\/script>
          </body>
        </html>
      `),n.document.close())}catch(r){throw console.error("Error printing barcode label:",r),r}};function dg(t={}){const[r,n]=v.useState(!1),[i,o]=v.useState(0),[a,s]=v.useState(null),[c,l]=v.useState(null),{onSuccess:m,onError:u,maxSize:d=10,allowedTypes:h=["image/jpeg","image/png","image/gif","image/webp","application/pdf"]}=t,p=v.useCallback(async x=>{if(n(!0),o(0),s(null),x.size/(1024*1024)>d){const b=`حجم الملف يجب أن يكون أقل من ${d}MB`;return s(b),u==null||u(b),n(!1),{success:!1,message:b,data:null}}if(h.length>0&&!h.includes(x.type)){const b="نوع الملف غير مدعوم";return s(b),u==null||u(b),n(!1),{success:!1,message:b,data:null}}try{const b=localStorage.getItem(xe),y=new FormData;y.append("file",x);let _=`${oe()}${W.UPLOAD}`;return b&&(_+=`?token=${b}`),new Promise(j=>{const I=new XMLHttpRequest;I.upload.addEventListener("progress",w=>{if(w.lengthComputable){const N=Math.round(w.loaded/w.total*100);o(N)}}),I.addEventListener("load",()=>{n(!1);try{const w=JSON.parse(I.responseText);w.success&&w.data?(l(w.data.url),m==null||m(w.data.url)):(s(w.message),u==null||u(w.message)),j(w)}catch{const N="خطأ في معالجة استجابة الخادم";s(N),u==null||u(N),j({success:!1,message:N,data:null})}}),I.addEventListener("error",()=>{n(!1);const w="خطأ في رفع الملف";s(w),u==null||u(w),j({success:!1,message:w,data:null})}),I.open("POST",_),I.send(y)})}catch(b){n(!1);const y=b instanceof Error?b.message:"خطأ في رفع الملف";return s(y),u==null||u(y),{success:!1,message:y,data:null}}},[d,h,m,u]),f=v.useCallback(()=>{n(!1),o(0),s(null),l(null)},[]);return{upload:p,isUploading:r,progress:i,error:a,uploadedUrl:c,reset:f}}const fs=[{value:"package",label:"عام",icon:ht,color:"text-gray-600"},{value:"store",label:"متجر",icon:ho,color:"text-emerald-600"},{value:"shopping-bag",label:"تسوق",icon:qm,color:"text-emerald-600"},{value:"apple",label:"فواكه",icon:Uu,color:"text-red-500"},{value:"carrot",label:"خضار",icon:tm,color:"text-orange-500"},{value:"milk",label:"ألبان",icon:Im,color:"text-blue-400"},{value:"sandwich",label:"مخبوزات",icon:Fm,color:"text-amber-600"},{value:"beef",label:"لحوم",icon:Wu,color:"text-red-700"},{value:"fish",label:"أسماك",icon:pm,color:"text-cyan-500"},{value:"cherry",label:"فواكه طازجة",icon:nm,color:"text-pink-500"},{value:"coffee",label:"مشروبات",icon:im,color:"text-brown-600"},{value:"cookie",label:"مسليات",icon:lm,color:"text-amber-700"},{value:"ice-cream",label:"مثلجات",icon:Cm,color:"text-pink-400"},{value:"pizza",label:"وجبات سريعة",icon:$m,color:"text-orange-600"},{value:"cake",label:"حلويات",icon:Yu,color:"text-pink-600"},{value:"candy",label:"حلوى",icon:Zu,color:"text-purple-500"},{value:"wine",label:"مشروبات غازية",icon:ch,color:"text-indigo-500"},{value:"egg",label:"بيض",icon:fm,color:"text-amber-200"},{value:"wheat",label:"حبوب",icon:ih,color:"text-yellow-600"},{value:"utensils",label:"أدوات مطبخ",icon:rh,color:"text-slate-600"},{value:"droplet",label:"سوائل",icon:mm,color:"text-blue-400"},{value:"smartphone",label:"هواتف",icon:Sr,color:"text-slate-600"},{value:"laptop",label:"حواسيب",icon:km,color:"text-gray-700"},{value:"headphones",label:"سماعات",icon:jm,color:"text-indigo-600"},{value:"tv",label:"تلفزيونات",icon:Zm,color:"text-blue-700"},{value:"battery",label:"بطاريات",icon:Gu,color:"text-green-500"},{value:"shirt",label:"ملابس",icon:Bm,color:"text-blue-500"},{value:"glasses",label:"نظارات",icon:vm,color:"text-gray-600"},{value:"watch",label:"ساعات",icon:ah,color:"text-amber-600"},{value:"gem",label:"مجوهرات",icon:ym,color:"text-purple-600"},{value:"sofa",label:"أثاث",icon:Gm,color:"text-amber-700"},{value:"lamp",label:"إضاءة",icon:Sm,color:"text-yellow-500"},{value:"bed",label:"غرف نوم",icon:Hu,color:"text-indigo-400"},{value:"sparkles",label:"تنظيف",icon:iu,color:"text-purple-600"},{value:"snowflake",label:"مجمدات",icon:Vm,color:"text-blue-300"},{value:"hammer",label:"أدوات",icon:_m,color:"text-gray-600"},{value:"wrench",label:"صيانة",icon:lh,color:"text-slate-500"},{value:"car",label:"سيارات",icon:em,color:"text-blue-600"},{value:"fuel",label:"وقود",icon:gm,color:"text-orange-500"},{value:"dumbbell",label:"رياضة",icon:hm,color:"text-red-600"},{value:"bike",label:"دراجات",icon:Xu,color:"text-green-600"},{value:"book",label:"كتب",icon:Ju,color:"text-amber-800"},{value:"pen",label:"قرطاسية",icon:Lm,color:"text-blue-800"},{value:"cat",label:"قطط",icon:rm,color:"text-orange-400"},{value:"dog",label:"كلاب",icon:um,color:"text-amber-600"},{value:"flower",label:"زهور",icon:xm,color:"text-pink-500"},{value:"tree",label:"نباتات",icon:Jm,color:"text-green-700"},{value:"gamepad",label:"ألعاب",icon:bm,color:"text-purple-500"},{value:"gift",label:"هدايا",icon:ac,color:"text-red-500"},{value:"heart",label:"عناية شخصية",icon:Nm,color:"text-rose-500"},{value:"scissors",label:"حلاقة",icon:Um,color:"text-gray-500"},{value:"spray",label:"عطور",icon:Hm,color:"text-violet-500"},{value:"pill",label:"صحة وعافية",icon:Dm,color:"text-green-600"},{value:"stethoscope",label:"طبية",icon:Wm,color:"text-teal-600"},{value:"baby",label:"منتجات أطفال",icon:qu,color:"text-pink-400"},{value:"archive",label:"معلبات",icon:zu,color:"text-gray-500"},{value:"cigarette",label:"تبغ",icon:om,color:"text-gray-400"}],So=t=>{const r=fs.find(n=>n.value===t);return(r==null?void 0:r.icon)||ht},ks=[{value:"blue",label:"أزرق",bg:"bg-blue-100",text:"text-blue-700",border:"border-blue-300",hover:"hover:bg-blue-200"},{value:"green",label:"أخضر",bg:"bg-green-100",text:"text-green-700",border:"border-green-300",hover:"hover:bg-green-200"},{value:"red",label:"أحمر",bg:"bg-red-100",text:"text-red-700",border:"border-red-300",hover:"hover:bg-red-200"},{value:"orange",label:"برتقالي",bg:"bg-orange-100",text:"text-orange-700",border:"border-orange-300",hover:"hover:bg-orange-200"},{value:"purple",label:"بنفسجي",bg:"bg-purple-100",text:"text-purple-700",border:"border-purple-300",hover:"hover:bg-purple-200"},{value:"yellow",label:"أصفر",bg:"bg-yellow-100",text:"text-yellow-700",border:"border-yellow-300",hover:"hover:bg-yellow-200"},{value:"pink",label:"وردي",bg:"bg-pink-100",text:"text-pink-700",border:"border-pink-300",hover:"hover:bg-pink-200"},{value:"indigo",label:"نيلي",bg:"bg-indigo-100",text:"text-indigo-700",border:"border-indigo-300",hover:"hover:bg-indigo-200"},{value:"teal",label:"تركواز",bg:"bg-teal-100",text:"text-teal-700",border:"border-teal-300",hover:"hover:bg-teal-200"},{value:"cyan",label:"سماوي",bg:"bg-cyan-100",text:"text-cyan-700",border:"border-cyan-300",hover:"hover:bg-cyan-200"}],Sn=t=>ks.find(n=>n.value===t)||ks[0],Ul=v.memo(({category:t,isActive:r,count:n,onClick:i})=>{const o=So(t.category_icon),a=Sn(t.category_color);return e.jsxs(V,{variant:r?"default":"outline",size:"sm",onClick:i,className:Z("flex items-center gap-2 shrink-0 transition-all duration-200",!r&&a.bg,!r&&a.text,!r&&a.border,!r&&a.hover,r&&"scale-105 shadow-lg ring-2 ring-primary"),children:[e.jsx(o,{className:"h-4 w-4"}),e.jsx("span",{children:t.category_name}),e.jsx(Ae,{variant:r?"secondary":"outline",className:Z("ml-1",!r&&a.bg),children:n})]})});Ul.displayName="CategoryButton";const ug=({categories:t,selectedCategoryId:r,onSelectCategory:n,productsCount:i})=>{const o=v.useRef(null),[a,s]=v.useState(!1),[c,l]=v.useState(!1),[m,u]=v.useState(!1),[d,h]=v.useState(0),[p,f]=v.useState(0),x=v.useRef(0),g=v.useRef(0),b=v.useRef(0),y=v.useRef(null),_=v.useCallback(()=>{if(!o.current)return;const{scrollLeft:E,scrollWidth:O,clientWidth:R}=o.current;s(E>5),l(E<O-R-5)},[]);v.useEffect(()=>{_();const E=o.current;return E&&(E.addEventListener("scroll",_),window.addEventListener("resize",_)),()=>{E&&E.removeEventListener("scroll",_),window.removeEventListener("resize",_)}},[_,t]),v.useEffect(()=>{if(r&&o.current){const E=o.current.querySelector(`[data-category-id="${r}"]`);E&&E.scrollIntoView({behavior:"smooth",inline:"center",block:"nearest"})}},[r]);const j=E=>{if(!o.current)return;const O=200;o.current.scrollBy({left:E==="right"?O:-O,behavior:"smooth"})},I=E=>{o.current&&Math.abs(E.deltaY)>Math.abs(E.deltaX)&&(E.preventDefault(),o.current.scrollLeft+=E.deltaY)},w=v.useCallback(()=>{if(!o.current)return;const E=.95,O=.5,R=()=>{if(Math.abs(x.current)<O){x.current=0,y.current=null;return}o.current&&(o.current.scrollLeft+=x.current,x.current*=E,y.current=requestAnimationFrame(R))};y.current=requestAnimationFrame(R)},[]),N=v.useCallback(()=>{y.current&&(cancelAnimationFrame(y.current),y.current=null),x.current=0},[]),C=E=>{var O,R;N(),u(!0),h(E.touches[0].pageX-(((O=o.current)==null?void 0:O.offsetLeft)||0)),f(((R=o.current)==null?void 0:R.scrollLeft)||0),g.current=E.touches[0].pageX,b.current=Date.now()},A=E=>{if(!m||!o.current)return;const O=E.touches[0].pageX,R=Date.now(),D=O-(o.current.offsetLeft||0),$=(d-D)*1.5;o.current.scrollLeft=p+$;const M=R-b.current;M>0&&(x.current=(g.current-O)/M*15),g.current=O,b.current=R},F=()=>{u(!1),Math.abs(x.current)>1&&w()},T=E=>{var O,R;N(),u(!0),h(E.pageX-(((O=o.current)==null?void 0:O.offsetLeft)||0)),f(((R=o.current)==null?void 0:R.scrollLeft)||0),o.current&&(o.current.style.cursor="grabbing")},k=E=>{if(!m||!o.current)return;E.preventDefault();const O=E.pageX-(o.current.offsetLeft||0),R=(d-O)*1.5;o.current.scrollLeft=p+R},P=()=>{u(!1),o.current&&(o.current.style.cursor="grab")},S=()=>{m&&(u(!1),o.current&&(o.current.style.cursor="grab"))};return e.jsx("div",{className:"sticky top-0 z-10 bg-background/95 backdrop-blur-sm border-b border-border py-2 mb-4",children:e.jsxs("div",{className:"relative flex items-center gap-1",children:[e.jsx(V,{variant:"ghost",size:"icon",onClick:()=>j("left"),className:Z("h-8 w-8 shrink-0 transition-all duration-200",a?"opacity-100":"opacity-0 pointer-events-none"),children:e.jsx(Go,{className:"h-5 w-5"})}),e.jsx("div",{className:Z("absolute right-10 top-0 bottom-0 w-8 bg-gradient-to-l from-transparent to-background/90 pointer-events-none z-10 transition-opacity duration-200",a?"opacity-100":"opacity-0")}),e.jsxs("div",{ref:o,onWheel:I,onTouchStart:C,onTouchMove:A,onTouchEnd:F,onMouseDown:T,onMouseMove:k,onMouseUp:P,onMouseLeave:S,className:Z("flex-1 flex gap-2 overflow-x-auto scrollbar-hide scroll-smooth px-1",m?"cursor-grabbing select-none":"cursor-grab"),style:{scrollBehavior:m?"auto":"smooth"},children:[e.jsxs(V,{variant:r===null?"default":"outline",size:"sm",onClick:()=>!m&&n(null),className:"flex items-center gap-2 shrink-0 transition-all duration-200","data-category-id":"all",children:[e.jsx(ht,{className:"h-4 w-4"}),e.jsx("span",{children:"الكل"}),e.jsx(Ae,{variant:r===null?"secondary":"outline",children:i.total||0})]}),t.map(E=>e.jsx("div",{"data-category-id":E.id,children:e.jsx(Ul,{category:E,isActive:r===E.id,count:i[E.id]||0,onClick:()=>!m&&n(E.id)})},E.id))]}),e.jsx("div",{className:Z("absolute left-10 top-0 bottom-0 w-8 bg-gradient-to-r from-transparent to-background/90 pointer-events-none z-10 transition-opacity duration-200",c?"opacity-100":"opacity-0")}),e.jsx(V,{variant:"ghost",size:"icon",onClick:()=>j("right"),className:Z("h-8 w-8 shrink-0 transition-all duration-200",c?"opacity-100":"opacity-0 pointer-events-none"),children:e.jsx(Ms,{className:"h-5 w-5"})})]})})},pa=v.memo(ug);pa.displayName="CategoryFilterBar";async function zl(t){console.log("🧹 Starting duplicate categories cleanup for seller:",t);try{const r=localStorage.getItem(xe),n=`${oe()}${W.GET_ALL("product_categories")}&filters=${encodeURIComponent(JSON.stringify({seller_id:t,is_active:1}))}&orderBy=created_at&orderDir=ASC`,i=await fetch(n,{headers:r?{Authorization:`Bearer ${r}`}:{}});if(!i.ok)throw new Error("Failed to fetch categories");const a=(await i.json()).data||[];if(console.log(`📦 Found ${a.length} active categories`),a.length===0)return{success:!0,deleted:0};const s=new Map;for(const m of a){const u=m.category_name.trim().toLowerCase(),d=s.get(u)||[];d.push(m),s.set(u,d)}const c=[];for(const[m,u]of s.entries())if(u.length>1){console.log(`🔄 Found ${u.length} duplicates for category: "${m}"`);const d=u[0],h=u.slice(1);c.push(...h.map(p=>({id:p.id,originalId:d.id})))}if(c.length===0)return console.log("✅ No duplicate categories found"),{success:!0,deleted:0};console.log(`🔄 Transferring products from ${c.length} duplicate categories...`);for(const m of c){const u=`${oe()}${W.GET_ALL("products")}&filters=${encodeURIComponent(JSON.stringify({seller_id:t,category_id:m.id}))}`,d=await fetch(u,{headers:r?{Authorization:`Bearer ${r}`}:{}});if(d.ok){const p=(await d.json()).data||[];if(p.length>0){console.log(`📦 Transferring ${p.length} products from category ${m.id} to ${m.originalId}`);for(const f of p)await fetch(`${oe()}${W.UPDATE("products",f.id)}`,{method:"POST",headers:{"Content-Type":"application/json",...r?{Authorization:`Bearer ${r}`}:{}},body:JSON.stringify({category_id:m.originalId})})}}}console.log(`🗑️ Deleting ${c.length} duplicate categories...`);const l=c.map(m=>fetch(`${oe()}${W.UPDATE("product_categories",m.id)}`,{method:"POST",headers:{"Content-Type":"application/json",...r?{Authorization:`Bearer ${r}`}:{}},body:JSON.stringify({is_active:0})}));return await Promise.all(l),console.log(`✅ Successfully deleted ${c.length} duplicate categories`),{success:!0,deleted:c.length}}catch(r){return console.error("❌ Error cleaning up duplicate categories:",r),{success:!1,deleted:0,error:r.message}}}const mg=()=>{const{toast:t}=et(),r=Mt(),{seller:n}=Ot(),{hasPermission:i}=lt(),{categories:o,refetch:a}=fa(r),s=i("can_manage_products"),[c,l]=v.useState(null),[m,u]=v.useState(!1),[d,h]=v.useState(""),[p,f]=v.useState(null),[x,g]=v.useState("all"),[b,y]=v.useState("idle"),[_,j]=v.useState(!1),I=v.useRef(null),w=v.useRef(null);v.useEffect(()=>{const L=setTimeout(()=>{var K;(K=I.current)==null||K.focus()},100);return()=>clearTimeout(L)},[]);const[N,C]=v.useState({product_name:"",description:"",unit_price:0,tax_percent:16,image_url:"",additional_images:[],stock_quantity:0,barcode:"",sku:"",cost_price:0,track_inventory:!0,low_stock_alert:!0,min_stock_level:10,reorder_point:20,category:"",category_id:""}),[A,F]=v.useState(!1),[T,k]=v.useState(!1),[P,S]=v.useState({current:0,total:0,fileName:""}),[E,O]=v.useState(null),[R,D]=v.useState(null),{upload:$}=dg(),M=L=>{if(!L.additional_images)return[];try{return JSON.parse(L.additional_images)}catch{return[]}},{data:X=[],isLoading:U,refetch:Q}=la(),B=Dr(),z=v.useCallback(async()=>{await Promise.all([Q(),a()])},[Q,a]),{isPulling:H,pullDistance:Y,isRefreshing:J,canRefresh:ie,progress:ce}=ua({onRefresh:z,enabled:B}),ke=v.useCallback(L=>{console.log("🔍 [Products] Barcode detected from camera:",L);const K=X.find(ge=>ge.barcode===L);K?(Kr(),y("success"),h(L),t({title:"✅ تم العثور على المنتج",description:K.product_name,duration:2e3})):(Et(),y("error"),h(L),t({title:"❌ لم يتم العثور",description:"لا يوجد منتج بهذا الباركود",variant:"destructive",duration:2e3})),setTimeout(()=>y("idle"),1500),j(!1),setTimeout(()=>{var ge;return(ge=I.current)==null?void 0:ge.focus()},50)},[X,t]),be=n&&"invoice_type"in n?n.invoice_type==="ضريبة عامة":!1;v.useEffect(()=>{const L=`product_images_fixed_v3_${r}`;r&&!localStorage.getItem(L)&&fu(r).then(K=>{K.success&&K.updated>0&&(console.log(`Fixed ${K.updated} product images`),Q()),localStorage.setItem(L,"true")})},[r,Q]),v.useEffect(()=>{r&&zl(r).then(L=>{L.success&&L.deleted>0&&(console.log(`Cleaned up ${L.deleted} duplicate categories`),Q(),a())})},[r,Q,a]);const Se=async L=>{var ge,Fe;const K=(ge=L.target.files)==null?void 0:ge[0];if(K){if(!K.type.startsWith("image/")){t({title:"خطأ",description:"يرجى اختيار ملف صورة صحيح",variant:"destructive"});return}if(K.size>5242880){t({title:"خطأ",description:"حجم الصورة يجب أن يكون أقل من 5 ميغابايت",variant:"destructive"});return}try{F(!0);const He=await $(K);if(He.success&&((Fe=He.data)!=null&&Fe.url))C({...N,image_url:He.data.url}),t({title:"تم الرفع",description:"تم رفع الصورة بنجاح"});else throw new Error(He.message||"Upload failed")}catch(He){console.error("Error uploading image:",He),t({title:"خطأ",description:"فشل في رفع الصورة",variant:"destructive"})}finally{F(!1)}}},je=async L=>{var He;const K=L.target.files;if(!K||K.length===0)return;const ge=[],Fe=[];for(let Pe=0;Pe<K.length;Pe++){const Ze=K[Pe];if(!Ze.type.startsWith("image/")){Fe.push(`${Ze.name}: ليس ملف صورة`);continue}if(Ze.size>5242880){Fe.push(`${Ze.name}: حجم الصورة أكبر من 5 ميغابايت`);continue}ge.push(Ze)}if(Fe.length>0&&t({title:"تحذير",description:`تم تجاهل ${Fe.length} ملف(ات): ${Fe[0]}${Fe.length>1?"...":""}`,variant:"destructive"}),ge.length===0){L.target.value="";return}try{k(!0),S({current:0,total:ge.length,fileName:""});const Pe=[];let Ze=0,Wt=0;for(let rr=0;rr<ge.length;rr++){const Qn=ge[rr];S({current:rr+1,total:ge.length,fileName:Qn.name});try{const gn=await $(Qn);gn.success&&((He=gn.data)!=null&&He.url)?(Pe.push(gn.data.url),Ze++):Wt++}catch{Wt++}}Pe.length>0&&C(rr=>({...rr,additional_images:[...rr.additional_images,...Pe]})),Ze>0&&Wt===0?t({title:"تم الرفع",description:`تم رفع ${Ze} صورة بنجاح`}):Ze>0&&Wt>0?t({title:"تم الرفع جزئياً",description:`تم رفع ${Ze} صورة، فشل رفع ${Wt} صورة`}):t({title:"خطأ",description:"فشل في رفع الصور",variant:"destructive"})}catch(Pe){console.error("Error uploading additional images:",Pe),t({title:"خطأ",description:"فشل في رفع الصور",variant:"destructive"})}finally{k(!1),S({current:0,total:0,fileName:""}),L.target.value=""}},Re=L=>{C(K=>({...K,additional_images:K.additional_images.filter((ge,Fe)=>Fe!==L)}))},We=v.useCallback(L=>{if(L.key==="Enter"){L.preventDefault();const K=d.trim();if(!K)return;if(X.find(Pe=>Pe.barcode===K)){y("success"),h(K),setTimeout(()=>y("idle"),1500);return}if(X.find(Pe=>{var Ze;return((Ze=Pe.sku)==null?void 0:Ze.toLowerCase())===K.toLowerCase()})){y("success"),h(K),setTimeout(()=>y("idle"),1500);return}if(X.find(Pe=>Pe.product_name.toLowerCase().includes(K.toLowerCase()))){y("success"),setTimeout(()=>y("idle"),1500);return}y("error"),setTimeout(()=>y("idle"),1500)}},[d,X]),se=v.useCallback(L=>{h(L),w.current&&clearTimeout(w.current),/^\d{8,14}$/.test(L.trim())&&(w.current=setTimeout(()=>{X.find(Fe=>Fe.barcode===L.trim())&&(y("success"),setTimeout(()=>y("idle"),1500))},300))},[X]),q=[{value:-1,label:"السلعة او الخدمة معفية"},{value:0,label:"0%"},{value:1,label:"1%"},{value:2,label:"2%"},{value:3,label:"3%"},{value:4,label:"4%"},{value:5,label:"5%"},{value:6,label:"6%"},{value:7,label:"7%"},{value:8,label:"8%"},{value:9,label:"9%"},{value:10,label:"10%"},{value:11,label:"11%"},{value:12,label:"12%"},{value:13,label:"13%"},{value:14,label:"14%"},{value:15,label:"15%"},{value:16,label:"16%"}],ne=async()=>{if(!N.product_name.trim()){t({title:"خطأ",description:"يرجى إدخال اسم المنتج",variant:"destructive"});return}if(!r){t({title:"خطأ",description:"تعذر تحديد البائع الحالي. أعد تسجيل الدخول.",variant:"destructive"});return}try{const L=localStorage.getItem(xe),K={product_name:N.product_name,description:N.description,unit_price:N.unit_price,seller_id:r,image_url:N.image_url||null,additional_images:N.additional_images.length>0?JSON.stringify(N.additional_images):null,stock_quantity:N.stock_quantity,barcode:N.barcode||null,sku:N.sku||null,cost_price:N.cost_price,track_inventory:N.track_inventory?1:0,low_stock_alert:N.low_stock_alert?1:0,min_stock_level:N.min_stock_level,reorder_point:N.reorder_point,category:N.category||null,category_id:N.category_id||null,...be&&{tax_percent:N.tax_percent}};if(c){if(!(await fetch(`${oe()}${W.UPDATE("products",c.id)}`,{method:"POST",headers:{"Content-Type":"application/json",...L?{Authorization:`Bearer ${L}`}:{}},body:JSON.stringify(K)})).ok)throw new Error("Failed to update product");t({title:"تم التحديث",description:"تم تحديث المنتج بنجاح"})}else{if(!(await fetch(`${oe()}${W.CREATE("products")}`,{method:"POST",headers:{"Content-Type":"application/json",...L?{Authorization:`Bearer ${L}`}:{}},body:JSON.stringify(K)})).ok)throw new Error("Failed to create product");t({title:"تم الإضافة",description:"تم إضافة المنتج بنجاح"})}u(!1),l(null),C({product_name:"",description:"",unit_price:0,tax_percent:16,image_url:"",additional_images:[],stock_quantity:0,barcode:"",sku:"",cost_price:0,track_inventory:!0,low_stock_alert:!0,min_stock_level:10,reorder_point:20,category:"",category_id:null}),await Q()}catch(L){console.error("Error saving product:",L),t({title:"خطأ",description:"فشل في حفظ المنتج",variant:"destructive"})}},re=(L,K=0)=>{const ge=Number(L??K);return parseFloat(ge.toFixed(2))},de=L=>{l(L);let K=[];if(L.additional_images)try{K=JSON.parse(L.additional_images)}catch{K=[]}C({product_name:L.product_name,description:L.description||"",unit_price:L.unit_price,tax_percent:L.tax_percent||16,image_url:L.image_url||"",additional_images:K,stock_quantity:re(L.stock_quantity),barcode:L.barcode||"",sku:L.sku||"",cost_price:L.cost_price||0,track_inventory:L.track_inventory??!0,low_stock_alert:L.low_stock_alert??!0,min_stock_level:re(L.min_stock_level,10),reorder_point:re(L.reorder_point,20),category:L.category||"",category_id:L.category_id||null}),u(!0)},ze=async L=>{if(confirm("هل أنت متأكد من حذف هذا المنتج؟"))try{const K=localStorage.getItem(xe);if(!(await fetch(`${oe()}${W.DELETE("products",L)}`,{method:"POST",headers:K?{Authorization:`Bearer ${K}`}:{}})).ok)throw new Error("Failed to delete product");t({title:"تم الحذف",description:"تم حذف المنتج بنجاح"}),await Q()}catch(K){console.error("Error deleting product:",K),t({title:"خطأ",description:"فشل في حذف المنتج",variant:"destructive"})}},Ce=v.useMemo(()=>{if(!o)return[];const L=new Map;return o.forEach(K=>{const ge=K.category_name.trim().toLowerCase(),Fe=X.filter(He=>He.category_id===K.id).length;if(!L.has(ge))L.set(ge,{category:K,count:Fe});else{const He=L.get(ge);Fe>He.count&&L.set(ge,{category:K,count:Fe})}}),Array.from(L.values()).map(K=>K.category)},[o,X]),st=v.useMemo(()=>{const L={total:X.length},K=new Map;return Ce.forEach(ge=>{const Fe=ge.category_name.trim().toLowerCase();K.set(Fe,ge.id)}),o==null||o.forEach(ge=>{const Fe=ge.category_name.trim().toLowerCase(),He=K.get(Fe);if(He){const Pe=X.filter(Ze=>Ze.category_id===ge.id).length;L[He]=(L[He]||0)+Pe}}),L},[X,o,Ce]),ot=v.useMemo(()=>X.filter(L=>{var Pe,Ze,Wt;const K=d.toLowerCase().trim(),ge=!K||L.product_name.toLowerCase().includes(K)||((Pe=L.description)==null?void 0:Pe.toLowerCase().includes(K))||((Ze=L.barcode)==null?void 0:Ze.toLowerCase().includes(K))||((Wt=L.sku)==null?void 0:Wt.toLowerCase().includes(K)),Fe=!p||L.category_id===p;let He=!0;return x==="low"?He=L.track_inventory&&(L.stock_quantity||0)>0&&(L.stock_quantity||0)<=(L.min_stock_level||10):x==="out"&&(He=L.track_inventory&&(L.stock_quantity||0)===0),ge&&Fe&&He}),[X,d,p,x]),dt=v.useMemo(()=>({totalProducts:X.length,lowStockProducts:X.filter(L=>L.track_inventory&&L.low_stock_alert&&(L.stock_quantity||0)<=(L.min_stock_level||10)).length,outOfStockProducts:X.filter(L=>L.track_inventory&&(L.stock_quantity||0)===0).length}),[X]);return U?e.jsx("div",{className:"flex items-center justify-center h-64",children:e.jsx("div",{className:"animate-spin rounded-full h-12 w-12 border-b-2 border-orange-600"})}):e.jsxs(e.Fragment,{children:[e.jsx(ma,{isPulling:H,pullDistance:Y,isRefreshing:J,canRefresh:ie,progress:ce}),e.jsxs("div",{className:"space-y-4 sm:space-y-6",dir:"rtl",children:[e.jsxs(fe,{className:"bg-gradient-to-r from-orange-50 to-amber-50 dark:from-orange-950/30 dark:to-amber-950/30 border-2 border-orange-200 dark:border-orange-800",children:[e.jsx(De,{className:"pb-2 sm:pb-4",children:e.jsxs($e,{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3 text-orange-900 dark:text-orange-100",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ht,{className:"h-5 w-5 sm:h-6 sm:w-6"}),e.jsx("span",{className:"text-lg sm:text-xl",children:"المنتجات والخدمات"})]}),s&&e.jsxs(gt,{open:m,onOpenChange:u,children:[e.jsx(mn,{asChild:!0,children:e.jsxs(V,{className:"w-full sm:w-auto bg-gradient-to-r from-orange-500 to-orange-600 hover:from-orange-600 hover:to-orange-700 min-h-[44px]",onClick:()=>{l(null),C({product_name:"",description:"",unit_price:0,tax_percent:16,image_url:"",additional_images:[],stock_quantity:0,barcode:"",sku:"",cost_price:0,track_inventory:!0,low_stock_alert:!0,min_stock_level:10,reorder_point:20,category:"",category_id:null})},children:[e.jsx(kt,{className:"h-4 w-4 ml-1"}),"إضافة منتج جديد"]})}),e.jsxs(bt,{className:"max-w-[95vw] sm:max-w-2xl max-h-[90vh] overflow-y-auto p-4 sm:p-6",dir:"rtl",children:[e.jsxs(Tt,{className:"pb-2",children:[e.jsx(At,{className:"text-lg",children:c?"تعديل المنتج":"إضافة منتج جديد"}),e.jsx(kn,{className:"text-sm",children:c?"قم بتعديل بيانات المنتج":"أدخل بيانات المنتج الجديد"})]}),e.jsxs("div",{className:"space-y-3 py-2",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"flex-shrink-0",children:e.jsxs(fr,{className:"h-20 w-20 border-2 border-orange-200",children:[e.jsx(Yr,{src:N.image_url,alt:"Product"}),e.jsx(pr,{className:"bg-orange-50",children:e.jsx(gs,{className:"h-10 w-10 text-orange-300"})})]})}),e.jsxs("div",{className:"flex-1",children:[e.jsx(_e,{htmlFor:"image_upload",className:"text-orange-900 font-semibold mb-2 block",children:"صورة المنتج"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Te,{id:"image_upload",type:"file",accept:"image/*",onChange:Se,disabled:A,className:"hidden"}),e.jsxs(V,{type:"button",variant:"outline",onClick:()=>{var L;return(L=document.getElementById("image_upload"))==null?void 0:L.click()},disabled:A,className:"border-2 border-orange-200",children:[e.jsx(eh,{className:"h-4 w-4 ml-1"}),A?"جاري الرفع...":"رفع صورة"]}),N.image_url&&e.jsx(V,{type:"button",variant:"ghost",onClick:()=>C({...N,image_url:""}),className:"text-red-600",children:e.jsx(at,{className:"h-4 w-4"})})]}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"الحد الأقصى: 5 ميغابايت (JPG, PNG, WEBP)"})]})]}),e.jsxs("div",{children:[e.jsx(_e,{htmlFor:"product_name",className:"text-orange-900 font-semibold",children:"اسم المنتج *"}),e.jsx(Te,{id:"product_name",value:N.product_name,onChange:L=>C({...N,product_name:L.target.value}),placeholder:"أدخل اسم المنتج",className:"border-2 border-orange-200 focus:border-orange-400"})]}),e.jsxs("div",{children:[e.jsx(_e,{htmlFor:"description",className:"text-orange-900 font-semibold",children:"الوصف"}),e.jsx(Te,{id:"description",value:N.description,onChange:L=>C({...N,description:L.target.value}),placeholder:"وصف المنتج (اختياري)",className:"border-2 border-orange-200 focus:border-orange-400"})]}),e.jsxs("div",{children:[e.jsx(_e,{htmlFor:"category_id",className:"text-orange-900 font-semibold",children:"الفئة"}),e.jsxs(vt,{value:N.category_id||"none",onValueChange:L=>C({...N,category_id:L==="none"?null:L}),children:[e.jsx(_t,{className:"font-cairo border-2 border-orange-200 focus:border-orange-400",children:e.jsx(wt,{placeholder:"اختر فئة (اختياري)"})}),e.jsxs(jt,{className:"font-cairo",children:[e.jsx(Je,{value:"none",children:"بدون فئة"}),o.map(L=>e.jsx(Je,{value:L.id,children:L.category_name},L.id))]})]})]}),e.jsxs("div",{children:[e.jsx(_e,{htmlFor:"unit_price",className:"text-orange-900 font-semibold",children:"السعر (د.أ)"}),e.jsx(Te,{id:"unit_price",type:"number",step:"0.01",value:N.unit_price,onChange:L=>C({...N,unit_price:Number(L.target.value)}),placeholder:"0.00",className:"border-2 border-orange-200 focus:border-orange-400"})]}),be&&e.jsxs("div",{children:[e.jsx(_e,{className:"text-orange-900 font-semibold",children:"نسبة الضريبة الافتراضية"}),e.jsxs(vt,{value:N.tax_percent.toString(),onValueChange:L=>C({...N,tax_percent:Number(L)}),children:[e.jsx(_t,{className:"font-cairo border-2 border-orange-200 focus:border-orange-400",children:e.jsx(wt,{})}),e.jsx(jt,{className:"font-cairo",children:q.map(L=>e.jsx(Je,{value:L.value.toString(),children:L.label},L.value))})]})]}),e.jsxs("div",{className:"border-t pt-4 mt-4",children:[e.jsx("h3",{className:"font-semibold text-orange-900 mb-3",children:"إدارة المخزون"}),e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx(_e,{htmlFor:"track_inventory",children:"تتبع المخزون"}),e.jsx(mr,{id:"track_inventory",checked:N.track_inventory,onCheckedChange:L=>C({...N,track_inventory:L})})]}),N.track_inventory&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(_e,{htmlFor:"stock_quantity",className:"text-sm",children:"الكمية الحالية"}),e.jsx(Te,{id:"stock_quantity",type:"number",value:N.stock_quantity,onChange:L=>C({...N,stock_quantity:Number(L.target.value)}),className:"border-2 border-orange-200"})]}),e.jsxs("div",{children:[e.jsx(_e,{htmlFor:"cost_price",className:"text-sm",children:"سعر التكلفة"}),e.jsx(Te,{id:"cost_price",type:"number",step:"0.01",value:N.cost_price,onChange:L=>C({...N,cost_price:Number(L.target.value)}),className:"border-2 border-orange-200"})]})]}),e.jsxs("div",{className:"flex items-center justify-between my-3",children:[e.jsx(_e,{htmlFor:"low_stock_alert",children:"تنبيه المخزون المنخفض"}),e.jsx(mr,{id:"low_stock_alert",checked:N.low_stock_alert,onCheckedChange:L=>C({...N,low_stock_alert:L})})]}),N.low_stock_alert&&e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(_e,{htmlFor:"min_stock_level",className:"text-sm",children:"الحد الأدنى للمخزون"}),e.jsx(Te,{id:"min_stock_level",type:"number",value:N.min_stock_level,onChange:L=>C({...N,min_stock_level:Number(L.target.value)}),className:"border-2 border-orange-200"})]}),e.jsxs("div",{children:[e.jsx(_e,{htmlFor:"reorder_point",className:"text-sm",children:"نقطة إعادة الطلب"}),e.jsx(Te,{id:"reorder_point",type:"number",value:N.reorder_point,onChange:L=>C({...N,reorder_point:Number(L.target.value)}),className:"border-2 border-orange-200"})]})]})]})]}),e.jsxs("div",{className:"border-t pt-4 mt-4",children:[e.jsx("h3",{className:"font-semibold text-orange-900 mb-3",children:"الباركود و SKU"}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(_e,{htmlFor:"barcode",className:"text-sm",children:"الباركود"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Te,{id:"barcode",value:N.barcode,onChange:L=>C({...N,barcode:L.target.value}),placeholder:"أدخل الباركود",className:"border-2 border-orange-200"}),e.jsx(V,{type:"button",variant:"outline",size:"icon",onClick:()=>C({...N,barcode:ig(crypto.randomUUID(),N.product_name||"product")}),title:"توليد باركود",children:e.jsx(En,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{children:[e.jsx(_e,{htmlFor:"sku",className:"text-sm",children:"رمز المنتج (SKU)"}),e.jsx(Te,{id:"sku",value:N.sku,onChange:L=>C({...N,sku:L.target.value}),placeholder:"SKU-001",className:"border-2 border-orange-200"})]})]})]}),e.jsxs("div",{className:"border-t pt-4 mt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(La,{className:"h-5 w-5 text-orange-600"}),e.jsx(_e,{className:"text-orange-900 font-semibold",children:"صور إضافية للتوثيق (اختياري)"})]}),e.jsx("p",{className:"text-xs text-gray-500 mb-3",children:"يمكنك إضافة صور إضافية للمنتج مثل فواتير الشراء، صور الباركود، أو أي وثائق أخرى"}),N.additional_images.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2 mb-3",children:N.additional_images.map((L,K)=>e.jsxs("div",{className:`relative group cursor-grab active:cursor-grabbing ${R===K?"opacity-50 scale-95":""}`,draggable:!0,onDragStart:ge=>{D(K),ge.dataTransfer.effectAllowed="move"},onDragOver:ge=>{ge.preventDefault(),ge.dataTransfer.dropEffect="move"},onDragEnter:ge=>{if(ge.preventDefault(),R!==null&&R!==K){const Fe=[...N.additional_images],He=Fe[R];Fe.splice(R,1),Fe.splice(K,0,He),C(Pe=>({...Pe,additional_images:Fe})),D(K)}},onDragEnd:()=>D(null),children:[e.jsxs("div",{className:"absolute top-0 left-0 right-0 bg-black/50 text-white text-xs text-center py-0.5 rounded-t opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center gap-1",children:[e.jsx(ic,{className:"h-3 w-3"}),e.jsx("span",{children:"اسحب للترتيب"})]}),e.jsx("img",{src:L,alt:`صورة إضافية ${K+1}`,className:"w-16 h-16 object-cover rounded border-2 border-orange-200 group-hover:border-purple-400 transition-colors"}),e.jsx(Ae,{variant:"secondary",className:"absolute -bottom-1 left-1/2 -translate-x-1/2 h-4 px-1 text-[10px] bg-gray-700 text-white",children:K+1}),e.jsx(V,{type:"button",size:"icon",variant:"destructive",className:"absolute -top-2 -right-2 h-5 w-5 opacity-0 group-hover:opacity-100 transition-opacity",onClick:()=>Re(K),children:e.jsx(at,{className:"h-3 w-3"})})]},K))}),N.additional_images.length>1&&e.jsx("p",{className:"text-xs text-purple-600 mb-2",children:"💡 اسحب الصور لإعادة ترتيبها"}),e.jsxs("div",{children:[e.jsx(Te,{id:"additional_image_upload",type:"file",accept:"image/*",multiple:!0,onChange:je,disabled:T,className:"hidden"}),T&&P.total>0&&e.jsxs("div",{className:"w-full mb-3 p-3 bg-purple-50 rounded-lg border border-purple-200",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("span",{className:"text-sm text-purple-700 font-medium",children:["جاري رفع الصور (",P.current,"/",P.total,")"]}),e.jsxs("span",{className:"text-xs text-purple-500",children:[Math.round(P.current/P.total*100),"%"]})]}),e.jsx("div",{className:"w-full h-2 bg-purple-200 rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full bg-gradient-to-r from-purple-500 to-purple-600 transition-all duration-300 ease-out",style:{width:`${P.current/P.total*100}%`}})}),e.jsxs("p",{className:"text-xs text-purple-600 mt-1 truncate",children:["📄 ",P.fileName]})]}),e.jsxs(V,{type:"button",variant:"outline",onClick:()=>{var L;return(L=document.getElementById("additional_image_upload"))==null?void 0:L.click()},disabled:T,className:"border-2 border-dashed border-orange-300 text-orange-600 hover:bg-orange-50",children:[e.jsx(kt,{className:"h-4 w-4 ml-1"}),T?`جاري الرفع (${P.current}/${P.total})...`:"إضافة صور"]}),N.additional_images.length>0&&!T&&e.jsxs(Ae,{variant:"secondary",className:"mr-2",children:[N.additional_images.length," صور"]})]})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-2 pt-4",children:[e.jsxs(V,{onClick:ne,className:"flex-1 bg-gradient-to-r from-green-500 to-green-600 hover:from-green-600 hover:to-green-700 min-h-[44px]",children:[e.jsx(Dn,{className:"h-4 w-4 ml-1"}),c?"تحديث":"حفظ"]}),e.jsxs(V,{variant:"outline",onClick:()=>u(!1),className:"flex-1 border-2 border-gray-300 min-h-[44px]",children:[e.jsx(at,{className:"h-4 w-4 ml-1"}),"إلغاء"]})]})]})]})]})]})}),e.jsxs(ve,{className:"pt-0",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row items-stretch sm:items-center gap-2",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(En,{className:`absolute right-3 top-1/2 transform -translate-y-1/2 h-5 w-5 transition-colors ${b==="success"?"text-green-500":b==="error"?"text-red-500":"text-muted-foreground"}`}),e.jsx(Te,{ref:I,placeholder:"البحث بالباركود، SKU، أو الاسم...",value:d,onChange:L=>se(L.target.value),onKeyDown:We,className:`pr-10 h-12 text-base font-mono border-2 transition-all ${b==="success"?"border-green-400 ring-2 ring-green-200 bg-green-50 dark:bg-green-950/30":b==="error"?"border-red-400 ring-2 ring-red-200 bg-red-50 dark:bg-red-950/30 animate-shake":"border-orange-200 dark:border-orange-800 focus:border-orange-400"}`}),d&&e.jsx(V,{variant:"ghost",size:"icon",onClick:()=>h(""),className:"absolute left-2 top-1/2 transform -translate-y-1/2 h-8 w-8 text-muted-foreground hover:text-foreground",children:e.jsx(at,{className:"h-4 w-4"})})]}),e.jsxs(V,{variant:"outline",onClick:()=>j(!0),title:"مسح باركود بالكاميرا",className:"h-12 min-h-[48px] min-w-[48px] sm:w-12 border-2 border-orange-200 dark:border-orange-800 hover:bg-orange-50 dark:hover:bg-orange-950/30 hover:border-orange-400",children:[e.jsx(Ls,{className:"h-6 w-6 text-orange-600"}),e.jsx("span",{className:"sm:hidden mr-2",children:"مسح بالكاميرا"})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-2",children:"اضغط Enter للبحث السريع بالباركود أو استخدم الكاميرا 📷"})]})]}),e.jsx(pa,{categories:Ce,selectedCategoryId:p,onSelectCategory:f,productsCount:st}),e.jsxs("div",{className:"grid grid-cols-2 lg:grid-cols-4 gap-2 sm:gap-4",children:[e.jsx(fe,{className:`cursor-pointer transition-all active:scale-95 ${x==="all"?"ring-2 ring-blue-400 ring-offset-2":""} bg-gradient-to-r from-blue-500 to-blue-600 text-white hover:scale-[1.02]`,onClick:()=>g("all"),children:e.jsx(ve,{className:"p-3 sm:p-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs sm:text-sm opacity-90",children:"إجمالي المنتجات"}),e.jsx("p",{className:"text-xl sm:text-2xl font-bold",children:dt.totalProducts})]}),e.jsx(ht,{className:"h-6 w-6 sm:h-8 sm:w-8 opacity-80"})]})})}),e.jsx(fe,{className:"cursor-pointer transition-all active:scale-95 bg-gradient-to-r from-green-500 to-green-600 text-white hover:scale-[1.02]",onClick:()=>g("all"),children:e.jsx(ve,{className:"p-3 sm:p-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs sm:text-sm opacity-90",children:"متوفر"}),e.jsx("p",{className:"text-xl sm:text-2xl font-bold",children:dt.totalProducts-dt.outOfStockProducts})]}),e.jsx(As,{className:"h-6 w-6 sm:h-8 sm:w-8 opacity-80"})]})})}),e.jsx(fe,{className:`cursor-pointer transition-all active:scale-95 ${x==="low"?"ring-2 ring-yellow-400 ring-offset-2":""} bg-gradient-to-r from-yellow-500 to-yellow-600 text-white hover:scale-[1.02]`,onClick:()=>g(x==="low"?"all":"low"),children:e.jsx(ve,{className:"p-3 sm:p-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs sm:text-sm opacity-90",children:"مخزون منخفض"}),e.jsx("p",{className:"text-xl sm:text-2xl font-bold",children:dt.lowStockProducts})]}),e.jsx(Zt,{className:"h-6 w-6 sm:h-8 sm:w-8 opacity-80"})]})})}),e.jsx(fe,{className:`cursor-pointer transition-all active:scale-95 ${x==="out"?"ring-2 ring-red-400 ring-offset-2":""} bg-gradient-to-r from-red-500 to-red-600 text-white hover:scale-[1.02]`,onClick:()=>g(x==="out"?"all":"out"),children:e.jsx(ve,{className:"p-3 sm:p-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs sm:text-sm opacity-90",children:"نفذ"}),e.jsx("p",{className:"text-xl sm:text-2xl font-bold",children:dt.outOfStockProducts})]}),e.jsx(ht,{className:"h-6 w-6 sm:h-8 sm:w-8 opacity-80"})]})})})]}),e.jsx(fe,{className:"shadow-xl border-2 border-border",children:e.jsxs(ve,{className:"p-0",children:[e.jsx("div",{className:"hidden md:block overflow-x-auto",children:e.jsxs(Io,{children:[e.jsx(Oo,{children:e.jsxs(ar,{className:"bg-gradient-to-r from-orange-50 to-amber-50",children:[e.jsx(rt,{className:"text-right font-bold text-orange-900",children:"الصورة"}),e.jsx(rt,{className:"text-right font-bold text-orange-900",children:"اسم المنتج"}),e.jsx(rt,{className:"text-right font-bold text-orange-900",children:"الفئة"}),e.jsx(rt,{className:"text-right font-bold text-orange-900",children:"السعر"}),be&&e.jsx(rt,{className:"text-right font-bold text-orange-900",children:"الضريبة"}),e.jsx(rt,{className:"text-right font-bold text-orange-900",children:"المخزون"}),e.jsx(rt,{className:"text-right font-bold text-orange-900",children:"الباركود"}),e.jsx(rt,{className:"text-right font-bold text-orange-900",children:"الإجراءات"})]})}),e.jsx(Ro,{children:ot.length===0?e.jsx(ar,{children:e.jsx(Qe,{colSpan:be?8:7,className:"text-center py-8 text-gray-500",children:"لا توجد منتجات"})}):ot.map(L=>{var K;return e.jsxs(ar,{className:"hover:bg-gray-50",children:[e.jsx(Qe,{children:e.jsxs("div",{className:"relative",children:[e.jsxs(fr,{className:"h-10 w-10 border border-orange-200",children:[e.jsx(Yr,{src:L.image_url,alt:L.product_name}),e.jsx(pr,{className:"bg-orange-50 text-orange-600 text-xs",children:L.product_name.charAt(0)})]}),M(L).length>0&&e.jsx(Ae,{variant:"secondary",className:"absolute -top-2 -left-2 h-5 w-5 p-0 flex items-center justify-center text-xs bg-purple-500 text-white cursor-pointer hover:bg-purple-600",onClick:()=>O(L),children:M(L).length})]})}),e.jsx(Qe,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:L.product_name}),L.description&&e.jsx("p",{className:"text-sm text-gray-500 truncate max-w-[200px]",children:L.description})]})}),e.jsx(Qe,{children:L.category_id?e.jsx(Ae,{variant:"outline",className:"bg-orange-50 text-orange-700 border-orange-200",children:((K=o==null?void 0:o.find(ge=>ge.id===L.category_id))==null?void 0:K.category_name)||"-"}):e.jsx("span",{className:"text-gray-400",children:"-"})}),e.jsx(Qe,{children:e.jsxs("div",{className:"flex items-center gap-1 text-green-600 font-bold",children:[e.jsx(gr,{className:"h-4 w-4"}),Number(L.unit_price||0).toFixed(2)," د.أ"]})}),be&&e.jsx(Qe,{children:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(cu,{className:"h-4 w-4 text-gray-400"}),L.tax_percent===-1?"معفي":`${L.tax_percent||16}%`]})}),e.jsx(Qe,{children:L.track_inventory?e.jsxs("div",{className:`flex items-center gap-1 ${(L.stock_quantity||0)===0?"text-red-600":(L.stock_quantity||0)<=(L.min_stock_level||10)?"text-yellow-600":"text-green-600"}`,children:[(L.stock_quantity||0)===0&&e.jsx(Zt,{className:"h-4 w-4"}),Math.floor(Number(L.stock_quantity||0))]}):e.jsx("span",{className:"text-gray-400",children:"-"})}),e.jsx(Qe,{children:L.barcode?e.jsx("code",{className:"text-xs bg-gray-100 px-2 py-1 rounded",children:L.barcode}):e.jsx("span",{className:"text-gray-400",children:"-"})}),e.jsx(Qe,{children:e.jsxs("div",{className:"flex gap-2",children:[s&&e.jsx(V,{variant:"outline",size:"sm",onClick:()=>de(L),className:"border-blue-300 text-blue-600 hover:bg-blue-50",children:e.jsx(en,{className:"h-4 w-4"})}),L.barcode&&e.jsx(V,{variant:"outline",size:"sm",onClick:()=>Si(L),className:"border-purple-300 text-purple-600 hover:bg-purple-50",title:"طباعة الباركود",children:e.jsx(En,{className:"h-4 w-4"})}),s&&e.jsx(V,{variant:"outline",size:"sm",onClick:()=>ze(L.id),className:"border-red-300 text-red-600 hover:bg-red-50",children:e.jsx(Ar,{className:"h-4 w-4"})})]})})]},L.id)})})]})}),e.jsx("div",{className:"md:hidden p-3",children:ot.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(ht,{className:"h-12 w-12 mx-auto mb-3 opacity-50"}),e.jsx("p",{children:"لا توجد منتجات"})]}):e.jsx("div",{className:"space-y-3",children:ot.map(L=>{var K;return e.jsx(fe,{className:"border-2 border-border overflow-hidden active:scale-[0.99] transition-transform",children:e.jsx(ve,{className:"p-3",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsxs("div",{className:"relative flex-shrink-0",children:[e.jsxs(fr,{className:"h-16 w-16 border-2 border-orange-200 dark:border-orange-800",children:[e.jsx(Yr,{src:L.image_url,alt:L.product_name,loading:"lazy"}),e.jsx(pr,{className:"bg-orange-50 dark:bg-orange-950 text-orange-600",children:e.jsx(ht,{className:"h-6 w-6"})})]}),M(L).length>0&&e.jsx(Ae,{variant:"secondary",className:"absolute -top-1 -right-1 h-5 w-5 p-0 flex items-center justify-center text-xs bg-purple-500 text-white cursor-pointer hover:bg-purple-600",onClick:()=>O(L),children:M(L).length}),L.track_inventory&&e.jsx(Ae,{variant:(L.stock_quantity||0)===0?"destructive":(L.stock_quantity||0)<=(L.min_stock_level||10)?"secondary":"default",className:"absolute -bottom-1 left-1/2 -translate-x-1/2 text-[10px] px-1.5",children:L.stock_quantity||0})]}),e.jsxs("div",{className:"flex-1 min-w-0 space-y-1",children:[e.jsx("h3",{className:"font-bold text-sm truncate",children:L.product_name}),L.category_id&&e.jsx(Ae,{variant:"outline",className:"text-[10px] bg-orange-50 dark:bg-orange-950/50 text-orange-700 dark:text-orange-300 border-orange-200 dark:border-orange-800",children:((K=o==null?void 0:o.find(ge=>ge.id===L.category_id))==null?void 0:K.category_name)||"-"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"text-green-600 dark:text-green-400 font-bold text-base",children:[Number(L.unit_price||0).toFixed(2)," د.أ"]}),be&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["(",L.tax_percent===-1?"معفي":`${L.tax_percent||16}%`,")"]})]}),L.barcode&&e.jsx("code",{className:"text-[10px] bg-muted px-1.5 py-0.5 rounded block truncate",children:L.barcode})]}),e.jsxs("div",{className:"flex flex-col gap-1 justify-center",children:[s&&e.jsxs(e.Fragment,{children:[e.jsx(V,{variant:"outline",size:"icon",onClick:()=>de(L),className:"h-10 w-10 min-h-[40px] border-blue-300 text-blue-600 hover:bg-blue-50 dark:hover:bg-blue-950/30",children:e.jsx(en,{className:"h-4 w-4"})}),e.jsx(V,{variant:"outline",size:"icon",onClick:()=>ze(L.id),className:"h-10 w-10 min-h-[40px] border-red-300 text-red-600 hover:bg-red-50 dark:hover:bg-red-950/30",children:e.jsx(Ar,{className:"h-4 w-4"})})]}),L.barcode&&e.jsx(V,{variant:"outline",size:"icon",onClick:()=>Si(L),className:"h-10 w-10 min-h-[40px] border-purple-300 text-purple-600 hover:bg-purple-50 dark:hover:bg-purple-950/30",title:"طباعة الباركود",children:e.jsx(En,{className:"h-4 w-4"})})]})]})})},L.id)})})})]})}),e.jsx(gt,{open:!!E,onOpenChange:L=>!L&&O(null),children:e.jsxs(bt,{className:"max-w-[95vw] sm:max-w-3xl max-h-[90vh] overflow-y-auto p-4 sm:p-6",dir:"rtl",children:[e.jsxs(Tt,{className:"pb-2",children:[e.jsxs(At,{className:"flex items-center gap-2 text-lg",children:[e.jsx(La,{className:"h-5 w-5 text-purple-600"}),"صور ",E==null?void 0:E.product_name]}),e.jsx(kn,{className:"text-sm",children:"الصورة الرئيسية والصور الإضافية للتوثيق"})]}),E&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(_e,{className:"text-sm font-semibold text-muted-foreground mb-2 block",children:"الصورة الرئيسية"}),e.jsx("div",{className:"flex justify-center",children:E.image_url?e.jsx("img",{src:E.image_url,alt:E.product_name,className:"max-w-full max-h-48 sm:max-h-64 object-contain rounded-lg border-2 border-orange-200 dark:border-orange-800"}):e.jsx("div",{className:"w-48 h-48 sm:w-64 sm:h-64 bg-muted rounded-lg flex items-center justify-center",children:e.jsx(gs,{className:"h-12 w-12 sm:h-16 sm:w-16 text-muted-foreground"})})})]}),M(E).length>0&&e.jsxs("div",{children:[e.jsxs(_e,{className:"text-sm font-semibold text-muted-foreground mb-2 block",children:["صور إضافية للتوثيق (",M(E).length,")"]}),e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-2 sm:gap-3",children:M(E).map((L,K)=>e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:L,alt:`صورة إضافية ${K+1}`,className:"w-full h-32 sm:h-40 object-cover rounded-lg border-2 border-purple-200 dark:border-purple-800 cursor-pointer hover:border-purple-400 transition-colors",onClick:()=>window.open(L,"_blank")}),e.jsx("div",{className:"absolute inset-0 bg-black/50 opacity-0 group-hover:opacity-100 transition-opacity rounded-lg flex items-center justify-center",children:e.jsx("span",{className:"text-white text-xs sm:text-sm",children:"اضغط للتكبير"})})]},K))})]})]})]})}),_&&e.jsx(Al,{onDetected:ke,onClose:()=>j(!1)})]})]})};var xa="Dialog",[Bl,ql]=Fn(xa),[hg,Ht]=Bl(xa),Vl=t=>{const{__scopeDialog:r,children:n,open:i,defaultOpen:o,onOpenChange:a,modal:s=!0}=t,c=v.useRef(null),l=v.useRef(null),[m=!1,u]=Zi({prop:i,defaultProp:o,onChange:a});return e.jsx(hg,{scope:r,triggerRef:c,contentRef:l,contentId:ir(),titleId:ir(),descriptionId:ir(),open:m,onOpenChange:u,onOpenToggle:v.useCallback(()=>u(d=>!d),[u]),modal:s,children:n})};Vl.displayName=xa;var Gl="DialogTrigger",Hl=v.forwardRef((t,r)=>{const{__scopeDialog:n,...i}=t,o=Ht(Gl,n),a=Mr(r,o.triggerRef);return e.jsx(Lt.button,{type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.contentId,"data-state":ya(o.open),...i,ref:a,onClick:cr(t.onClick,o.onOpenToggle)})});Hl.displayName=Gl;var ga="DialogPortal",[fg,Wl]=Bl(ga,{forceMount:void 0}),Xl=t=>{const{__scopeDialog:r,forceMount:n,children:i,container:o}=t,a=Ht(ga,r);return e.jsx(fg,{scope:r,forceMount:n,children:v.Children.map(i,s=>e.jsx(Ps,{present:n||a.open,children:e.jsx(Tu,{asChild:!0,container:o,children:s})}))})};Xl.displayName=ga;var Ts="DialogOverlay",Jl=v.forwardRef((t,r)=>{const n=Wl(Ts,t.__scopeDialog),{forceMount:i=n.forceMount,...o}=t,a=Ht(Ts,t.__scopeDialog);return a.modal?e.jsx(Ps,{present:i||a.open,children:e.jsx(pg,{...o,ref:r})}):null});Jl.displayName=Ts;var pg=v.forwardRef((t,r)=>{const{__scopeDialog:n,...i}=t,o=Ht(Ts,n);return e.jsx(wu,{as:ju,allowPinchZoom:!0,shards:[o.contentRef],children:e.jsx(Lt.div,{"data-state":ya(o.open),...i,ref:r,style:{pointerEvents:"auto",...i.style}})})}),Pr="DialogContent",Kl=v.forwardRef((t,r)=>{const n=Wl(Pr,t.__scopeDialog),{forceMount:i=n.forceMount,...o}=t,a=Ht(Pr,t.__scopeDialog);return e.jsx(Ps,{present:i||a.open,children:a.modal?e.jsx(xg,{...o,ref:r}):e.jsx(gg,{...o,ref:r})})});Kl.displayName=Pr;var xg=v.forwardRef((t,r)=>{const n=Ht(Pr,t.__scopeDialog),i=v.useRef(null),o=Mr(r,n.contentRef,i);return v.useEffect(()=>{const a=i.current;if(a)return Nu(a)},[]),e.jsx(Yl,{...t,ref:o,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:cr(t.onCloseAutoFocus,a=>{var s;a.preventDefault(),(s=n.triggerRef.current)==null||s.focus()}),onPointerDownOutside:cr(t.onPointerDownOutside,a=>{const s=a.detail.originalEvent,c=s.button===0&&s.ctrlKey===!0;(s.button===2||c)&&a.preventDefault()}),onFocusOutside:cr(t.onFocusOutside,a=>a.preventDefault())})}),gg=v.forwardRef((t,r)=>{const n=Ht(Pr,t.__scopeDialog),i=v.useRef(!1),o=v.useRef(!1);return e.jsx(Yl,{...t,ref:r,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:a=>{var s,c;(s=t.onCloseAutoFocus)==null||s.call(t,a),a.defaultPrevented||(i.current||(c=n.triggerRef.current)==null||c.focus(),a.preventDefault()),i.current=!1,o.current=!1},onInteractOutside:a=>{var l,m;(l=t.onInteractOutside)==null||l.call(t,a),a.defaultPrevented||(i.current=!0,a.detail.originalEvent.type==="pointerdown"&&(o.current=!0));const s=a.target;((m=n.triggerRef.current)==null?void 0:m.contains(s))&&a.preventDefault(),a.detail.originalEvent.type==="focusin"&&o.current&&a.preventDefault()}})}),Yl=v.forwardRef((t,r)=>{const{__scopeDialog:n,trapFocus:i,onOpenAutoFocus:o,onCloseAutoFocus:a,...s}=t,c=Ht(Pr,n),l=v.useRef(null),m=Mr(r,l);return Cu(),e.jsxs(e.Fragment,{children:[e.jsx(Eu,{asChild:!0,loop:!0,trapped:i,onMountAutoFocus:o,onUnmountAutoFocus:a,children:e.jsx(Su,{role:"dialog",id:c.contentId,"aria-describedby":c.descriptionId,"aria-labelledby":c.titleId,"data-state":ya(c.open),...s,ref:m,onDismiss:()=>c.onOpenChange(!1)})}),e.jsxs(e.Fragment,{children:[e.jsx(yg,{titleId:c.titleId}),e.jsx(_g,{contentRef:l,descriptionId:c.descriptionId})]})]})}),ba="DialogTitle",Ql=v.forwardRef((t,r)=>{const{__scopeDialog:n,...i}=t,o=Ht(ba,n);return e.jsx(Lt.h2,{id:o.titleId,...i,ref:r})});Ql.displayName=ba;var Zl="DialogDescription",ed=v.forwardRef((t,r)=>{const{__scopeDialog:n,...i}=t,o=Ht(Zl,n);return e.jsx(Lt.p,{id:o.descriptionId,...i,ref:r})});ed.displayName=Zl;var td="DialogClose",rd=v.forwardRef((t,r)=>{const{__scopeDialog:n,...i}=t,o=Ht(td,n);return e.jsx(Lt.button,{type:"button",...i,ref:r,onClick:cr(t.onClick,()=>o.onOpenChange(!1))})});rd.displayName=td;function ya(t){return t?"open":"closed"}var nd="DialogTitleWarning",[bg,sd]=ku(nd,{contentName:Pr,titleName:ba,docsSlug:"dialog"}),yg=({titleId:t})=>{const r=sd(nd),n=`\`${r.contentName}\` requires a \`${r.titleName}\` for the component to be accessible for screen reader users.

If you want to hide the \`${r.titleName}\`, you can wrap it with our VisuallyHidden component.

For more information, see https://radix-ui.com/primitives/docs/components/${r.docsSlug}`;return v.useEffect(()=>{t&&(document.getElementById(t)||console.error(n))},[n,t]),null},vg="DialogDescriptionWarning",_g=({contentRef:t,descriptionId:r})=>{const i=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${sd(vg).contentName}}.`;return v.useEffect(()=>{var a;const o=(a=t.current)==null?void 0:a.getAttribute("aria-describedby");r&&o&&(document.getElementById(r)||console.warn(i))},[i,t,r]),null},wg=Vl,jg=Hl,Ng=Xl,Cg=Jl,Eg=Kl,Sg=Ql,kg=ed,od=rd,ad="AlertDialog",[Tg,Fy]=Fn(ad,[ql]),dr=ql(),id=t=>{const{__scopeAlertDialog:r,...n}=t,i=dr(r);return e.jsx(wg,{...i,...n,modal:!0})};id.displayName=ad;var Ag="AlertDialogTrigger",Ig=v.forwardRef((t,r)=>{const{__scopeAlertDialog:n,...i}=t,o=dr(n);return e.jsx(jg,{...o,...i,ref:r})});Ig.displayName=Ag;var Og="AlertDialogPortal",cd=t=>{const{__scopeAlertDialog:r,...n}=t,i=dr(r);return e.jsx(Ng,{...i,...n})};cd.displayName=Og;var Rg="AlertDialogOverlay",ld=v.forwardRef((t,r)=>{const{__scopeAlertDialog:n,...i}=t,o=dr(n);return e.jsx(Cg,{...o,...i,ref:r})});ld.displayName=Rg;var Qr="AlertDialogContent",[Pg,Mg]=Tg(Qr),dd=v.forwardRef((t,r)=>{const{__scopeAlertDialog:n,children:i,...o}=t,a=dr(n),s=v.useRef(null),c=Mr(r,s),l=v.useRef(null);return e.jsx(bg,{contentName:Qr,titleName:ud,docsSlug:"alert-dialog",children:e.jsx(Pg,{scope:n,cancelRef:l,children:e.jsxs(Eg,{role:"alertdialog",...a,...o,ref:c,onOpenAutoFocus:cr(o.onOpenAutoFocus,m=>{var u;m.preventDefault(),(u=l.current)==null||u.focus({preventScroll:!0})}),onPointerDownOutside:m=>m.preventDefault(),onInteractOutside:m=>m.preventDefault(),children:[e.jsx(Au,{children:i}),e.jsx(Dg,{contentRef:s})]})})})});dd.displayName=Qr;var ud="AlertDialogTitle",md=v.forwardRef((t,r)=>{const{__scopeAlertDialog:n,...i}=t,o=dr(n);return e.jsx(Sg,{...o,...i,ref:r})});md.displayName=ud;var hd="AlertDialogDescription",fd=v.forwardRef((t,r)=>{const{__scopeAlertDialog:n,...i}=t,o=dr(n);return e.jsx(kg,{...o,...i,ref:r})});fd.displayName=hd;var Lg="AlertDialogAction",pd=v.forwardRef((t,r)=>{const{__scopeAlertDialog:n,...i}=t,o=dr(n);return e.jsx(od,{...o,...i,ref:r})});pd.displayName=Lg;var xd="AlertDialogCancel",gd=v.forwardRef((t,r)=>{const{__scopeAlertDialog:n,...i}=t,{cancelRef:o}=Mg(xd,n),a=dr(n),s=Mr(r,o);return e.jsx(od,{...a,...i,ref:s})});gd.displayName=xd;var Dg=({contentRef:t})=>{const r=`\`${Qr}\` requires a description for the component to be accessible for screen reader users.

You can add a description to the \`${Qr}\` by passing a \`${hd}\` component as a child, which also benefits sighted users by adding visible context to the dialog.

Alternatively, you can use your own component as a description by assigning it an \`id\` and passing the same value to the \`aria-describedby\` prop in \`${Qr}\`. If the description is confusing or duplicative for sighted users, you can use the \`@radix-ui/react-visually-hidden\` primitive as a wrapper around your description component.

For more information, see https://radix-ui.com/primitives/docs/components/alert-dialog`;return v.useEffect(()=>{var i;document.getElementById((i=t.current)==null?void 0:i.getAttribute("aria-describedby"))||console.warn(r)},[r,t]),null},$g=id,Fg=cd,bd=ld,yd=dd,vd=pd,_d=gd,wd=md,jd=fd;const Ug=$g,zg=Fg,Nd=v.forwardRef(({className:t,...r},n)=>e.jsx(bd,{className:Z("fixed inset-0 z-50 bg-black/80  data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",t),...r,ref:n}));Nd.displayName=bd.displayName;const Cd=v.forwardRef(({className:t,...r},n)=>e.jsxs(zg,{children:[e.jsx(Nd,{}),e.jsx(yd,{ref:n,className:Z("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",t),...r})]}));Cd.displayName=yd.displayName;const Ed=({className:t,...r})=>e.jsx("div",{className:Z("flex flex-col space-y-2 text-center sm:text-left",t),...r});Ed.displayName="AlertDialogHeader";const Sd=({className:t,...r})=>e.jsx("div",{className:Z("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",t),...r});Sd.displayName="AlertDialogFooter";const kd=v.forwardRef(({className:t,...r},n)=>e.jsx(wd,{ref:n,className:Z("text-lg font-semibold",t),...r}));kd.displayName=wd.displayName;const Td=v.forwardRef(({className:t,...r},n)=>e.jsx(jd,{ref:n,className:Z("text-sm text-muted-foreground",t),...r}));Td.displayName=jd.displayName;const Ad=v.forwardRef(({className:t,...r},n)=>e.jsx(vd,{ref:n,className:Z(Do(),t),...r}));Ad.displayName=vd.displayName;const Id=v.forwardRef(({className:t,...r},n)=>e.jsx(_d,{ref:n,className:Z(Do({variant:"outline"}),"mt-2 sm:mt-0",t),...r}));Id.displayName=_d.displayName;const qs=Lu,Vs=Du,Yn=v.forwardRef(({className:t,align:r="center",sideOffset:n=4,...i},o)=>e.jsx(Mu,{children:e.jsx(sc,{ref:o,align:r,sideOffset:n,className:Z("z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",t),...i})}));Yn.displayName=sc.displayName;const Bg=({value:t,onChange:r})=>{const[n,i]=v.useState(!1),o=fs.find(s=>s.value===t),a=(o==null?void 0:o.icon)||fs[0].icon;return e.jsxs(qs,{open:n,onOpenChange:i,modal:!0,children:[e.jsx(Vs,{asChild:!0,children:e.jsxs(V,{variant:"outline",className:"w-full justify-start gap-2",type:"button",children:[e.jsx(a,{className:Z("h-5 w-5",o==null?void 0:o.color)}),e.jsx("span",{children:(o==null?void 0:o.label)||"اختر أيقونة"})]})}),e.jsx(Yn,{className:"w-80 p-0 z-50",align:"start",children:e.jsx(un,{className:"h-72",children:e.jsx("div",{className:"grid grid-cols-4 gap-2 p-4",children:fs.map(s=>{const c=s.icon;return e.jsxs(V,{type:"button",variant:"outline",className:Z("h-16 flex flex-col items-center justify-center gap-1",t===s.value&&"border-primary border-2 bg-primary/10"),onClick:()=>{r(s.value),i(!1)},children:[e.jsx(c,{className:Z("h-6 w-6",s.color)}),e.jsx("span",{className:"text-xs",children:s.label})]},s.value)})})})})]})},qg=()=>{const t=Mt(),r=dn(),{checkPermission:n,silentCheck:i}=Kn(),{categories:o,isLoading:a,createCategory:s,updateCategory:c,deleteCategory:l}=fa(t),m=i("can_manage_categories"),[u,d]=v.useState(!1),[h,p]=v.useState(null),[f,x]=v.useState(null);v.useEffect(()=>{const w=`categories_cleaned_v1_${t}`;t&&!localStorage.getItem(w)&&zl(t).then(N=>{N.success&&N.deleted>0&&(console.log(`🧹 Cleaned up ${N.deleted} duplicate categories`),r.invalidateQueries({queryKey:["categories",t]})),localStorage.setItem(w,"true")})},[t,r]);const[g,b]=v.useState({category_name:"",category_icon:"package",category_color:"blue",display_order:0}),y=()=>{b({category_name:"",category_icon:"package",category_color:"blue",display_order:0}),p(null)},_=w=>{p(w),b({category_name:w.category_name,category_icon:w.category_icon,category_color:w.category_color,display_order:w.display_order}),d(!0)},j=async w=>{if(w.preventDefault(),!!n("can_manage_categories","ليس لديك صلاحية إدارة الفئات"))try{h?await c({id:h.id,updates:g}):await s({...g,display_order:o.length}),d(!1),y()}catch(N){console.error("Error saving category:",N)}},I=async w=>{if(n("can_manage_categories","ليس لديك صلاحية حذف الفئات"))try{await l(w),x(null)}catch(N){console.error("Error deleting category:",N)}};return a?e.jsx(fe,{className:"p-8 text-center",children:e.jsx("p",{className:"text-muted-foreground",children:"جاري التحميل..."})}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold",children:"إدارة الفئات"}),e.jsx("p",{className:"text-muted-foreground",children:"نظّم منتجاتك في فئات لتسهيل البحث والوصول"})]}),e.jsxs(gt,{open:u,onOpenChange:w=>{d(w),w||y()},children:[m&&e.jsx(mn,{asChild:!0,children:e.jsxs(V,{className:"gap-2",children:[e.jsx(kt,{className:"h-4 w-4"}),"إضافة فئة جديدة"]})}),e.jsxs(bt,{className:"max-w-md",children:[e.jsx(Tt,{children:e.jsx(At,{children:h?"تعديل الفئة":"إضافة فئة جديدة"})}),e.jsxs("form",{onSubmit:j,className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(_e,{children:"اسم الفئة *"}),e.jsx(Te,{value:g.category_name,onChange:w=>b({...g,category_name:w.target.value}),placeholder:"مثال: خضار وفواكه",required:!0})]}),e.jsxs("div",{children:[e.jsx(_e,{children:"الأيقونة"}),e.jsx(Bg,{value:g.category_icon,onChange:w=>b({...g,category_icon:w})})]}),e.jsxs("div",{children:[e.jsx(_e,{children:"اللون"}),e.jsxs(vt,{value:g.category_color,onValueChange:w=>b({...g,category_color:w}),children:[e.jsx(_t,{children:e.jsx(wt,{})}),e.jsx(jt,{children:ks.map(w=>e.jsx(Je,{value:w.value,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:Z("w-4 h-4 rounded-full",w.bg,w.border,"border-2")}),w.label]})},w.value))})]})]}),e.jsxs("div",{className:"p-4 border border-border rounded-lg",children:[e.jsx(_e,{className:"text-sm text-muted-foreground mb-2 block",children:"معاينة"}),e.jsxs(V,{type:"button",variant:"outline",className:Z("w-full",Sn(g.category_color).bg,Sn(g.category_color).text,Sn(g.category_color).border),children:[we.createElement(So(g.category_icon),{className:"h-4 w-4 ml-2"}),g.category_name||"اسم الفئة"]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(V,{type:"submit",className:"flex-1",children:h?"حفظ التعديلات":"إضافة"}),e.jsx(V,{type:"button",variant:"outline",onClick:()=>{d(!1),y()},children:"إلغاء"})]})]})]})]})]}),e.jsx(fe,{children:e.jsxs(Io,{children:[e.jsx(Oo,{children:e.jsxs(ar,{children:[e.jsx(rt,{className:"w-12"}),e.jsx(rt,{className:"w-16",children:"الترتيب"}),e.jsx(rt,{className:"w-20",children:"الأيقونة"}),e.jsx(rt,{children:"اسم الفئة"}),e.jsx(rt,{className:"w-32",children:"اللون"}),e.jsx(rt,{className:"w-32 text-center",children:"الإجراءات"})]})}),e.jsx(Ro,{children:o.length===0?e.jsx(ar,{children:e.jsx(Qe,{colSpan:6,className:"text-center py-8 text-muted-foreground",children:"لا توجد فئات. ابدأ بإضافة فئة جديدة!"})}):o.map((w,N)=>{var F;const C=So(w.category_icon),A=Sn(w.category_color);return e.jsxs(ar,{children:[e.jsx(Qe,{children:e.jsx(ic,{className:"h-4 w-4 text-muted-foreground cursor-grab"})}),e.jsx(Qe,{className:"font-mono",children:N+1}),e.jsx(Qe,{children:e.jsx("div",{className:Z("w-10 h-10 rounded-lg flex items-center justify-center",A.bg,A.border,"border"),children:e.jsx(C,{className:Z("h-5 w-5",A.text)})})}),e.jsx(Qe,{className:"font-medium",children:w.category_name}),e.jsx(Qe,{children:e.jsx("div",{className:Z("px-3 py-1 rounded-full inline-block text-sm",A.bg,A.text),children:(F=ks.find(T=>T.value===w.category_color))==null?void 0:F.label})}),e.jsx(Qe,{children:e.jsx("div",{className:"flex items-center justify-center gap-2",children:m&&e.jsxs(e.Fragment,{children:[e.jsx(V,{variant:"ghost",size:"sm",onClick:()=>_(w),children:e.jsx(en,{className:"h-4 w-4"})}),e.jsx(V,{variant:"ghost",size:"sm",onClick:()=>x(w.id),children:e.jsx(Ar,{className:"h-4 w-4 text-destructive"})})]})})})]},w.id)})})]})}),e.jsx(Ug,{open:!!f,onOpenChange:w=>!w&&x(null),children:e.jsxs(Cd,{children:[e.jsxs(Ed,{children:[e.jsx(kd,{children:"تأكيد الحذف"}),e.jsx(Td,{children:"هل أنت متأكد من حذف هذه الفئة؟ المنتجات المرتبطة بها لن تُحذف، فقط سيتم إلغاء ارتباطها بالفئة."})]}),e.jsxs(Sd,{children:[e.jsx(Id,{children:"إلغاء"}),e.jsx(Ad,{onClick:()=>f&&I(f),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"حذف"})]})]})})]})},ki=()=>localStorage.getItem(xe),Od=t=>{const[r,n]=v.useState([]),[i,o]=v.useState(!0),a=async c=>{if(!t){o(!1);return}try{const l=ki(),m=`${oe()}${W.GET_ALL("audit_log")}&token=${l}&filters=${encodeURIComponent(JSON.stringify({seller_id:t}))}`,d=await(await fetch(m)).json();if(d.success){let h=d.data||[];c!=null&&c.employeeId&&(h=h.filter(p=>p.employee_id===c.employeeId)),c!=null&&c.entityType&&(h=h.filter(p=>p.entity_type===c.entityType)),c!=null&&c.actionType&&(h=h.filter(p=>p.action_type===c.actionType)),c!=null&&c.startDate&&(h=h.filter(p=>new Date(p.created_at)>=new Date(c.startDate))),c!=null&&c.endDate&&(h=h.filter(p=>new Date(p.created_at)<=new Date(c.endDate))),h=h.sort((p,f)=>new Date(f.created_at).getTime()-new Date(p.created_at).getTime()).slice(0,100),n(h)}else throw new Error(d.message)}catch(l){console.error("Error fetching audit logs:",l),Ge.error("فشل في تحميل سجل التدقيق")}finally{o(!1)}};return v.useEffect(()=>{a()},[t]),{logs:r,loading:i,fetchLogs:a,logAction:async(c,l,m,u=null,d=null,h=null,p=null)=>{if(t)try{const f=ki(),g=await(await fetch(`${oe()}${W.CREATE("audit_log")}&token=${f}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({seller_id:t,employee_id:h,action_type:c,entity_type:l,entity_id:m,old_values:u?JSON.stringify(u):null,new_values:d?JSON.stringify(d):null,notes:p})})).json();if(!g.success)throw new Error(g.message)}catch(f){console.error("Error logging action:",f)}}}};function Vg({readOnly:t=!1}){const{seller:r,isLoading:n,sellerId:i,invalidateSellerData:o}=Po(),{currentEmployee:a}=lt(),{logAction:s}=Od(i||""),{toast:c}=et(),l=v.useRef(null),[m,u]=v.useState({seller_name:"",password:"",seller_logo_url:""}),[d,h]=v.useState(!1),[p,f]=v.useState(!1);v.useEffect(()=>{if(r){const _={seller_name:r.seller_name||"",password:r.password||"",seller_logo_url:r.seller_logo_url||""};u(_),l.current={..._}}},[r]);function x(_){const{name:j,value:I}=_.target;u(w=>({...w,[j]:I}))}async function g(_,j){if(!t){h(!0);try{const I=localStorage.getItem(xe),w=new FormData;w.append("file",j),w.append("folder","logos");const N=await fetch(`${oe()}upload.php?token=${I}`,{method:"POST",body:w});if(!N.ok)throw new Error("Failed to upload logo");const C=await N.json();if(C.success&&C.data&&C.data.url)u(A=>({...A,[_]:C.data.url})),c({title:"تم رفع الشعار بنجاح",description:`الملف: ${C.data.filename}`});else throw new Error(C.message||"فشل رفع الملف")}catch(I){c({title:"خطأ في رفع الشعار",description:I.message,variant:"destructive"})}h(!1)}}async function b(_){_.target.files&&_.target.files[0]&&await g("seller_logo_url",_.target.files[0])}async function y(_){if(_.preventDefault(),t||!i)return;f(!0);const j={seller_name:m.seller_name,password:m.password,seller_logo_url:m.seller_logo_url};try{const I=localStorage.getItem(xe),w=await fetch(`${oe()}${W.UPDATE("sellers",i)}&token=${I}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(j)});if(!w.ok)throw new Error("Failed to save settings");const N=await w.json();if(!N.success)throw new Error(N.message||"Save failed");if(a&&l.current){const C=[];l.current.seller_name!==m.seller_name&&C.push(`اسم الشركة: "${l.current.seller_name}" → "${m.seller_name}"`),l.current.password!==m.password&&C.push("تم تغيير كلمة المرور"),l.current.seller_logo_url!==m.seller_logo_url&&C.push("تم تغيير شعار الشركة"),C.length>0&&await s("UPDATE","settings",i,`تعديل بيانات الشركة: ${C.join("، ")}`,JSON.stringify(l.current),JSON.stringify(m)),l.current={...m}}o(),c({title:"✅ تم حفظ بيانات الشركة بنجاح"})}catch(I){c({title:"فشل الحفظ",description:I.message,variant:"destructive"})}f(!1)}return n?e.jsx(fe,{children:e.jsxs(ve,{className:"font-cairo p-8 flex items-center justify-center gap-3",children:[e.jsx(ct,{className:"h-5 w-5 animate-spin text-blue-500"}),e.jsx("span",{children:"جاري تحميل بيانات الشركة..."})]})}):i?r?e.jsx("form",{onSubmit:y,children:e.jsxs(fe,{className:"border-2 hover:shadow-lg transition-all duration-300",children:[e.jsx(De,{className:"bg-gradient-to-r from-blue-500 to-blue-600 text-white",children:e.jsxs($e,{className:"font-cairo text-xl flex items-center gap-2",children:[e.jsx(Mo,{className:"h-6 w-6 animate-pulse"}),"بيانات الشركة",t&&e.jsx("span",{className:"text-xs bg-white/20 px-2 py-1 rounded-full mr-2",children:"قراءة فقط"})]})}),e.jsxs(ve,{className:"space-y-6 font-cairo pt-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"flex items-center gap-2 font-medium text-base",children:[e.jsx(Bt,{className:"h-4 w-4 text-blue-500"}),"اسم الشركة"]}),e.jsx(Te,{name:"seller_name",value:m.seller_name,onChange:x,required:!0,disabled:t,className:"transition-all focus:scale-[1.01] disabled:opacity-70 disabled:cursor-not-allowed"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"flex items-center gap-2 font-medium text-base",children:[e.jsx(Tn,{className:"h-4 w-4 text-blue-500"}),"كلمة المرور"]}),e.jsx(Te,{name:"password",value:m.password,type:"password",onChange:x,required:!0,disabled:t,className:"transition-all focus:scale-[1.01] disabled:opacity-70 disabled:cursor-not-allowed"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"flex items-center gap-2 font-medium text-base",children:[e.jsx(gs,{className:"h-4 w-4 text-blue-500"}),"شعار الشركة"]}),!t&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("input",{type:"file",accept:"image/*",onChange:b,className:"file:mr-3 file:px-4 file:py-2 file:rounded-lg file:border-0 file:bg-blue-500 file:text-white file:cursor-pointer hover:file:bg-blue-600 transition-all"}),d&&e.jsx("span",{className:"text-sm text-blue-600 animate-pulse",children:"جاري الرفع..."})]}),m.seller_logo_url&&e.jsx("div",{className:"mt-3 p-3 bg-accent/20 rounded-lg border-2 border-dashed border-accent inline-block",children:e.jsx("img",{src:m.seller_logo_url,alt:"شعار الشركة",className:"h-16 rounded shadow-md"})})]})]}),!t&&e.jsx(nc,{children:e.jsxs(V,{type:"submit",disabled:p,className:"font-cairo w-full text-lg py-6 bg-gradient-to-r from-blue-500 to-blue-600 hover:from-blue-600 hover:to-blue-700 transition-all duration-300 hover:scale-[1.02] shadow-lg hover:shadow-xl",children:[e.jsx(Dn,{className:"h-5 w-5 ml-2"}),p?"جاري الحفظ...":"حفظ بيانات الشركة"]})})]})}):e.jsx(fe,{children:e.jsx(ve,{className:"font-cairo p-8 text-center text-lg text-destructive",children:"لا يوجد بيانات شركة"})}):e.jsx(fe,{children:e.jsx(ve,{className:"font-cairo p-8 text-center text-lg text-destructive",children:"يرجى تسجيل الدخول"})})}function Gg({readOnly:t=!1}){const{seller:r,isLoading:n,sellerId:i,invalidateSellerData:o}=Po(),[a,s]=v.useState(!1),{toast:c}=et(),[l,m]=v.useState({show_company_logo:!0,enable_thermal_printing:!1,auto_print_thermal:!0,thermal_paper_width:"80mm",enable_bw_print:!0,show_cashier_name:!1,footer_text:""});v.useEffect(()=>{r&&m({show_company_logo:r.show_company_logo,enable_thermal_printing:r.enable_thermal_printing,auto_print_thermal:r.auto_print_thermal,thermal_paper_width:r.thermal_paper_width||"80mm",enable_bw_print:r.enable_bw_print,show_cashier_name:r.show_cashier_name,footer_text:r.footer_text||""})},[r]);async function u(d){if(d.preventDefault(),!i||t)return;s(!0);const h={show_company_logo:l.show_company_logo?1:0,enable_thermal_printing:l.enable_thermal_printing?1:0,auto_print_thermal:l.auto_print_thermal?1:0,thermal_paper_width:l.thermal_paper_width,enable_bw_print:l.enable_bw_print?1:0,show_cashier_name:l.show_cashier_name?1:0,footer_text:l.footer_text};try{const p=localStorage.getItem(xe),f=await fetch(`${oe()}${W.UPDATE("sellers",i)}&token=${p}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(h)});if(!f.ok)throw new Error("Failed to save settings");const x=await f.json();if(!x.success)throw new Error(x.message||"Save failed");o(),c({title:"✅ تم حفظ إعدادات الفاتورة بنجاح",description:`الطباعة الحرارية: ${l.enable_thermal_printing?"مفعّلة":"معطّلة"}`})}catch(p){c({title:"فشل الحفظ",description:p.message,variant:"destructive"})}s(!1)}return n?e.jsx(fe,{children:e.jsxs(ve,{className:"font-cairo p-8 flex items-center justify-center gap-3",children:[e.jsx(ct,{className:"h-5 w-5 animate-spin text-orange-500"}),e.jsx("span",{children:"جاري تحميل إعدادات الفاتورة..."})]})}):i?e.jsx("form",{onSubmit:u,children:e.jsxs(fe,{className:"border-2 hover:shadow-lg transition-all duration-300",children:[e.jsxs(De,{className:"bg-gradient-to-r from-orange-500 to-orange-600 text-white",children:[e.jsxs($e,{className:"font-cairo text-xl flex items-center gap-2",children:[e.jsx(It,{className:"h-6 w-6 animate-pulse"}),"إعدادات الفاتورة",t&&e.jsx("span",{className:"text-xs bg-white/20 px-2 py-1 rounded-full mr-2",children:"قراءة فقط"})]}),e.jsx("p",{className:"text-sm opacity-90 mt-1",children:"التحكم بمظهر الفاتورة وإعدادات الطباعة"})]}),e.jsxs(ve,{className:"space-y-6 font-cairo pt-6",children:[e.jsxs("div",{className:"space-y-3 p-4 bg-accent/10 rounded-lg border border-accent/30",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("label",{htmlFor:"show_company_logo",className:"flex items-center gap-2 font-medium text-base cursor-pointer",children:[e.jsx(gs,{className:"h-4 w-4 text-orange-500"}),"عرض الشعار في الفاتورة"]}),e.jsx(mr,{id:"show_company_logo",checked:l.show_company_logo,onCheckedChange:d=>m(h=>({...h,show_company_logo:d})),className:"data-[state=checked]:bg-orange-500",disabled:t})]}),e.jsx("p",{className:"text-xs text-muted-foreground pr-6",children:"إظهار أو إخفاء شعار الشركة عند طباعة الفاتورة"})]}),e.jsxs("div",{className:"space-y-3 p-4 bg-accent/10 rounded-lg border border-accent/30",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("label",{htmlFor:"enable_thermal_printing",className:"flex items-center gap-2 font-medium text-base cursor-pointer",children:[e.jsx(Zr,{className:"h-4 w-4 text-orange-500"}),"الطباعة الحرارية"]}),e.jsx(mr,{id:"enable_thermal_printing",checked:l.enable_thermal_printing,onCheckedChange:d=>m(h=>({...h,enable_thermal_printing:d})),className:"data-[state=checked]:bg-orange-500",disabled:t})]}),e.jsx("p",{className:"text-xs text-muted-foreground pr-6",children:"تفعيل زر الطباعة الحرارية في صفحة تفاصيل الفاتورة"})]}),l.enable_thermal_printing&&e.jsxs("div",{className:"space-y-3 p-4 bg-green-50 dark:bg-green-950/20 rounded-lg border border-green-200 dark:border-green-800",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("label",{htmlFor:"auto_print_thermal",className:"flex items-center gap-2 font-medium text-base cursor-pointer",children:[e.jsx(Zr,{className:"h-4 w-4 text-green-600"}),"الطباعة الفورية"]}),e.jsx(mr,{id:"auto_print_thermal",checked:l.auto_print_thermal,onCheckedChange:d=>m(h=>({...h,auto_print_thermal:d})),className:"data-[state=checked]:bg-green-600",disabled:t})]}),e.jsx("p",{className:"text-xs text-muted-foreground pr-6",children:"طباعة الفاتورة الحرارية تلقائياً فور إنشائها دون الحاجة للنقر على زر الطباعة"})]}),l.enable_thermal_printing&&e.jsxs("div",{className:"space-y-3 p-4 bg-blue-50 dark:bg-blue-950/20 rounded-lg border border-blue-200 dark:border-blue-800",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("label",{className:"flex items-center gap-2 font-medium text-base",children:[e.jsx(lu,{className:"h-4 w-4 text-blue-600"}),"حجم ورق الطباعة الحرارية"]}),e.jsxs(vt,{value:l.thermal_paper_width,onValueChange:d=>m(h=>({...h,thermal_paper_width:d})),disabled:t,children:[e.jsx(_t,{className:"w-36",children:e.jsx(wt,{})}),e.jsxs(jt,{children:[e.jsx(Je,{value:"58mm",children:"58mm (صغير)"}),e.jsx(Je,{value:"70mm",children:"70mm (متوسط)"}),e.jsx(Je,{value:"80mm",children:"80mm (قياسي)"})]})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground pr-6",children:"اختر حجم ورق الطابعة الحرارية المتوافق مع طابعتك"})]}),e.jsxs("div",{className:"space-y-3 p-4 bg-gray-50 dark:bg-gray-950/20 rounded-lg border border-gray-200 dark:border-gray-800",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("label",{htmlFor:"enable_bw_print",className:"flex items-center gap-2 font-medium text-base cursor-pointer",children:[e.jsx(zi,{className:"h-4 w-4 text-gray-600"}),"الطباعة بالأبيض والأسود"]}),e.jsx(mr,{id:"enable_bw_print",checked:l.enable_bw_print,onCheckedChange:d=>m(h=>({...h,enable_bw_print:d})),className:"data-[state=checked]:bg-gray-600",disabled:t})]}),e.jsx("p",{className:"text-xs text-muted-foreground pr-6",children:"عند التفعيل، ستتم الطباعة بالأبيض والأسود فقط. تحميل PDF يبقى بالألوان"})]}),e.jsxs("div",{className:"space-y-3 p-4 bg-accent/10 rounded-lg border border-accent/30",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("label",{htmlFor:"show_cashier_name",className:"flex items-center gap-2 font-medium text-base cursor-pointer",children:[e.jsx(Bt,{className:"h-4 w-4 text-orange-500"}),"عرض اسم الكاشير في الفاتورة"]}),e.jsx(mr,{id:"show_cashier_name",checked:l.show_cashier_name,onCheckedChange:d=>m(h=>({...h,show_cashier_name:d})),className:"data-[state=checked]:bg-orange-500",disabled:t})]}),e.jsx("p",{className:"text-xs text-muted-foreground pr-6",children:"إظهار أو إخفاء اسم الموظف الذي أنشأ الفاتورة عند الطباعة"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"flex items-center gap-2 font-medium text-base",children:[e.jsx(It,{className:"h-4 w-4 text-orange-500"}),"نص التذييل المخصص"]}),e.jsx(Is,{name:"footer_text",value:l.footer_text,onChange:d=>m(h=>({...h,footer_text:d.target.value})),placeholder:"أدخل النص المخصص لتذييل الفاتورة (اختياري)",rows:3,className:"resize-none transition-all focus:scale-[1.01]",disabled:t}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"نص مخصص يظهر في تذييل الفاتورة - اتركه فارغاً إذا لم ترغب بإضافة تذييل"})]})]}),!t&&e.jsx(nc,{children:e.jsxs(V,{type:"submit",disabled:a,className:"font-cairo w-full text-lg py-6 bg-gradient-to-r from-orange-500 to-orange-600 hover:from-orange-600 hover:to-orange-700 transition-all duration-300 hover:scale-[1.02] shadow-lg hover:shadow-xl",children:[e.jsx(Dn,{className:"h-5 w-5 ml-2"}),a?"جاري الحفظ...":"حفظ إعدادات الفاتورة"]})})]})}):null}function Hg(){const[t,r]=v.useState(()=>localStorage.getItem("theme")||"system");return v.useEffect(()=>{const i=window.document.documentElement;if(i.classList.remove("light","dark"),t==="system"){const o=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light";i.classList.add(o)}else i.classList.add(t)},[t]),{theme:t,setTheme:i=>{localStorage.setItem("theme",i),r(i)}}}const Wg=()=>{const{theme:t,setTheme:r}=Hg(),n=[{value:"light",label:"وضع فاتح",icon:Xm,description:"مظهر فاتح مريح للعين",preview:"bg-gradient-to-br from-gray-50 to-gray-100",iconColor:"text-yellow-500"},{value:"dark",label:"وضع داكن",icon:Rm,description:"مظهر داكن للاستخدام الليلي",preview:"bg-gradient-to-br from-gray-800 to-gray-900",iconColor:"text-blue-400"},{value:"system",label:"تلقائي",icon:$u,description:"يتبع إعدادات النظام",preview:"bg-gradient-to-br from-gray-400 to-gray-600",iconColor:"text-purple-400"}];return e.jsxs(fe,{dir:"rtl",className:"font-cairo border-2 hover:shadow-lg transition-all duration-300",children:[e.jsx(De,{className:"bg-gradient-to-r from-orange-400 to-amber-500 text-white",children:e.jsxs($e,{className:"flex items-center gap-2 text-xl",children:[e.jsx(zi,{className:"h-6 w-6 animate-pulse"}),"إعدادات المظهر"]})}),e.jsxs(ve,{className:"space-y-4 pt-6",children:[e.jsx(ca,{value:t,onValueChange:r,className:"space-y-3",children:n.map(i=>{const o=i.icon,a=t===i.value;return e.jsx("div",{className:"relative",children:e.jsxs(_e,{htmlFor:i.value,className:`flex items-center gap-4 p-4 rounded-lg border-2 cursor-pointer transition-all duration-300 ${a?"border-primary bg-primary/10 shadow-md scale-[1.02]":"border-border hover:border-primary/50 hover:bg-accent/50"}`,children:[e.jsx(Ss,{value:i.value,id:i.value,className:"shrink-0"}),e.jsx("div",{className:`p-3 rounded-full ${i.preview} flex items-center justify-center`,children:e.jsx(o,{className:`h-6 w-6 ${i.iconColor}`})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"font-bold text-lg",children:i.label}),e.jsx("div",{className:"text-sm text-muted-foreground",children:i.description})]}),a&&e.jsx("div",{className:"absolute top-2 left-2 bg-primary text-primary-foreground text-xs px-2 py-1 rounded-full animate-scale-in",children:"محدد"})]})},i.value)})}),e.jsx("div",{className:"mt-6 p-4 bg-accent/20 rounded-lg border-2 border-dashed border-accent",children:e.jsx("p",{className:"text-sm text-center text-muted-foreground",children:"💡 التغييرات تطبق فوراً على كامل التطبيق"})})]})]})},Xg=()=>{const[t,r]=v.useState(Rr());v.useEffect(()=>{r(Rr())},[]);const n=o=>{Zx(o),r(o)},i=o=>{t&&o()};return e.jsxs(fe,{dir:"rtl",className:"font-cairo border-2 hover:shadow-lg transition-all duration-300",children:[e.jsx(De,{className:"bg-gradient-to-r from-purple-500 to-purple-600 text-white",children:e.jsxs($e,{className:"flex items-center gap-2 text-xl",children:[t?e.jsx(oh,{className:"h-6 w-6 animate-pulse"}):e.jsx(sh,{className:"h-6 w-6"}),"إعدادات الأصوات"]})}),e.jsxs(ve,{className:"space-y-6 pt-6",children:[e.jsxs("div",{className:"flex items-center justify-between p-4 bg-accent/10 rounded-lg border border-accent/30",children:[e.jsxs("label",{htmlFor:"sound-toggle",className:"text-base font-medium cursor-pointer flex items-center gap-2",children:[e.jsx(nh,{className:"h-5 w-5 text-purple-500"}),"تفعيل الأصوات"]}),e.jsx(mr,{id:"sound-toggle",checked:t,onCheckedChange:n,className:"data-[state=checked]:bg-purple-500"})]}),e.jsxs("div",{className:"space-y-3 pt-2",children:[e.jsxs("p",{className:"text-sm font-medium text-muted-foreground mb-4 flex items-center gap-2",children:[e.jsx(Ur,{className:"h-4 w-4"}),"اختبار الأصوات"]}),e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg hover:bg-accent/20 transition-all border border-transparent hover:border-blue-300",children:[e.jsxs("span",{className:"text-sm flex items-center gap-2",children:[e.jsx(Ls,{className:"h-4 w-4 text-blue-500"}),"صوت مسح الباركود"]}),e.jsxs(V,{variant:"outline",size:"sm",onClick:()=>i(Kr),disabled:!t,className:"hover:bg-blue-500 hover:text-white transition-all hover:scale-105 border-blue-300",children:[e.jsx(Ur,{className:"h-4 w-4 ml-2"}),"تجربة"]})]}),e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg hover:bg-accent/20 transition-all border border-transparent hover:border-green-300",children:[e.jsxs("span",{className:"text-sm flex items-center gap-2",children:[e.jsx(As,{className:"h-4 w-4 text-green-500"}),"صوت النجاح"]}),e.jsxs(V,{variant:"outline",size:"sm",onClick:()=>i(Eo),disabled:!t,className:"hover:bg-green-500 hover:text-white transition-all hover:scale-105 border-green-300",children:[e.jsx(Ur,{className:"h-4 w-4 ml-2"}),"تجربة"]})]}),e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg hover:bg-accent/20 transition-all border border-transparent hover:border-red-300",children:[e.jsxs("span",{className:"text-sm flex items-center gap-2",children:[e.jsx(Lo,{className:"h-4 w-4 text-red-500"}),"صوت الخطأ"]}),e.jsxs(V,{variant:"outline",size:"sm",onClick:()=>i(Et),disabled:!t,className:"hover:bg-red-500 hover:text-white transition-all hover:scale-105 border-red-300",children:[e.jsx(Ur,{className:"h-4 w-4 ml-2"}),"تجربة"]})]}),e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg hover:bg-accent/20 transition-all border border-transparent hover:border-gray-300",children:[e.jsxs("span",{className:"text-sm flex items-center gap-2",children:[e.jsx(Pm,{className:"h-4 w-4 text-gray-500"}),"صوت النقر"]}),e.jsxs(V,{variant:"outline",size:"sm",onClick:()=>i(Qx),disabled:!t,className:"hover:bg-gray-500 hover:text-white transition-all hover:scale-105 border-gray-300",children:[e.jsx(Ur,{className:"h-4 w-4 ml-2"}),"تجربة"]})]})]}),e.jsx("div",{className:"mt-4 p-3 bg-purple-50 dark:bg-purple-950/20 rounded-lg border border-purple-200 dark:border-purple-800",children:e.jsx("p",{className:"text-xs text-center text-purple-700 dark:text-purple-300",children:"💡 تساعدك الأصوات على معرفة نتيجة العمليات بشكل فوري"})})]})]})},Jg=({readOnly:t=!1})=>{const{toast:r}=et(),{seller:n,isLoading:i,sellerId:o,invalidateSellerData:a}=Po(),{currentEmployee:s}=lt(),{logAction:c}=Od(o||""),[l,m]=v.useState("JOD"),[u,d]=v.useState(!1),h=bn[l];v.useEffect(()=>{n!=null&&n.default_currency&&(m(n.default_currency),Qs(n.default_currency))},[n]);const p=async f=>{var g;if(t)return;const x=l;d(!0);try{if(Qs(f),m(f),o){const b=localStorage.getItem(xe);if(!(await fetch(`${oe()}${W.UPDATE("sellers",o)}&token=${b}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({default_currency:f})})).ok)throw new Error("Failed to save currency");a(),s&&await c("UPDATE","settings",o,`تغيير العملة من ${((g=bn[x])==null?void 0:g.name)||x} إلى ${bn[f].name}`,JSON.stringify({currency:x}),JSON.stringify({currency:f}))}r({title:"تم تحديث العملة",description:`تم تغيير العملة إلى ${bn[f].name}`})}catch(b){Qs(x),m(x),r({title:"خطأ في حفظ العملة",description:b.message,variant:"destructive"})}d(!1)};return i?e.jsxs(fe,{dir:"rtl",className:"font-cairo border-2",children:[e.jsx(De,{className:"bg-gradient-to-r from-emerald-500 to-emerald-600 text-white",children:e.jsxs($e,{className:"flex items-center gap-2 text-xl",children:[e.jsx(ds,{className:"h-6 w-6"}),"إعدادات العملة"]})}),e.jsxs(ve,{className:"p-8 flex items-center justify-center gap-3",children:[e.jsx(ct,{className:"h-6 w-6 animate-spin text-emerald-500"}),e.jsx("span",{children:"جاري التحميل..."})]})]}):e.jsxs(fe,{dir:"rtl",className:"font-cairo border-2 hover:shadow-lg transition-all duration-300",children:[e.jsx(De,{className:"bg-gradient-to-r from-emerald-500 to-emerald-600 text-white",children:e.jsxs($e,{className:"flex items-center gap-2 text-xl",children:[e.jsx(ds,{className:"h-6 w-6 animate-pulse"}),"إعدادات العملة",t&&e.jsx("span",{className:"text-xs bg-white/20 px-2 py-1 rounded-full mr-2",children:"قراءة فقط"})]})}),e.jsxs(ve,{className:"space-y-6 pt-6",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("label",{htmlFor:"currency-select",className:"text-base font-medium flex items-center gap-2",children:[e.jsx(Ym,{className:"h-4 w-4 text-emerald-500"}),"العملة الافتراضية"]}),e.jsxs(vt,{value:l,onValueChange:p,disabled:t||u,children:[e.jsx(_t,{id:"currency-select",className:"h-12 transition-all focus:scale-[1.01] disabled:opacity-70 disabled:cursor-not-allowed",children:u?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ct,{className:"h-4 w-4 animate-spin"}),e.jsx("span",{children:"جاري الحفظ..."})]}):e.jsx(wt,{placeholder:"اختر العملة"})}),e.jsx(jt,{children:Object.values(bn).map(f=>e.jsx(Je,{value:f.code,className:"cursor-pointer",children:e.jsxs("div",{className:"flex items-center gap-3 py-1",children:[e.jsx("span",{className:"text-2xl",children:f.flag}),e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"font-medium",children:f.name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:f.code})]})]})},f.code))})]})]}),e.jsxs("div",{className:"space-y-3 pt-4",children:[e.jsxs("p",{className:"text-sm font-medium text-muted-foreground flex items-center gap-2",children:[e.jsx(ds,{className:"h-4 w-4"}),"معاينة التنسيق"]}),e.jsxs("div",{className:"bg-gradient-to-br from-emerald-50 to-green-50 dark:from-emerald-950/30 dark:to-green-950/30 p-5 rounded-lg border-2 border-emerald-200 dark:border-emerald-800 space-y-3 shadow-sm",children:[e.jsxs("div",{className:"flex justify-between items-center p-3 bg-white/80 dark:bg-gray-900/50 rounded-md",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"مثال:"}),e.jsx("span",{className:"text-2xl font-bold text-emerald-600 dark:text-emerald-400",children:du(1234.567)})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"flex flex-col p-3 bg-white/80 dark:bg-gray-900/50 rounded-md",children:[e.jsx("span",{className:"text-xs text-muted-foreground mb-1",children:"رمز العملة"}),e.jsx("span",{className:"text-lg font-semibold text-emerald-600",children:(h==null?void 0:h.symbol)||"-"})]}),e.jsxs("div",{className:"flex flex-col p-3 bg-white/80 dark:bg-gray-900/50 rounded-md",children:[e.jsx("span",{className:"text-xs text-muted-foreground mb-1",children:"الكسور العشرية"}),e.jsx("span",{className:"text-lg font-semibold text-emerald-600",children:(h==null?void 0:h.decimals)||3})]})]}),e.jsx("div",{className:"flex justify-center p-3 bg-white/80 dark:bg-gray-900/50 rounded-md",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"كود العملة:"}),e.jsx("span",{className:"text-lg font-bold text-emerald-600 px-3 py-1 bg-emerald-100 dark:bg-emerald-900/30 rounded",children:(h==null?void 0:h.code)||l})]})})]})]}),e.jsx("div",{className:"mt-4 p-3 bg-emerald-50 dark:bg-emerald-950/20 rounded-lg border border-emerald-200 dark:border-emerald-800",children:e.jsx("p",{className:"text-xs text-center text-emerald-700 dark:text-emerald-300",children:"يتم تطبيق العملة المختارة على جميع الفواتير والتقارير"})})]})]})};function Kg({readOnly:t=!1}){const r=Di(),{isOnline:n}=jr(),{isInstalled:i,isInstallable:o,promptInstall:a}=$o();return e.jsx("div",{className:"space-y-6",children:e.jsxs(fe,{children:[e.jsx(De,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs($e,{className:"flex items-center gap-2",children:[e.jsx(Pa,{className:"h-5 w-5"}),"نظام Online-First"]}),e.jsx(kr,{children:"جميع البيانات محفوظة على السيرفر - يتطلب اتصال بالإنترنت"})]}),e.jsxs(Ae,{variant:n?"default":"destructive",className:"gap-1",children:[n?e.jsx(bs,{className:"h-3 w-3"}):e.jsx(tn,{className:"h-3 w-3"}),n?"متصل":"غير متصل"]})]})}),e.jsxs(ve,{className:"space-y-6",children:[e.jsxs(Ta,{className:"border-green-500/20 bg-green-500/5",children:[e.jsx(Tr,{className:"h-4 w-4 text-green-500"}),e.jsx(Aa,{className:"text-green-700 dark:text-green-400",children:"نظام سحابي آمن"}),e.jsx(Ia,{className:"text-sm text-muted-foreground",children:"جميع الفواتير والبيانات تُحفظ مباشرة على السيرفر. هذا يضمن أمان البيانات وعدم فقدانها."})]}),e.jsx("div",{className:"p-4 rounded-lg border bg-muted/30",children:e.jsx("div",{className:"flex items-center gap-3",children:n?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"h-10 w-10 rounded-full bg-green-500/10 flex items-center justify-center",children:e.jsx(bs,{className:"h-5 w-5 text-green-500"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-green-700 dark:text-green-400",children:"متصل بالسيرفر"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"جميع العمليات متاحة"})]})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"h-10 w-10 rounded-full bg-red-500/10 flex items-center justify-center",children:e.jsx(tn,{className:"h-5 w-5 text-red-500"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-red-700 dark:text-red-400",children:"غير متصل"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"البيع غير متاح - يرجى التحقق من الاتصال"})]})]})})}),!i&&e.jsxs(Ta,{className:"border-blue-500/20 bg-blue-500/5",children:[e.jsx(Sr,{className:"h-4 w-4 text-blue-500"}),e.jsx(Aa,{className:"text-blue-700 dark:text-blue-400",children:"ثبّت التطبيق للأداء الأفضل"}),e.jsxs(Ia,{className:"space-y-3",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"تثبيت التطبيق يوفر تجربة أسرع وأفضل مع إمكانية الوصول من الشاشة الرئيسية"}),e.jsx("div",{className:"flex gap-2",children:o?e.jsxs(V,{size:"sm",onClick:a,className:"gap-2",children:[e.jsx(Sr,{className:"h-4 w-4"}),"تثبيت الآن"]}):e.jsxs(V,{size:"sm",variant:"outline",onClick:()=>r("/install"),className:"gap-2",children:[e.jsx(Sr,{className:"h-4 w-4"}),"تعليمات التثبيت"]})})]})]}),i&&e.jsxs("div",{className:"flex items-center gap-3 p-4 rounded-lg border border-green-500/20 bg-green-500/5",children:[e.jsx(Tr,{className:"h-5 w-5 text-green-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-green-700 dark:text-green-400",children:"التطبيق مثبت"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"تستمتع بأفضل أداء ممكن"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2 p-3 rounded-lg bg-muted/50",children:[e.jsx(zo,{className:"h-4 w-4 text-yellow-500"}),e.jsx("span",{className:"text-sm",children:"تحميل سريع للصفحات"})]}),e.jsxs("div",{className:"flex items-center gap-2 p-3 rounded-lg bg-muted/50",children:[e.jsx(Pa,{className:"h-4 w-4 text-blue-500"}),e.jsx("span",{className:"text-sm",children:"حفظ تلقائي على السحابة"})]})]})]})]})})}const Yg=()=>{const{isInstallable:t,isInstalled:r,promptInstall:n}=$o(),i=jr(),o=async()=>{await n()&&console.log("PWA installed successfully")},a=[{icon:zo,title:"سرعة فائقة",description:"يعمل التطبيق بسرعة عالية حتى مع اتصال بطيء"},{icon:tn,title:"العمل بدون إنترنت",description:"يمكنك استخدام التطبيق حتى بدون اتصال بالإنترنت"},{icon:us,title:"الإشعارات",description:"احصل على إشعارات فورية للتحديثات المهمة"},{icon:Ru,title:"آمن وموثوق",description:"يتم تحديث التطبيق تلقائياً مع أحدث الميزات"}];return e.jsxs("div",{className:"space-y-6",children:[e.jsxs(fe,{children:[e.jsxs(De,{children:[e.jsxs($e,{className:"flex items-center gap-2",children:[e.jsx(Sr,{className:"h-5 w-5"}),"حالة التطبيق"]}),e.jsx(kr,{children:"معلومات حول تثبيت التطبيق وحالة الاتصال"})]}),e.jsxs(ve,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between p-3 bg-muted rounded-lg",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[r?e.jsx(As,{className:"h-5 w-5 text-green-500"}):e.jsx(Lo,{className:"h-5 w-5 text-muted-foreground"}),e.jsx("span",{children:"حالة التثبيت"})]}),e.jsx(Ae,{variant:r?"default":"secondary",children:r?"مثبت":"غير مثبت"})]}),e.jsxs("div",{className:"flex items-center justify-between p-3 bg-muted rounded-lg",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[i?e.jsx(bs,{className:"h-5 w-5 text-green-500"}):e.jsx(tn,{className:"h-5 w-5 text-red-500"}),e.jsx("span",{children:"حالة الاتصال"})]}),e.jsx(Ae,{variant:i?"default":"destructive",children:i?"متصل":"غير متصل"})]}),!r&&t&&e.jsxs(V,{onClick:o,className:"w-full",size:"lg",children:[e.jsx(Rs,{className:"h-4 w-4 ml-2"}),"تثبيت التطبيق"]}),!r&&!t&&e.jsx("div",{className:"p-3 bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800 rounded-lg",children:e.jsx("p",{className:"text-sm text-amber-800 dark:text-amber-200",children:'لتثبيت التطبيق، افتح القائمة في متصفحك واختر "إضافة إلى الشاشة الرئيسية" أو "تثبيت التطبيق"'})}),r&&e.jsx("div",{className:"p-3 bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800 rounded-lg",children:e.jsx("p",{className:"text-sm text-green-800 dark:text-green-200",children:"✅ التطبيق مثبت بنجاح! يمكنك الوصول إليه من الشاشة الرئيسية"})})]})]}),e.jsxs(fe,{children:[e.jsxs(De,{children:[e.jsx($e,{children:"مميزات التطبيق"}),e.jsx(kr,{children:"استمتع بهذه المميزات عند تثبيت التطبيق"})]}),e.jsx(ve,{children:e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:a.map((s,c)=>e.jsxs("div",{className:"flex items-start gap-3 p-4 bg-muted/50 rounded-lg",children:[e.jsx("div",{className:"p-2 bg-primary/10 rounded-lg",children:e.jsx(s.icon,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium",children:s.title}),e.jsx("p",{className:"text-sm text-muted-foreground",children:s.description})]})]},c))})})]})]})},Qg=()=>{const{seller:t}=Ot(),{data:r}=vr({queryKey:["sent-invoices-count",t==null?void 0:t.id],queryFn:async()=>{if(!t)return[];const a=localStorage.getItem(xe),s=await fetch(`${oe()}${W.GET_ALL("invoices")}&token=${a}&seller_id=${t.id}`,{method:"GET"});if(!s.ok)return[];const l=(await s.json()).data||[],m=["مرسلة للحكومة","مرسلة إلى فوترة","مرسلة","تم الإرسال","نجح الإرسال","مكتملة"];return l.filter(u=>!!(u.qr_code&&u.qr_code.trim()!==""||m.includes(u.status)||u.is_return&&u.api_response)).slice(0,1)},enabled:!!t}),n=(t==null?void 0:t.is_trial)||r&&r.length>0,i=(t==null?void 0:t.seller_logo_url)||"/assets/images/7154f88c-bb2e-4c96-ad09-50b2f44c1637.png",o=t!=null&&t.seller_logo_url?t.seller_name:"زاجل";return e.jsx(fe,{className:"shadow-lg sm:shadow-xl border-2 border-gray-200 bg-gradient-to-br from-blue-50 to-indigo-50",children:e.jsxs(ve,{className:"p-4 sm:p-6 md:p-8 text-center",children:[e.jsx("div",{className:"flex justify-center items-center mb-3 sm:mb-4 md:mb-6",children:e.jsxs("div",{className:"bg-white p-2 sm:p-3 md:p-4 rounded-lg sm:rounded-xl shadow-md sm:shadow-lg",children:[e.jsx("img",{src:i,alt:o,className:"h-8 sm:h-12 md:h-16 w-auto object-contain",onError:a=>{const s=a.currentTarget;if(s.src!=="/assets/images/7154f88c-bb2e-4c96-ad09-50b2f44c1637.png")s.src="/assets/images/7154f88c-bb2e-4c96-ad09-50b2f44c1637.png",s.alt="زاجل";else{s.style.display="none";const c=s.nextElementSibling;c&&(c.style.display="block")}}}),e.jsx(It,{className:"h-8 sm:h-12 md:h-16 w-8 sm:w-12 md:w-16 text-blue-600 hidden"})]})}),e.jsx("p",{className:"text-mobile-xs sm:text-mobile-sm md:text-mobile-base text-gray-600 mb-1 sm:mb-2 font-light",children:"اهلا وسهلا بك"}),e.jsx("h1",{className:"text-mobile-xl sm:text-mobile-2xl md:text-mobile-3xl font-bold bg-gradient-to-r from-blue-600 to-indigo-600 bg-clip-text text-transparent mb-2",children:(t==null?void 0:t.seller_name)||"زاجل"}),e.jsx("p",{className:"text-mobile-sm sm:text-mobile-base md:text-mobile-lg text-gray-700 mb-3 sm:mb-4 md:mb-6 font-medium px-2",children:'نسخة أصلية من برنامج "فـــوترة بلــس " للفوترة الإلكترونية'}),(t==null?void 0:t.enable_fawatrah)!==!1&&e.jsxs("div",{className:"flex flex-col sm:flex-row sm:justify-between sm:items-center gap-2 sm:gap-3 mb-4 sm:mb-6 md:mb-8",children:[e.jsx("div",{className:"order-2 sm:order-1",children:e.jsx("span",{className:`inline-block px-3 sm:px-4 py-2 rounded-full font-bold text-mobile-xs sm:text-mobile-sm ${n?"bg-green-100 text-green-800 border border-green-300":"bg-red-100 text-red-800 border border-red-300"}`,children:n?"جاهز":"غير جاهز"})}),e.jsx("div",{className:"order-1 sm:order-2",children:e.jsx("span",{className:"text-gray-700 font-medium text-center text-mobile-sm sm:text-mobile-base block",children:"حالة الربط مع نظام الفوترة الوطني"})})]})]})})},Zg=({onCreateInvoice:t,onCreateCustomer:r,onCreateProduct:n})=>e.jsxs("div",{className:"flex flex-col items-center my-4 sm:my-6 md:my-8 space-y-3 sm:space-y-4 px-2",children:[e.jsxs(V,{onClick:t,className:"bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-700 hover:to-indigo-700 text-white font-bold px-6 sm:px-8 py-3 sm:py-4 text-mobile-base sm:text-mobile-lg rounded-lg sm:rounded-xl shadow-lg transform hover:scale-105 transition-all duration-200 w-full max-w-sm border-0 !text-white",size:"lg",children:[e.jsx(kt,{className:"h-4 w-4 sm:h-5 sm:w-5 md:h-6 md:w-6 ml-2 text-white"}),e.jsx("span",{className:"text-white font-bold",children:"إصدار فاتورة جديدة"})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-2 sm:gap-3 md:gap-4 w-full max-w-md",children:[e.jsxs(V,{onClick:r,className:"bg-gradient-to-r from-green-500 to-green-600 hover:from-green-600 hover:to-green-700 text-white font-semibold px-3 sm:px-4 py-2 text-mobile-xs sm:text-mobile-sm rounded-lg shadow-md transform hover:scale-105 transition-all duration-200 flex-1 border-0 !text-white",size:"sm",children:[e.jsx(kt,{className:"h-3 w-3 sm:h-4 sm:w-4 ml-1 text-white"}),e.jsx("span",{className:"text-white font-semibold",children:"إضافة عميل جديد"})]}),e.jsxs(V,{onClick:n,className:"bg-gradient-to-r from-orange-500 to-orange-600 hover:from-orange-600 hover:to-orange-700 text-white font-semibold px-3 sm:px-4 py-2 text-mobile-xs sm:text-mobile-sm rounded-lg shadow-md transform hover:scale-105 transition-all duration-200 flex-1 border-0 !text-white",size:"sm",children:[e.jsx(kt,{className:"h-3 w-3 sm:h-4 sm:w-4 ml-1 text-white"}),e.jsx("span",{className:"text-white font-semibold",children:"إضافة منتج جديد"})]})]})]}),Gs=({className:t,...r})=>e.jsx("nav",{role:"navigation","aria-label":"pagination",className:Z("mx-auto flex w-full justify-center",t),...r});Gs.displayName="Pagination";const Hs=v.forwardRef(({className:t,...r},n)=>e.jsx("ul",{ref:n,className:Z("flex flex-row items-center gap-1",t),...r}));Hs.displayName="PaginationContent";const Qt=v.forwardRef(({className:t,...r},n)=>e.jsx("li",{ref:n,className:Z("",t),...r}));Qt.displayName="PaginationItem";const xn=({className:t,isActive:r,size:n="icon",...i})=>e.jsx("a",{"aria-current":r?"page":void 0,className:Z(Do({variant:r?"outline":"ghost",size:n}),t),...i});xn.displayName="PaginationLink";const Ws=({className:t,...r})=>e.jsxs(xn,{"aria-label":"Go to previous page",size:"default",className:Z("gap-1 pl-2.5",t),...r,children:[e.jsx(Ms,{className:"h-4 w-4"}),e.jsx("span",{children:"Previous"})]});Ws.displayName="PaginationPrevious";const Xs=({className:t,...r})=>e.jsxs(xn,{"aria-label":"Go to next page",size:"default",className:Z("gap-1 pr-2.5",t),...r,children:[e.jsx("span",{children:"Next"}),e.jsx(Go,{className:"h-4 w-4"})]});Xs.displayName="PaginationNext";const eb=t=>{if(!t||typeof t!="string")return console.error("❌ Invalid XML content provided for value extraction"),null;try{console.log("🔍 Extracting monetary values from XML for return invoice consistency");const r=(m,u)=>{let d=t;if(u){const f=new RegExp(`<${u}[^>]*>([\\s\\S]*?)<\\/${u}>`,"i"),x=t.match(f);x&&x[1]&&(d=x[1])}const h=new RegExp(`<cbc:${m}[^>]*>([^<]+)</cbc:${m}>`,"i"),p=d.match(h);if(p&&p[1]){const f=parseFloat(p[1]);return console.log(`✅ Extracted ${m} from ${u||"root"}:`,f),isNaN(f)?0:f}return console.warn(`⚠️ Could not extract ${m} from ${u||"root"}`),0},n=r("TaxExclusiveAmount","cac:LegalMonetaryTotal"),i=r("TaxInclusiveAmount","cac:LegalMonetaryTotal"),o=r("AllowanceTotalAmount","cac:LegalMonetaryTotal"),a=r("PayableAmount","cac:LegalMonetaryTotal"),s=r("TaxAmount","cac:TaxTotal"),c=r("LineExtensionAmount","cac:InvoiceLine"),l={taxExclusiveAmount:n,taxInclusiveAmount:i,totalTaxAmount:s,allowanceChargeAmount:o,payableAmount:a,lineExtensionAmount:c};return console.log("✅ XML monetary values extracted successfully:",l),l}catch(r){return console.error("❌ Error extracting monetary values from XML:",r),null}},tb=t=>{if(!t||typeof t!="string")return console.error("❌ Invalid XML content provided for string value extraction"),null;try{console.log("🔍 Extracting exact string monetary values from XML for return invoice precision");const r=(x,g)=>{let b=t;if(g){const j=new RegExp(`<${g}[^>]*>([\\s\\S]*?)<\\/${g}>`,"i"),I=t.match(j);I&&I[1]&&(b=I[1])}const y=new RegExp(`<cbc:${x}[^>]*>([^<]+)</cbc:${x}>`,"i"),_=b.match(y);if(_&&_[1]){const j=_[1].trim();return console.log(`✅ Extracted ${x} string from ${g||"root"}:`,j),j}return console.warn(`⚠️ Could not extract ${x} string from ${g||"root"}`),"0"},n=r("TaxExclusiveAmount","cac:LegalMonetaryTotal"),i=r("TaxInclusiveAmount","cac:LegalMonetaryTotal"),o=r("AllowanceTotalAmount","cac:LegalMonetaryTotal"),a=r("PayableAmount","cac:LegalMonetaryTotal"),s=r("TaxAmount","cac:TaxTotal"),c=r("LineExtensionAmount","cac:InvoiceLine"),l=r("PriceAmount","cac:InvoiceLine"),m=[],u=/<cac:InvoiceLine[^>]*>([\s\S]*?)<\/cac:InvoiceLine>/gi;let d,h=1;for(;(d=u.exec(t))!==null;){const x=d[1],g=/<cbc:PriceAmount[^>]*>([^<]+)<\/cbc:PriceAmount>/i,b=x.match(g);if(b&&b[1]){const y=b[1].trim();m.push(y),console.log(`✅ Extracted price amount for line ${h}:`,y)}else console.warn(`⚠️ Could not extract price amount for line ${h}`),m.push("0");h++}console.log("✅ All price amounts extracted:",m);const p=r("TaxAmount","cac:InvoiceLine"),f={taxExclusiveAmount:n,taxInclusiveAmount:i,totalTaxAmount:s,allowanceChargeAmount:o,payableAmount:a,lineExtensionAmount:c,priceAmount:l,lineTaxAmount:p,allPriceAmounts:m};return console.log("✅ XML monetary string values extracted successfully:",f),f}catch(r){return console.error("❌ Error extracting monetary string values from XML:",r),null}},rb=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(t){const r=Math.random()*16|0;return(t==="x"?r:r&3|8).toString(16)}),nb=({originalInvoice:t,onReturnCreated:r,buttonText:n="ارجاع"})=>{const[i,o]=v.useState(!1),[a,s]=v.useState(!1),[c,l]=v.useState(!1),[m,u]=v.useState(""),[d,h]=v.useState(""),[p,f]=v.useState(null),[x,g]=v.useState(null),{toast:b}=et(),y=Mt(),{hasPermission:_}=lt(),{checkPermission:j}=Kn(),I=_("can_approve_returns");v.useEffect(()=>{i&&!p&&w()},[i]);const w=async()=>{l(!0);try{const T=localStorage.getItem(xe),k=`${oe()}${W.GET_BY_ID("invoices",t.id)}`;console.log("🔄 Fetching full invoice data for UUID extraction...");const S=await(await fetch(k,{headers:T?{Authorization:`Bearer ${T}`}:{}})).json();if(S.success&&S.data){const E=S.data;if(console.log("✅ Fetched invoice data, api_response exists:",!!E.api_response),E.api_response){f(E.api_response);const O=N(E.api_response);g(O),console.log("✅ Extracted UUID from fresh data:",O)}else console.warn("⚠️ Invoice has no api_response - may not have been sent to government")}}catch(T){console.error("❌ Failed to fetch invoice data:",T)}finally{l(!1)}},N=T=>{var S,E,O,R;if(!T)return null;const k=typeof T=="string"?JSON.parse(T):T;console.log("🔍 API Response for UUID extraction:",JSON.stringify(k,null,2));const P=[(S=k==null?void 0:k.data)==null?void 0:S.EINV_INV_UUID,k==null?void 0:k.EINV_INV_UUID,k==null?void 0:k.uuid,k==null?void 0:k.invoiceUuid,(E=k==null?void 0:k.data)==null?void 0:E.uuid,(O=k==null?void 0:k.result)==null?void 0:O.uuid,(R=k==null?void 0:k.response)==null?void 0:R.uuid];for(const D of P)if(D&&typeof D=="string"&&D.length>0)return console.log("✅ Found UUID:",D),D;return console.log("❌ No UUID found in API response"),null},C=async()=>{var T;try{const k=localStorage.getItem(xe),P=`${oe()}${W.GET_BY_ID("sellers",y)}`,R=(((T=(await(await fetch(P,{headers:k?{Authorization:`Bearer ${k}`}:{}})).json()).data)==null?void 0:T.current_icv_counter)||0)+1;return await fetch(`${oe()}${W.UPDATE("sellers",y)}`,{method:"POST",headers:{"Content-Type":"application/json",...k?{Authorization:`Bearer ${k}`}:{}},body:JSON.stringify({current_icv_counter:R})}),console.log("🔢 Generated ICV for return invoice:",R),R}catch(k){return console.error("Error generating ICV for return invoice:",k),1}},A=()=>{var S;const T=p||t.api_response;if(!T)return null;const k=typeof T=="string"?JSON.parse(T):T;let P=(k==null?void 0:k.EINV_SINGED_INVOICE)||((S=k==null?void 0:k.data)==null?void 0:S.EINV_SINGED_INVOICE);if(!P)return console.warn("⚠️ No EINV_SINGED_INVOICE found in api_response"),null;if(!P.includes("<"))try{P=atob(P),console.log("✅ Decoded signed XML from Base64")}catch(E){return console.error("❌ Failed to decode signed XML:",E),null}return P},F=async()=>{if(j("can_approve_returns","ليس لديك صلاحية إنشاء فواتير الإرجاع")){if(!m.trim()||!d){b({title:"خطأ",description:"يرجى ملء جميع الحقول المطلوبة",variant:"destructive"});return}if(!x){b({title:"خطأ",description:"لا يمكن إنشاء فاتورة إرجاع. الفاتورة الأصلية لم يتم إرسالها للنظام الحكومي بعد",variant:"destructive"});return}if(!y){b({title:"خطأ",description:"تعذر تحديد البائع الحالي. أعد تسجيل الدخول.",variant:"destructive"});return}try{s(!0);const T=localStorage.getItem(xe);console.log("🔄 Starting return invoice creation using generateXML approach...");const k=new Date,P=k.getFullYear(),S=String(k.getMonth()+1).padStart(2,"0"),E=String(k.getDate()).padStart(2,"0"),O=String(k.getTime()).slice(-4),R=`RET-${P}${S}${E}-${O}`,D=`${oe()}${W.GET_BY_ID("sellers",y)}`,M=await(await fetch(D,{headers:T?{Authorization:`Bearer ${T}`}:{}})).json();if(!M.success||!M.data)throw new Error("Failed to fetch seller data");const X=M.data;console.log("✅ Fetched seller data:",X.seller_name);const U=`${oe()}${W.GET_BY_ID("invoices",t.id)}`,B=await(await fetch(U,{headers:T?{Authorization:`Bearer ${T}`}:{}})).json();if(!B.success||!B.data)throw new Error("Failed to fetch original invoice");const z=B.data;console.log("✅ Fetched original invoice:",z.invoice_number);let H=X.invoice_type||"دخل";if(z.xml_file){const K=dx(z.xml_file);H=K==="general_tax"?"ضريبة عامة":"دخل",console.log("📋 Detected original invoice type from XML:",K,"→",H)}else console.warn("⚠️ No XML file in original invoice, using seller default type:",H);const Y=JSON.stringify({invoice_id:t.id}),J=`${oe()}${W.GET_ALL("invoice_items")}&filters=${encodeURIComponent(Y)}`,ce=await(await fetch(J,{headers:T?{Authorization:`Bearer ${T}`}:{}})).json();if(!ce.success)throw new Error("Failed to fetch invoice items");const ke=ce.data.filter(K=>K.invoice_id===t.id);console.log("✅ Fetched",ke.length,"invoice items");const be=await C();console.log("🔢 Using ICV for return invoice:",be);const Se=rb();console.log("🆔 Generated new UUID:",Se);const je=m&&m.trim().length>0?m.trim():`إرجاع فاتورة رقم ${t.invoice_number}`;console.log("📝 ===== RETURN INVOICE DEBUG (SIGNED XML approach) ====="),console.log("📝 Return reason:",je),console.log("📝 Original invoice number:",t.invoice_number),console.log("📝 Original UUID:",x),console.log("📝 New ICV:",be),console.log("📝 New UUID:",Se);const Re=A(),We=Re||z.xml_file;if(!We)throw new Error("No XML content available from original invoice");console.log("📄 Using XML source:",Re?"EINV_SINGED_INVOICE (government signed)":"Stored XML file");const se=tb(We);console.log("📊 Extracted exact values from signed XML:",se);const q=cx(We,R,je,Se,String(be),t.invoice_number,x,String(t.total_amount));console.log("✅ Generated return XML using generateReturnXmlFromOriginal"),console.log("📄 Return XML length:",q.length);const ne=ox(q);if(!ne.isValid){console.error("❌ Return invoice XML validation failed:",ne.errors),b({title:"خطأ في التحقق",description:`فشل التحقق من XML: ${ne.errors.join(", ")}`,variant:"destructive"}),s(!1);return}console.log("✅ Return invoice XML passed validation");const re=Jn(q),de=se?parseFloat(se.taxExclusiveAmount):Number(t.total_amount),ze=se?parseFloat(se.totalTaxAmount):0,Ce=se?parseFloat(se.taxInclusiveAmount):Number(t.total_amount);console.log("💰 Return invoice values from signed XML:"),console.log("   TaxExclusiveAmount:",de),console.log("   TotalTaxAmount:",ze),console.log("   TaxInclusiveAmount:",Ce);const st={invoice_number:R,invoice_sequence:R,invoice_counter:be,invoice_date:new Date().toISOString().split("T")[0],customer_name:t.customer_name,customer_number:t.customer_number,customer_type:t.customer_type,phone_number:t.phone_number,city:t.city,payment_method:d,subtotal:de,total_amount:Ce,status:"فاتورة إرجاع",is_return:!0,return_reason:m,return_payment_type:d,original_invoice_id:t.id,original_invoice_number:t.invoice_number,original_invoice_uuid:x,original_invoice_total:t.total_amount,tax_exclusive_amount:de,tax_inclusive_amount:Ce,total_tax_amount:ze,allowance_charge_amount:0,xml_file:q,xml_base64:re,encoded_xml:re,seller_id:y},dt=await(await fetch(`${oe()}${W.CREATE("invoices")}`,{method:"POST",headers:{"Content-Type":"application/json",...T?{Authorization:`Bearer ${T}`}:{}},body:JSON.stringify(st)})).json();if(!dt.success)throw new Error(dt.message);const L=dt.data;console.log("✅ Return invoice saved to database:",L.id);for(const K of ke){const ge={invoice_id:L.id,product_id:K.product_id,item_name:K.item_name,quantity:K.quantity,unit_price:K.unit_price,discount_amount:K.discount_amount||0,tax_percent:K.tax_percent||0,line_extension_amount:K.line_extension_amount,tax_amount:K.tax_amount||0,rounding_amount:K.rounding_amount||K.line_total,line_total:K.line_total,line_number:K.line_number||1,xml_quantity:K.xml_quantity,xml_unit_price:K.xml_unit_price,xml_line_total:K.xml_line_total,price_before_tax:K.price_before_tax||K.unit_price,price_after_tax:K.price_after_tax||K.line_total,tax_category_code:K.tax_category_code||"S",tax_calculation_mode:K.tax_calculation_mode};await fetch(`${oe()}${W.CREATE("invoice_items")}`,{method:"POST",headers:{"Content-Type":"application/json",...T?{Authorization:`Bearer ${T}`}:{}},body:JSON.stringify(ge)})}console.log("✅ Invoice items copied to return invoice");try{console.log("📤 Sending return invoice to government API...");const K=await fetch(`${oe()}government-invoice.php`,{method:"POST",headers:{"Content-Type":"application/json",...T?{Authorization:`Bearer ${T}`}:{}},body:JSON.stringify({xml_base64:re,invoice_number:R,seller_id:y})}),ge=await K.json();K.ok?(console.log("✅ Government API response:",ge),await fetch(`${oe()}${W.UPDATE("invoices",L.id)}`,{method:"POST",headers:{"Content-Type":"application/json",...T?{Authorization:`Bearer ${T}`}:{}},body:JSON.stringify({api_response:JSON.stringify(ge),status:ge!=null&&ge.success?"مرسلة للحكومة":"فشل الإرسال"})}),ge!=null&&ge.success&&b({title:"نجاح",description:"تم إنشاء فاتورة الإرجاع وإرسالها للنظام الحكومي بنجاح"})):(console.error("❌ Error sending to government API:",ge),b({title:"تحذير",description:"تم حفظ فاتورة الإرجاع لكن فشل إرسالها للنظام الحكومي",variant:"destructive"}))}catch(K){console.error("❌ Government API call failed:",K)}o(!1),u(""),h(""),r()}catch(T){console.error("❌ Error creating return invoice:",T),b({title:"خطأ",description:"فشل في إنشاء فاتورة الإرجاع",variant:"destructive"})}finally{s(!1)}}};return e.jsxs(gt,{open:i,onOpenChange:o,children:[e.jsx(mn,{asChild:!0,children:e.jsxs(V,{variant:"outline",size:"sm",className:"text-orange-600 hover:text-orange-700 hover:bg-orange-50 border-orange-200",children:[e.jsx(xs,{className:"h-4 w-4 ml-1"}),n]})}),e.jsxs(bt,{className:"max-w-md font-cairo",dir:"rtl",children:[e.jsx(Tt,{children:e.jsx(At,{className:"text-orange-800",children:"إنشاء فاتورة إرجاع"})}),e.jsx("div",{className:"space-y-4 mt-4",children:I?c?e.jsxs("div",{className:"text-center py-8",children:[e.jsx(ct,{className:"h-8 w-8 animate-spin mx-auto mb-3 text-orange-600"}),e.jsx("p",{className:"text-muted-foreground",children:"جاري التحقق من بيانات الفاتورة..."})]}):x?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"bg-orange-50 p-3 rounded-lg border border-orange-200",children:[e.jsxs("p",{className:"text-sm text-orange-800",children:[e.jsx("strong",{children:"الفاتورة الأصلية:"})," ",t.invoice_number]}),e.jsxs("p",{className:"text-sm text-orange-800",children:[e.jsx("strong",{children:"المبلغ:"})," ",Number(t.total_amount||0).toFixed(2)," د.أ"]}),e.jsxs("p",{className:"text-sm text-orange-800",children:[e.jsx("strong",{children:"العميل:"})," ",t.customer_name]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(_e,{htmlFor:"returnReason",children:"سبب الإرجاع *"}),e.jsx(Is,{id:"returnReason",value:m,onChange:T=>u(T.target.value),placeholder:"أدخل سبب إرجاع الفاتورة...",className:"min-h-[80px]"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(_e,{htmlFor:"returnPaymentType",children:"طريقة إرجاع المبلغ *"}),e.jsxs(vt,{value:d,onValueChange:h,children:[e.jsx(_t,{children:e.jsx(wt,{placeholder:"اختر طريقة الإرجاع"})}),e.jsxs(jt,{children:[e.jsx(Je,{value:"نقداً",children:"نقداً"}),e.jsx(Je,{value:"بطاقة",children:"بطاقة"}),e.jsx(Je,{value:"تحويل بنكي",children:"تحويل بنكي"}),e.jsx(Je,{value:"شيك",children:"شيك"})]})]})]}),e.jsxs("div",{className:"flex gap-2 justify-end mt-6",children:[e.jsx(V,{variant:"outline",onClick:()=>o(!1),disabled:a,children:"إلغاء"}),e.jsx(V,{onClick:F,disabled:a||!m.trim()||!d,className:"bg-orange-600 hover:bg-orange-700 text-white",children:a?e.jsxs(e.Fragment,{children:[e.jsx(ct,{className:"h-4 w-4 animate-spin ml-2"}),"جاري الإنشاء..."]}):e.jsxs(e.Fragment,{children:[e.jsx(xs,{className:"h-4 w-4 ml-2"}),"إنشاء فاتورة الإرجاع"]})})]})]}):e.jsxs("div",{className:"text-center py-6 bg-destructive/10 rounded-lg border border-destructive/20 p-4",children:[e.jsx("p",{className:"text-destructive font-medium text-lg mb-2",children:"لا يمكن إنشاء فاتورة إرجاع"}),e.jsx("p",{className:"text-destructive/80 text-sm",children:"هذه الفاتورة لم يتم إرسالها للنظام الحكومي بعد أو لا تحتوي على UUID صالح."}),e.jsx(V,{variant:"outline",onClick:()=>o(!1),className:"mt-4",children:"إغلاق"})]}):e.jsxs("div",{className:"text-center py-6 bg-red-50 rounded-lg border border-red-200 p-4",children:[e.jsx(Bi,{className:"h-12 w-12 text-red-500 mx-auto mb-3"}),e.jsx("p",{className:"text-red-700 font-medium text-lg mb-2",children:"غير مصرح"}),e.jsx("p",{className:"text-red-600 text-sm",children:"ليس لديك صلاحية الموافقة على الإرجاع. تواصل مع المدير للحصول على الصلاحية."}),e.jsx(V,{variant:"outline",onClick:()=>o(!1),className:"mt-4",children:"إغلاق"})]})})]})]})},Rd=({invoice:t,onView:r,onEdit:n,onReturnCreated:i})=>{var N;const{toast:o}=et(),[a,s]=v.useState(!1);v.useState(!1);const c=Mt(),{seller:l}=Ot(),{currentEmployee:m,hasPermission:u}=lt(),[d,h]=v.useState(!1),[p,f]=v.useState(null),[x,g]=v.useState(!1);v.useEffect(()=>{b()},[t.id]);const b=async()=>{try{const C=t.seller_id||c;if(!C)return;const A=localStorage.getItem(xe),F=JSON.stringify({seller_id:C}),T=await fetch(`${oe()}${W.GET_ALL("invoices")}&filters=${encodeURIComponent(F)}`,{method:"GET",headers:A?{Authorization:`Bearer ${A}`}:{}});if(!T.ok)return;const S=((await T.json()).data||[]).filter(E=>E.original_invoice_number===t.invoice_number&&E.is_return).some(E=>E.qr_code||E.status==="مرسلة للحكومة"||E.status==="مرسلة إلى فوترة"||E.api_response&&qt(E.api_response));g(S)}catch(C){console.error("Error checking for successful return:",C)}},y=()=>!!(t.qr_code||t.qr_code_image||t.api_response&&qt(t.api_response)),_=()=>{const C=["مرسلة للحكومة","مرسلة إلى فوترة","مرسلة"];return t.status&&C.some(A=>t.status.includes(A))},j=()=>!y()&&u("can_edit_invoices"),I=()=>!t.is_return&&_()&&y()&&!x,w=async(C=!1)=>{s(!0);const A=localStorage.getItem(xe);try{const F=t.seller_id||c;let T=t.encoded_xml;if(!T||C){console.log("🔄 Regenerating XML with fresh UUID...");const E=JSON.stringify({invoice_id:t.id}),D=((await(await fetch(`${oe()}${W.GET_ALL("invoice_items")}&filters=${encodeURIComponent(E)}`,{method:"GET",headers:A?{Authorization:`Bearer ${A}`}:{}})).json()).data||[]).map(Y=>({...Y,unit_price:Number(Y.unit_price),quantity:Number(Y.quantity),tax_percent:Number(Y.tax_percent||0),discount_amount:Number(Y.discount_amount||0),line_total:Number(Y.line_total),tax_amount:Number(Y.tax_amount||0)})),X=(await(await fetch(`${oe()}${W.GET_BY_ID("sellers",F||"")}`,{method:"GET",headers:A?{Authorization:`Bearer ${A}`}:{}})).json()).data,B=(await(await fetch(`${oe()}${W.GET_BY_ID("invoices",t.id)}`,{method:"GET",headers:A?{Authorization:`Bearer ${A}`}:{}})).json()).data,z={customer_name:t.customer_name||"عميل نقدي",customer_number:t.customer_number||"",customer_type:t.customer_type||"NIN",phone_number:t.phone_number||"",city:t.city||"",invoice_date:t.invoice_date,notes:(B==null?void 0:B.notes)||"",payment_method:t.payment_method||"نقدي",tax_calculation_mode:"tax_exclusive"},H=await Bs(t.invoice_number,Number(t.total_amount),z,D,X,(B==null?void 0:B.invoice_counter)||1,F||"",{isReturn:t.is_return,returnReason:t.return_reason,originalInvoiceNumber:t.original_invoice_number,originalInvoiceUUID:B==null?void 0:B.original_invoice_uuid});T=Jn(H),console.log("✅ Fresh XML generated with new UUID"),await fetch(`${oe()}${W.UPDATE("invoices",t.id)}`,{method:"POST",headers:{"Content-Type":"application/json",...A?{Authorization:`Bearer ${A}`}:{}},body:JSON.stringify({encoded_xml:T})})}if(!T){o({title:"خطأ",description:"لا يوجد XML للفاتورة",variant:"destructive"});return}const k=await fetch(`${oe()}government-invoice.php`,{method:"POST",headers:{"Content-Type":"application/json",...A?{Authorization:`Bearer ${A}`}:{}},body:JSON.stringify({invoice_number:t.invoice_number,xml_base64:T,seller_id:F})}),P=await k.text();console.log("Government API raw response:",P),console.log("Response status:",k.status);let S;if(!P||P.trim()==="")throw new Error("الخادم أرجع استجابة فارغة - تحقق من ملفات PHP على cPanel");try{S=JSON.parse(P)}catch(E){throw console.error("JSON parse error:",E),new Error(`استجابة غير صالحة من الخادم: ${P.substring(0,200)}`)}await fetch(`${oe()}${W.UPDATE("invoices",t.id)}`,{method:"POST",headers:{"Content-Type":"application/json",...A?{Authorization:`Bearer ${A}`}:{}},body:JSON.stringify({api_response:JSON.stringify(S),status:S!=null&&S.success?"مرسلة للحكومة":"فشل الإرسال للحكومة"})}),S!=null&&S.success?o({title:"تم الإرسال بنجاح",description:`تم إرسال الفاتورة ${t.invoice_number} للنظام الحكومي`}):o({title:"فشل الإرسال",description:(S==null?void 0:S.message)||(S==null?void 0:S.error)||"حدث خطأ",variant:"destructive"}),i&&i()}catch(F){console.error("Send to government error:",F),o({title:"خطأ في الإرسال",description:F.message,variant:"destructive"})}s(!1)};return e.jsxs(e.Fragment,{children:[e.jsx(El,{open:d,onOpenChange:h,htmlContent:p,invoiceNumber:t.invoice_number}),e.jsxs("div",{className:"flex flex-wrap gap-2 justify-end",children:[j()&&n&&e.jsxs(V,{variant:"outline",size:"sm",className:"text-orange-600 border-orange-300 hover:bg-orange-50",onClick:()=>n(t.id),children:[e.jsx(en,{className:"h-4 w-4"}),"تعديل"]}),e.jsxs(V,{variant:"outline",size:"sm",className:"text-purple-600 border-purple-300 hover:bg-purple-50",onClick:()=>r(t.id),children:[e.jsx(Rs,{className:"h-4 w-4"}),"عرض"]}),I()&&e.jsx(nb,{originalInvoice:{id:t.id,invoice_number:t.invoice_number,invoice_sequence:t.invoice_number,total_amount:t.total_amount,customer_name:t.customer_name,customer_number:t.customer_number,customer_type:t.customer_type,phone_number:t.phone_number||"",city:t.city||"",payment_method:t.payment_method||"",api_response:t.api_response},onReturnCreated:()=>{i&&i(),b()},buttonText:"ارجاع"}),(l==null?void 0:l.enable_fawatrah)!==!1&&!y()&&e.jsxs(e.Fragment,{children:[e.jsx(V,{variant:"outline",size:"sm",className:"text-purple-600 border-purple-300 hover:bg-purple-50 text-xs",onClick:()=>w(!1),disabled:a,children:a?e.jsx(ct,{className:"h-4 w-4 animate-spin"}):e.jsx(e.Fragment,{children:"إرسال إلى فوترة"})}),t.encoded_xml&&((N=t.status)==null?void 0:N.includes("فشل"))&&e.jsx(V,{variant:"outline",size:"sm",className:"text-orange-600 border-orange-300 hover:bg-orange-50 text-xs",onClick:()=>w(!0),disabled:a,title:"إعادة توليد XML جديد وإرسال",children:a?e.jsx(ct,{className:"h-4 w-4 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(_r,{className:"h-3 w-3 ml-1"}),"إعادة إرسال"]})})]})]})]})},sb=t=>t.toISOString().slice(0,19).replace("T"," "),Pd=()=>{const[t,r]=v.useState(!1),{toast:n}=et(),{seller:i}=Ot();return{cancelInvoice:async(s,c)=>{if(!i)return n({title:"خطأ",description:"لم يتم العثور على بيانات البائع",variant:"destructive"}),!1;r(!0);try{const l=localStorage.getItem(xe),m=await fetch(`${oe()}${W.GET_BY_ID("invoices",s)}&token=${l}`,{method:"GET"});if(!m.ok)throw new Error("Failed to fetch invoice");const d=(await m.json()).data;let h={status:"ملغية",cancelled_at:sb(new Date),cancelled_by:i.seller_name||i.id,notes:c?`سبب الالغاء: ${c}`:"تم الغاء الفاتورة"};if(d!=null&&d.is_return&&(d.xml_file||d.encoded_xml)){const f=d.xml_file||d.encoded_xml;if(f){console.log("🔍 Extracting XML values for return invoice cancellation");const x=eb(f);x&&(h={...h,tax_exclusive_amount:x.taxExclusiveAmount,tax_inclusive_amount:x.taxInclusiveAmount,total_tax_amount:x.totalTaxAmount,allowance_charge_amount:x.allowanceChargeAmount,total_amount:x.payableAmount,line_extension_amount:x.lineExtensionAmount},console.log("✅ XML values extracted and will be stored for consistency"))}}if(!(await fetch(`${oe()}${W.UPDATE("invoices",s)}&token=${l}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(h)})).ok)throw new Error("Failed to cancel invoice");return n({title:"تم الالغاء",description:"تم الغاء الفاتورة بنجاح"}),!0}catch(l){return console.error("Error cancelling invoice:",l),n({title:"خطأ في الالغاء",description:l.message||"فشل في الغاء الفاتورة",variant:"destructive"}),!1}finally{r(!1)}},restoreInvoice:async s=>{r(!0);try{const c=localStorage.getItem(xe);if(!(await fetch(`${oe()}${W.UPDATE("invoices",s)}&token=${c}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({status:"مسودة",cancelled_at:null,cancelled_by:null})})).ok)throw new Error("Failed to restore invoice");return n({title:"تم الاستعادة",description:"تم استعادة الفاتورة بنجاح"}),!0}catch(c){return console.error("Error restoring invoice:",c),n({title:"خطأ في الاستعادة",description:c.message||"فشل في استعادة الفاتورة",variant:"destructive"}),!1}finally{r(!1)}},isLoading:t}},ob=({invoiceId:t,invoiceNumber:r,onInvoiceCancelled:n})=>{const[i,o]=v.useState(!1),[a,s]=v.useState(""),{cancelInvoice:c,isLoading:l}=Pd(),{checkPermission:m,silentCheck:u}=Kn(),d=u("can_delete_invoices"),h=async()=>{if(!m("can_delete_invoices","ليس لديك صلاحية إلغاء الفواتير"))return;await c(t,a)&&(o(!1),s(""),n&&n())};return d?e.jsxs(gt,{open:i,onOpenChange:o,children:[e.jsx(mn,{asChild:!0,children:e.jsxs(V,{variant:"outline",size:"sm",className:"text-red-600 border-red-300 hover:bg-red-50",children:[e.jsx(at,{className:"h-4 w-4"}),"الغاء"]})}),e.jsxs(bt,{className:"max-w-md",dir:"rtl",children:[e.jsx(Tt,{children:e.jsx(At,{className:"text-right",children:"الغاء الفاتورة"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"text-sm text-gray-600",children:["هل أنت متأكد من الغاء الفاتورة رقم: ",e.jsx("strong",{children:r}),"؟"]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(_e,{htmlFor:"reason",className:"text-right block",children:"سبب الالغاء (اختياري)"}),e.jsx(Is,{id:"reason",value:a,onChange:p=>s(p.target.value),placeholder:"اكتب سبب الغاء الفاتورة...",className:"text-right",dir:"rtl"})]}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(V,{variant:"outline",onClick:()=>o(!1),disabled:l,children:"تراجع"}),e.jsx(V,{variant:"destructive",onClick:h,disabled:l,children:l?"جاري الالغاء...":"تأكيد الالغاء"})]})]})]})]}):null},io=20,ab=t=>{if(!t.is_return)return!1;const r=t.qr_code||t.qr_code_image,n=t.api_response&&qt(t.api_response),i=t.sent_at;return!!(r||n||i)},ib=t=>t.is_return&&!ab(t)?!0:["مسودة","فاتورة جديدة - غير مرسلة","غير مرسلة","فشل الإرسال للحكومة","فشل الإرسال","خطأ في الإرسال"].includes(t.status),cb=(t,r)=>{if(!r.trim())return t;const n=r.toLowerCase();return t.filter(i=>{const o=(i.invoice_number||"").toLowerCase(),a=(i.customer_name||"").toLowerCase(),s=(i.customer_number||"").toLowerCase(),c=(i.status||"").toLowerCase(),l=(i.total_amount||"").toString().toLowerCase(),m=(i.original_invoice_number||"").toLowerCase();return o.includes(n)||a.includes(n)||s.includes(n)||c.includes(n)||l.includes(n)||m.includes(n)})},Ti=({onViewInvoice:t,onEditInvoice:r})=>{const{seller:n}=Ot(),{hasPermission:i}=lt(),[o,a]=v.useState(1),[s,c]=v.useState(""),[l,m]=v.useState(!1),{toast:u}=et(),d=i("can_edit_invoices");console.log("🔍 PendingInvoices - Seller ID:",n==null?void 0:n.id);const{data:h,isLoading:p,refetch:f}=vr({queryKey:["all-pending-invoices",n==null?void 0:n.id],queryFn:async()=>{if(!n)return[];const A=localStorage.getItem(xe),F=await fetch(`${oe()}${W.GET_ALL("invoices")}&token=${A}&seller_id=${n.id}`,{method:"GET"});if(!F.ok)throw new Error("Failed to fetch pending invoices");const S=((await F.json()).data||[]).filter(E=>E.is_hidden?!1:["مسودة","فاتورة جديدة - غير مرسلة","غير مرسلة","فشل الإرسال للحكومة","فشل الإرسال","خطأ في الإرسال"].includes(E.status)||E.is_return).filter(ib);return S.sort((E,O)=>new Date(O.created_at).getTime()-new Date(E.created_at).getTime()),console.log("🔍 All pending invoices fetched:",S.length),S},enabled:!!n}),x=cb(h||[],s),g=x.length,b=Math.ceil(g/io),y=(o-1)*io,_=y+io,j=x.slice(y,_),I=A=>{c(A),a(1)},w=()=>{c(""),a(1)},N=async()=>{m(!0);try{await f(),u({title:"تم التحديث",description:"تم تحديث قائمة الفواتير المنتظرة بنجاح"})}catch{u({title:"خطأ في التحديث",description:"فشل في تحديث قائمة الفواتير",variant:"destructive"})}finally{m(!1)}};console.log("🔍 Pending invoices summary:",{totalCount:g,filteredCount:x.length,currentPage:o,totalPages:b,invoicesOnPage:j.length,searchTerm:s,sellerConnected:!!n});const C=A=>!!(A.qr_code||A.qr_code_image||A.api_response&&qt(A.api_response));return p?e.jsx(fe,{className:"shadow-lg border-2 border-yellow-200",children:e.jsx(ve,{className:"p-6",children:e.jsx("div",{className:"text-center",children:"جاري التحميل..."})})}):e.jsxs(fe,{className:"shadow-lg border-2 border-yellow-200",children:[e.jsxs(De,{className:"bg-gradient-to-r from-yellow-50 to-orange-50 border-b-2 border-yellow-200",children:[e.jsxs($e,{className:"flex items-center justify-between gap-2 text-yellow-900 text-base sm:text-lg",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"bg-gradient-to-r from-yellow-500 to-orange-500 p-2 rounded-lg",children:e.jsx(xr,{className:"h-4 w-4 sm:h-5 sm:w-5 text-white"})}),(n==null?void 0:n.enable_fawatrah)===!0||(n==null?void 0:n.enable_fawatrah)==1?"بيانات الفواتير المنتظر إرسالها ويمكن تعديلها":"الفواتير القابلة للتعديل",g>0&&e.jsxs("span",{className:"text-xs sm:text-sm bg-yellow-100 px-2 py-1 rounded-full",children:["(",s?x.length:g,")"]})]}),e.jsxs(V,{variant:"outline",size:"sm",onClick:N,disabled:l,className:"flex items-center gap-1 text-yellow-700 border-yellow-300 hover:bg-yellow-50",children:[e.jsx(_r,{className:`h-4 w-4 ${l?"animate-spin":""}`}),"تحديث"]})]}),e.jsxs("div",{className:"relative mt-4",children:[e.jsx("div",{className:"absolute inset-y-0 right-3 flex items-center pointer-events-none",children:e.jsx(zt,{className:"h-4 w-4 text-gray-400"})}),e.jsx(Te,{type:"text",placeholder:"البحث برقم الفاتورة، اسم العميل، رقم العميل، الحالة، المبلغ...",value:s,onChange:A=>I(A.target.value),className:"pl-10 pr-10 text-right",dir:"rtl"}),s&&e.jsx("button",{onClick:w,className:"absolute inset-y-0 left-3 flex items-center",children:e.jsx(at,{className:"h-4 w-4 text-gray-400 hover:text-gray-600"})})]})]}),e.jsx(ve,{className:"p-4 sm:p-6",children:j&&j.length>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"space-y-3 sm:space-y-4",children:j.map(A=>e.jsxs("div",{className:"flex flex-col gap-2 p-3 sm:p-4 border border-yellow-200 rounded-lg hover:bg-yellow-50 transition-colors flex-row-reverse",children:[e.jsxs("div",{className:"flex items-center gap-3 sm:gap-4 flex-row-reverse justify-between",children:[e.jsxs("div",{className:"text-left",children:[e.jsxs("p",{className:"font-bold text-base sm:text-lg text-green-600",children:[A.total_amount," د.أ"]}),e.jsx("span",{className:"inline-block px-2 py-1 rounded-full text-xs font-medium bg-yellow-100 text-yellow-800",children:(n==null?void 0:n.enable_fawatrah)===!0||(n==null?void 0:n.enable_fawatrah)==1?A.status:A.is_return?"فاتورة إرجاع":"فاتورة"})]}),e.jsxs("div",{children:[e.jsxs("p",{className:"font-semibold text-gray-900 text-sm sm:text-base",children:["فاتورة رقم: ",A.invoice_number]}),e.jsxs("p",{className:"text-xs sm:text-sm text-gray-600",children:["العميل: ",A.customer_name||"غير محدد"]}),e.jsxs("p",{className:"text-xs sm:text-sm text-gray-600",children:["التاريخ: ",new Date(A.invoice_date).toLocaleDateString("ar",{calendar:"gregory"})]}),C(A)&&e.jsx("span",{className:"text-green-600 text-xs font-bold inline-flex items-center mt-1",children:"✓ QR Code متوفر"}),A.is_return&&e.jsxs("div",{className:"mt-2 text-xs text-red-600 bg-red-50 border border-red-200 rounded px-2 py-1",children:["إرجاع من: ",A.original_invoice_number||"---"," (لم يتم الإرسال)"]})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2 justify-end",children:[e.jsx(ob,{invoiceId:A.id,invoiceNumber:A.invoice_number,onInvoiceCancelled:f}),e.jsx(Rd,{invoice:A,onView:t,onEdit:d?r:void 0,onReturnCreated:f},`actions-${A.id}`)]})]},A.id))}),b>1&&e.jsx(Gs,{className:"mt-4 mb-2",children:e.jsxs(Hs,{children:[e.jsx(Qt,{children:e.jsx(Ws,{onClick:()=>a(Math.max(1,o-1)),className:o===1?"pointer-events-none opacity-60":"",href:"#"})}),[...Array(b)].map((A,F)=>e.jsx(Qt,{children:e.jsx(xn,{isActive:o===F+1,onClick:()=>a(F+1),href:"#",children:F+1})},F)),e.jsx(Qt,{children:e.jsx(Xs,{onClick:()=>a(Math.min(b,o+1)),className:o===b?"pointer-events-none opacity-60":"",href:"#"})})]})})]}):e.jsxs("div",{className:"text-center py-6 sm:py-8 text-gray-500",children:[e.jsx(xr,{className:"h-10 w-10 sm:h-12 sm:w-12 mx-auto mb-3 sm:mb-4 text-gray-300"}),s?e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-sm sm:text-base",children:['لا توجد نتائج للبحث "',s,'"']}),e.jsx("button",{onClick:w,className:"text-xs mt-2 text-blue-600 hover:text-blue-800 underline",children:"مسح البحث"})]}):e.jsx(e.Fragment,{children:(n==null?void 0:n.enable_fawatrah)===!0||(n==null?void 0:n.enable_fawatrah)==1?e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-sm sm:text-base",children:"لا توجد فواتير منتظرة للإرسال"}),e.jsx("p",{className:"text-xs mt-2",children:"شامل فواتير الإرجاع غير المرسلة"})]}):e.jsx("p",{className:"text-sm sm:text-base",children:"لا توجد فواتير قابلة للتعديل"})})]})})]})},co=20,lb=t=>{if(t.is_return){const r=t.qr_code||t.qr_code_image,n=t.api_response&&qt(t.api_response),i=t.sent_at;return!!(r||n||i)}return["مرسلة للحكومة","مرسلة إلى فوترة","مرسلة","تم الإرسال","نجح الإرسال","مكتملة"].includes(t.status)},db=(t,r)=>{if(!r.trim())return t;const n=r.toLowerCase();return t.filter(i=>{const o=(i.invoice_number||"").toLowerCase(),a=(i.customer_name||"").toLowerCase(),s=(i.customer_number||"").toLowerCase(),c=(i.status||"").toLowerCase(),l=(i.total_amount||"").toString().toLowerCase(),m=(i.original_invoice_number||"").toLowerCase();return o.includes(n)||a.includes(n)||s.includes(n)||c.includes(n)||l.includes(n)||m.includes(n)})},Ai=({onViewInvoice:t})=>{const{seller:r}=Ot(),[n,i]=v.useState(1),[o,a]=v.useState(""),[s,c]=v.useState(!1),{toast:l}=et();if((r==null?void 0:r.enable_fawatrah)===!1)return null;console.log("🔍 SentInvoices - Seller ID:",r==null?void 0:r.id);const{data:m,isLoading:u,refetch:d}=vr({queryKey:["all-sent-invoices",r==null?void 0:r.id],queryFn:async()=>{if(!r)return[];const w=localStorage.getItem(xe),N=await fetch(`${oe()}${W.GET_ALL("invoices")}&token=${w}&seller_id=${r.id}`,{method:"GET"});if(!N.ok)throw new Error("Failed to fetch sent invoices");const T=((await N.json()).data||[]).filter(k=>k.is_hidden?!1:["مرسلة للحكومة","مرسلة إلى فوترة","مرسلة","تم الإرسال","نجح الإرسال","مكتملة"].includes(k.status)||k.is_return).filter(lb);return T.sort((k,P)=>new Date(P.created_at).getTime()-new Date(k.created_at).getTime()),console.log("🔍 All sent invoices fetched:",T.length),T},enabled:!!r}),h=db(m||[],o),p=h.length,f=Math.ceil(p/co),x=(n-1)*co,g=x+co,b=h.slice(x,g),y=w=>{a(w),i(1)},_=()=>{a(""),i(1)},j=async()=>{c(!0);try{await d(),l({title:"تم التحديث",description:"تم تحديث قائمة الفواتير المرسلة بنجاح"})}catch{l({title:"خطأ في التحديث",description:"فشل في تحديث قائمة الفواتير",variant:"destructive"})}finally{c(!1)}};console.log("🔍 Sent invoices summary:",{totalCount:p,filteredCount:h.length,currentPage:n,totalPages:f,invoicesOnPage:b.length,searchTerm:o,sellerConnected:!!r});const I=w=>!!(w.qr_code||w.qr_code_image||w.api_response&&qt(w.api_response));return u?e.jsx(fe,{className:"shadow-lg border-2 border-green-200",children:e.jsx(ve,{className:"p-6",children:e.jsx("div",{className:"text-center",children:"جاري التحميل..."})})}):e.jsxs(fe,{className:"shadow-lg border-2 border-green-200",children:[e.jsxs(De,{className:"bg-gradient-to-r from-green-50 to-emerald-50 border-b-2 border-green-200",children:[e.jsxs($e,{className:"flex items-center justify-between gap-2 text-green-900 text-base",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"bg-gradient-to-r from-green-500 to-emerald-500 p-2 rounded-lg",children:e.jsx(Tr,{className:"h-5 w-5 text-white"})}),"الفواتير المرسلة إلى نظام الفوترة الوطني",p>0&&e.jsxs("span",{className:"text-sm bg-green-100 px-2 py-1 rounded-full",children:["(",o?h.length:p,")"]})]}),e.jsxs(V,{variant:"outline",size:"sm",onClick:j,disabled:s,className:"flex items-center gap-1 text-green-700 border-green-300 hover:bg-green-50",children:[e.jsx(_r,{className:`h-4 w-4 ${s?"animate-spin":""}`}),"تحديث"]})]}),e.jsxs("div",{className:"relative mt-4",children:[e.jsx("div",{className:"absolute inset-y-0 right-3 flex items-center pointer-events-none",children:e.jsx(zt,{className:"h-4 w-4 text-gray-400"})}),e.jsx(Te,{type:"text",placeholder:"البحث برقم الفاتورة، اسم العميل، رقم العميل، الحالة، المبلغ...",value:o,onChange:w=>y(w.target.value),className:"pl-10 pr-10 text-right",dir:"rtl"}),o&&e.jsx("button",{onClick:_,className:"absolute inset-y-0 left-3 flex items-center",children:e.jsx(at,{className:"h-4 w-4 text-gray-400 hover:text-gray-600"})})]})]}),e.jsx(ve,{className:"p-6",children:b&&b.length>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"space-y-4",children:b.map(w=>e.jsxs("div",{className:"flex flex-col gap-2 p-4 border border-green-200 rounded-lg hover:bg-green-50 transition-colors flex-row-reverse",children:[e.jsxs("div",{className:"flex items-center gap-4 flex-row-reverse justify-between",children:[e.jsxs("div",{className:"text-left",children:[e.jsxs("p",{className:"font-bold text-lg text-green-600",children:[w.total_amount," د.أ"]}),e.jsx("span",{className:"inline-block px-2 py-1 rounded-full text-xs font-medium bg-green-100 text-green-800",children:w.status})]}),e.jsxs("div",{children:[e.jsxs("p",{className:"font-semibold text-gray-900",children:["فاتورة رقم: ",w.invoice_number]}),e.jsxs("p",{className:"text-sm text-gray-600",children:["العميل: ",w.customer_name||"غير محدد"]}),e.jsxs("p",{className:"text-sm text-gray-600",children:["التاريخ: ",new Date(w.invoice_date).toLocaleDateString("ar",{calendar:"gregory"})]}),I(w)&&e.jsx("span",{className:"text-green-600 text-xs font-bold inline-flex items-center mt-1",children:"✓ QR Code متوفر"}),w.is_return&&e.jsxs("div",{className:"mt-2 text-xs text-red-600 bg-red-50 border border-red-200 rounded px-2 py-1",children:["إرجاع من: ",w.original_invoice_number||"---"]})]})]}),e.jsx(Rd,{invoice:w,onView:t,onReturnCreated:d},`actions-${w.id}`)]},w.id))}),f>1&&e.jsx(Gs,{className:"mt-4 mb-2",children:e.jsxs(Hs,{children:[e.jsx(Qt,{children:e.jsx(Ws,{onClick:()=>i(Math.max(1,n-1)),className:n===1?"pointer-events-none opacity-60":"",href:"#"})}),[...Array(f)].map((w,N)=>e.jsx(Qt,{children:e.jsx(xn,{isActive:n===N+1,onClick:()=>i(N+1),href:"#",children:N+1})},N)),e.jsx(Qt,{children:e.jsx(Xs,{onClick:()=>i(Math.min(f,n+1)),className:n===f?"pointer-events-none opacity-60":"",href:"#"})})]})})]}):e.jsxs("div",{className:"text-center py-8 text-gray-500",children:[e.jsx(Tr,{className:"h-12 w-12 mx-auto mb-4 text-gray-300"}),o?e.jsxs(e.Fragment,{children:[e.jsxs("p",{children:['لا توجد نتائج للبحث "',o,'"']}),e.jsx("button",{onClick:_,className:"text-xs mt-2 text-blue-600 hover:text-blue-800 underline",children:"مسح البحث"})]}):e.jsxs(e.Fragment,{children:[e.jsx("p",{children:"لا توجد فواتير مرسلة بعد"}),e.jsx("p",{className:"text-xs mt-2",children:"البحث في الفواتير المرسلة فعلياً للحكومة"})]})]})})]})},lo=20,ub=(t,r)=>{if(!r.trim())return t;const n=r.toLowerCase();return t.filter(i=>{const o=(i.invoice_number||"").toLowerCase(),a=(i.customer_name||"").toLowerCase(),s=(i.customer_number||"").toLowerCase(),c=(i.total_amount||"").toString().toLowerCase(),l=(i.notes||"").toLowerCase();return o.includes(n)||a.includes(n)||s.includes(n)||c.includes(n)||l.includes(n)})},mb=({onViewInvoice:t})=>{const{seller:r}=Ot(),[n,i]=v.useState(1),[o,a]=v.useState(""),[s,c]=v.useState(!1),{toast:l}=et(),{restoreInvoice:m,isLoading:u}=Pd(),{data:d,isLoading:h,refetch:p}=vr({queryKey:["cancelled-invoices",r==null?void 0:r.id],queryFn:async()=>{if(!r)return[];const C=localStorage.getItem(xe),A=await fetch(`${oe()}${W.GET_ALL("invoices")}&token=${C}&seller_id=${r.id}`,{method:"GET"});if(!A.ok)throw new Error("Failed to fetch cancelled invoices");const k=((await A.json()).data||[]).filter(P=>P.status==="ملغية");return k.sort((P,S)=>{const E=P.cancelled_at?new Date(P.cancelled_at).getTime():0;return(S.cancelled_at?new Date(S.cancelled_at).getTime():0)-E}),console.log("🔍 Cancelled invoices fetched:",k.length),k},enabled:!!r}),f=ub(d||[],o),x=f.length,g=Math.ceil(x/lo),b=(n-1)*lo,y=b+lo,_=f.slice(b,y),j=C=>{a(C),i(1)},I=()=>{a(""),i(1)},w=async()=>{c(!0);try{await p(),l({title:"تم التحديث",description:"تم تحديث قائمة الفواتير الملغية بنجاح"})}catch{l({title:"خطأ في التحديث",description:"فشل في تحديث قائمة الفواتير",variant:"destructive"})}finally{c(!1)}},N=async C=>{await m(C)&&p()};return h?e.jsx(fe,{className:"shadow-lg border-2 border-red-200",children:e.jsx(ve,{className:"p-6",children:e.jsx("div",{className:"text-center",children:"جاري التحميل..."})})}):e.jsxs(fe,{className:"shadow-lg border-2 border-red-200",children:[e.jsxs(De,{className:"bg-gradient-to-r from-red-50 to-pink-50 border-b-2 border-red-200",children:[e.jsxs($e,{className:"flex items-center justify-between gap-2 text-red-900 text-base sm:text-lg",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"bg-gradient-to-r from-red-500 to-pink-500 p-2 rounded-lg",children:e.jsx(at,{className:"h-4 w-4 sm:h-5 sm:w-5 text-white"})}),"الفواتير الملغية",x>0&&e.jsxs("span",{className:"text-xs sm:text-sm bg-red-100 px-2 py-1 rounded-full",children:["(",o?f.length:x,")"]})]}),e.jsxs(V,{variant:"outline",size:"sm",onClick:w,disabled:s,className:"flex items-center gap-1 text-red-700 border-red-300 hover:bg-red-50",children:[e.jsx(_r,{className:`h-4 w-4 ${s?"animate-spin":""}`}),"تحديث"]})]}),e.jsxs("div",{className:"relative mt-4",children:[e.jsx("div",{className:"absolute inset-y-0 right-3 flex items-center pointer-events-none",children:e.jsx(zt,{className:"h-4 w-4 text-gray-400"})}),e.jsx(Te,{type:"text",placeholder:"البحث برقم الفاتورة، اسم العميل، المبلغ، سبب الالغاء...",value:o,onChange:C=>j(C.target.value),className:"pl-10 pr-10 text-right",dir:"rtl"}),o&&e.jsx("button",{onClick:I,className:"absolute inset-y-0 left-3 flex items-center",children:e.jsx(at,{className:"h-4 w-4 text-gray-400 hover:text-gray-600"})})]})]}),e.jsx(ve,{className:"p-4 sm:p-6",children:_&&_.length>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"space-y-3 sm:space-y-4",children:_.map(C=>e.jsxs("div",{className:"flex flex-col gap-2 p-3 sm:p-4 border border-red-200 rounded-lg hover:bg-red-50 transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-3 sm:gap-4 flex-row-reverse justify-between",children:[e.jsxs("div",{className:"text-left",children:[e.jsxs("p",{className:"font-bold text-base sm:text-lg text-red-600",children:[C.total_amount," د.أ"]}),e.jsx("span",{className:"inline-block px-2 py-1 rounded-full text-xs font-medium bg-red-100 text-red-800",children:"ملغية"})]}),e.jsxs("div",{children:[e.jsxs("p",{className:"font-semibold text-gray-900 text-sm sm:text-base",children:["فاتورة رقم: ",C.invoice_number]}),e.jsxs("p",{className:"text-xs sm:text-sm text-gray-600",children:["العميل: ",C.customer_name||"غير محدد"]}),e.jsxs("p",{className:"text-xs sm:text-sm text-gray-600",children:["تاريخ الالغاء: ",C.cancelled_at?new Date(C.cancelled_at).toLocaleDateString("ar",{calendar:"gregory"}):"---"]}),C.cancelled_by&&e.jsxs("p",{className:"text-xs sm:text-sm text-gray-600",children:["ألغيت بواسطة: ",C.cancelled_by]}),C.notes&&e.jsx("p",{className:"text-xs sm:text-sm text-gray-600 mt-1",children:C.notes})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2 justify-end",children:[e.jsxs(V,{variant:"outline",size:"sm",className:"text-green-600 border-green-300 hover:bg-green-50",onClick:()=>N(C.id),disabled:u,children:[e.jsx(xs,{className:"h-4 w-4"}),u?"جاري الاستعادة...":"استعادة"]}),e.jsx(V,{variant:"outline",size:"sm",className:"text-purple-600 border-purple-300 hover:bg-purple-50",onClick:()=>t(C.id),children:"عرض"})]})]},C.id))}),g>1&&e.jsx(Gs,{className:"mt-4 mb-2",children:e.jsxs(Hs,{children:[e.jsx(Qt,{children:e.jsx(Ws,{onClick:()=>i(Math.max(1,n-1)),className:n===1?"pointer-events-none opacity-60":"",href:"#"})}),[...Array(g)].map((C,A)=>e.jsx(Qt,{children:e.jsx(xn,{isActive:n===A+1,onClick:()=>i(A+1),href:"#",children:A+1})},A)),e.jsx(Qt,{children:e.jsx(Xs,{onClick:()=>i(Math.min(g,n+1)),className:n===g?"pointer-events-none opacity-60":"",href:"#"})})]})})]}):e.jsxs("div",{className:"text-center py-6 sm:py-8 text-gray-500",children:[e.jsx(at,{className:"h-10 w-10 sm:h-12 sm:w-12 mx-auto mb-3 sm:mb-4 text-gray-300"}),o?e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-sm sm:text-base",children:['لا توجد نتائج للبحث "',o,'"']}),e.jsx("button",{onClick:I,className:"text-xs mt-2 text-blue-600 hover:text-blue-800 underline",children:"مسح البحث"})]}):e.jsx("p",{className:"text-sm sm:text-base",children:"لا توجد فواتير ملغية"})]})})]})},Ii=({className:t})=>{const r=dn(),[n,i]=v.useState(!1),[o,a]=nl("app-notifications",[]),{data:s=[]}=vr({queryKey:["inventory-alerts"],queryFn:async()=>{const g=localStorage.getItem(xe),b=JSON.stringify({is_read:0}),y=await fetch(`${oe()}${W.GET_ALL("inventory_alerts")}&filters=${encodeURIComponent(b)}&orderBy=created_at&orderDir=DESC`,{headers:g?{Authorization:`Bearer ${g}`}:{}});return y.ok?(await y.json()).data||[]:[]},refetchInterval:3e4}),l=[...s.map(g=>({id:`inv-${g.id}`,source:"inventory",type:g.alert_type==="out_of_stock"?"error":"warning",title:g.alert_type==="out_of_stock"?"نفاذ مخزون":"مخزون منخفض",message:g.message||`منتج ${g.product_id}`,timestamp:new Date(g.created_at),read:!1,productId:g.product_id,alertType:g.alert_type,stockQuantity:g.stock_quantity||0})),...o.filter(g=>!g.read)].sort((g,b)=>new Date(b.timestamp).getTime()-new Date(g.timestamp).getTime()),m=l.length,u=$t({mutationFn:async g=>{const b=localStorage.getItem(xe),y=g.replace("inv-","");await fetch(`${oe()}${W.UPDATE("inventory_alerts",y)}`,{method:"POST",headers:{"Content-Type":"application/json",...b?{Authorization:`Bearer ${b}`}:{}},body:JSON.stringify({is_read:1})})},onSuccess:()=>{r.invalidateQueries({queryKey:["inventory-alerts"]})}}),d=async()=>{for(const g of s)await u.mutateAsync(`inv-${g.id}`);a(o.map(g=>({...g,read:!0})))},h=g=>{g.source==="inventory"?u.mutate(g.id):a(o.filter(b=>b.id!==g.id))},p=async()=>{for(const g of s)await u.mutateAsync(`inv-${g.id}`);a([])},f=g=>{if(g.source==="inventory")return g.alertType==="out_of_stock"?e.jsx(ht,{className:"h-5 w-5 text-destructive"}):e.jsx(Zt,{className:"h-5 w-5 text-orange-500"});switch(g.type){case"success":return e.jsx(Tr,{className:"h-5 w-5 text-green-500"});case"error":return e.jsx(Bo,{className:"h-5 w-5 text-destructive"});case"warning":return e.jsx(Zt,{className:"h-5 w-5 text-orange-500"});case"info":return e.jsx(Vo,{className:"h-5 w-5 text-blue-500"})}},x=g=>{const y=new Date().getTime()-new Date(g).getTime(),_=Math.floor(y/6e4),j=Math.floor(y/36e5),I=Math.floor(y/864e5);return _<1?"الآن":_<60?`منذ ${_} د`:j<24?`منذ ${j} س`:`منذ ${I} يوم`};return e.jsxs(qs,{open:n,onOpenChange:i,children:[e.jsx(Vs,{asChild:!0,children:e.jsxs("button",{className:Z("relative cursor-pointer hover:bg-white/10 p-2 rounded-lg transition-all",t),children:[e.jsx(us,{className:"h-5 w-5"}),m>0&&e.jsx(Ae,{variant:"destructive",className:"absolute -top-1 -right-1 h-5 min-w-5 p-0.5 flex items-center justify-center text-xs",children:m>9?"9+":m})]})}),e.jsxs(Yn,{className:"w-80 sm:w-96 p-0",align:"end",sideOffset:8,children:[e.jsxs("div",{className:"flex items-center justify-between p-3 border-b bg-muted/30",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(us,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("h3",{className:"font-semibold text-sm",children:"الإشعارات"}),m>0&&e.jsx(Ae,{variant:"secondary",className:"text-xs",children:m})]}),e.jsx("div",{className:"flex items-center gap-1",children:m>0&&e.jsxs(V,{variant:"ghost",size:"sm",onClick:d,className:"text-xs h-7",children:[e.jsx(qi,{className:"h-3 w-3 ml-1"}),"قراءة الكل"]})})]}),e.jsx(un,{className:"max-h-[350px]",children:l.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-10 text-center",children:[e.jsx(us,{className:"h-10 w-10 text-muted-foreground/30 mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"لا توجد إشعارات"})]}):e.jsx("div",{className:"divide-y",children:l.map(g=>e.jsx("div",{className:Z("p-3 hover:bg-muted/50 transition-colors",g.source==="inventory"&&g.alertType==="out_of_stock"&&"bg-destructive/5"),children:e.jsxs("div",{className:"flex gap-2.5",children:[e.jsx("div",{className:"flex-shrink-0 mt-0.5",children:f(g)}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-1.5 mb-0.5",children:[e.jsx("h4",{className:"text-sm font-semibold",children:g.title}),g.source==="inventory"&&e.jsx(Ae,{variant:g.alertType==="out_of_stock"?"destructive":"outline",className:"text-[10px] h-4 px-1",children:g.alertType==="out_of_stock"?"نفذ":"منخفض"})]}),e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2",children:g.message}),g.source==="inventory"&&g.stockQuantity!==void 0&&e.jsxs("p",{className:"text-[10px] text-muted-foreground mt-1",children:["الكمية: ",e.jsx("span",{className:"font-semibold",children:g.stockQuantity})]}),e.jsx("span",{className:"text-[10px] text-muted-foreground",children:x(g.timestamp)})]}),e.jsx(V,{variant:"ghost",size:"icon",className:"h-6 w-6 shrink-0",onClick:()=>h(g),children:e.jsx(at,{className:"h-3 w-3"})})]})})]})},g.id))})}),l.length>0&&e.jsx("div",{className:"p-2 border-t bg-muted/30",children:e.jsx(V,{variant:"ghost",size:"sm",onClick:p,className:"w-full text-xs h-7 text-muted-foreground",children:"مسح جميع الإشعارات"})})]})]})},ps=t=>({admin:"مدير النظام",manager:"مشرف",cashier:"أمين صندوق",inventory_manager:"مدير مخزون",accountant:"محاسب"})[t]||"موظف",hb=t=>({admin:"bg-red-500",manager:"bg-amber-500",cashier:"bg-blue-500",inventory_manager:"bg-green-500",accountant:"bg-purple-500"})[t]||"bg-gray-500",fb=({children:t})=>{const r=Di(),{sellerData:n,logout:i}=tr(),{currentEmployee:o,logout:a}=lt(),[s,c]=v.useState(new Date);v.useState(!1);const l=Dr();v.useEffect(()=>{const h=setInterval(()=>c(new Date),1e3);return()=>clearInterval(h)},[]);const m=s.toLocaleDateString("ar-JO",{weekday:"long",day:"numeric",month:"long",year:"numeric"}),u=s.toLocaleTimeString("ar-JO",{hour:"2-digit",minute:"2-digit",second:"2-digit"});s.toLocaleDateString("ar-JO",{day:"numeric",month:"short"});const d=()=>{a(),i(),r("/login")};return n?l?e.jsx(po,{children:e.jsxs("nav",{className:"bg-blue-800 dark:bg-gray-900 py-2.5 px-3 flex justify-between items-center text-white font-cairo shadow-lg border-b dark:border-gray-700 sticky top-0 z-40",children:[e.jsx("div",{className:"flex items-center gap-2 min-w-0",children:e.jsx("span",{className:"font-bold text-base truncate max-w-[120px]",children:n.seller_name})}),o&&e.jsxs("div",{className:"flex items-center gap-1.5 bg-white/15 px-2 py-1 rounded-lg",children:[e.jsx(Bt,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"text-xs font-medium truncate max-w-[60px]",children:o.employee_name.split(" ")[0]})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[t,e.jsx(Ii,{}),e.jsxs(Hi,{children:[e.jsx(Wi,{asChild:!0,children:e.jsx("button",{onClick:d,className:"bg-white/20 hover:bg-white/30 p-2 rounded-lg transition-all",children:e.jsx(rn,{className:"h-5 w-5"})})}),e.jsx(Xi,{side:"bottom",children:e.jsx("p",{children:"تسجيل خروج"})})]})]})]})}):e.jsx(po,{children:e.jsxs("nav",{className:"bg-blue-800 dark:bg-gray-900 py-3 px-4 flex justify-between items-center text-white font-cairo shadow-lg border-b dark:border-gray-700 sticky top-0 z-40",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("span",{className:"font-bold text-xl",children:n.seller_name}),o&&e.jsx("div",{className:"flex items-center gap-3 bg-white/10 dark:bg-gray-800/50 px-4 py-1.5 rounded-lg backdrop-blur-sm",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Bt,{className:"h-4 w-4"}),e.jsx("span",{className:"font-semibold",children:o.employee_name}),e.jsx("span",{className:`${hb(o.role)} text-white text-xs px-2 py-0.5 rounded-full font-bold`,children:ps(o.role)})]})}),e.jsxs("div",{className:"hidden lg:flex items-center gap-2 bg-white/10 dark:bg-gray-800/50 px-3 py-1.5 rounded-lg backdrop-blur-sm",children:[e.jsx(oc,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm",children:m})]}),e.jsxs("div",{className:"flex items-center gap-2 bg-white/10 dark:bg-gray-800/50 px-3 py-1.5 rounded-lg backdrop-blur-sm",children:[e.jsx(xr,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm font-mono",children:u})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[t,e.jsx(Ii,{}),e.jsxs("button",{onClick:d,className:"bg-white text-blue-800 dark:bg-gray-700 dark:text-white px-4 py-2 rounded-lg shadow-lg font-bold hover:bg-blue-100 dark:hover:bg-gray-600 hover:scale-105 transition-all duration-200 hover:shadow-xl flex items-center gap-2",children:[e.jsx(rn,{className:"h-4 w-4"}),e.jsx("span",{children:"تسجيل خروج"})]})]})]})}):null},pb=t=>{if(!t)return"";const n=Math.floor((new Date().getTime()-t.getTime())/6e4);return n<1?"الآن":n<60?`منذ ${n} دقيقة`:n<1440?`منذ ${Math.floor(n/60)} ساعة`:t.toLocaleDateString("ar")},xb=({className:t})=>{const{isOnline:r,wasOffline:n,resetWasOffline:i}=jr();tr();const{isInstallable:o,isInstalled:a,promptInstall:s,isIOS:c}=$o(),{notification:l,history:m,clearHistory:u,notify:d}=K0(),h=v.useRef(r);v.useEffect(()=>{h.current!==r&&(r?n&&(d.success("تم استعادة الاتصال بالإنترنت",3e3),i()):d.warning("أنت غير متصل بالإنترنت - لا يمكن إنشاء فواتير",5e3),h.current=r)},[r,n,i,d]),v.useEffect(()=>{const g=pu(b=>{switch(b.type){case"online":d.success("تم استعادة الاتصال بالإنترنت",3e3);break;case"offline":d.warning("انقطع الاتصال بالإنترنت",5e3);break}});return()=>{g()}},[d]);const p=async()=>{if(c){window.location.href="/install";return}await s()},f=g=>{switch(g){case"success":return e.jsx(Tr,{className:"h-3.5 w-3.5"});case"error":return e.jsx(Lo,{className:"h-3.5 w-3.5"});case"warning":return e.jsx(Zt,{className:"h-3.5 w-3.5"});case"info":return e.jsx(Vo,{className:"h-3.5 w-3.5"})}},x=g=>{switch(g){case"success":return"text-green-600 dark:text-green-400";case"error":return"text-red-600 dark:text-red-400";case"warning":return"text-yellow-600 dark:text-yellow-400";case"info":return"text-blue-600 dark:text-blue-400"}};return e.jsxs("div",{className:Z("fixed bottom-0 left-0 right-0 z-40 backdrop-blur-sm border-t border-border px-4 py-1.5 flex items-center justify-between text-xs transition-colors duration-300",r?"bg-muted/95":"bg-destructive/10",t),dir:"rtl",children:[e.jsxs(qs,{children:[e.jsx(Vs,{asChild:!0,children:e.jsx("button",{className:"flex-1 flex items-center justify-start gap-2 min-w-0 cursor-pointer hover:opacity-80 transition-opacity text-right",children:l?e.jsxs("div",{className:Z("flex items-center gap-1.5 animate-in fade-in slide-in-from-right-2 duration-300",x(l.type)),children:[f(l.type),e.jsx("span",{className:"truncate max-w-[300px] sm:max-w-none",children:l.message})]}):e.jsxs("div",{className:"flex items-center gap-1.5 text-muted-foreground",children:[e.jsx(Ma,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"سجل الإشعارات"}),m.length>0&&e.jsx("span",{className:"bg-primary/20 text-primary px-1.5 py-0.5 rounded-full text-[10px] font-medium",children:m.length})]})})}),e.jsxs(Yn,{side:"top",align:"start",className:"w-80 p-0",dir:"rtl",children:[e.jsxs("div",{className:"p-3 border-b flex justify-between items-center",children:[e.jsx("h4",{className:"font-medium text-sm",children:"آخر الإشعارات"}),m.length>0&&e.jsxs(V,{size:"sm",variant:"ghost",onClick:u,className:"h-7 px-2 text-xs gap-1 text-muted-foreground hover:text-destructive",children:[e.jsx(Ar,{className:"h-3 w-3"}),"مسح"]})]}),e.jsx(un,{className:"h-64",children:m.length===0?e.jsxs("div",{className:"p-6 text-center text-muted-foreground",children:[e.jsx(Ma,{className:"h-8 w-8 mx-auto mb-2 opacity-50"}),e.jsx("p",{className:"text-sm",children:"لا توجد إشعارات"})]}):e.jsx("div",{className:"divide-y",children:m.map(g=>e.jsxs("div",{className:"p-3 flex items-start gap-2 hover:bg-muted/50",children:[e.jsx("div",{className:Z("mt-0.5",x(g.type)),children:f(g.type)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm",children:g.message}),e.jsx("p",{className:"text-[10px] text-muted-foreground mt-0.5",children:pb(g.timestamp)})]})]},g.id))})})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[o&&!a&&e.jsxs(V,{size:"sm",variant:"ghost",onClick:p,className:"h-6 px-2 text-xs gap-1 hover:bg-primary/10",children:[e.jsx(Rs,{className:"h-3 w-3"}),e.jsx("span",{className:"hidden sm:inline",children:"تثبيت"})]}),e.jsx("div",{className:"flex items-center gap-1.5 text-muted-foreground",children:r?e.jsxs(e.Fragment,{children:[e.jsx(bs,{className:"h-3.5 w-3.5 text-green-500"}),e.jsx("span",{className:"text-green-600 dark:text-green-400 hidden sm:inline",children:"متصل"})]}):e.jsxs(e.Fragment,{children:[e.jsx(tn,{className:"h-3.5 w-3.5 text-destructive animate-pulse"}),e.jsx("span",{className:"text-destructive",children:"غير متصل"})]})})]})]})};function gb(t){const{user:r,sellerData:n}=tr(),i=t||(n==null?void 0:n.id)||(r==null?void 0:r.seller_id)||null,o=da("employees",{autoFetch:!!i,filters:i?{seller_id:i}:{},orderBy:"created_at",orderDir:"DESC"});return{...o,employees:o.data,isLoading:o.isLoading||!i,error:o.error}}const ut={products:!1,categories:!1,customers:!1,employees:!1,lastPrefetchTime:0,lastTableUpdate:{}},sr={products:null,categories:null,customers:null,employees:null},bb=5*60*1e3,yb=10*60*1e3,vb=5*60*1e3;let Oi=null;function _b(){return Date.now()-ut.lastPrefetchTime>bb}function uo(t){const r=ut.lastTableUpdate[t]||0;return Date.now()-r>yb}async function Md(t,r){var n;try{const i=localStorage.getItem(xe),o=`${oe()}batch.php?tables=${t.join(",")}&seller_id=${r}`,a=await fetch(o,{headers:i?{Authorization:`Bearer ${i}`}:{}});if(!a.ok)return console.warn("[Prefetch] Batch fetch failed:",a.status),{};const s=await a.json();return s.success?((n=s.data)==null?void 0:n.data)||{}:(console.warn("[Prefetch] Batch fetch error:",s.message),{})}catch(i){return console.warn("[Prefetch] Batch fetch error:",i),{}}}async function Ri(t){if(!t)return console.warn("[Prefetch] No sellerId provided"),{products:[],categories:[],customers:[],duration:0};if(!_b()&&ut.products&&ut.categories)return console.log("[Prefetch] ⏭️ Skipping prefetch - data is fresh"),{products:sr.products||[],categories:sr.categories||[],customers:sr.customers||[],duration:0};console.log("[Prefetch] 🚀 Starting batch prefetch for seller:",t);const r=performance.now(),n=await Md(["products","categories","customers"],t),i=n.products||[],o=n.categories||[],a=n.customers||[];sr.products=i,sr.categories=o,sr.customers=a,ut.products=!0,ut.categories=!0,ut.customers=!0,ut.lastPrefetchTime=Date.now(),ut.lastTableUpdate.products=Date.now(),ut.lastTableUpdate.categories=Date.now(),ut.lastTableUpdate.customers=Date.now();const s=Math.round(performance.now()-r);return console.log(`[Prefetch] 🎯 Batch prefetch completed in ${s}ms`),console.log(`[Prefetch] 📊 Summary: ${i.length} products, ${o.length} categories, ${a.length} customers`),wb(t),{products:i,categories:o,customers:a,duration:s}}function wb(t){Oi||(Oi=setInterval(async()=>{const r=[];if(uo("products")&&ut.products&&r.push("products"),uo("categories")&&ut.categories&&r.push("categories"),uo("customers")&&ut.customers&&r.push("customers"),r.length>0){console.log(`[Prefetch] 🔄 Background refresh for: ${r.join(", ")}`);try{const n=await Md(r,t);n.products&&(sr.products=n.products,ut.lastTableUpdate.products=Date.now()),n.categories&&(sr.categories=n.categories,ut.lastTableUpdate.categories=Date.now()),n.customers&&(sr.customers=n.customers,ut.lastTableUpdate.customers=Date.now()),console.log("[Prefetch] ✅ Background refresh completed")}catch(n){console.debug("[Prefetch] Background refresh failed:",n)}}},vb))}function jb({onLoginSuccess:t}){const{loginWithPin:r}=lt(),{sellerData:n,logout:i}=tr(),{employees:o,isLoading:a,refetch:s}=gb(n==null?void 0:n.id),[c,l]=v.useState(null),[m,u]=v.useState(!1),[d,h]=v.useState(""),[p,f]=v.useState(!1),[x,g]=v.useState(!1);v.useEffect(()=>{n!=null&&n.id&&(!o||o.length===0)&&(console.log("CashierSelection - triggering refetch for seller:",n.id),s())},[n==null?void 0:n.id,s]),v.useEffect(()=>{console.log("CashierSelection - sellerData?.id:",n==null?void 0:n.id),console.log("CashierSelection - employees:",o),console.log("CashierSelection - isLoading:",a)},[n,o,a]);const b=(o==null?void 0:o.filter(T=>T.is_active===!0||T.is_active===1||T.is_active==="1"))||[];console.log("CashierSelection - activeEmployees:",b);const y=T=>{switch(T){case"manager":return{icon:ns,color:"ring-amber-500",bgColor:"bg-amber-500/10",textColor:"text-amber-600",label:ps(T)};case"cashier":return{icon:Ku,color:"ring-blue-500",bgColor:"bg-blue-500/10",textColor:"text-blue-600",label:ps(T)};default:return{icon:Bt,color:"ring-green-500",bgColor:"bg-green-500/10",textColor:"text-green-600",label:ps(T)}}},_=T=>{l(T),u(!1),h("")},j=()=>{const T=o==null?void 0:o.find(k=>k.is_owner===!0||k.is_owner===1||k.is_owner==="1");l(T||{id:n==null?void 0:n.id,employee_name:(n==null?void 0:n.owner_name)||"المالك",is_owner:!0}),u(!0),h("")},I=T=>{d.length<4&&h(d+T)},w=()=>{h(d.slice(0,-1))},N=()=>{h("")},C=()=>{l(null),h("")},A=()=>{localStorage.removeItem("currentEmployee"),localStorage.removeItem("lastActivity"),i(),Ge.success("تم تسجيل الخروج بنجاح")},F=async()=>{const T=m?3:4;if(d.length!==T){Ge.error(`الرجاء إدخال رقم PIN مكون من ${T} أرقام`);return}f(!0);try{if(m)if(d===(n==null?void 0:n.owner_pin)){const k=o==null?void 0:o.find(E=>E.is_owner===!0||E.is_owner===1||E.is_owner==="1"),P=k?{...k,role:"owner",is_owner:!0}:{id:n.id,seller_id:n.id,employee_name:n.owner_name||"المالك",role:"owner",is_owner:!0,is_active:!0,can_access_pos:!0,can_create_invoices:!0,can_edit_invoices:!0,can_delete_invoices:!0,can_manage_products:!0,can_manage_inventory:!0,can_manage_employees:!0,can_view_reports:!0,can_view_dashboard:!0,can_view_customers:!0,can_view_settings:!0,can_view_administration:!0,can_approve_discounts:!0,can_approve_returns:!0,can_manage_shifts:!0,max_discount_percent:100},S=Date.now();localStorage.setItem("currentEmployee",JSON.stringify(P)),localStorage.setItem("lastActivity",S.toString()),g(!0),Ge.success(`مرحباً ${P.employee_name} 👑`);try{const E=await Ri(n.id);console.log(`[Login] Data prefetched in ${E.duration}ms`)}catch(E){console.warn("[Login] Prefetch failed, continuing anyway:",E)}g(!1),window.location.reload()}else Ge.error("رقم PIN غير صحيح"),h("");else if(await r(c.id,d,c.seller_id)){g(!0);try{const P=await Ri(c.seller_id);console.log(`[Login] Data prefetched in ${P.duration}ms`)}catch(P){console.warn("[Login] Prefetch failed, continuing anyway:",P)}g(!1),t()}else h("")}catch{Ge.error("حدث خطأ أثناء تسجيل الدخول"),h("")}finally{f(!1),g(!1)}};return v.useEffect(()=>{const T=m?3:4;d.length===T&&c&&F()},[d,m]),a?e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 via-background to-accent/5",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"animate-spin rounded-full h-12 w-12 border-b-2 border-primary mx-auto mb-4"}),e.jsx("p",{className:"text-muted-foreground",children:"جاري التحميل..."})]})}):e.jsxs("div",{className:"min-h-screen flex flex-col bg-gradient-to-br from-indigo-50 via-purple-50 to-pink-50 dark:from-gray-900 dark:via-gray-800 dark:to-gray-900",children:[e.jsx(Ji,{}),e.jsx("div",{className:"flex-1 flex items-center justify-center p-3 sm:p-4",children:e.jsxs(fe,{className:"w-full max-w-4xl shadow-2xl border-0 overflow-hidden",children:[e.jsxs("div",{className:"bg-gradient-to-br from-indigo-600 via-purple-600 to-pink-600 text-white p-5 sm:p-8 rounded-t-lg",children:[e.jsx("div",{className:"flex items-center justify-center gap-4 mb-3 sm:mb-4",children:n!=null&&n.seller_logo_url?e.jsxs(fr,{className:"h-16 w-16 sm:h-20 sm:w-20 ring-4 ring-white/30 shadow-xl",children:[e.jsx(Yr,{src:n.seller_logo_url,alt:n.seller_name}),e.jsx(pr,{className:"bg-white/20 text-white text-xl sm:text-2xl",children:e.jsx(ho,{className:"h-8 w-8 sm:h-10 sm:w-10"})})]}):e.jsx("div",{className:"h-16 w-16 sm:h-20 sm:w-20 rounded-full bg-white/20 flex items-center justify-center ring-4 ring-white/30 shadow-xl",children:e.jsx(ho,{className:"h-8 w-8 sm:h-10 sm:w-10 text-white"})})}),e.jsx("h1",{className:"text-2xl sm:text-3xl font-bold text-center mb-1 sm:mb-2",children:(n==null?void 0:n.seller_name)||"فوترة بلس"}),e.jsx("p",{className:"text-center text-white/90 text-base sm:text-lg",children:"نظام نقطة البيع - POS System"})]}),e.jsxs("div",{className:"p-4 sm:p-8",children:[e.jsx("p",{className:"text-center text-muted-foreground text-base sm:text-lg mb-5 sm:mb-8",children:c?`مرحباً ${c.employee_name}`:"اختر حسابك للمتابعة"}),!c&&e.jsxs(e.Fragment,{children:[(!(n!=null&&n.owner_name)||!(n!=null&&n.owner_pin))&&e.jsx("div",{className:"mb-6 p-4 bg-amber-50 dark:bg-amber-900/20 border-2 border-amber-300 dark:border-amber-700 rounded-lg",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(ns,{className:"h-6 w-6 text-amber-600 flex-shrink-0 mt-1"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-bold text-amber-900 dark:text-amber-100 mb-1",children:"بيانات المالك غير مكتملة"}),e.jsxs("p",{className:"text-sm text-amber-800 dark:text-amber-200",children:["يرجى إضافة ",e.jsx("span",{className:"font-semibold",children:"اسم المالك ورقم PIN (3 أرقام)"})," من لوحة تحكم الأدمن لتتمكن من تسجيل الدخول كمالك"]})]})]})}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-3 sm:gap-4",children:[(n==null?void 0:n.owner_name)&&(n==null?void 0:n.owner_pin)&&e.jsx(fe,{className:"p-4 sm:p-6 cursor-pointer hover:shadow-xl hover:scale-105 transition-all duration-300 hover:border-amber-500 border-2 bg-gradient-to-br from-amber-50 to-yellow-100 dark:from-amber-900/30 dark:to-yellow-900/30 ring-2 ring-amber-400 active:scale-95",onClick:j,children:e.jsxs("div",{className:"flex flex-col items-center gap-2 sm:gap-3",children:[e.jsx(fr,{className:"h-14 w-14 sm:h-20 sm:w-20 ring-4 ring-amber-500 shadow-lg",children:e.jsx(pr,{className:"text-xl sm:text-2xl font-bold bg-amber-500/20 text-amber-600",children:e.jsx(ns,{className:"h-6 w-6 sm:h-8 sm:w-8"})})}),e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"font-bold text-sm sm:text-lg mb-0.5 sm:mb-1 truncate max-w-[100px] sm:max-w-none",children:n.owner_name}),e.jsxs("div",{className:"flex items-center justify-center gap-1 text-[10px] sm:text-xs text-amber-600 font-semibold",children:[e.jsx(ns,{className:"h-2.5 w-2.5 sm:h-3 sm:w-3"}),e.jsx("span",{children:"المالك"})]})]})]})}),b.map(T=>{const k=y(T.role),P=k.icon;return e.jsx(fe,{className:`p-4 sm:p-6 cursor-pointer hover:shadow-xl hover:scale-105 transition-all duration-300 hover:border-primary border-2 ${k.bgColor} active:scale-95`,onClick:()=>_(T),children:e.jsxs("div",{className:"flex flex-col items-center gap-2 sm:gap-3",children:[e.jsx(fr,{className:`h-14 w-14 sm:h-20 sm:w-20 ring-4 ${k.color} shadow-lg`,children:e.jsx(pr,{className:`text-lg sm:text-2xl font-bold ${k.bgColor} ${k.textColor}`,children:T.employee_name.substring(0,2)})}),e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"font-bold text-sm sm:text-lg mb-0.5 sm:mb-1 truncate max-w-[100px] sm:max-w-none",children:T.employee_name}),e.jsxs("div",{className:`flex items-center justify-center gap-1 text-[10px] sm:text-xs ${k.textColor} font-semibold`,children:[e.jsx(P,{className:"h-2.5 w-2.5 sm:h-3 sm:w-3"}),e.jsx("span",{children:k.label})]})]})]})},T.id)})]}),e.jsx("div",{className:"mt-6 pt-4 border-t border-border/50",children:e.jsxs(V,{variant:"ghost",className:"w-full text-destructive hover:text-destructive hover:bg-destructive/10",onClick:A,children:[e.jsx(rn,{className:"h-4 w-4 ml-2"}),"تسجيل الخروج من النظام"]})})]}),c&&e.jsxs("div",{className:"max-w-sm sm:max-w-md mx-auto",children:[e.jsxs("div",{className:"text-center mb-4 sm:mb-6",children:[e.jsx("p",{className:"text-muted-foreground text-base sm:text-lg mb-1 sm:mb-2",children:"أدخل رقم PIN الخاص بك"}),e.jsxs("p",{className:"text-xs sm:text-sm text-muted-foreground",children:["الموظف: ",e.jsx("span",{className:"font-semibold",children:c.employee_name})]})]}),e.jsx("div",{className:"flex justify-center gap-2 sm:gap-3 mb-5 sm:mb-8",children:Array.from({length:m?3:4}).map((T,k)=>e.jsx("div",{className:"w-12 h-12 sm:w-16 sm:h-16 rounded-xl border-2 border-primary/40 flex items-center justify-center bg-gradient-to-br from-primary/5 to-primary/10 shadow-sm",children:d.length>k&&e.jsx("div",{className:`w-3 h-3 sm:w-4 sm:h-4 rounded-full ${m?"bg-gradient-to-r from-amber-500 to-yellow-500":"bg-gradient-to-r from-indigo-500 to-purple-500"} animate-in zoom-in-50 duration-200 shadow-lg`})},k))}),e.jsxs("div",{className:"grid grid-cols-3 gap-2 sm:gap-3 mb-4 sm:mb-6",children:[[1,2,3,4,5,6,7,8,9].map(T=>e.jsx(V,{variant:"outline",size:"lg",className:"h-12 sm:h-16 text-xl sm:text-2xl font-bold hover:bg-gradient-to-r hover:from-indigo-500 hover:to-purple-500 hover:text-white transition-all shadow-sm hover:shadow-lg active:scale-95",onClick:()=>I(T.toString()),disabled:p,children:T},T)),e.jsx(V,{variant:"outline",size:"lg",className:"h-12 sm:h-16 hover:bg-red-500 hover:text-white transition-all shadow-sm active:scale-95",onClick:N,disabled:p,children:e.jsx(at,{className:"h-5 w-5 sm:h-6 sm:w-6"})}),e.jsx(V,{variant:"outline",size:"lg",className:"h-12 sm:h-16 text-xl sm:text-2xl font-bold hover:bg-gradient-to-r hover:from-indigo-500 hover:to-purple-500 hover:text-white transition-all shadow-sm hover:shadow-lg active:scale-95",onClick:()=>I("0"),disabled:p,children:"0"}),e.jsx(V,{variant:"outline",size:"lg",className:"h-12 sm:h-16 hover:bg-gray-200 dark:hover:bg-gray-700 transition-all shadow-sm active:scale-95",onClick:w,disabled:p,children:e.jsx(dm,{className:"h-5 w-5 sm:h-6 sm:w-6"})})]}),e.jsxs("div",{className:"flex gap-2 sm:gap-3",children:[e.jsxs(V,{variant:"outline",className:"flex-1 h-11 sm:h-12 text-sm sm:text-base",onClick:C,disabled:p,children:[e.jsx(qo,{className:"ml-1 sm:ml-2 h-4 w-4"}),"رجوع"]}),e.jsx(V,{className:"flex-1 h-11 sm:h-12 text-sm sm:text-base bg-gradient-to-r from-indigo-600 to-purple-600 hover:from-indigo-700 hover:to-purple-700 shadow-lg",onClick:F,disabled:(m?d.length!==3:d.length!==4)||p||x,children:x?e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(ct,{className:"h-4 w-4 animate-spin"}),"جاري تحضير البيانات..."]}):p?"جاري التسجيل...":"تسجيل الدخول"})]})]}),!c&&b.length===0&&!a&&(n==null?void 0:n.id)&&e.jsxs("div",{className:"text-center py-12",children:[e.jsx("div",{className:"mb-4 text-muted-foreground",children:e.jsx(Bt,{className:"h-16 w-16 mx-auto mb-4 opacity-50"})}),e.jsx("p",{className:"text-lg font-semibold text-muted-foreground mb-2",children:"لا يوجد موظفين نشطين"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"يرجى إضافة موظفين من قسم الإدارة"})]})]})]})})]})}const Ld=Ki,Dd=Ou,Nb=Yi,$d=v.forwardRef(({className:t,...r},n)=>e.jsx(Fo,{className:Z("fixed inset-0 z-50 bg-black/80  data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",t),...r,ref:n}));$d.displayName=Fo.displayName;const Cb=Gi("fixed z-50 gap-4 bg-background p-6 shadow-lg transition ease-in-out data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:duration-300 data-[state=open]:duration-500",{variants:{side:{top:"inset-x-0 top-0 border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",bottom:"inset-x-0 bottom-0 border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",left:"inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm",right:"inset-y-0 right-0 h-full w-3/4  border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm"}},defaultVariants:{side:"right"}}),va=v.forwardRef(({side:t="right",className:r,children:n,...i},o)=>e.jsxs(Nb,{children:[e.jsx($d,{}),e.jsxs(Uo,{ref:o,className:Z(Cb({side:t}),r),...i,children:[n,e.jsxs(Iu,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-secondary",children:[e.jsx(at,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));va.displayName=Uo.displayName;const Fd=({className:t,...r})=>e.jsx("div",{className:Z("flex flex-col space-y-2 text-center sm:text-left",t),...r});Fd.displayName="SheetHeader";const Eb=({className:t,...r})=>e.jsx("div",{className:Z("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",t),...r});Eb.displayName="SheetFooter";const Ud=v.forwardRef(({className:t,...r},n)=>e.jsx(tc,{ref:n,className:Z("text-lg font-semibold text-foreground",t),...r}));Ud.displayName=tc.displayName;const Sb=v.forwardRef(({className:t,...r},n)=>e.jsx(rc,{ref:n,className:Z("text-sm text-muted-foreground",t),...r}));Sb.displayName=rc.displayName;function mo({className:t,...r}){return e.jsx("div",{className:Z("animate-pulse rounded-md bg-muted",t),...r})}const zd=v.memo(()=>e.jsx(fe,{className:"min-h-[100px] sm:min-h-[120px] p-3 sm:p-5 animate-pulse",children:e.jsxs("div",{className:"flex flex-col items-center space-y-2",children:[e.jsx(mo,{className:"h-10 w-10 sm:h-12 sm:w-12 rounded-full"}),e.jsx(mo,{className:"h-4 w-3/4"}),e.jsx(mo,{className:"h-5 w-1/2"})]})}));zd.displayName="ProductSkeleton";const Bd=v.memo(({count:t=12})=>e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-2 sm:gap-3 lg:gap-4",children:Array.from({length:t}).map((r,n)=>e.jsx(zd,{},n))}));Bd.displayName="ProductGridSkeleton";const qd=v.memo(({product:t,onSelect:r})=>e.jsxs(fe,{onClick:()=>r(t),className:"cursor-pointer group relative overflow-hidden bg-gradient-to-br from-white to-blue-50 dark:from-background dark:to-blue-950/30 border-2 border-blue-100 dark:border-blue-900 hover:border-blue-400 hover:shadow-xl transition-all duration-200 active:scale-95 sm:hover:scale-105 min-h-[100px] sm:min-h-[120px] flex flex-col justify-center p-3 sm:p-5 animate-fade-in touch-manipulation",children:[e.jsx("div",{className:`absolute top-1.5 left-1.5 sm:top-2 sm:left-2 text-white text-[10px] sm:text-xs px-1.5 sm:px-2 py-0.5 sm:py-1 rounded-full font-bold shadow-md ${t.track_inventory&&t.stock_quantity!==void 0?t.stock_quantity>0?"bg-green-600":"bg-red-600":"bg-blue-600"}`,children:t.track_inventory&&t.stock_quantity!==void 0?t.stock_quantity>0?`${Number(t.stock_quantity).toFixed(0)}`:"نفذ":"متاح"}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-r from-blue-400 to-blue-600 opacity-0 group-hover:opacity-10 transition-opacity duration-300"}),e.jsxs("div",{className:"text-center space-y-1.5 sm:space-y-3 relative z-10",children:[e.jsx("div",{className:"flex justify-center mb-1 sm:mb-2",children:e.jsxs(fr,{className:"h-10 w-10 sm:h-12 sm:w-12 border-2 border-blue-200 dark:border-blue-800 shadow-md",children:[e.jsx(Yr,{src:t.image_url,alt:t.product_name,className:"object-cover",loading:"lazy"}),e.jsx(pr,{className:"bg-blue-50 dark:bg-blue-900",children:e.jsx(ht,{className:"h-5 w-5 sm:h-6 sm:w-6 text-blue-400"})})]})}),e.jsx("p",{className:"font-bold text-foreground text-sm sm:text-base leading-tight line-clamp-2 font-cairo group-hover:text-blue-700 dark:group-hover:text-blue-300 transition-colors",children:t.product_name}),e.jsxs("div",{className:"flex items-center justify-center gap-1 sm:gap-2",children:[e.jsx("span",{className:"text-blue-600 dark:text-blue-400 font-bold text-lg sm:text-xl font-cairo",children:Number(t.unit_price||0).toFixed(2)}),e.jsx("span",{className:"text-muted-foreground text-xs sm:text-sm font-cairo",children:"د.أ"})]})]}),e.jsx("div",{className:"absolute bottom-1.5 right-1.5 sm:bottom-2 sm:right-2 bg-green-500 text-white rounded-full w-7 h-7 sm:w-8 sm:h-8 flex items-center justify-center opacity-100 sm:opacity-0 sm:group-hover:opacity-100 transition-opacity duration-300 shadow-lg",children:e.jsx(kt,{className:"h-4 w-4 sm:h-5 sm:w-5"})})]}));qd.displayName="ProductCard";const Vd=v.memo(({products:t,onProductSelect:r,searchTerm:n,selectedCategoryId:i,isLoading:o=!1})=>{if(o)return e.jsx(Bd,{count:12});const a=v.useMemo(()=>t.filter(c=>{const l=c.product_name.toLowerCase().includes(n.toLowerCase()),m=!i||c.category_id===i;return l&&m}),[t,n,i]),s=v.useCallback(c=>{r(c)},[r]);return a.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center h-64 text-gray-400",children:[e.jsx(ht,{className:"h-16 w-16 mb-4"}),e.jsx("p",{className:"text-lg font-cairo",children:"لا توجد منتجات"})]}):e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-2 sm:gap-3 lg:gap-4",children:a.map(c=>e.jsx(qd,{product:c,onSelect:s},c.id))})});Vd.displayName="ProductGrid";const kb={Banknote:Vu,CreditCard:Un,Smartphone:Sr,Building2:Mo,Clock:xr,Wallet:Ds},Pi={green:{bg:"bg-green-50",border:"border-green-300",text:"text-green-700",activeBg:"bg-green-500"},blue:{bg:"bg-blue-50",border:"border-blue-300",text:"text-blue-700",activeBg:"bg-blue-500"},purple:{bg:"bg-purple-50",border:"border-purple-300",text:"text-purple-700",activeBg:"bg-purple-500"},gray:{bg:"bg-gray-50",border:"border-gray-300",text:"text-gray-700",activeBg:"bg-gray-500"},orange:{bg:"bg-orange-50",border:"border-orange-300",text:"text-orange-700",activeBg:"bg-orange-500"},default:{bg:"bg-gray-50",border:"border-gray-300",text:"text-gray-700",activeBg:"bg-gray-500"}},Tb=({methods:t,selectedMethod:r,onSelect:n,disabled:i=!1,selectedCustomer:o=null,onCreditClick:a,compact:s=!1})=>t.length?e.jsx(po,{children:e.jsxs("div",{className:Z("space-y-2",s&&"space-y-1.5"),children:[!s&&e.jsx("p",{className:"text-sm font-bold text-gray-700 font-cairo flex items-center gap-2",children:"💳 طريقة الدفع:"}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:t.map(c=>{const l=kb[c.icon_name||"Wallet"]||Ds,m=Pi[c.color||"default"]||Pi.default,u=(r==null?void 0:r.id)===c.id,d=c.method_type==="credit"&&!o;return e.jsxs(Hi,{children:[e.jsx(Wi,{asChild:!0,children:e.jsxs(V,{variant:"outline",disabled:i,onClick:()=>{d&&a?a():n(c)},className:Z("flex items-center justify-center gap-1.5 transition-all duration-200 relative","border-2 font-cairo px-3",s?"h-10":"h-12",d?"opacity-50 cursor-not-allowed bg-gray-100 border-gray-300":u?`${m.activeBg} text-white border-transparent shadow-lg scale-105`:`${m.bg} ${m.border} ${m.text} hover:scale-102`),children:[d?e.jsx(Tn,{className:"h-4 w-4 text-gray-400"}):e.jsx(l,{className:Z("h-5 w-5",u&&"text-white")}),e.jsx("span",{className:Z("font-bold text-sm",d&&"text-gray-400"),children:c.method_name}),u&&!d&&e.jsx("span",{className:"absolute -top-1 -right-1 bg-white text-green-600 rounded-full flex items-center justify-center shadow text-xs w-4 h-4",children:"✓"})]})}),d&&e.jsx(Xi,{side:"bottom",className:"font-cairo",children:e.jsx("p",{children:"يجب اختيار عميل أولاً"})})]},c.id)})}),r&&e.jsxs("p",{className:"text-sm text-center text-muted-foreground font-cairo mt-1",children:["💳 طريقة الدفع: ",e.jsx("span",{className:"font-bold text-primary",children:r.method_name})]})]})}):null,Gd=v.memo(Tb);Gd.displayName="PaymentMethodSelector";const Ab=()=>{const{token:t,sellerData:r}=tr(),{toast:n}=et(),[i,o]=v.useState([]),[a,s]=v.useState(!1),[c,l]=v.useState(null),m=v.useCallback(()=>{const b=Number(r==null?void 0:r.id)||0;return[{id:1,seller_id:b,method_name:"نقدي",method_code:"cash",method_type:"cash",affects_cash_drawer:!0,is_default:!0,is_active:!0,display_order:1,icon_name:"Banknote",color:"green"},{id:2,seller_id:b,method_name:"بطاقة ائتمان",method_code:"card",method_type:"card",affects_cash_drawer:!1,is_default:!1,is_active:!0,display_order:2,icon_name:"CreditCard",color:"blue"},{id:3,seller_id:b,method_name:"كليك (CliQ)",method_code:"cliq",method_type:"digital",affects_cash_drawer:!1,is_default:!1,is_active:!0,display_order:3,icon_name:"Smartphone",color:"purple"},{id:4,seller_id:b,method_name:"تحويل بنكي",method_code:"bank_transfer",method_type:"digital",affects_cash_drawer:!1,is_default:!1,is_active:!0,display_order:4,icon_name:"Building2",color:"cyan"},{id:5,seller_id:b,method_name:"آجل (ذمم)",method_code:"credit",method_type:"credit",affects_cash_drawer:!1,is_default:!1,is_active:!0,display_order:5,icon_name:"Clock",color:"orange"}]},[r==null?void 0:r.id]),u=v.useCallback(async()=>{if(!t||!(r!=null&&r.id)){console.log("[PaymentMethods] No token or seller, using defaults"),o(m());return}s(!0),l(null);try{console.log("[PaymentMethods] Fetching for seller:",r.id);const b=await fetch(`${oe()}${W.GET_ALL("payment_methods")}&seller_id=${r.id}&is_active=1&_sort=display_order&_order=asc`,{headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"}});if(!b.ok)throw console.warn("[PaymentMethods] API error, using defaults"),new Error("فشل في جلب طرق الدفع");const y=await b.json();if(console.log("[PaymentMethods] API response:",y),!y.data||y.data.length===0){console.log("[PaymentMethods] No methods in DB, using defaults"),o(m());return}const _=y.data.map(j=>({...j,affects_cash_drawer:j.affects_cash_drawer===1||j.affects_cash_drawer===!0,is_default:j.is_default===1||j.is_default===!0,is_active:j.is_active===1||j.is_active===!0}));console.log("[PaymentMethods] Loaded",_.length,"methods"),o(_)}catch(b){console.error("[PaymentMethods] Error:",b),l(b instanceof Error?b.message:"خطأ غير معروف"),console.log("[PaymentMethods] Using fallback defaults"),o(m())}finally{s(!1)}},[t,r==null?void 0:r.id,m]),d=v.useCallback(()=>i.find(b=>b.is_default)||i[0],[i]),h=v.useCallback(b=>i.find(y=>y.id===b),[i]),p=v.useCallback(b=>i.find(y=>y.method_code===b),[i]),f=v.useCallback(async b=>{if(!t||!(r!=null&&r.id))return null;try{const y=await fetch(`${oe()}${W.CREATE("payment_methods")}`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({...b,seller_id:r.id})});if(!y.ok)throw new Error("فشل في إنشاء طريقة الدفع");const _=await y.json();return n({title:"تم الإنشاء",description:"تم إضافة طريقة الدفع بنجاح"}),await u(),_.data}catch(y){return console.error("Error creating payment method:",y),n({title:"خطأ",description:"فشل في إنشاء طريقة الدفع",variant:"destructive"}),null}},[t,r==null?void 0:r.id,u,n]),x=v.useCallback(async(b,y)=>{if(!t)return!1;try{if(!(await fetch(`${oe()}${W.UPDATE("payment_methods",String(b))}`,{method:"PUT",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify(y)})).ok)throw new Error("فشل في تحديث طريقة الدفع");return n({title:"تم التحديث",description:"تم تحديث طريقة الدفع بنجاح"}),await u(),!0}catch(_){return console.error("Error updating payment method:",_),n({title:"خطأ",description:"فشل في تحديث طريقة الدفع",variant:"destructive"}),!1}},[t,u,n]),g=v.useCallback(async b=>{if(!t)return!1;try{if(!(await fetch(`${oe()}${W.DELETE("payment_methods",String(b))}`,{method:"DELETE",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"}})).ok)throw new Error("فشل في حذف طريقة الدفع");return n({title:"تم الحذف",description:"تم حذف طريقة الدفع بنجاح"}),await u(),!0}catch(y){return console.error("Error deleting payment method:",y),n({title:"خطأ",description:"فشل في حذف طريقة الدفع",variant:"destructive"}),!1}},[t,u,n]);return v.useEffect(()=>{u()},[u]),{paymentMethods:i,isLoading:a,error:c,fetchPaymentMethods:u,getDefaultMethod:d,getMethodById:h,getMethodByCode:p,createPaymentMethod:f,updatePaymentMethod:x,deletePaymentMethod:g}},Ib=({items:t,onUpdateQuantity:r,onRemoveItem:n,onCheckoutWithPayment:i,isProcessing:o,totals:a,isMobile:s=!1,loyaltyDiscount:c=0,selectedCustomer:l=null,customers:m=[],onSelectCustomer:u,customerSearchOpen:d=!1,setCustomerSearchOpen:h,lastAddedItemId:p=null})=>{const f=t.length===0,{currentEmployee:x,hasPermission:g}=lt(),{toast:b}=et(),{paymentMethods:y,getDefaultMethod:_}=Ab(),[j,I]=v.useState(0),[w,N]=v.useState(null),C=a.taxInclusiveAmount,A=j-C;v.useEffect(()=>{if(y.length>0&&!w){const S=_();S&&N(S)}},[y,w,_]);const F=S=>{const E=[],O=Math.ceil(S);E.push(O);const R=Math.ceil(S/5)*5;R!==O&&E.length<5&&E.push(R);const D=Math.ceil(S/10)*10;!E.includes(D)&&E.length<5&&E.push(D);const $=Math.ceil(S/20)*20;!E.includes($)&&E.length<5&&E.push($);const M=Math.ceil(S/50)*50;return!E.includes(M)&&E.length<5&&E.push(M),E.slice(0,5)},T=c>0||t.some(S=>S.discount_amount>0),k=()=>{if(!x){b({title:"يجب تسجيل الدخول",description:"يجب تسجيل دخول الموظف قبل إتمام البيع",variant:"destructive"});return}if(!g("can_create_invoices")){b({title:"غير مصرح",description:"ليس لديك صلاحية إنشاء الفواتير",variant:"destructive"});return}if(T&&!g("can_approve_discounts")){b({title:"غير مصرح بالخصومات",description:"ليس لديك صلاحية الموافقة على الخصومات. تواصل مع المدير للحصول على الموافقة.",variant:"destructive"});return}const S=w||_();if(!S){b({title:"خطأ",description:"يرجى اختيار طريقة الدفع",variant:"destructive"});return}if(S.method_type==="credit"&&!l){b({title:"يجب اختيار عميل",description:"طريقة الدفع الآجل تتطلب اختيار عميل مسبقاً",variant:"destructive"});return}if(S.affects_cash_drawer&&j<C){b({title:"المبلغ غير كافي",description:`الإجمالي: ${C.toFixed(2)} د.أ`,variant:"destructive"});return}const E=S.affects_cash_drawer?j:C,O=S.affects_cash_drawer?A:0;i(E,O,S)},P=e.jsxs(fe,{className:"h-full flex flex-col bg-gradient-to-br from-white to-blue-50 border-2 border-blue-200 shadow-xl animate-fade-in overflow-hidden",children:[e.jsxs("div",{className:"flex items-center justify-between border-b p-2 bg-white/80 backdrop-blur-sm shrink-0",style:{height:"44px"},children:[e.jsxs("h3",{className:"text-sm font-bold font-cairo text-gray-800 flex items-center gap-1",children:[e.jsx(Xr,{className:"h-4 w-4"}),"السلة"]}),e.jsx("span",{className:"bg-blue-600 text-white px-2 py-0.5 rounded-full text-xs font-bold",children:t.length})]}),e.jsx("div",{className:"overflow-y-auto overscroll-contain touch-pan-y scroll-smooth p-2 space-y-2 flex flex-col-reverse space-y-reverse",style:{flex:"1 1 auto",minHeight:"80px"},children:f?e.jsxs("div",{className:"text-center py-8 text-gray-400",children:[e.jsx(Xr,{className:"h-12 w-12 mx-auto mb-2 opacity-50"}),e.jsx("p",{className:"font-cairo text-base",children:"السلة فارغة"}),e.jsx("p",{className:"font-cairo text-sm mt-1",children:"اضغط على منتج لإضافته"})]}):t.map(S=>{const E=S.id===p;return e.jsxs("div",{className:Z("bg-white rounded-xl p-4 border-2 shadow-sm hover:shadow-md transition-shadow active:bg-blue-50 flex items-center gap-3",E?"border-blue-400 bg-blue-50/50 ring-2 ring-blue-300":"border-gray-200"),children:[e.jsx(V,{variant:"ghost",size:"sm",onClick:()=>n(S.id),className:"h-10 w-10 p-0 hover:bg-red-100 shrink-0",children:e.jsx(at,{className:"h-5 w-5 text-red-500"})}),e.jsx("p",{className:"font-bold text-lg text-gray-800 flex-1 font-cairo leading-tight truncate",children:S.item_name}),E?e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsx(V,{variant:"outline",size:"sm",onClick:()=>r(S.id,S.quantity-1),disabled:S.quantity<=1,className:"h-10 w-10 p-0 active:scale-95 transition-transform",children:e.jsx(Om,{className:"h-5 w-5"})}),e.jsx("span",{className:"font-bold text-lg w-10 text-center font-cairo",children:S.quantity}),e.jsx(V,{variant:"outline",size:"sm",onClick:()=>r(S.id,S.quantity+1),className:"h-10 w-10 p-0 active:scale-95 transition-transform",children:e.jsx(kt,{className:"h-5 w-5"})})]}):e.jsxs("span",{className:"font-bold text-lg text-gray-600 font-cairo bg-gray-100 px-3 py-1.5 rounded-lg shrink-0",children:["x",S.quantity]}),e.jsxs("p",{className:"font-black text-blue-600 font-cairo text-lg shrink-0 min-w-[70px] text-left",children:[Number(S.line_total||0).toFixed(2)," د.أ"]})]},S.id)})}),!f&&e.jsxs("div",{className:"shrink-0 border-t-2 border-blue-200 bg-white p-3 space-y-2",children:[e.jsxs("div",{className:"bg-gradient-to-r from-green-50 to-emerald-50 rounded-lg p-3 border border-green-200",children:[e.jsxs("div",{className:"flex justify-between items-center gap-3 text-sm font-cairo",children:[e.jsxs("span",{className:"text-gray-600",children:["قبل الضريبة: ",e.jsx("b",{className:"text-base",children:ft(a.taxExclusiveAmount)})]}),e.jsxs("span",{className:"text-gray-600",children:["ضريبة: ",e.jsx("b",{className:"text-base",children:ft(a.totalTaxAmount)})]}),c>0&&e.jsxs("span",{className:"text-purple-600",children:["خصم: ",e.jsxs("b",{className:"text-base",children:["-",ft(c)]})]})]}),e.jsxs("div",{className:"flex justify-between text-xl font-bold border-t pt-2 mt-2 font-cairo",children:[e.jsx("span",{className:"text-gray-800",children:"الإجمالي:"}),e.jsxs("span",{className:"text-green-600 font-black",children:[ft(a.taxInclusiveAmount)," د.أ"]})]})]}),m.length>0&&u&&e.jsxs(qs,{open:d,onOpenChange:h,children:[e.jsx(Vs,{asChild:!0,children:e.jsxs(V,{variant:"outline",size:"sm",className:Z("w-full justify-between font-cairo h-7 text-xs",l?"border-blue-400 bg-blue-50":""),children:[l?e.jsxs("span",{className:"flex items-center gap-1 truncate",children:[e.jsx(Ra,{className:"h-3 w-3 text-blue-600 shrink-0"}),e.jsx("span",{className:"font-bold text-blue-700 truncate",children:l.name})]}):e.jsx("span",{className:"text-muted-foreground truncate",children:"👤 اختر عميل"}),e.jsx(sm,{className:"h-3 w-3 shrink-0"})]})}),e.jsx(Yn,{className:"w-64 p-0 z-50",align:"start",children:e.jsxs(Wo,{children:[e.jsx(Xo,{placeholder:"ابحث عن عميل...",className:"font-cairo"}),e.jsxs(Jo,{children:[e.jsx(Ko,{className:"font-cairo p-4 text-center text-sm",children:"لا يوجد عملاء"}),e.jsxs(Yo,{children:[l&&e.jsxs(_s,{onSelect:()=>{u(null),h==null||h(!1)},className:"font-cairo text-red-600 cursor-pointer",children:[e.jsx(th,{className:"h-4 w-4 ml-2"}),"بدون عميل"]}),m.map(S=>e.jsxs(_s,{onSelect:()=>{u(S),h==null||h(!1)},className:"font-cairo cursor-pointer",children:[e.jsx(Ra,{className:"h-4 w-4 ml-2"}),e.jsx("span",{className:"font-bold truncate",children:S.customer_name})]},S.id))]})]})]})})]}),e.jsx(Gd,{methods:y,selectedMethod:w,onSelect:N,disabled:o,selectedCustomer:l,onCreditClick:()=>h==null?void 0:h(!0),compact:!0}),(w==null?void 0:w.affects_cash_drawer)&&e.jsxs("div",{className:"bg-gradient-to-r from-yellow-50 to-amber-50 rounded-lg p-2 border border-yellow-200 space-y-2",children:[e.jsx("div",{className:"flex gap-1",children:F(C).slice(0,4).map(S=>e.jsx(V,{variant:j===S?"default":"outline",size:"sm",onClick:()=>I(S),className:"flex-1 text-sm font-cairo font-bold h-10 px-2",children:S},S))}),e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx(Te,{type:"number",value:j||"",onChange:S=>I(Number(S.target.value)),placeholder:"مبلغ...",className:"h-10 text-base text-center font-bold font-cairo flex-1"}),j>0&&e.jsxs("div",{className:`px-3 py-2 rounded-lg text-sm font-bold font-cairo whitespace-nowrap ${A>=0?"bg-green-100 text-green-700":"bg-red-100 text-red-700"}`,children:["الباقي: ",A>=0?`${A.toFixed(2)}`:`-${Math.abs(A).toFixed(2)}`]})]})]}),w&&!w.affects_cash_drawer&&e.jsx("div",{className:Z("rounded p-1.5 border text-center text-xs",w.method_type==="credit"&&!l?"bg-red-50 border-red-200":"bg-blue-50 border-blue-200"),children:w.method_type==="credit"?l?e.jsxs("p",{className:"font-bold text-blue-700 font-cairo",children:["📋 ذمة: ",e.jsx("span",{className:"text-blue-900",children:l.name})," - ",ft(C)," د.أ"]}):e.jsx("p",{className:"font-bold text-red-700 font-cairo",children:"⚠️ اختر عميل للدفع الآجل"}):e.jsxs("p",{className:"font-bold text-blue-700 font-cairo",children:["✅ ",w.method_name,": ",ft(C)," د.أ"]})}),e.jsx(V,{onClick:k,disabled:f||o,className:"w-full h-10 text-sm font-bold gap-2 bg-gradient-to-r from-green-600 to-emerald-600 hover:from-green-700 hover:to-emerald-700 text-white shadow-lg active:scale-[0.98] transition-transform font-cairo",children:o?e.jsxs(e.Fragment,{children:[e.jsx(ct,{className:"mr-2 h-4 w-4 animate-spin"}),"جاري الإنشاء..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Xr,{className:"mr-2 h-4 w-4"}),"إتمام البيع - ",ft(C)," د.أ"]})})]})]});return s?P:e.jsx("div",{className:"sticky top-4",children:P})},ko=v.memo(Ib);ko.displayName="POSCart";const Ob=({thermalHTML:t})=>e.jsxs("div",{className:"thermal-preview-container",dir:"rtl",children:[e.jsx("div",{className:"thermal-preview-frame bg-white border-4 border-dashed border-gray-300 rounded-lg shadow-inner overflow-hidden",children:e.jsx("div",{className:"thermal-content overflow-y-auto max-h-[400px] p-4",dangerouslySetInnerHTML:{__html:t}})}),e.jsx("style",{children:`
        .thermal-preview-container {
          width: 100%;
          max-width: 320px;
          margin: 0 auto;
        }
        
        .thermal-preview-frame {
          background: linear-gradient(to bottom, #f9fafb 0%, #ffffff 10%);
        }
        
        .thermal-content {
          font-family: 'Cairo', sans-serif;
        }
        
        /* Ensure thermal receipt styles work in preview */
        .thermal-content body {
          width: 100% !important;
          margin: 0 !important;
          padding: 0 !important;
        }
      `})]}),Rb=({open:t,onClose:r,invoiceNumber:n,invoiceId:i,onPrintThermal:o,onDownloadPDF:a,onViewInvoice:s,thermalPrintingEnabled:c=!1,autoPrinted:l=!1,thermalPreviewHTML:m,onSendToGovernment:u,isSendingToGov:d=!1,sentToGov:h=!1,sendToGovFailed:p=!1,sendToGovError:f,qrCode:x,fawatrahEnabled:g=!0})=>e.jsx(gt,{open:t,onOpenChange:r,children:e.jsx(bt,{className:"sm:max-w-2xl font-cairo animate-scale-in max-h-[90vh] overflow-y-auto",dir:"rtl",children:e.jsxs("div",{className:"space-y-4",children:[l&&e.jsx("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-3 text-center",children:e.jsxs("p",{className:"text-sm text-blue-700 font-bold flex items-center justify-center gap-2",children:[e.jsx(Zr,{className:"h-4 w-4"}),"تم إرسال الفاتورة للطباعة الحرارية تلقائياً"]})}),h&&e.jsx("div",{className:"bg-green-50 border-2 border-green-300 rounded-lg p-3 text-center",children:e.jsxs("p",{className:"text-sm text-green-700 font-bold flex items-center justify-center gap-2",children:[e.jsx(Tr,{className:"h-5 w-5"}),"تم إرسال الفاتورة بنجاح إلى النظام الحكومي"]})}),p&&!h&&e.jsxs("div",{className:"bg-red-50 border-2 border-red-300 rounded-lg p-3 text-center",children:[e.jsxs("p",{className:"text-sm text-red-700 font-bold flex items-center justify-center gap-2",children:[e.jsx(Bo,{className:"h-5 w-5"}),"فشل إرسال الفاتورة للنظام الحكومي"]}),f&&e.jsx("p",{className:"text-xs text-red-600 mt-1",children:f})]}),h&&x&&e.jsxs("div",{className:"bg-gray-50 border border-gray-200 rounded-lg p-4 text-center",children:[e.jsxs("div",{className:"flex items-center justify-center gap-2 mb-3",children:[e.jsx(uu,{className:"h-5 w-5 text-blue-600"}),e.jsx("span",{className:"font-bold text-gray-700",children:"رمز التحقق"})]}),e.jsx("img",{src:`https://api.qrserver.com/v1/create-qr-code/?size=150x150&data=${encodeURIComponent(x)}`,alt:"QR Code",className:"mx-auto w-32 h-32"})]}),o&&e.jsxs(V,{onClick:o,className:"w-full justify-center gap-4 h-16 text-xl font-bold bg-gradient-to-r from-green-500 to-green-600 hover:from-green-600 hover:to-green-700 font-cairo",children:[e.jsx(Zr,{className:"h-8 w-8"}),l?"طباعة مرة أخرى":"طباعة الفاتورة"]}),u&&!h&&g!==!1&&e.jsx(V,{onClick:u,disabled:d,className:`w-full justify-center gap-4 h-14 text-lg font-bold font-cairo disabled:opacity-70 ${p?"bg-gradient-to-r from-orange-500 to-orange-600 hover:from-orange-600 hover:to-orange-700":"bg-gradient-to-r from-blue-500 to-blue-600 hover:from-blue-600 hover:to-blue-700"}`,children:d?e.jsxs(e.Fragment,{children:[e.jsx(ct,{className:"h-6 w-6 animate-spin"}),"جاري الإرسال..."]}):p?e.jsxs(e.Fragment,{children:[e.jsx(_r,{className:"h-6 w-6"}),"إعادة محاولة الإرسال"]}):e.jsxs(e.Fragment,{children:[e.jsx(zm,{className:"h-6 w-6"}),"إرسال إلى فوترة"]})}),m&&e.jsx(Ob,{thermalHTML:m}),e.jsxs(V,{onClick:r,variant:"outline",className:"w-full h-12 text-lg font-bold font-cairo",children:[e.jsx(at,{className:"h-6 w-6 ml-2"}),"خروج"]})]})})}),Pb=({open:t,onOpenChange:r,onSuccess:n})=>{const[i,o]=v.useState(""),{loginWithPin:a}=lt(),s=Mt(),c=d=>{i.length<4&&o(i+d)},l=()=>{o(i.slice(0,-1))},m=()=>{o("")},u=async()=>{if(i.length===4&&s)try{const d=localStorage.getItem(xe);let h=`${nt}auto-crud.php?action=get&table=employees&filter[pin_code]=${i}&filter[seller_id]=${s}&filter[is_active]=1`;d&&(h+=`&token=${d}`);const f=await(await fetch(h)).json();if(!f.success||!f.data||f.data.length===0){Ge.error("رقم PIN غير صحيح"),o("");return}if(f.data.length>1){Ge.error("خطأ: يوجد أكثر من موظف بنفس رقم PIN"),o("");return}const x=f.data[0];await a(x.id,i,s)?(o(""),r(!1),n==null||n()):o("")}catch(d){console.error("Quick login error:",d),Ge.error("حدث خطأ أثناء تسجيل الدخول"),o("")}};return e.jsx(gt,{open:t,onOpenChange:r,children:e.jsxs(bt,{className:"sm:max-w-md md:max-w-lg w-full mx-4",children:[e.jsx(Tt,{children:e.jsx(At,{className:"text-lg sm:text-xl text-center",children:"تسجيل دخول سريع"})}),e.jsxs("div",{className:"space-y-4 sm:space-y-6",children:[e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"text-sm sm:text-base text-muted-foreground mb-3",children:"أدخل رقم PIN الخاص بك"}),e.jsx(Te,{type:"password",value:i,readOnly:!0,className:"text-center text-xl sm:text-2xl tracking-widest py-3 sm:py-4",placeholder:"••••",maxLength:4})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-2 sm:gap-3",children:[[1,2,3,4,5,6,7,8,9].map(d=>e.jsx(V,{variant:"outline",size:"lg",onClick:()=>c(d.toString()),className:"text-xl sm:text-2xl h-14 sm:h-16 hover:bg-primary hover:text-primary-foreground transition-colors",children:d},d)),e.jsx(V,{variant:"outline",size:"lg",onClick:m,className:"h-14 sm:h-16 text-sm sm:text-base hover:bg-destructive hover:text-destructive-foreground transition-colors",children:"مسح"}),e.jsx(V,{variant:"outline",size:"lg",onClick:()=>c("0"),className:"text-xl sm:text-2xl h-14 sm:h-16 hover:bg-primary hover:text-primary-foreground transition-colors",children:"0"}),e.jsx(V,{variant:"outline",size:"lg",onClick:l,className:"h-14 sm:h-16 text-xl sm:text-2xl hover:bg-secondary transition-colors",children:"⌫"})]}),e.jsx(V,{className:"w-full h-12 sm:h-14 text-base sm:text-lg font-bold",size:"lg",onClick:u,disabled:i.length!==4,children:"تسجيل الدخول"})]})]})})},Fr=()=>localStorage.getItem(xe),Mb=t=>{const[r,n]=v.useState([]),[i,o]=v.useState([]),[a,s]=v.useState(!0);v.useEffect(()=>{t&&l()},[t]);const c=async f=>{if(t)try{const x=Fr(),g=`${nt}${W.GET_ALL("loyalty_transactions")}&token=${x}&filters=${encodeURIComponent(JSON.stringify({customer_id:f}))}`,y=await(await fetch(g)).json();if(y.success){const _=(y.data||[]).sort((j,I)=>new Date(I.created_at).getTime()-new Date(j.created_at).getTime());n(_)}else throw new Error(y.message)}catch(x){console.error("Error fetching transactions:",x),Ge.error("فشل في تحميل سجل النقاط")}},l=async()=>{if(!t){s(!1);return}try{const f=Fr(),x=`${nt}${W.GET_ALL("promotions")}&token=${f}&filters=${encodeURIComponent(JSON.stringify({seller_id:t}))}`,b=await(await fetch(x)).json();if(b.success){const y=(b.data||[]).sort((_,j)=>new Date(j.created_at).getTime()-new Date(_.created_at).getTime());o(y)}else throw new Error(b.message)}catch(f){console.error("Error fetching promotions:",f),Ge.error("فشل في تحميل العروض")}finally{s(!1)}};return{transactions:r,promotions:i,loading:a,fetchTransactions:c,fetchPromotions:l,redeemPoints:async(f,x,g=null)=>{if(!t)return 0;try{const b=Fr(),y=`${nt}${W.GET_BY_ID("customers",f)}&token=${b}`,j=await(await fetch(y)).json();if(!j.success)throw new Error(j.message);const w=j.data.loyalty_points||0;if(w<x)return Ge.error("النقاط غير كافية"),0;const N=x*.1,C=w-x,F=await(await fetch(`${nt}${W.UPDATE("customers",f)}&token=${b}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({loyalty_points:C})})).json();if(!F.success)throw new Error(F.message);const k=await(await fetch(`${nt}${W.CREATE("loyalty_transactions")}&token=${b}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({customer_id:f,seller_id:t,transaction_type:"redeem",points:-x,previous_balance:w,new_balance:C,invoice_id:g,notes:`استبدال ${x} نقطة بخصم ${N.toFixed(2)} دينار`})})).json();if(!k.success)throw new Error(k.message);return Ge.success(`تم استبدال ${x} نقطة بخصم ${N.toFixed(2)} دينار`),N}catch(b){return console.error("Error redeeming points:",b),Ge.error("فشل في استبدال النقاط"),0}},createPromotion:async f=>{if(!t)return null;try{const x=Fr(),g={...f,seller_id:t,target_ids:f.target_ids&&f.target_ids.length>0?JSON.stringify(f.target_ids):null,is_active:f.is_active?1:0},y=await(await fetch(`${nt}${W.CREATE("promotions")}&token=${x}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(g)})).json();if(!y.success)throw new Error(y.message);return Ge.success("تم إضافة العرض بنجاح"),await l(),y.data}catch(x){return console.error("Error creating promotion:",x),Ge.error("فشل في إضافة العرض"),null}},updatePromotion:async(f,x)=>{try{const g=Fr(),b={...x};x.target_ids!==void 0&&(b.target_ids=x.target_ids&&x.target_ids.length>0?JSON.stringify(x.target_ids):null),x.is_active!==void 0&&(b.is_active=x.is_active?1:0);const _=await(await fetch(`${nt}${W.UPDATE("promotions",f)}&token=${g}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(b)})).json();if(!_.success)throw new Error(_.message);return Ge.success("تم تحديث العرض"),await l(),_.data}catch(g){return console.error("Error updating promotion:",g),Ge.error("فشل في تحديث العرض"),null}},deletePromotion:async f=>{try{const x=Fr(),b=await(await fetch(`${nt}${W.DELETE("promotions",f)}&token=${x}`,{method:"POST"})).json();if(!b.success)throw new Error(b.message);return Ge.success("تم حذف العرض"),await l(),!0}catch(x){return console.error("Error deleting promotion:",x),Ge.error("فشل في حذف العرض"),!1}},getActivePromotions:()=>{const f=new Date;return i.filter(x=>{if(!x.is_active)return!1;const g=new Date(x.start_date),b=new Date(x.end_date);return f>=g&&f<=b})}}},Lb=({open:t,onOpenChange:r,customerId:n,customerName:i,availablePoints:o,onRedeemSuccess:a,mode:s="immediate"})=>{const c=Mt(),{redeemPoints:l}=Mb(c),[m,u]=v.useState(0),[d,h]=v.useState(!1),p=m*.1,f=async()=>{if(m<=0){Ge.error("يرجى إدخال عدد النقاط");return}if(m>o){Ge.error("النقاط المدخلة أكبر من النقاط المتاحة");return}h(!0);try{if(s==="preview")a==null||a(p),r(!1),u(0),Ge.success(`سيتم تطبيق خصم ${p.toFixed(2)} د.أ عند إتمام البيع`);else{const g=await l(n,m);g>0&&(a==null||a(g),r(!1),u(0))}}catch(g){console.error("Error redeeming points:",g),Ge.error("حدث خطأ أثناء استبدال النقاط")}finally{h(!1)}},x=g=>{const b=Math.floor(o*(g/100));u(b)};return e.jsx(gt,{open:t,onOpenChange:r,children:e.jsxs(bt,{className:"sm:max-w-md",children:[e.jsx(Tt,{children:e.jsxs(At,{className:"flex items-center gap-2",children:[e.jsx(ac,{className:"text-primary"}),"استبدال نقاط الولاء"]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"bg-muted/50 p-4 rounded-lg",children:[e.jsx("p",{className:"text-sm text-muted-foreground mb-1",children:"العميل"}),e.jsx("p",{className:"font-semibold",children:i}),e.jsxs("div",{className:"flex items-center gap-2 mt-2",children:[e.jsx(ds,{size:16,className:"text-primary"}),e.jsxs("span",{className:"text-sm",children:["النقاط المتاحة: ",e.jsx("strong",{children:o})," نقطة"]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(_e,{children:"عدد النقاط المراد استبدالها"}),e.jsx(Te,{type:"number",min:"0",max:o,value:m,onChange:g=>u(Math.min(Number(g.target.value),o)),placeholder:"أدخل عدد النقاط"})]}),e.jsx("div",{className:"grid grid-cols-4 gap-2",children:[25,50,75,100].map(g=>e.jsxs(V,{variant:"outline",size:"sm",onClick:()=>x(g),disabled:o===0,children:[g,"%"]},g))}),m>0&&e.jsxs("div",{className:"bg-primary/10 p-4 rounded-lg border border-primary/20",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"النقاط المستبدلة"}),e.jsxs("span",{className:"font-semibold",children:[m," نقطة"]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"text-sm flex items-center gap-1",children:[e.jsx(Km,{size:16,className:"text-primary"}),"قيمة الخصم"]}),e.jsxs("span",{className:"text-2xl font-bold text-primary",children:[p.toFixed(2)," د"]})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-2 text-center",children:"1 نقطة = 0.10 دينار خصم"})]}),e.jsx("div",{className:"text-xs text-muted-foreground text-center",children:s==="preview"?"سيتم خصم النقاط عند إتمام البيع":"سيتم خصم النقاط فوراً ولا يمكن التراجع عن العملية"})]}),e.jsxs(Vi,{className:"flex gap-2",children:[e.jsx(V,{variant:"outline",onClick:()=>r(!1),disabled:d,children:"إلغاء"}),e.jsx(V,{onClick:f,disabled:m===0||m>o||d,children:d?"جاري الاستبدال...":`استبدال ${m} نقطة`})]})]})})};async function St(t,r="GET",n){const i=localStorage.getItem(xe),o={method:r,headers:{"Content-Type":"application/json",...i?{Authorization:`Bearer ${i}`}:{}}};n&&(o.body=JSON.stringify(n));const a=await fetch(`${oe()}${t}`,o);if(!a.ok)throw new Error(`API request failed: ${a.statusText}`);return a.json()}async function Db(t,r,n,i,o=!1,a){console.log("📦 [InvoiceService] Starting inventory update...",{isReturn:o,itemCount:r.length});for(const s of r){if(!s.product_id){console.log("⏭️ [InvoiceService] Skipping item without product_id:",s.item_name);continue}try{const c=await St(W.GET_BY_ID("products",s.product_id)),l=c==null?void 0:c.data;if(!l){console.warn("⚠️ [InvoiceService] Product not found:",s.product_id);continue}if(!l.track_inventory){console.log("⏭️ [InvoiceService] Product does not track inventory:",l.product_name);continue}const m=Number(l.stock_quantity)||0,u=Number(s.quantity)||0,d=o?m+u:Math.max(0,m-u);console.log(`📦 [InvoiceService] ${o?"Adding":"Deducting"} inventory for ${l.product_name}:`,{currentStock:m,quantityChange:u,newStock:d}),await St(W.UPDATE("products",s.product_id),"POST",{stock_quantity:d});const h={id:crypto.randomUUID(),seller_id:t,product_id:s.product_id,movement_type:o?"return_in":"sale",quantity:o?u:-u,previous_quantity:m,new_quantity:d,unit_cost:Number(l.cost_price)||0,total_cost:(Number(l.cost_price)||0)*u,reference_type:"invoice",reference_id:n,notes:o?`مرتجع - فاتورة رقم ${i}`:`بيع - فاتورة رقم ${i}`,created_by:a||null};await St(W.CREATE("inventory_movements"),"POST",h),console.log("✅ [InvoiceService] Inventory movement recorded for:",l.product_name),!o&&l.low_stock_alert&&d<=(Number(l.min_stock_level)||0)&&(console.log("⚠️ [InvoiceService] Low stock alert triggered for:",l.product_name),await St(W.CREATE("inventory_alerts"),"POST",{id:crypto.randomUUID(),seller_id:t,product_id:s.product_id,alert_type:"low_stock",message:`المنتج "${l.product_name}" وصل للحد الأدنى للمخزون (${d} قطعة)`,is_read:0,created_at:new Date().toISOString()}),console.log("🔔 [InvoiceService] Low stock alert created for:",l.product_name))}catch(c){console.error(`⚠️ [InvoiceService] Failed to update inventory for product ${s.product_id}:`,c)}}console.log("✅ [InvoiceService] Inventory update completed")}const $b=async({invoiceData:t,items:r,seller:n,sellerId:i,invoiceType:o,taxCalculationMode:a="tax_exclusive",notes:s="",status:c="فاتورة جديدة - غير مرسلة",employeeId:l,shiftId:m,loyaltyDiscount:u=0,customerId:d,paymentMethodId:h,paidAmount:p,changeAmount:f})=>{if(console.log("💾 [InvoiceService] Starting createAndSaveInvoice with status:",c),console.log("📋 [InvoiceService] Invoice data:",t),console.log("📝 [InvoiceService] Items:",r),console.log("🏢 [InvoiceService] Seller:",n),console.log("🔢 [InvoiceService] Tax calculation mode:",a),console.log("👤 [InvoiceService] Employee ID:",l||"None"),console.log("🕐 [InvoiceService] Shift ID:",m||"None"),console.log("🎁 [InvoiceService] Loyalty Discount:",u),o==="general_tax"&&r.forEach(x=>{const g=Ut(x.tax_percent||16);x.tax_category_code!==g&&(console.warn("⚠️ [InvoiceService] Tax category mismatch, correcting:",x),x.tax_category_code=g)}),!t.customer_name||r.some(x=>!x.item_name))throw new Error("يرجى ملء جميع الحقول المطلوبة");if(!n||!i)throw new Error("لم يتم العثور على بيانات البائع");try{console.log("🔢 [InvoiceService] Generating invoice number and ICV...");const{invoiceNumber:x,icv:g}=await ol(i);console.log("✅ [InvoiceService] Generated:",{invoiceNumber:x,icvValue:g});const b=r.map(R=>xt({quantity:R.quantity,unitPrice:R.unit_price,discountAmount:R.discount_amount||0,taxPercent:R.tax_percent||0,taxCalculationMode:a})),y=lr(b);console.log("📊 [InvoiceService] Invoice totals:",y);const _=Math.max(0,y.taxInclusiveAmount-u);console.log("🎁 [InvoiceService] Final amount after loyalty discount:",_);const j=Ke(y.taxExclusiveAmount),I=Ke(_),w=Ke(y.totalTaxAmount),N=Ke(y.allowanceChargeAmount+u);console.log("💾 [InvoiceService] XML formatted values:",{xmlTaxExclusiveAmount:j,xmlTaxInclusiveAmount:I,xmlTotalTaxAmount:w,xmlAllowanceChargeAmount:N});const C={...t,invoice_type:o,tax_calculation_mode:a,notes:s};console.log("🔄 [InvoiceService] Generating XML content...");const A=await Bs(x,_,C,r,n,g,i),F=Jn(A);console.log("✅ [InvoiceService] XML content generated and encoded"),console.log("💾 [InvoiceService] Inserting invoice into database...");const T={invoice_number:x,invoice_sequence:x,invoice_counter:g,invoice_date:t.invoice_date,customer_name:t.customer_name,customer_number:t.customer_number,customer_type:t.customer_type,phone_number:t.phone_number,city:t.city,payment_method:t.payment_method,subtotal:y.taxExclusiveAmount,total_amount:_,allowance_charge_amount:y.allowanceChargeAmount+u,tax_exclusive_amount:y.taxExclusiveAmount,tax_inclusive_amount:_,total_tax_amount:y.totalTaxAmount,xml_tax_exclusive_amount:j,xml_tax_inclusive_amount:I,xml_total_tax_amount:w,xml_allowance_charge_amount:N,status:c,xml_file:A,xml_base64:F,encoded_xml:F,notes:s||null,seller_id:i};l&&(T.created_by=l),m&&(T.shift_id=m),h&&(T.payment_method_id=h),p!==void 0&&(T.paid_amount=p),f!==void 0&&(T.change_amount=f);const k=await St(W.CREATE("invoices"),"POST",T);if(!k.success)throw new Error(`Invoice insertion failed: ${k.message}`);const P=k.data;if(console.log("✅ [InvoiceService] Invoice saved successfully:",P),u>0&&d){console.log("🎁 [InvoiceService] Processing loyalty points redemption (background)...");const R=Math.round(u/.1);(async()=>{try{const D=await St(W.GET_BY_ID("customers",d));if(D.success&&D.data){const $=D.data.loyalty_points||0,M=Math.max(0,$-R);await Promise.all([St(W.UPDATE("customers",d),"POST",{loyalty_points:M}),St(W.CREATE("loyalty_transactions"),"POST",{customer_id:d,seller_id:i,transaction_type:"redeem",points:-R,previous_balance:$,new_balance:M,invoice_id:P.id,notes:`استبدال ${R} نقطة بخصم ${u.toFixed(2)} دينار في الفاتورة ${x}`})]),console.log("✅ [InvoiceService] Loyalty points redeemed:",{pointsRedeemed:R,newPoints:M})}}catch(D){console.error("⚠️ [InvoiceService] Failed to process loyalty redemption:",D)}})()}l&&(console.log("📋 [InvoiceService] Logging audit trail for employee:",l),St(W.CREATE("audit_log"),"POST",{seller_id:i,employee_id:l,action_type:"create",entity_type:"invoice",entity_id:P.id,new_values:JSON.stringify({invoice_number:x,customer_name:t.customer_name,total_amount:y.taxInclusiveAmount,payment_method:t.payment_method}),notes:"إنشاء فاتورة جديدة من نظام POS"}).catch(R=>{console.error("⚠️ [InvoiceService] Failed to create audit log:",R)}));const S=r.map((R,D)=>{const $=b[D],M=Ke(R.quantity),X=Ke(R.unit_price),U=Ke($.roundingAmount);return{invoice_id:P.id,product_id:R.product_id||null,item_name:R.item_name,quantity:R.quantity,unit_price:R.unit_price,discount_amount:R.discount_amount||0,tax_percent:R.tax_percent||0,line_extension_amount:$.lineExtensionAmount,tax_amount:$.taxAmount,rounding_amount:$.roundingAmount,line_total:$.roundingAmount,line_number:D+1,xml_quantity:M,xml_unit_price:X,xml_line_total:U,price_before_tax:$.unitPriceBeforeTax,price_after_tax:$.unitPriceAfterTax,tax_category_code:R.tax_category_code,tax_calculation_mode:a}});console.log("💾 [InvoiceService] Inserting invoice items + background tasks in parallel...");const E=[];m&&E.push((async()=>{var R;try{const D=await St(W.GET_BY_ID("shifts",m));if(D.success&&D.data){const $=D.data,M=_,X=(Number($.total_sales)||0)+M,U=(Number($.total_invoices)||0)+1,Q=((R=t.payment_method)==null?void 0:R.toLowerCase())||"";let B=Number($.total_cash_sales)||0,z=Number($.total_card_sales)||0,H=Number($.total_credit_sales)||0;Q==="نقدي"||Q==="cash"?B+=M:Q==="بطاقة"||Q==="card"?z+=M:H+=M,await St(W.UPDATE("shifts",m),"POST",{total_sales:X,total_cash_sales:B,total_card_sales:z,total_credit_sales:H,total_invoices:U}),console.log("✅ [InvoiceService] Shift totals updated (parallel)")}}catch(D){console.error("⚠️ [InvoiceService] Failed to update shift totals:",D)}})()),l&&E.push(St(W.CREATE("audit_log"),"POST",{seller_id:i,employee_id:l,action_type:"create",entity_type:"invoice",entity_id:P.id,new_values:JSON.stringify({invoice_number:x,customer_name:t.customer_name,total_amount:y.taxInclusiveAmount,payment_method:t.payment_method}),notes:"إنشاء فاتورة جديدة من نظام POS"}).catch(R=>{console.error("⚠️ [InvoiceService] Failed to create audit log:",R)})),await Promise.all([Promise.all(S.map(R=>St(W.CREATE("invoice_items"),"POST",R))),...E.map(R=>R.catch(()=>{}))]),console.log("✅ [InvoiceService] All invoice items saved successfully");const O=t.is_return||!1;return Db(i,r,P.id,x,O,l).catch(R=>{console.error("⚠️ [InvoiceService] Failed to update inventory:",R)}),console.log("🎉 [InvoiceService] Invoice creation completed successfully"),P}catch(x){throw console.error("❌ [InvoiceService] Error creating invoice:",x),x}},Fb=t=>{switch(t){case"cash":return Ds;case"card":return Un;case"cliq":return Sr;case"bank_transfer":return Mo;case"credit":return Os;default:return gr}},Ub=t=>{switch(t){case"cash":return"text-green-600 bg-green-100 dark:bg-green-950/50";case"card":return"text-blue-600 bg-blue-100 dark:bg-blue-950/50";case"cliq":return"text-purple-600 bg-purple-100 dark:bg-purple-950/50";case"bank_transfer":return"text-cyan-600 bg-cyan-100 dark:bg-cyan-950/50";case"credit":return"text-orange-600 bg-orange-100 dark:bg-orange-950/50";default:return"text-gray-600 bg-gray-100 dark:bg-gray-950/50"}},zb=({open:t,onOpenChange:r,shift:n,currencySymbol:i="د.أ",cashVarianceThreshold:o=5,onSuccess:a,hasItemsInCart:s=!1,onCartWarning:c})=>{const{currentShift:l,closeShift:m,isClosingShift:u,sellerSettings:d,paymentBreakdown:h,cashDeposits:p,cashWithdrawals:f,getExpectedCashDrawer:x,getCashOnlySales:g}=$n(),b=n||l,[y,_]=v.useState(0),[j,I]=v.useState(""),[w,N]=v.useState(!1),C=Number(b==null?void 0:b.opening_cash)||0,A=g(),F=Number(b==null?void 0:b.total_sales)||0,T=Number(b==null?void 0:b.total_invoices)||0,k=x(),P=y-k,S=(d==null?void 0:d.cash_variance_threshold)||o,E=Math.abs(P)>S;v.useEffect(()=>{t&&(_(0),I(""),N(!1))},[t]),v.useEffect(()=>{t&&s&&(c==null||c())},[t,s,c]);const O=()=>{_(k),N(!0),Ge.success("تم تعبئة المبلغ المتوقع تلقائياً")},R=async()=>{await m(y,j)&&(r(!1),a==null||a())},D=M=>`${M.toFixed(2)} ${i}`,$=M=>F===0?0:(M/F*100).toFixed(0);return b?e.jsx(gt,{open:t,onOpenChange:r,children:e.jsxs(bt,{className:"max-w-lg max-h-[90vh]",dir:"rtl",children:[e.jsxs(Tt,{children:[e.jsxs(At,{className:"flex items-center gap-2 text-xl font-cairo",children:[e.jsx(Tn,{className:"h-5 w-5 text-primary"}),"إغلاق الشفت"]}),e.jsxs(kn,{className:"font-cairo",children:["شفت رقم ",b.shift_number]})]}),e.jsx(un,{className:"max-h-[60vh] pr-3",children:e.jsxs("div",{className:"space-y-4",children:[h.length>0&&e.jsxs("div",{className:"p-4 bg-muted/30 rounded-lg border",children:[e.jsxs("h4",{className:"font-semibold text-sm mb-3 flex items-center gap-2",children:[e.jsx(Os,{className:"h-4 w-4"}),"تفاصيل المبيعات حسب طريقة الدفع"]}),e.jsxs("div",{className:"space-y-2",children:[h.map(M=>{const X=Fb(M.method_code);return e.jsxs("div",{className:Z("flex items-center justify-between p-2 rounded-md",Ub(M.method_code)),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(X,{className:"h-4 w-4"}),e.jsx("span",{className:"font-medium text-sm",children:M.method_name}),e.jsxs("span",{className:"text-xs opacity-70",children:["(",M.invoice_count," فاتورة)"]}),M.affects_cash_drawer&&e.jsx("span",{className:"text-xs bg-primary/20 text-primary px-1.5 py-0.5 rounded",children:"نقدي"})]}),e.jsxs("div",{className:"text-left",children:[e.jsx("span",{className:"font-bold",children:D(M.total_amount)}),e.jsxs("span",{className:"text-xs opacity-70 mr-1",children:["(",$(M.total_amount),"%)"]})]})]},M.method_code)}),e.jsxs("div",{className:"border-t border-border/50 mt-2 pt-2 flex justify-between items-center font-bold",children:[e.jsx("span",{children:"إجمالي المبيعات"}),e.jsx("span",{className:"text-green-600",children:D(F)})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3 p-4 bg-muted/50 rounded-lg border",children:[e.jsxs("div",{className:"text-center p-3 bg-background rounded-md",children:[e.jsxs("div",{className:"flex items-center justify-center gap-1 text-muted-foreground text-sm mb-1",children:[e.jsx(gr,{className:"h-4 w-4"}),e.jsx("span",{children:"إجمالي المبيعات"})]}),e.jsx("p",{className:"font-bold text-lg text-green-600",children:D(F)})]}),e.jsxs("div",{className:"text-center p-3 bg-background rounded-md",children:[e.jsxs("div",{className:"flex items-center justify-center gap-1 text-muted-foreground text-sm mb-1",children:[e.jsx(It,{className:"h-4 w-4"}),e.jsx("span",{children:"عدد الفواتير"})]}),e.jsx("p",{className:"font-bold text-lg text-primary",children:T})]}),e.jsxs("div",{className:"text-center p-3 bg-background rounded-md",children:[e.jsxs("div",{className:"flex items-center justify-center gap-1 text-muted-foreground text-sm mb-1",children:[e.jsx(xr,{className:"h-4 w-4"}),e.jsx("span",{children:"المبلغ الافتتاحي"})]}),e.jsx("p",{className:"font-bold text-lg text-blue-600",children:D(C)})]}),e.jsxs("div",{className:"text-center p-3 bg-background rounded-md",children:[e.jsxs("div",{className:"flex items-center justify-center gap-1 text-muted-foreground text-sm mb-1",children:[e.jsx(Ds,{className:"h-4 w-4"}),e.jsx("span",{children:"مبيعات نقدية"})]}),e.jsx("p",{className:"font-bold text-lg text-emerald-600",children:D(A)})]})]}),e.jsxs("div",{className:"p-4 bg-amber-50 dark:bg-amber-950/30 rounded-lg border border-amber-200 dark:border-amber-800",children:[e.jsxs("h4",{className:"font-semibold text-amber-800 dark:text-amber-200 mb-2 flex items-center gap-2",children:[e.jsx($i,{className:"h-4 w-4"}),"حساب الدرج النقدي"]}),e.jsxs("div",{className:"space-y-1 text-sm",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{children:"المبلغ الافتتاحي:"}),e.jsx("span",{className:"font-mono",children:D(C)})]}),e.jsxs("div",{className:"flex justify-between text-green-600",children:[e.jsx("span",{children:"+ مبيعات نقدية:"}),e.jsx("span",{className:"font-mono",children:D(A)})]}),p>0&&e.jsxs("div",{className:"flex justify-between text-blue-600",children:[e.jsx("span",{children:"+ إيداعات:"}),e.jsx("span",{className:"font-mono",children:D(p)})]}),f>0&&e.jsxs("div",{className:"flex justify-between text-red-600",children:[e.jsx("span",{children:"- سحوبات:"}),e.jsx("span",{className:"font-mono",children:D(f)})]}),e.jsx("div",{className:"border-t border-amber-300 dark:border-amber-700 my-2"}),e.jsxs("div",{className:"flex justify-between font-bold text-amber-800 dark:text-amber-200 text-base",children:[e.jsx("span",{children:"المتوقع في الدرج:"}),e.jsx("span",{className:"font-mono",children:D(k)})]})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(_e,{htmlFor:"closing-cash",className:"font-cairo",children:"المبلغ الفعلي في الدرج"}),e.jsxs(V,{type:"button",variant:"outline",size:"sm",onClick:O,className:"gap-1 text-xs h-7",children:[e.jsx(qi,{className:"h-3 w-3"}),"المبلغ مطابق"]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(gr,{className:"absolute right-3 top-1/2 -translate-y-1/2 h-5 w-5 text-muted-foreground"}),e.jsx(Te,{id:"closing-cash",type:"number",step:"0.01",value:y,onChange:M=>{_(parseFloat(M.target.value)||0),N(!1)},className:Z("pr-10 text-lg h-12 font-mono",w&&"border-green-500 bg-green-50"),placeholder:"0.00"})]}),y>0&&E&&e.jsxs("div",{className:"p-3 bg-red-50 dark:bg-red-950/30 border border-red-200 dark:border-red-800 rounded-lg",children:[e.jsxs("div",{className:"flex items-center gap-2 text-red-700 dark:text-red-300",children:[e.jsx(Zt,{className:"h-5 w-5"}),e.jsxs("span",{className:"font-semibold",children:["فرق كبير في الكاش: ",D(P)]})]}),e.jsx("p",{className:"text-sm text-red-600 dark:text-red-400 mt-1",children:"يرجى مراجعة المبلغ أو إضافة ملاحظة توضيحية"})]}),y>0&&!E&&e.jsx("div",{className:Z("p-2 rounded-lg text-center",P===0?"bg-green-100 dark:bg-green-950/30 text-green-700 dark:text-green-300":"bg-amber-100 dark:bg-amber-950/30 text-amber-700 dark:text-amber-300"),children:e.jsxs("span",{className:"font-semibold",children:["الفرق: ",D(P),P===0&&" ✓ مطابق"]})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(_e,{htmlFor:"notes",className:"font-cairo",children:"ملاحظات (اختياري)"}),e.jsx(Is,{id:"notes",value:j,onChange:M=>I(M.target.value),placeholder:"أي ملاحظات على الشفت...",className:"font-cairo resize-none",rows:2})]})]})}),e.jsxs(Vi,{className:"gap-2 sm:gap-0",children:[e.jsx(V,{variant:"outline",onClick:()=>r(!1),disabled:u,className:"font-cairo",children:"إلغاء"}),e.jsx(V,{onClick:R,disabled:u||y<0,className:"bg-gradient-to-r from-red-500 to-red-600 hover:from-red-600 hover:to-red-700 font-cairo gap-2",children:u?e.jsxs(e.Fragment,{children:[e.jsx(ct,{className:"h-4 w-4 animate-spin"}),"جاري الإغلاق..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Tn,{className:"h-4 w-4"}),"إغلاق الشفت"]})})]})]})}):null},Bb=({currencySymbol:t="د.أ",onCloseShift:r})=>{const{currentShift:n,getShiftDuration:i,isShiftOvertime:o,refreshShift:a,isClosingShift:s}=$n(),[c,l]=v.useState(i()),[m,u]=v.useState(!1),[d,h]=v.useState(!1),p=v.useRef((n==null?void 0:n.total_invoices)||0),f=o();v.useEffect(()=>{const y=(n==null?void 0:n.total_invoices)||0;y>p.current&&(h(!0),setTimeout(()=>h(!1),600)),p.current=y},[n==null?void 0:n.total_invoices]),v.useEffect(()=>{l(i());const y=setInterval(()=>{l(i())},6e4);return()=>clearInterval(y)},[i]);const x=async()=>{u(!0),await a(),u(!1)},g=()=>c?c.hours===0?`${c.minutes} دقيقة`:`${c.hours} ساعة ${c.minutes>0?`و ${c.minutes} دقيقة`:""}`:"0 دقيقة",b=y=>`${(Number(y)||0).toFixed(2)} ${t}`;return n?e.jsx("div",{className:Z("border-b px-4 py-2 transition-colors",f?"bg-gradient-to-r from-red-50 to-orange-50 dark:from-red-950/30 dark:to-orange-950/30 border-red-200 dark:border-red-800":"bg-gradient-to-r from-blue-50 to-indigo-50 dark:from-blue-950/30 dark:to-indigo-950/30 border-blue-200 dark:border-blue-800"),children:e.jsxs("div",{className:"flex items-center justify-between gap-2 flex-wrap",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(Ae,{variant:"outline",className:Z("gap-1 font-mono",f?"border-red-300 bg-red-100 text-red-800 dark:border-red-700 dark:bg-red-900/50 dark:text-red-200":"border-blue-300 bg-blue-100 text-blue-800 dark:border-blue-700 dark:bg-blue-900/50 dark:text-blue-200"),children:[e.jsx(wm,{className:"h-3 w-3"}),e.jsx("span",{className:"hidden sm:inline",children:"شفت "}),n.shift_number]}),e.jsx(V,{variant:"ghost",size:"icon",onClick:x,disabled:m,className:"h-7 w-7 p-0",title:"تحديث بيانات الشفت",children:e.jsx(_r,{className:Z("h-3.5 w-3.5",m&&"animate-spin")})})]}),e.jsxs("div",{className:"flex items-center gap-3 sm:gap-4 text-sm flex-wrap",children:[e.jsxs("div",{className:Z("flex items-center gap-1.5",f?"text-red-700 dark:text-red-300":"text-muted-foreground"),children:[f?e.jsx(Zt,{className:"h-4 w-4 text-red-500 animate-pulse"}):e.jsx(xr,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:g()}),e.jsx("span",{className:"sm:hidden",children:c?`${c.hours}:${c.minutes.toString().padStart(2,"0")}`:"0:00"})]}),e.jsxs("div",{className:"flex items-center gap-1.5 text-green-700 dark:text-green-400",children:[e.jsx(gr,{className:"h-4 w-4"}),e.jsx("span",{className:"font-semibold",children:b(n.total_sales||0)})]}),e.jsxs("div",{className:Z("flex items-center gap-1.5 transition-all duration-300",d?"text-blue-600 dark:text-blue-400 scale-110":"text-muted-foreground"),children:[e.jsx(It,{className:Z("h-4 w-4",d&&"animate-bounce")}),e.jsx("span",{className:Z("font-bold tabular-nums transition-all",d&&"text-blue-600 dark:text-blue-400"),children:n.total_invoices||0}),e.jsx("span",{className:"hidden sm:inline",children:"فاتورة"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[f&&e.jsxs(Ae,{variant:"destructive",className:"gap-1 animate-pulse",children:[e.jsx(Zt,{className:"h-3 w-3"}),e.jsx("span",{className:"hidden sm:inline",children:"تجاوز الحد الأقصى"}),e.jsx("span",{className:"sm:hidden",children:"تجاوز"})]}),r&&e.jsxs(V,{variant:"destructive",size:"sm",onClick:r,disabled:s,className:"gap-1.5 h-8 px-3 bg-red-500 hover:bg-red-600 shadow-sm",children:[s?e.jsx(ct,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(Tn,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"hidden sm:inline",children:"إغلاق الشفت"}),e.jsx("span",{className:"sm:hidden",children:"إغلاق"})]})]})]})}):null},qb=t=>{v.useEffect(()=>{const r=n=>{var o,a,s,c,l,m,u,d,h,p,f,x;const i=n.target;if(i.tagName==="INPUT"||i.tagName==="TEXTAREA"){n.key==="Escape"&&t.cancel&&(n.preventDefault(),t.cancel());return}switch(n.key){case"F1":n.preventDefault(),(o=t.newSale)==null||o.call(t);break;case"F2":n.preventDefault(),(a=t.checkout)==null||a.call(t);break;case"F3":n.preventDefault(),(s=t.scanBarcode)==null||s.call(t);break;case"F4":n.preventDefault(),(c=t.searchProduct)==null||c.call(t);break;case"F5":n.preventDefault(),(l=t.calculator)==null||l.call(t);break;case"F7":n.preventDefault(),(m=t.printInvoice)==null||m.call(t);break;case"F8":n.preventDefault(),(u=t.clearCart)==null||u.call(t);break;case"F9":n.preventDefault(),(d=t.cashDrawer)==null||d.call(t);break;case"F10":n.preventDefault(),(h=t.shiftReport)==null||h.call(t);break;case"Escape":n.preventDefault(),(p=t.cancel)==null||p.call(t);break}(n.ctrlKey||n.metaKey)&&n.key==="s"&&(n.preventDefault(),(f=t.quickSave)==null||f.call(t)),(n.ctrlKey||n.metaKey)&&n.key==="p"&&(n.preventDefault(),(x=t.printInvoice)==null||x.call(t))};return window.addEventListener("keydown",r),()=>window.removeEventListener("keydown",r)},[t])},Vb=async(t,r)=>{try{console.log(`🔄 Processing QR code for invoice: ${t}`);const n=localStorage.getItem(xe),i=await fetch(`${nt}${W.GET_BY_ID("invoices",t)}`,{headers:n?{Authorization:`Bearer ${n}`}:{}});if(!i.ok)throw console.error(`❌ Error fetching invoice ${t}`),new Error("Failed to fetch invoice");const a=(await i.json()).data;if(!a){console.error(`❌ Invoice not found: ${t}`);return}if(a.is_duplicate){console.log(`⏭️ Skipping QR generation for duplicate invoice: ${a.invoice_number}`);return}if(a.qr_code){console.log(`⏭️ QR code already exists for invoice: ${a.invoice_number}, skipping to prevent overwrite`);return}const s=qt(r);if(!s){console.warn(`⚠️ No QR data found in API response for invoice: ${t}`);return}const c=Nl(s);if(!(await fetch(`${nt}${W.UPDATE("invoices",t)}`,{method:"POST",headers:{"Content-Type":"application/json",...n?{Authorization:`Bearer ${n}`}:{}},body:JSON.stringify({qr_code:s,qr_code_image:c})})).ok)throw console.error(`❌ Error updating invoice ${t} with QR code`),new Error("Failed to update invoice with QR code");console.log(`✅ QR code processed and saved for invoice: ${a.invoice_number}`)}catch(n){throw console.error(`❌ Error processing QR code for invoice ${t}:`,n),n}},Gb=({isFullscreen:t=!1,onToggleFullscreen:r}={})=>{const{toast:n}=et(),{data:i=[],isLoading:o,updateCartStockOptimistically:a,forceRefetch:s}=la(),{data:c=[]}=kl(),{categories:l}=fa(Mt()),m=Mt();Ot();const{currentEmployee:u,logout:d,hasPermission:h,updateActivity:p}=lt(),{currentShift:f,getShiftDuration:x,isShiftOvertime:g,isShiftsEnabled:b,refreshShift:y,isClosingShift:_,incrementInvoiceCount:j}=$n(),{isOnline:I}=jr(),[w,N]=v.useState(null),[C,A]=v.useState(!u),[F,T]=v.useState("income"),[k,P]=v.useState("tax_exclusive"),[S,E]=v.useState([]),[O,R]=v.useState(""),[D,$]=v.useState(null);v.useState("نقدي");const[M,X]=v.useState(!1),[U,Q]=v.useState(!1),[B,z]=v.useState(""),[H,Y]=v.useState("");v.useState(!0);const[J,ie]=v.useState(!1),[ce,ke]=v.useState(""),[be,Se]=v.useState(!1),[je,Re]=v.useState(!1),[We,se]=v.useState(""),[q,ne]=v.useState(!1),[re,de]=v.useState(null),[ze,Ce]=v.useState(!1),[st,ot]=v.useState(0),[dt,L]=v.useState(!1),[K,ge]=v.useState(!1),[Fe,He]=v.useState(null),Pe=v.useRef(null),[Ze,Wt]=v.useState(new Date),[rr,Qn]=v.useState(void 0),[gn,_a]=v.useState(!1),[Hd,wa]=v.useState(!1),[Wd,Zn]=v.useState(!1),[Xd,es]=v.useState(""),[Jd,ja]=v.useState("");v.useEffect(()=>{const ee=setInterval(()=>Wt(new Date),6e4);return()=>clearInterval(ee)},[]),v.useEffect(()=>{m&&(console.log("POSSystem - forcing products refetch for seller:",m),s())},[m,s]),v.useEffect(()=>{A(!u)},[u]),v.useEffect(()=>{if(u&&Pe.current){const ee=setTimeout(()=>{var ue;(ue=Pe.current)==null||ue.focus()},100);return()=>clearTimeout(ee)}},[u]);const Kd=v.useMemo(()=>{const ee={total:i.length};return i.forEach(ue=>{ue.category_id&&(ee[ue.category_id]=(ee[ue.category_id]||0)+1)}),ee},[i]);v.useEffect(()=>{const ee=Ne=>{if(Ne.key==="F11"){Ne.preventDefault(),(async()=>{try{document.fullscreenElement?await document.exitFullscreen():await document.documentElement.requestFullscreen()}catch(le){console.log("Fullscreen API error:",le),r==null||r()}})();return}if(Ne.ctrlKey&&Ne.key>="0"&&Ne.key<="9"){Ne.preventDefault();const le=parseInt(Ne.key);le===0?$(null):l[le-1]&&$(l[le-1].id)}},ue=()=>{!!document.fullscreenElement!==t&&(r==null||r())};return window.addEventListener("keydown",ee),document.addEventListener("fullscreenchange",ue),()=>{window.removeEventListener("keydown",ee),document.removeEventListener("fullscreenchange",ue)}},[l,t,r]),v.useEffect(()=>{m&&Yd()},[m]);const Yd=async()=>{if(m)try{const ee=localStorage.getItem(xe),ue=await fetch(`${oe()}${W.GET_BY_ID("sellers",m)}`,{headers:ee?{Authorization:`Bearer ${ee}`}:{}});if(!ue.ok){console.error("❌ [POS] Error fetching seller");return}const Ne=await ue.json();if(Ne.success&&Ne.data){const le=Ne.data;le.show_cashier_name=le.show_cashier_name==1||le.show_cashier_name===!0||le.show_cashier_name==="1",le.enable_thermal_printing=le.enable_thermal_printing==1||le.enable_thermal_printing===!0||le.enable_thermal_printing==="1",le.auto_print_thermal=le.auto_print_thermal==1||le.auto_print_thermal===!0||le.auto_print_thermal==="1",le.enable_fawatrah=le.enable_fawatrah==1||le.enable_fawatrah===!0||le.enable_fawatrah==="1",le.enable_bw_print=le.enable_bw_print==1||le.enable_bw_print===!0||le.enable_bw_print==="1",N(le);const Ue=le.invoice_type==="ضريبة عامة"||le.invoice_type==="مبيعات عامة"?"general_tax":"income";T(Ue),console.log("✅ [POS] Seller data loaded:",le),Ao(le.id).then(qe=>{Qn(qe),console.log("✅ [POS] Display settings cached")}).catch(qe=>console.warn("⚠️ [POS] Failed to cache display settings:",qe))}}catch(ee){console.error("❌ [POS] Error fetching seller:",ee)}},Qd=async ee=>{console.log("🔍 [POS] Searching for barcode:",ee);let ue=i.find(Ne=>Ne.barcode===ee);ue||(ue=i.find(Ne=>{var le;return Ne.product_name.toLowerCase().includes(ee.toLowerCase())||((le=Ne.sku)==null?void 0:le.toLowerCase())===ee.toLowerCase()})),ue?(Js(ue),Kr(),n({title:"✅ تمت الإضافة",description:`${ue.product_name}`,duration:1500})):(Et(),n({title:"❌ غير موجود",description:"لم يتم العثور على منتج بهذا الباركود أو الاسم",variant:"destructive",duration:2e3})),Re(!1),se(""),R(""),setTimeout(()=>{var Ne;return(Ne=Pe.current)==null?void 0:Ne.focus()},50)},Js=ee=>{if(!u){Et(),n({title:"يجب تسجيل الدخول",description:"يجب تسجيل دخول الموظف قبل البدء بالبيع",variant:"destructive"}),ne(!0);return}if(!h("can_access_pos")){Et(),n({title:"غير مصرح",description:"ليس لديك صلاحية الوصول لنظام POS",variant:"destructive"});return}if(console.log("🛒 [POS] Adding product to cart:",ee),ee.track_inventory&&ee.stock_quantity<=0){Et(),n({title:"غير متوفر",description:"هذا المنتج نفذ من المخزون",variant:"destructive"});return}const ue=S.find(Ne=>Ne.product_id===ee.id);if(Kr(),ue)Ks(ue.id,ue.quantity+1),He(ue.id);else{const Ne=F==="general_tax"?ee.tax_percent||16:0,le=F==="general_tax"?Ut(Ne):null,Ue=xt({quantity:1,unitPrice:Number(ee.unit_price)||0,discountAmount:0,taxPercent:Ne,taxCalculationMode:k}),qe={id:Date.now().toString(),product_id:ee.id,item_name:ee.product_name,quantity:1,unit_price:Number(ee.unit_price)||0,discount_amount:0,tax_percent:Ne,line_extension_amount:Ue.lineExtensionAmount,tax_amount:Ue.taxAmount,rounding_amount:Ue.roundingAmount,line_total:Ue.roundingAmount,price_before_tax:Ue.unitPriceBeforeTax,price_after_tax:Ue.unitPriceAfterTax,tax_category_code:le};E([...S,qe]),He(qe.id),p(),n({title:"تمت الإضافة",description:`${ee.product_name} تم إضافته للسلة`,duration:1e3})}setTimeout(()=>{var Ne;return(Ne=Pe.current)==null?void 0:Ne.focus()},50)},Ks=v.useCallback((ee,ue)=>{ue<1||(p(),E(Ne=>Ne.map(le=>{if(le.id===ee){const Ue=xt({quantity:ue,unitPrice:le.unit_price,discountAmount:le.discount_amount,taxPercent:le.tax_percent,taxCalculationMode:k});return{...le,quantity:ue,line_extension_amount:Ue.lineExtensionAmount,tax_amount:Ue.taxAmount,rounding_amount:Ue.roundingAmount,line_total:Ue.roundingAmount,price_before_tax:Ue.unitPriceBeforeTax,price_after_tax:Ue.unitPriceAfterTax}}return le})))},[k,p]),Na=v.useCallback(ee=>{E(ue=>ue.filter(Ne=>Ne.id!==ee))},[]),Ca=v.useCallback(()=>{E([]),R(""),de(null),ot(0),setTimeout(()=>{var ee;return(ee=Pe.current)==null?void 0:ee.focus()},50)},[]),ts=v.useMemo(()=>{const ee=S.map(le=>xt({quantity:le.quantity,unitPrice:le.unit_price,discountAmount:le.discount_amount,taxPercent:le.tax_percent,taxCalculationMode:k})),ue=lr(ee),Ne=Math.max(0,ue.taxInclusiveAmount-st);return{...ue,loyaltyDiscount:st,taxInclusiveAmount:Ne}},[S,k,st]),Ea=async(ee,ue,Ne)=>{if(!u){Et(),n({title:"يجب تسجيل الدخول",description:"يجب تسجيل دخول الموظف قبل إنشاء فاتورة",variant:"destructive"}),ne(!0);return}if(!h("can_create_invoices")){Et(),n({title:"غير مصرح",description:"ليس لديك صلاحية إنشاء الفواتير",variant:"destructive"});return}if(S.length===0){n({title:"خطأ",description:"السلة فارغة",variant:"destructive"});return}try{X(!0),console.log("🛒 [POS] Starting checkout with payment..."),console.log("💰 Paid:",ee,"Change:",ue,"Method:",Ne.method_name),p();const le=Ne.method_name,Ue={customer_id:(re==null?void 0:re.id)||"",customer_name:(re==null?void 0:re.customer_name)||"عميل نقدي",customer_number:(re==null?void 0:re.customer_number)||"0000000000",customer_type:(re==null?void 0:re.customer_type)||"NIN",phone_number:(re==null?void 0:re.phone_number)||"",city:(re==null?void 0:re.city)||"",payment_method:le,invoice_date:new Date().toISOString().split("T")[0]},qe=S.map(Xe=>({id:Xe.id,product_id:Xe.product_id,item_name:Xe.item_name,quantity:Xe.quantity,unit_price:Xe.unit_price,discount_amount:Xe.discount_amount,tax_percent:Xe.tax_percent,line_extension_amount:Xe.line_extension_amount,tax_amount:Xe.tax_amount,rounding_amount:Xe.rounding_amount,line_total:Xe.line_total,price_before_tax:Xe.price_before_tax,price_after_tax:Xe.price_after_tax,tax_category_code:Xe.tax_category_code}));if(!I){Et(),n({title:"⚠️ لا يوجد اتصال بالإنترنت",description:"يجب الاتصال بالإنترنت لإتمام عملية البيع. يرجى التحقق من اتصالك والمحاولة مرة أخرى.",variant:"destructive",duration:5e3}),X(!1);return}const it=await $b({invoiceData:Ue,items:qe,seller:w,sellerId:m,invoiceType:F,taxCalculationMode:k,notes:`مدفوع: ${ee.toFixed(2)} د.أ | الباقي: ${ue.toFixed(2)} د.أ`,status:"فاتورة جديدة - غير مرسلة",employeeId:u==null?void 0:u.id,shiftId:f==null?void 0:f.id,loyaltyDiscount:st,customerId:re==null?void 0:re.id,paymentMethodId:String(Ne.id),paidAmount:ee,changeAmount:ue});if(console.log("✅ [POS] Invoice created:",it),f!=null&&f.id&&(j(ts.taxInclusiveAmount,Ne.method_code,Ne.method_name,Ne.affects_cash_drawer),setTimeout(()=>{y().catch(Xe=>{console.warn("⚠️ [POS] Failed to refresh shift after invoice:",Xe)})},2e3)),w){console.log("📋 [POS] Generating thermal receipt with",qe.length,"items from cart");const Xe=Sl(it.invoice_number,it.total_amount||0,Ue,qe,it.qr_code||"",{is_return:!1},w,"",{tax_exclusive_amount:it.tax_exclusive_amount||0,total_tax_amount:it.total_tax_amount||0,allowance_charge_amount:it.allowance_charge_amount||0,tax_inclusive_amount:it.total_amount||0},void 0,{paidAmount:ee,changeAmount:ue},w!=null&&w.show_cashier_name&&u?u.employee_name:void 0,rr);ke(Xe),w!=null&&w.enable_thermal_printing&&(w!=null&&w.auto_print_thermal)?(ka(Xe),ie(!0)):ie(!1)}z(it.invoice_number),Y(it.id),f&&y(),Eo(),a(S.map(Xe=>({product_id:Xe.product_id,quantity:Xe.quantity}))),console.log("⚡ [POS] Inventory updated optimistically after sale"),E([]),de(null),ot(0),Q(!0),n({title:"تم إنشاء الفاتورة",description:`رقم الفاتورة: ${it.invoice_number}`})}catch(le){console.error("❌ [POS] Checkout error:",le),Et(),n({title:"خطأ",description:le instanceof Error?le.message:"فشل في إنشاء الفاتورة",variant:"destructive"})}finally{X(!1)}},[Nr,rs]=v.useState("idle"),Sa=ee=>{if(ee.key==="Enter"&&O.trim()){const ue=O.trim();console.log("🔍 [POS] Quick barcode search:",ue);const Ne=/^\d{4,}$/.test(ue)||/^[A-Za-z0-9-]{6,}$/.test(ue);let le=i.find(Ue=>Ue.barcode===ue);le||(le=i.find(Ue=>{var qe;return((qe=Ue.sku)==null?void 0:qe.toLowerCase())===ue.toLowerCase()})),!le&&!Ne&&(le=i.find(Ue=>Ue.product_name.toLowerCase().includes(ue.toLowerCase()))),le?(Js(le),Kr(),rs("success"),R(""),setTimeout(()=>rs("idle"),500),n({title:"✅ تمت الإضافة",description:`${le.product_name}`,duration:1500})):(Et(),rs("error"),setTimeout(()=>rs("idle"),500),n({title:"❌ غير موجود",description:`لم يتم العثور على منتج بالباركود: ${ue}`,variant:"destructive",duration:2e3})),setTimeout(()=>{var Ue;return(Ue=Pe.current)==null?void 0:Ue.focus()},50)}};v.useEffect(()=>{const ee=setTimeout(()=>{O&&/^\d{8,14}$/.test(O.trim())&&Sa({key:"Enter"})},300);return()=>clearTimeout(ee)},[O]);const ka=ee=>{const ue=window.open("","_blank","width=400,height=600");ue&&(ue.document.write(ee),ue.document.close(),ue.onload=()=>{setTimeout(()=>{ue.focus(),ue.print()},300)})},Zd=()=>{ce&&ka(ce)},eu=async()=>{if(!(!H||!w)){_a(!0);try{const ee=localStorage.getItem(xe),le=(await(await fetch(`${oe()}${W.GET_BY_ID("invoices",H)}`,{headers:ee?{Authorization:`Bearer ${ee}`}:{}})).json()).data;if(!(le!=null&&le.encoded_xml))throw new Error("لا يوجد XML للفاتورة");const qe=await(await fetch(`${oe()}government-invoice.php`,{method:"POST",headers:{"Content-Type":"application/json",...ee?{Authorization:`Bearer ${ee}`}:{}},body:JSON.stringify({invoice_number:B,xml_base64:le.encoded_xml,seller_id:m})})).json();if(await fetch(`${oe()}${W.UPDATE("invoices",H)}`,{method:"POST",headers:{"Content-Type":"application/json",...ee?{Authorization:`Bearer ${ee}`}:{}},body:JSON.stringify({api_response:JSON.stringify(qe),status:qe!=null&&qe.success?"مرسلة":"فشل الإرسال"})}),qe!=null&&qe.success){await Vb(H,qe);const it=qt(qe);if(it&&(ja(it),ce)){const Xe=`
              <div class="qr-section" style="text-align:center;margin-top:15px;padding:10px;border-top:1px dashed #333;">
                <p style="font-weight:bold;margin-bottom:8px;font-size:12px;">رمز التحقق:</p>
                <img src="https://api.qrserver.com/v1/create-qr-code/?size=150x150&data=${encodeURIComponent(it)}" 
                     alt="QR Code" style="width:120px;height:120px;">
              </div>
            `;let Ys=ce;ce.includes('<div class="footer">')?Ys=ce.replace('<div class="footer">',`${Xe}<div class="footer">`):ce.includes("</body>")&&(Ys=ce.replace("</body>",`${Xe}</body>`)),ke(Ys)}wa(!0),Zn(!1),es(""),Eo(),n({title:"تم الإرسال بنجاح",description:`تم إرسال الفاتورة ${B} للنظام الحكومي`})}else{const it=(qe==null?void 0:qe.error)||(qe==null?void 0:qe.message)||"حدث خطأ أثناء الإرسال";Zn(!0),es(it),Et(),n({title:"فشل الإرسال",description:it,variant:"destructive"})}}catch(ee){const ue=ee.message||"فشل في إرسال الفاتورة";Zn(!0),es(ue),Et(),n({title:"خطأ في الإرسال",description:ue,variant:"destructive"})}finally{_a(!1)}}},tu=S.reduce((ee,ue)=>ee+ue.quantity,0),ru=v.useMemo(()=>i.filter(ee=>{var le,Ue;const ue=!O||ee.product_name.toLowerCase().includes(O.toLowerCase())||((le=ee.barcode)==null?void 0:le.toLowerCase().includes(O.toLowerCase()))||((Ue=ee.sku)==null?void 0:Ue.toLowerCase().includes(O.toLowerCase())),Ne=!D||ee.category_id===D;return ue&&Ne}),[i,O,D]);qb({searchProduct:()=>{var ee;return(ee=Pe.current)==null?void 0:ee.focus()},newSale:Ca,checkout:S.length>0?()=>{}:void 0,scanBarcode:()=>Re(ee=>!ee)});const nu=(ee,ue)=>{ot(ue),L(!1),n({title:"تم استبدال النقاط",description:`تم خصم ${ue.toFixed(2)} د.أ من الفاتورة`})};return e.jsxs("div",{className:Z("flex flex-col h-full",t&&"fixed inset-0 z-50 bg-background"),dir:"rtl",children:[e.jsxs("div",{className:"flex items-center justify-between p-4 border-b bg-card",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("h1",{className:"text-xl font-bold",children:"نقطة البيع"}),t&&e.jsx(Ae,{variant:"secondary",className:"animate-pulse",children:"وضع ملء الشاشة"}),u&&!t&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2 px-4 py-2 bg-gradient-to-r from-green-500 to-emerald-600 text-white rounded-full shadow-lg ring-2 ring-green-400/50",children:[e.jsxs("span",{className:"relative flex h-3 w-3",children:[e.jsx("span",{className:"animate-ping absolute inline-flex h-full w-full rounded-full bg-green-300 opacity-75"}),e.jsx("span",{className:"relative inline-flex rounded-full h-3 w-3 bg-green-200"})]}),e.jsx(Bt,{className:"h-4 w-4"}),e.jsx("span",{className:"font-bold",children:u.employee_name}),e.jsx(Ae,{className:Z("text-white text-xs",u.role==="admin"&&"bg-red-500",u.role==="manager"&&"bg-amber-500",u.role==="cashier"&&"bg-blue-500",u.role==="inventory_manager"&&"bg-teal-500",u.role==="accountant"&&"bg-purple-500",!["admin","manager","cashier","inventory_manager","accountant"].includes(u.role)&&"bg-gray-500"),children:u.role==="admin"?"مدير النظام":u.role==="manager"?"مشرف":u.role==="cashier"?"أمين صندوق":u.role==="inventory_manager"?"مدير مخزون":u.role==="accountant"?"محاسب":"موظف"})]}),e.jsxs(V,{variant:"destructive",size:"sm",onClick:d,className:"gap-2 bg-red-500 hover:bg-red-600 shadow-md hover:shadow-lg transition-all hover:scale-105",children:[e.jsx(rn,{className:"h-4 w-4"}),"خروج"]})]}),u&&t&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2 px-4 py-2 bg-gradient-to-r from-green-500 to-emerald-600 text-white rounded-full shadow-lg ring-2 ring-green-400/50",children:[e.jsxs("span",{className:"relative flex h-3 w-3",children:[e.jsx("span",{className:"animate-ping absolute inline-flex h-full w-full rounded-full bg-green-300 opacity-75"}),e.jsx("span",{className:"relative inline-flex rounded-full h-3 w-3 bg-green-200"})]}),e.jsx(Bt,{className:"h-4 w-4"}),e.jsx("span",{className:"font-bold",children:u.employee_name}),e.jsx(Ae,{className:Z("text-white text-xs",u.role==="admin"&&"bg-red-500",u.role==="manager"&&"bg-amber-500",u.role==="cashier"&&"bg-blue-500",!["admin","manager","cashier"].includes(u.role)&&"bg-gray-500"),children:u.role==="admin"?"مدير":u.role==="manager"?"مشرف":u.role==="cashier"?"كاشير":"موظف"})]}),e.jsxs("div",{className:"flex items-center gap-2 px-3 py-1.5 bg-blue-500/90 text-white rounded-full text-sm",children:[e.jsx(oc,{className:"h-4 w-4"}),e.jsx("span",{children:Ze.toLocaleDateString("ar-JO",{weekday:"short",day:"numeric",month:"short"})})]}),e.jsxs("div",{className:"flex items-center gap-2 px-3 py-1.5 bg-purple-500/90 text-white rounded-full text-sm font-mono",children:[e.jsx(xr,{className:"h-4 w-4"}),e.jsx("span",{children:Ze.toLocaleTimeString("ar-JO",{hour:"2-digit",minute:"2-digit"})})]}),e.jsxs(V,{variant:"destructive",size:"sm",onClick:d,className:"gap-2 bg-red-500 hover:bg-red-600 shadow-md hover:shadow-lg transition-all",children:[e.jsx(rn,{className:"h-4 w-4"}),"خروج"]})]}),!u&&!t&&e.jsxs(V,{variant:"outline",size:"sm",onClick:()=>ne(!0),className:"gap-2",children:[e.jsx(xu,{className:"h-4 w-4"}),"تسجيل دخول"]})]}),e.jsx("div",{className:"flex items-center gap-2",children:r&&e.jsx(V,{variant:"outline",size:"icon",onClick:async()=>{try{document.fullscreenElement?await document.exitFullscreen():await document.documentElement.requestFullscreen()}catch{console.log("Fullscreen API not supported, using internal mode"),r()}},className:Z("transition-all",t&&"hover:scale-105"),title:t?"خروج من ملء الشاشة (F11)":"ملء الشاشة (F11)",children:t?e.jsx(at,{className:"h-5 w-5"}):e.jsx(Tm,{className:"h-5 w-5"})})})]}),b()&&f&&e.jsx(Bb,{currencySymbol:(w==null?void 0:w.currency_symbol)||"د.أ",onCloseShift:()=>{if(S.length>0){n({title:"⚠️ يوجد منتجات في السلة",description:"يرجى إتمام البيع أو إفراغ السلة قبل إغلاق الشفت",variant:"destructive"});return}ge(!0)}}),!I&&e.jsx("div",{className:"bg-destructive/10 border-b-2 border-destructive px-4 py-4",children:e.jsxs("div",{className:"flex items-center justify-center gap-3",children:[e.jsx(Bo,{className:"h-6 w-6 text-destructive animate-pulse"}),e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"text-destructive font-bold text-lg",children:"⚠️ لا يوجد اتصال بالإنترنت"}),e.jsx("p",{className:"text-destructive/80 text-sm",children:"البيع غير متاح حالياً - يرجى التحقق من اتصالك بالإنترنت"})]})]})}),C&&!u&&e.jsx("div",{className:"bg-yellow-50 border-b border-yellow-200 p-3 text-center",children:e.jsxs("p",{className:"text-yellow-800 text-sm",children:["يجب تسجيل دخول الموظف للبدء بالبيع",e.jsx(V,{variant:"link",className:"text-yellow-900 font-bold mx-2",onClick:()=>ne(!0),children:"تسجيل الدخول"})]})}),e.jsxs("div",{className:"flex-1 flex overflow-hidden",children:[e.jsxs("div",{className:Z("flex-1 flex flex-col overflow-hidden",t?"lg:w-[50%]":"lg:w-[60%]"),children:[e.jsxs("div",{className:"p-4 border-b bg-card space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:Z("relative flex-1 transition-all duration-200",Nr==="success"&&"ring-2 ring-green-500 rounded-md",Nr==="error"&&"ring-2 ring-red-500 rounded-md animate-shake"),children:[e.jsx(En,{className:Z("absolute right-3 top-1/2 -translate-y-1/2 h-5 w-5 transition-colors",Nr==="idle"&&"text-muted-foreground",Nr==="success"&&"text-green-500",Nr==="error"&&"text-red-500")}),e.jsx(Te,{ref:Pe,placeholder:"🔍 مسح باركود أو اسم المنتج + Enter",value:O,onChange:ee=>R(ee.target.value),onKeyDown:Sa,className:Z("pr-11 text-lg h-12 font-mono transition-all",Nr==="success"&&"bg-green-50 border-green-500",Nr==="error"&&"bg-red-50 border-red-500"),autoComplete:"off",autoFocus:!0}),O&&e.jsx(V,{variant:"ghost",size:"icon",className:"absolute left-2 top-1/2 -translate-y-1/2 h-7 w-7",onClick:()=>{var ee;R(""),(ee=Pe.current)==null||ee.focus()},children:e.jsx(at,{className:"h-4 w-4"})})]}),e.jsx(V,{variant:"outline",size:"icon",onClick:()=>Re(!0),title:"مسح باركود بالكاميرا",className:"h-12 w-12",children:e.jsx(Ls,{className:"h-6 w-6"})})]}),e.jsx(pa,{categories:l,selectedCategoryId:D,onSelectCategory:$,productsCount:Kd})]}),e.jsx("div",{className:"flex-1 overflow-auto p-4",children:e.jsx(Vd,{products:ru,onProductSelect:Js,searchTerm:"",selectedCategoryId:D,isLoading:o})})]}),e.jsx("div",{className:Z("hidden lg:flex flex-col border-r bg-card overflow-hidden h-full",t?"lg:w-[50%]":"lg:w-[40%]"),children:e.jsx(ko,{items:S,totals:ts,onUpdateQuantity:Ks,onRemoveItem:Na,onCheckoutWithPayment:Ea,isProcessing:M,loyaltyDiscount:st,selectedCustomer:re?{id:re.id,name:re.customer_name}:null,customers:c.map(ee=>({id:ee.id,customer_name:ee.customer_name,phone_number:ee.phone_number})),onSelectCustomer:ee=>{de(ee&&c.find(ue=>ue.id===ee.id)||null)},customerSearchOpen:ze,setCustomerSearchOpen:Ce,lastAddedItemId:Fe})})]}),e.jsx("div",{className:"lg:hidden fixed bottom-4 left-4 right-4 z-40",children:e.jsxs(Ld,{open:be,onOpenChange:Se,children:[e.jsx(Dd,{asChild:!0,children:e.jsxs(V,{className:"w-full h-14 text-lg gap-3 shadow-lg",size:"lg",children:[e.jsx(Xr,{className:"h-6 w-6"}),e.jsxs("span",{children:["السلة (",tu,")"]}),e.jsxs("span",{className:"font-bold",children:[ts.taxInclusiveAmount.toFixed(2)," د.أ"]})]})}),e.jsx(va,{side:"bottom",className:"h-[85vh] p-0",children:e.jsx(ko,{items:S,totals:ts,onUpdateQuantity:Ks,onRemoveItem:Na,onCheckoutWithPayment:Ea,isProcessing:M,isMobile:!0,loyaltyDiscount:st,selectedCustomer:re?{id:re.id,name:re.customer_name}:null,customers:c.map(ee=>({id:ee.id,customer_name:ee.customer_name,phone_number:ee.phone_number})),onSelectCustomer:ee=>{de(ee&&c.find(ue=>ue.id===ee.id)||null)},customerSearchOpen:ze,setCustomerSearchOpen:Ce,lastAddedItemId:Fe})})]})}),t&&e.jsx("div",{className:"fixed bottom-4 left-1/2 -translate-x-1/2 bg-black/70 text-white px-4 py-2 rounded-full text-sm z-50",children:"اضغط ESC للخروج من ملء الشاشة"}),je&&e.jsx(Al,{onDetected:ee=>{Qd(ee),Re(!1)},onClose:()=>Re(!1)}),e.jsx(Rb,{open:U,onClose:()=>{Q(!1),wa(!1),Zn(!1),es(""),ja(""),Ca(),setTimeout(()=>{var ee;return(ee=Pe.current)==null?void 0:ee.focus()},100)},invoiceNumber:B,invoiceId:H,thermalPreviewHTML:ce,thermalPrintingEnabled:(w==null?void 0:w.enable_thermal_printing)||!1,autoPrinted:J,onPrintThermal:Zd,onViewInvoice:()=>{Q(!1),setTimeout(()=>{var ee;return(ee=Pe.current)==null?void 0:ee.focus()},100)},onSendToGovernment:eu,isSendingToGov:gn,sentToGov:Hd,sendToGovFailed:Wd,sendToGovError:Xd,qrCode:Jd,fawatrahEnabled:(w==null?void 0:w.enable_fawatrah)===!0}),e.jsx(Pb,{open:q,onOpenChange:ne}),re&&e.jsx(Lb,{open:dt,onOpenChange:L,customerId:re.id,customerName:re.customer_name||"عميل",availablePoints:re.loyalty_points||0,onRedeemSuccess:ee=>nu(0,ee),mode:"preview"}),e.jsx(zb,{open:K,onOpenChange:ge,currencySymbol:(w==null?void 0:w.currency_symbol)||"د.أ",hasItemsInCart:S.length>0,onCartWarning:()=>{n({title:"⚠️ يوجد منتجات في السلة",description:"يرجى إتمام البيع أو إفراغ السلة قبل إغلاق الشفت",variant:"destructive"})},onSuccess:()=>{y()}})]})},Hb=({shiftOwnerName:t,shiftNumber:r,currentEmployeeName:n,onLogout:i})=>e.jsx("div",{className:"min-h-[80vh] flex items-center justify-center p-4",dir:"rtl",children:e.jsxs(fe,{className:"w-full max-w-md border-2 border-red-300 bg-gradient-to-br from-red-50 to-orange-50 dark:from-red-950/30 dark:to-orange-950/30 shadow-xl",children:[e.jsxs(De,{className:"text-center pb-2",children:[e.jsx("div",{className:"mx-auto mb-4 w-20 h-20 rounded-full bg-red-100 dark:bg-red-900/50 flex items-center justify-center",children:e.jsx(Bi,{className:"h-10 w-10 text-red-600"})}),e.jsx($e,{className:"text-2xl font-bold text-red-800 dark:text-red-200 font-cairo",children:"لا يمكنك الدخول حالياً"}),e.jsx(kr,{className:"text-red-700 dark:text-red-300 font-cairo text-base",children:"يوجد شفت مفتوح لموظف آخر"})]}),e.jsxs(ve,{className:"space-y-6",children:[e.jsx("div",{className:"bg-white dark:bg-background/50 rounded-lg p-4 border border-gray-200",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-12 h-12 rounded-full bg-gray-100 flex items-center justify-center",children:e.jsx(Bt,{className:"h-6 w-6 text-gray-500"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground font-cairo",children:"أنت"}),e.jsx("p",{className:"font-semibold font-cairo",children:n})]})]})}),e.jsx("div",{className:"bg-amber-50 dark:bg-amber-950/30 rounded-lg p-4 border-2 border-amber-300",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-12 h-12 rounded-full bg-amber-100 flex items-center justify-center",children:e.jsx(xr,{className:"h-6 w-6 text-amber-600"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-sm text-amber-700 dark:text-amber-300 font-cairo",children:"الشفت مفتوح باسم"}),e.jsx("p",{className:"font-bold text-amber-800 dark:text-amber-200 font-cairo text-lg",children:t}),r&&e.jsx(Ae,{variant:"outline",className:"mt-1 border-amber-400 text-amber-700",children:r})]})]})}),e.jsxs("div",{className:"flex items-start gap-3 p-4 bg-blue-50 dark:bg-blue-950/30 rounded-lg border border-blue-200",children:[e.jsx(Zt,{className:"h-5 w-5 text-blue-600 mt-0.5 flex-shrink-0"}),e.jsxs("div",{className:"text-sm text-blue-700 dark:text-blue-300 font-cairo space-y-1",children:[e.jsx("p",{className:"font-semibold",children:"ما الذي يجب فعله؟"}),e.jsxs("ul",{className:"list-disc list-inside space-y-1 text-blue-600 dark:text-blue-400",children:[e.jsxs("li",{children:["اطلب من ",e.jsx("strong",{children:t})," إغلاق شفته أولاً"]}),e.jsx("li",{children:"أو تواصل مع المدير لإغلاق الشفت نيابةً عنه"})]})]})]}),e.jsxs(V,{onClick:i,variant:"outline",size:"lg",className:"w-full h-14 text-lg font-bold border-2 border-red-300 text-red-700 hover:bg-red-50 hover:text-red-800 font-cairo",children:[e.jsx(rn,{className:"ml-2 h-6 w-6"}),"تسجيل الخروج واختيار موظف آخر"]}),e.jsx("p",{className:"text-center text-xs text-muted-foreground font-cairo",children:"ملاحظة: المديرون والمالكون يمكنهم الدخول والإشراف حتى لو كان الشفت لموظف آخر"})]})]})}),Wb=({children:t})=>{const{currentShift:r,sellerSettings:n,isLoading:i,isOpeningShift:o,openShift:a,isShiftsEnabled:s,canAccessWithOthersShift:c,getShiftOwnerName:l}=$n(),{currentEmployee:m,logout:u}=lt(),[d,h]=v.useState(0),p=async()=>{await a(d),h(0)};return i&&!n?e.jsxs("div",{className:"animate-pulse p-4",dir:"rtl",children:[e.jsx("div",{className:"h-16 bg-muted rounded-lg mb-4"}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[...Array(8)].map((f,x)=>e.jsx("div",{className:"h-32 bg-muted rounded-lg"},x))})]}):s()?r?c()?e.jsx(e.Fragment,{children:t}):e.jsx(Hb,{shiftOwnerName:l()||"غير معروف",shiftNumber:r.shift_number,currentEmployeeName:(m==null?void 0:m.employee_name)||"غير معروف",onLogout:u}):e.jsx("div",{className:"min-h-[80vh] flex items-center justify-center p-4",dir:"rtl",children:e.jsxs(fe,{className:"w-full max-w-md border-2 border-amber-300 bg-gradient-to-br from-amber-50 to-orange-50 dark:from-amber-950/30 dark:to-orange-950/30 shadow-xl",children:[e.jsxs(De,{className:"text-center pb-2",children:[e.jsx("div",{className:"mx-auto mb-4 w-20 h-20 rounded-full bg-amber-100 dark:bg-amber-900/50 flex items-center justify-center",children:e.jsx(Zt,{className:"h-10 w-10 text-amber-600"})}),e.jsx($e,{className:"text-2xl font-bold text-amber-800 dark:text-amber-200 font-cairo",children:"يجب فتح شفت أولاً"}),e.jsx(kr,{className:"text-amber-700 dark:text-amber-300 font-cairo",children:"لا يمكنك إنشاء فواتير أو استخدام نقطة البيع بدون فتح شفت عمل"})]}),e.jsxs(ve,{className:"space-y-6",children:[m&&e.jsx("div",{className:"bg-white dark:bg-background/50 rounded-lg p-4 border",children:e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-12 h-12 rounded-full bg-primary/10 flex items-center justify-center",children:e.jsx(Bt,{className:"h-6 w-6 text-primary"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold font-cairo",children:m.employee_name}),e.jsx(Ae,{variant:"outline",className:"mt-1",children:m.role==="admin"?"مدير":m.role==="manager"?"مشرف":m.role==="owner"?"مالك":"موظف"})]})]}),e.jsxs(V,{variant:"outline",size:"sm",onClick:u,className:"text-amber-600 border-amber-300 hover:bg-amber-50 dark:hover:bg-amber-950/50 font-cairo",children:[e.jsx(_r,{className:"h-4 w-4 ml-1"}),"تغيير"]})]})}),e.jsxs("div",{className:"flex items-start gap-2 p-3 bg-amber-50 dark:bg-amber-950/30 rounded-lg border border-amber-200 dark:border-amber-800",children:[e.jsx(Vo,{className:"h-5 w-5 text-amber-600 mt-0.5 flex-shrink-0"}),e.jsx("p",{className:"text-sm text-amber-700 dark:text-amber-300 font-cairo",children:'إذا لم تكن أنت من سيعمل في هذا الشفت، اضغط "تغيير" للعودة لشاشة اختيار الموظفين'})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs(_e,{htmlFor:"opening-cash",className:"font-cairo text-base flex items-center gap-2",children:[e.jsx(gr,{className:"h-5 w-5 text-green-600"}),"المبلغ الافتتاحي في الدرج"]}),e.jsx(Te,{id:"opening-cash",type:"number",step:"0.01",min:"0",value:d,onChange:f=>h(parseFloat(f.target.value)||0),className:"text-xl text-center h-14 font-bold",placeholder:"0.00"}),e.jsx("p",{className:"text-sm text-muted-foreground text-center font-cairo",children:"أدخل المبلغ الموجود حالياً في درج النقود"})]}),e.jsx(V,{onClick:p,disabled:o,size:"lg",className:"w-full h-14 text-lg font-bold bg-gradient-to-r from-green-500 to-emerald-600 hover:from-green-600 hover:to-emerald-700 font-cairo shadow-lg",children:o?e.jsxs(e.Fragment,{children:[e.jsx(ct,{className:"ml-2 h-6 w-6 animate-spin"}),"جاري فتح الشفت..."]}):e.jsxs(e.Fragment,{children:[e.jsx(mu,{className:"ml-2 h-6 w-6"}),"فتح الشفت والبدء بالعمل"]})}),e.jsxs("div",{className:"flex items-start gap-2 p-3 bg-blue-50 dark:bg-blue-950/30 rounded-lg border border-blue-200 dark:border-blue-800",children:[e.jsx(hu,{className:"h-5 w-5 text-blue-600 mt-0.5 flex-shrink-0"}),e.jsx("p",{className:"text-sm text-blue-700 dark:text-blue-300 font-cairo",children:"سيتم ربط جميع المبيعات والفواتير بهذا الشفت لتتبع أدائك بشكل دقيق"})]})]})]})}):e.jsx(e.Fragment,{children:t})},Mi=[{id:"pos",icon:Un,label:"البيع"},{id:"invoices",icon:Os,label:"الفواتير"},{id:"products",icon:ht,label:"المنتجات"},{id:"customers",icon:Rt,label:"العملاء"}],Xb=({activeTab:t,onNavigate:r,menuItems:n=[]})=>{const[i,o]=we.useState(!1),a=n.filter(c=>!Mi.find(l=>l.id===c.id)),s=c=>{r(c),o(!1)};return e.jsx("nav",{className:"fixed bottom-0 left-0 right-0 bg-background/95 backdrop-blur-lg border-t border-border z-50 safe-area-bottom",children:e.jsxs("div",{className:"flex justify-around items-center h-16 max-w-lg mx-auto",children:[Mi.map(c=>{const l=c.icon,m=t===c.id;return e.jsxs("button",{onClick:()=>s(c.id),className:Z("flex flex-col items-center justify-center flex-1 h-full py-2 transition-all duration-200 tap-highlight-none touch-active",m?"text-primary":"text-muted-foreground hover:text-foreground"),children:[e.jsx("div",{className:Z("p-1.5 rounded-xl transition-all duration-200",m&&"bg-primary/10"),children:e.jsx(l,{className:Z("h-5 w-5 transition-transform",m&&"scale-110")})}),e.jsx("span",{className:Z("text-[10px] mt-1 font-medium transition-all",m?"font-bold":"font-normal"),children:c.label}),m&&e.jsx("div",{className:"absolute bottom-1 w-1 h-1 rounded-full bg-primary"})]},c.id)}),e.jsxs(Ld,{open:i,onOpenChange:o,children:[e.jsx(Dd,{asChild:!0,children:e.jsxs("button",{className:Z("flex flex-col items-center justify-center flex-1 h-full py-2 transition-all duration-200 tap-highlight-none touch-active",i?"text-primary":"text-muted-foreground hover:text-foreground"),children:[e.jsx("div",{className:Z("p-1.5 rounded-xl transition-all duration-200",i&&"bg-primary/10"),children:e.jsx(Am,{className:"h-5 w-5"})}),e.jsx("span",{className:"text-[10px] mt-1 font-medium",children:"المزيد"})]})}),e.jsxs(va,{side:"bottom",className:"h-auto max-h-[60vh] rounded-t-3xl",children:[e.jsx(Fd,{className:"pb-4",children:e.jsx(Ud,{className:"text-center",children:"القائمة"})}),e.jsx("div",{className:"grid grid-cols-3 gap-4 pb-6",children:a.map(c=>{const l=c.icon,m=t===c.id;return e.jsxs(V,{variant:m?"default":"outline",className:Z("flex flex-col items-center justify-center h-24 gap-2",m&&"ring-2 ring-primary ring-offset-2"),onClick:()=>s(c.id),children:[e.jsx(l,{className:"h-6 w-6"}),e.jsx("span",{className:"text-xs font-medium",children:c.label})]},c.id)})})]})]})]})})},Jb=v.lazy(()=>Ve(()=>import("./AnalyticsDashboard-B_WKlADe.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18]))),Kb=v.lazy(()=>Ve(()=>import("./ExecutiveDashboard-CX2xhCpd.js"),__vite__mapDeps([19,1,2,4,5,6,7,8,9,3,10,20,13,17,18])).then(t=>({default:t.ExecutiveDashboard}))),Yb=v.lazy(()=>Ve(()=>import("./ShiftManagement-25WIPYWd.js"),__vite__mapDeps([21,1,2,3,4,5,6,7,8,9,10,17,18])).then(t=>({default:t.ShiftManagement}))),Qb=v.lazy(()=>Ve(()=>import("./ShiftReport-yqYKdCeT.js"),__vite__mapDeps([22,1,2,3,4,5,6,7,8,9,10,16,23,13,17,18])).then(t=>({default:t.ShiftReport}))),Zb=v.lazy(()=>Ve(()=>import("./CashDrawerMovements-CS-g03RT.js"),__vite__mapDeps([24,1,2,3,4,5,6,7,8,9,10,16,13,17,18])).then(t=>({default:t.CashDrawerMovements}))),ey=v.lazy(()=>Ve(()=>import("./EmployeeManagement-9UtVvY9l.js"),__vite__mapDeps([25,1,2,26,4,5,6,7,8,9,3,10,27,17,28,18])).then(t=>({default:t.EmployeeManagement}))),ty=v.lazy(()=>Ve(()=>import("./EmployeePerformance-B7C3sIht.js"),__vite__mapDeps([29,1,2,26,4,5,6,7,8,9,3,10,20,13,17,18])).then(t=>({default:t.EmployeePerformance}))),ry=v.lazy(()=>Ve(()=>import("./AuditLog-BXpf9x1X.js"),__vite__mapDeps([30,1,2,4,5,6,7,8,9,26,3,10,12,13,16,17,18])).then(t=>({default:t.AuditLog}))),ny=v.lazy(()=>Ve(()=>import("./LoyaltyProgram-BO1F64_F.js"),__vite__mapDeps([31,1,2,3,4,5,6,7,8,9,10,20,17,18])).then(t=>({default:t.LoyaltyProgram}))),sy=v.lazy(()=>Ve(()=>import("./PromotionsManagement-BBLo4qRm.js"),__vite__mapDeps([32,1,2,4,5,6,7,8,9,3,10,33,13,17,18])).then(t=>({default:t.PromotionsManagement}))),oy=v.lazy(()=>Ve(()=>import("./CustomerAnalyticsReport-BAM5vZQg.js"),__vite__mapDeps([34,1,2,4,5,6,7,8,9,3,10,12,13,16,17,18])).then(t=>({default:t.CustomerAnalyticsReport}))),ay=v.lazy(()=>Ve(()=>import("./ABCAnalysisReport-BpL_eVGY.js"),__vite__mapDeps([35,1,2,4,5,6,7,8,9,3,10,12,13,16,17,18])).then(t=>({default:t.ABCAnalysisReport}))),iy=v.lazy(()=>Ve(()=>import("./SalesForecastReport-Ew-TzkrD.js"),__vite__mapDeps([36,1,2,4,5,6,7,8,9,3,10,12,13,16,37,17,18])).then(t=>({default:t.SalesForecastReport}))),cy=v.lazy(()=>Ve(()=>import("./ProductPerformanceReport-DsoViFYp.js"),__vite__mapDeps([38,1,2,4,5,6,7,8,9,3,10,12,13,39,16,15,17,18])).then(t=>({default:t.ProductPerformanceReport}))),ly=v.lazy(()=>Ve(()=>import("./ExpenseManagement-BSOtSAIi.js"),__vite__mapDeps([40,1,2,41,4,5,6,7,8,9,3,10,42,43,33,11,12,13,16,17,18])).then(t=>({default:t.ExpenseManagement}))),dy=v.lazy(()=>Ve(()=>import("./ExpenseCategoriesManager-y5iMrB00.js"),__vite__mapDeps([44,1,2,42,43,7,4,5,6,8,9,41,10,33,3,45,17,18])).then(t=>({default:t.ExpenseCategoriesManager}))),uy=v.lazy(()=>Ve(()=>import("./ExpenseReport-DshfdAS1.js"),__vite__mapDeps([46,1,2,4,5,6,7,8,9,11,12,13,3,10,39,47,48,23,15,45,17,18])).then(t=>({default:t.ExpenseReport}))),my=v.lazy(()=>Ve(()=>import("./StocktakeSessionsList-CTDuNBng.js"),__vite__mapDeps([49,1,2,3,4,5,6,7,8,9,10,50,51,14,33,45,47,52,17,53,13,18])).then(t=>({default:t.StocktakeSessionsList}))),hy=v.lazy(()=>Ve(()=>import("./VarianceReasonsManager-Dlu2kZGI.js"),__vite__mapDeps([54,1,2,3,4,5,6,7,8,9,10,52,14,17,18])).then(t=>({default:t.VarianceReasonsManager}))),fy=v.lazy(()=>Ve(()=>import("./StocktakeReport-Cxkc5PcG.js"),__vite__mapDeps([55,1,2,3,4,5,6,7,8,9,10,51,14,52,16,56,13,17,18])).then(t=>({default:t.StocktakeReport}))),py=v.lazy(()=>Ve(()=>import("./SupplierManagement-CH79Q6bY.js"),__vite__mapDeps([57,1,2,3,4,5,6,7,8,9,10,58,42,43,50,28,53,11,12,13,16,17,18])).then(t=>({default:t.SupplierManagement}))),xy=v.lazy(()=>Ve(()=>import("./PurchaseOrderList-D5dKnRq1.js"),__vite__mapDeps([59,1,2,3,4,5,6,7,8,9,10,58,13,33,17,18])).then(t=>({default:t.PurchaseOrderList}))),gy=v.lazy(()=>Ve(()=>import("./SupplierPayments-w43Rrauu.js"),__vite__mapDeps([60,1,2,3,4,5,6,7,8,9,10,58,13,17,18])).then(t=>({default:t.SupplierPayments}))),by=v.lazy(()=>Ve(()=>import("./SupplierReport-DY1AAreQ.js"),__vite__mapDeps([61,1,2,3,4,5,6,7,8,9,10,58,11,12,13,17,18])).then(t=>({default:t.SupplierReport}))),yy=v.lazy(()=>Ve(()=>import("./OfflineSyncReport-BI2deLJe.js"),__vite__mapDeps([62,1,2,3,4,5,6,7,8,9,47,56,63,10,17,18])).then(t=>({default:t.OfflineSyncReport}))),vy=v.lazy(()=>Ve(()=>import("./RegenerateQRCodes-CsvsSvtr.js"),__vite__mapDeps([64,1,2,4,5,6,7,8,9,10,3,17,18])).then(t=>({default:t.RegenerateQRCodes}))),_y=v.lazy(()=>Ve(()=>import("./FixDuplicateQRCodes-BMjrOnad.js"),__vite__mapDeps([65,1,2,4,5,6,7,8,9,10,3,17,18])).then(t=>({default:t.FixDuplicateQRCodes}))),wy=v.lazy(()=>Ve(()=>import("./BulkResendInvoices-BXQSwXEP.js"),__vite__mapDeps([66,1,2,4,5,6,7,8,9,10,47,17,3,18])).then(t=>({default:t.BulkResendInvoices}))),jy=v.lazy(()=>Ve(()=>import("./DuplicateCleanup-D3-m0Svs.js"),__vite__mapDeps([67,1,2,4,5,6,7,8,9,10,3,17,18])).then(t=>({default:t.DuplicateCleanup}))),ur=()=>e.jsx("div",{className:"flex items-center justify-center p-8",children:e.jsx(ct,{className:"h-6 w-6 animate-spin text-muted-foreground"})}),Ny=()=>{var Y;const{seller:t}=Ot(),{currentEmployee:r}=lt(),{toast:n}=et(),i=dn(),o=v.useCallback(J=>{if(!r)return!1;if(r.role==="admin")return!0;switch(J){case"pos":return r.can_access_pos??!1;case"dashboard":return r.can_view_dashboard??!1;case"invoices":return r.can_create_invoices??!1;case"customers":return r.can_view_customers??!1;case"products":return(r.can_manage_products||r.can_view_stocktake)??!1;case"expenses":return r.can_view_expenses??r.can_view_administration??!1;case"suppliers":return r.can_view_suppliers??r.can_view_administration??!1;case"administration":return r.can_view_administration??!1;case"settings":return r.can_view_settings??!1;default:return!1}},[r]),[a,s]=v.useState("pos"),[c,l]=v.useState(""),[m,u]=v.useState("home"),[d,h]=v.useState(""),[p,f]=v.useState(!1),[x,g]=v.useState(!1),[b,y]=v.useState(!1),[_,j]=v.useState(!1),[I,w]=v.useState(!1),N=Dr(),[C,A]=ou();v.useEffect(()=>{const J=C.get("tab"),ie=C.get("subTab");J&&o(J)&&(s(J),ie&&l(ie),A({},{replace:!0}))},[C,o,A]),v.useEffect(()=>{const J={dashboard:"executive",invoices:"home",customers:"list",products:"products-list",expenses:"list",suppliers:"list",administration:"employees",settings:"company"};C.get("subTab")||l(J[a]||"")},[a,C]);const F=()=>{j(!_)};v.useEffect(()=>{const J=ie=>{ie.key==="Escape"&&_&&j(!1)};return window.addEventListener("keydown",J),()=>window.removeEventListener("keydown",J)},[_]);const T=v.useCallback(async()=>{console.log("🔄 [Pull-to-Refresh] Refreshing data..."),await i.invalidateQueries(),n({title:"✅ تم التحديث",description:"تم تحديث جميع البيانات بنجاح",duration:2e3}),console.log("✅ [Pull-to-Refresh] Data refreshed successfully")},[i,n]),k=ua({onRefresh:T,threshold:80,resistance:2.5,enabled:!_&&N}),P=[{id:"pos",label:"نقطة البيع",icon:Un},{id:"invoices",label:"الفواتير",icon:ys},{id:"products",label:"المنتجات",icon:ht},{id:"customers",label:"العملاء",icon:Rt},{id:"suppliers",label:"الموردين",icon:Qm},{id:"expenses",label:"المصروفات",icon:Os},{id:"administration",label:"الإدارة",icon:lc},{id:"dashboard",label:"التحليلات",icon:cc}],S=t!=null&&t.is_trial?P:[...P,{id:"settings",label:"الإعدادات",icon:To}],E=()=>{u("create"),s("invoices")},O=()=>{s("customers")},R=()=>{s("products")},D=J=>{h(J),u("edit"),s("invoices")},$=J=>{h(J),u("view"),s("invoices")},M=()=>{u("home"),s("invoices")},X=(J,ie)=>{switch(J){case"create-invoice":E();break;case"create-customer":O();break;case"create-product":R();break;case"scan-barcode":break;case"open-calculator":break;default:console.log("Unhandled action:",J)}};Hh({onCommandPalette:()=>f(!0),onHelp:()=>g(!0),onNewInvoice:E,onNavigate:J=>s(J),onSearch:()=>y(!0)});const U=(J,ie)=>{J==="invoice"?$(ie):J==="customer"?s("customers"):J==="product"&&s("products")},Q=()=>{M()},B=J=>{if(J==="database"){window.location.href="/admin/database";return}const ce={home:"invoices",executive:"dashboard",analytics:"dashboard",reports:"dashboard",cancelled:"invoices",loyalty:"customers",promotions:"customers",employees:"administration"}[J]||J;if(!o(ce)){n({title:"غير مسموح",description:"ليس لديك صلاحية الوصول إلى هذه الصفحة",variant:"destructive"});return}s(ce),u("home"),h("")},z=()=>{switch(m){case"create":return e.jsx(Wx,{onInvoiceSaved:Q,onCancel:M});case"edit":return e.jsx(Xx,{invoiceId:d,onBack:M});case"view":return e.jsx(Yx,{invoiceId:d,onBack:M});default:return null}};if(v.useEffect(()=>{if(r&&!o(a)){const ie=["pos","dashboard","invoices","customers","products","administration","settings"].find(ce=>o(ce));ie&&s(ie)}},[r,a,o]),!r)return e.jsx(jb,{onLoginSuccess:()=>{}});const H=()=>m==="create"||m==="edit"||m==="view"?z():e.jsxs("div",{className:"space-y-4 sm:space-y-6",children:[e.jsx(Qg,{}),e.jsx(Zg,{onCreateInvoice:E,onCreateCustomer:O,onCreateProduct:R}),e.jsx(v.Suspense,{fallback:e.jsx(ur,{}),children:e.jsxs("div",{className:"mb-4 flex flex-wrap gap-2",children:[(t==null?void 0:t.enable_fawatrah)!==!1&&e.jsxs(e.Fragment,{children:[e.jsx(vy,{}),e.jsx(_y,{}),e.jsx(wy,{})]}),e.jsx(jy,{})]})}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-4 sm:gap-6",dir:"rtl",children:[e.jsx(Ti,{onViewInvoice:$,onEditInvoice:D}),(t==null?void 0:t.enable_fawatrah)!==!1&&e.jsx(Ai,{onViewInvoice:$})]})]});return e.jsxs(e.Fragment,{children:[e.jsx(ma,{isPulling:k.isPulling,pullDistance:k.pullDistance,isRefreshing:k.isRefreshing,canRefresh:k.canRefresh,progress:k.progress}),e.jsxs("div",{ref:J=>{J&&(k.containerRef.current=J)},className:"min-h-screen w-full flex flex-col",children:[!_&&e.jsx(Ji,{}),!_&&e.jsxs(e.Fragment,{children:[e.jsx(fb,{}),e.jsx(q0,{activeTab:a,onNavigate:B,menuItems:S}),e.jsx(H0,{activeTab:a,activeSubTab:c,onSubTabChange:l})]}),e.jsx("div",{className:"flex-1 flex flex-col min-w-0",children:e.jsx("div",{className:Z("flex-1 overflow-x-hidden",_?"bg-white dark:bg-gray-950":"bg-gradient-to-br from-blue-50 to-indigo-100 dark:from-gray-900 dark:to-gray-800"),dir:"rtl",children:e.jsxs("div",{className:Z("w-full min-w-0 font-cairo box-border",_?"p-0 m-0":"px-3 sm:px-4 py-2 sm:py-4 md:py-8"),style:{maxWidth:_||N?"100vw":"1280px",margin:_?"0":"0 auto"},children:[!_&&(t==null?void 0:t.is_trial)&&e.jsx("div",{className:"mb-3 sm:mb-4 p-3 sm:p-4 bg-gradient-to-r from-orange-100 to-red-100 border-2 border-orange-300 rounded-lg shadow-md",children:e.jsx("p",{className:"text-orange-800 font-bold text-center text-mobile-sm sm:text-base leading-relaxed",children:"هذه نسخة تجريبية فقط لعرض البرنامج ولا يمكن إرسال فواتير إلى نظام الفوترة الوطني. يرجى الحصول على نسخة أصلية لإرسال الفواتير."})}),!N&&!_&&e.jsxs("div",{className:"mb-6 flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(ys,{className:"h-4 w-4"}),e.jsx(Ms,{className:"h-3 w-3"}),e.jsx("span",{className:"font-semibold text-foreground",children:(Y=S.find(J=>J.id===a))==null?void 0:Y.label})]}),e.jsxs("div",{className:Z(_?"h-screen":"space-y-4 sm:space-y-6"),children:[a==="pos"&&e.jsx(Wb,{children:e.jsx(Gb,{isFullscreen:_,onToggleFullscreen:F})}),a==="dashboard"&&e.jsxs(v.Suspense,{fallback:e.jsx(ur,{}),children:[c==="executive"&&e.jsx(Kb,{}),c==="analytics"&&e.jsx(Jb,{}),c==="reports"&&e.jsxs(Fi,{defaultValue:"customer",className:"w-full",dir:"rtl",children:[e.jsxs(Ui,{className:"grid w-full grid-cols-4 mb-4",children:[e.jsx(Vr,{value:"customer",children:"تحليل العملاء"}),e.jsx(Vr,{value:"abc",children:"تحليل ABC"}),e.jsx(Vr,{value:"forecast",children:"توقعات المبيعات"}),e.jsx(Vr,{value:"products",children:"أداء المنتجات"})]}),e.jsx(Gr,{value:"customer",children:e.jsx(oy,{})}),e.jsx(Gr,{value:"abc",children:e.jsx(ay,{})}),e.jsx(Gr,{value:"forecast",children:e.jsx(iy,{})}),e.jsx(Gr,{value:"products",children:e.jsx(cy,{})})]})]}),a==="invoices"&&e.jsxs(e.Fragment,{children:[c==="home"&&H(),c==="pending"&&e.jsx(Ti,{onViewInvoice:$,onEditInvoice:D}),c==="sent"&&e.jsx(Ai,{onViewInvoice:$}),c==="cancelled"&&e.jsx(mb,{onViewInvoice:$})]}),a==="customers"&&e.jsxs(v.Suspense,{fallback:e.jsx(ur,{}),children:[c==="list"&&e.jsx(tg,{}),c==="loyalty"&&e.jsx(ny,{}),c==="promotions"&&e.jsx(sy,{})]}),a==="products"&&e.jsxs(v.Suspense,{fallback:e.jsx(ur,{}),children:[c==="products-list"&&e.jsx(mg,{}),c==="categories"&&e.jsx(qg,{}),c==="stocktake"&&e.jsx(my,{}),c==="stocktake-reasons"&&e.jsx(hy,{}),c==="stocktake-reports"&&e.jsx(fy,{})]}),a==="expenses"&&e.jsxs(v.Suspense,{fallback:e.jsx(ur,{}),children:[(c==="list"||c==="")&&e.jsx(ly,{}),c==="categories"&&e.jsx(dy,{}),c==="report"&&e.jsx(uy,{})]}),a==="suppliers"&&e.jsxs(v.Suspense,{fallback:e.jsx(ur,{}),children:[(c==="list"||c==="")&&e.jsx(py,{}),c==="orders"&&e.jsx(xy,{}),c==="payments"&&e.jsx(gy,{}),c==="reports"&&e.jsx(by,{})]}),a==="administration"&&e.jsxs(v.Suspense,{fallback:e.jsx(ur,{}),children:[c==="employees"&&e.jsx(ey,{}),c==="performance"&&e.jsx(ty,{}),c==="shifts"&&e.jsx(Yb,{}),c==="shifts-reports"&&e.jsx(Qb,{}),c==="cash-movements"&&e.jsx(Zb,{}),c==="audit-log"&&e.jsx(ry,{})]}),!(t!=null&&t.is_trial)&&a==="settings"&&e.jsxs(v.Suspense,{fallback:e.jsx(ur,{}),children:[c==="company"&&e.jsx(Vg,{}),c==="invoice"&&e.jsx(Gg,{}),c==="theme"&&e.jsx(Wg,{}),c==="sound"&&e.jsx(Xg,{}),c==="currency"&&e.jsx(Jg,{}),c==="offline"&&e.jsx("div",{className:"space-y-6",children:e.jsx(Kg,{})}),c==="sync-report"&&e.jsx(yy,{}),c==="app"&&e.jsx(Yg,{}),c==="shortcuts"&&e.jsx(U0,{}),c==="tour"&&e.jsx(B0,{onStartTour:(J,ie)=>{s(ie),w(!0),setTimeout(()=>w(!1),1e3)}})]})]})]})})})]}),!_&&e.jsxs(e.Fragment,{children:[e.jsx(Vh,{open:p,onOpenChange:f,onNavigate:s,onAction:X}),e.jsx(W0,{open:b,onOpenChange:y,onNavigate:U}),e.jsx(Gh,{open:x,onOpenChange:g})]}),!_&&a==="pos"&&e.jsx(oo,{tourId:"pos-tour",steps:P0,autoStart:!1,forceStart:I&&a==="pos"}),!_&&a==="home"&&m==="home"&&e.jsx(oo,{tourId:"invoices-tour",steps:M0,autoStart:!1,forceStart:I&&a==="home"}),!_&&a==="settings"&&e.jsx(oo,{tourId:"settings-tour",steps:L0,autoStart:!1,forceStart:I&&a==="settings"}),!_&&e.jsx(xb,{className:"pb-safe"}),N&&!_&&a!=="pos"&&e.jsx(Xb,{activeTab:a,onNavigate:B,menuItems:S}),N&&!_&&a!=="pos"&&e.jsx("div",{className:"h-16"})]})},Uy=Object.freeze(Object.defineProperty({__proto__:null,default:Ny},Symbol.toStringTag,{value:"Module"}));export{Xo as $,Ug as A,Vu as B,oc as C,gr as D,Dd as E,va as F,ym as G,Fd as H,Ud as I,Eb as J,da as K,_e as L,et as M,Kr as N,Et as O,ma as P,zm as Q,Qu as R,An as S,Ym as T,eh as U,Om as V,Ds as W,Al as X,ic as Y,sm as Z,Wo as _,Km as a,Jo as a0,Ko as a1,Yo as a2,_s as a3,zx as a4,Da as a5,Qm as a6,Go as a7,am as a8,Gx as a9,Xr as aa,Ms as ab,Pa as ac,Ot as ad,Ly as ae,Vb as af,Uy as ag,Ar as b,Cd as c,Ed as d,qt as e,kd as f,Td as g,Sd as h,Id as i,Ad as j,Un as k,Dr as l,ua as m,$a as n,Od as o,qs as p,Vs as q,Yn as r,Mb as s,fa as t,Kn as u,la as v,kl as w,ac as x,Er as y,Ld as z};
