﻿[{"filePath":"C:\\xampp\\htdocs\\order\\order\\app\\business-card\\page.tsx","messages":[],"suppressedMessages":[{"ruleId":"react-hooks/set-state-in-effect","severity":2,"message":"Error: Calling setState synchronously within an effect can trigger cascading renders\n\nEffects are intended to synchronize state between React and external systems such as manually updating the DOM, state management libraries, or other platform APIs. In general, the body of an effect should do one or both of the following:\n* Update external systems with the latest state from React.\n* Subscribe for updates from some external system, calling setState in a callback function when external state changes.\n\nCalling setState synchronously within an effect body causes cascading renders that can hurt performance, and is not recommended. (https://react.dev/learn/you-might-not-need-an-effect).\n\nC:\\xampp\\htdocs\\order\\order\\app\\business-card\\page.tsx:66:5\n  64 |     // Read the selected product after browser hydration.\n  65 |     // eslint-disable-next-line react-hooks/set-state-in-effect\n> 66 |     setSelectedId(new URLSearchParams(window.location.search).get(\"productId\"));\n     |     ^^^^^^^^^^^^^ Avoid calling setState() directly within an effect\n  67 |   }, []);\n  68 |   const cardProducts = products.filter((product) => product.isBusinessCard && product.status === \"active\");\n  69 |   const product = cardProducts.find((product) => product.id === selectedId) ?? (!selectedId && cardProducts.length === 1 ? cardProducts[0] : undefined);","line":66,"column":5,"nodeType":null,"endLine":66,"endColumn":18,"suppressions":[{"kind":"directive","justification":""}]}],"errorCount":0,"fatalErrorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0,"usedDeprecatedRules":[]},{"filePath":"C:\\xampp\\htdocs\\order\\order\\app\\cart\\confirm\\page.tsx","messages":[{"ruleId":"@typescript-eslint/no-unused-vars","severity":1,"message":"'ShoppingCart' is defined but never used.","line":12,"column":3,"nodeType":"Identifier","messageId":"unusedVar","endLine":12,"endColumn":15,"suggestions":[{"messageId":"removeUnusedVar","data":{"varName":"ShoppingCart"},"fix":{"range":[192,209],"text":""},"desc":"Remove unused variable \"ShoppingCart\"."}]},{"ruleId":"@next/next/no-img-element","severity":1,"message":"Using `<img>` could result in slower LCP and higher bandwidth. Consider using `<Image />` from `next/image` or a custom image loader to automatically optimize images. This may incur additional usage or cost from your provider. See: https://nextjs.org/docs/messages/no-img-element","line":191,"column":19,"nodeType":"JSXOpeningElement","endLine":195,"endColumn":21}],"suppressedMessages":[],"errorCount":0,"fatalErrorCount":0,"warningCount":2,"fixableErrorCount":0,"fixableWarningCount":0,"source":"\"use client\";\r\n\r\nimport { useState, useEffect } from \"react\";\r\nimport { useRouter } from \"next/navigation\";\r\nimport {\r\n  ArrowLeft,\r\n  CheckCircle2,\r\n  Package,\r\n  CreditCard,\r\n  Tag,\r\n  Ruler,\r\n  ShoppingCart,\r\n} from \"lucide-react\";\r\nimport { Button } from \"@/components/ui/button\";\r\nimport { AdminLayout } from \"@/components/admin-layout\";\r\nimport { useCartContext } from \"@/features/cart/components/cart-context\";\r\nimport { useOrders } from \"@/features/orders/hooks/use-orders\";\r\nimport { getCurrentUserContext } from \"@/features/auth/user-context\";\r\nimport { productService } from \"@/features/products/services/product.service\";\nimport { departmentService } from \"@/features/companies/services/company.service\";\nimport { toast } from \"react-hot-toast\";\nimport type { OrderCreateRequestDTO } from \"@/features/orders/dtos/order.dto\";\r\n\r\n// ============================================\r\n// Order Confirmation Page\r\n// Shows cart items as order summary and confirm button.\r\n// Company/department is auto-selected based on user context.\r\n// ============================================\r\n\r\nexport default function OrderConfirmPage() {\r\n  const router = useRouter();\r\n  const userCtx = getCurrentUserContext();\r\n  const isDeptUser = userCtx.role === \"department_user\";\r\n\r\n  const { items, summary, clearCart, isHydrated } = useCartContext();\r\n  const { createOrder } = useOrders();\r\n\r\n  const [isSubmitting, setIsSubmitting] = useState(false);\r\n  const [orderSuccess, setOrderSuccess] = useState(false);\r\n\r\n  // Auto-select company/department from user context\r\n\r\n\r\n  // If cart is empty, redirect to cart\r\n  useEffect(() => {\r\n    if (isHydrated && items.length === 0 && !orderSuccess) {\r\n      router.push(\"/cart\");\r\n    }\r\n  }, [isHydrated, items.length, orderSuccess, router]);\r\n\r\n  const handleConfirm = async () => {\r\n    if (!isHydrated || isSubmitting || items.length === 0) return;\r\n\r\n    setIsSubmitting(true);\r\n    try {\n      const saved = JSON.parse(sessionStorage.getItem(\"order-selection\") ?? \"null\");\n      const selection = saved?.userId === userCtx.id ? saved : null;\n      const companyId = isDeptUser ? userCtx.companyId : selection?.companyId;\n      const departmentId = isDeptUser ? userCtx.departmentId : selection?.departmentId;\n      if (!companyId || !departmentId) {\n        toast.error(\"Select a company and department on the order page first.\");\n        router.push(\"/orders/new\");\n        return;\n      }\n      await departmentService.getDepartment(companyId, departmentId);\n      await Promise.all(items.map(async (item) => {\n        if (!/^\\d+$/.test(item.productId)) throw new Error(\"A cart product is outdated. Remove it and add the product again from the shop.\");\n        const product = await productService.getProduct(item.productId);\n        if (product.status !== \"active\") throw new Error(product.name + \" is no longer active.\");\n        if (item.quantity < product.minimumQuantity) throw new Error(product.name + \" requires at least \" + product.minimumQuantity + \" units.\");\n      }));\n      const payload: OrderCreateRequestDTO = {\r\n        companyId,\r\n        departmentId,\r\n        status: \"ordered\",\r\n        notes: null,\r\n        items: items.map((item) => ({\r\n          orderId: \"\",\r\n          productId: item.productId,\r\n          productName: item.productName,\r\n          productVariantId: item.productVariantId,\r\n          variantName: item.variantName,\r\n          size: item.size,\r\n          quantity: item.quantity,\r\n          unitPrice: null,\r\n          isBusinessCard: item.isBusinessCard,\r\n          // Pass through business card designs from the cart item\r\n          businessCards: (item.businessCards ?? []).map((bc, idx) => ({\r\n            ...bc,\r\n            orderItemId: item.id,\r\n            cardNumber: idx + 1,\r\n          })),\r\n        })),\r\n      };\r\n  \r\n      const success = await createOrder(payload);\r\n  \r\n      if (success) {\r\n        setOrderSuccess(true);\n        clearCart();\r\n        // Show toast success\r\n        if (typeof window !== \"undefined\") {\r\n          const { toast } = await import(\"react-hot-toast\");\r\n          toast.success(\"Order placed successfully!\");\r\n        }\r\n      }\n      } catch (error) {\n      toast.error(error instanceof Error ? error.message : \"Unable to confirm the order.\");\n    } finally {\n      setIsSubmitting(false);\n    }\n  };\r\n\r\n  // Success state\r\n  if (orderSuccess) {\r\n    return (\r\n      <AdminLayout>\r\n        <div className=\"mx-auto max-w-lg py-12\">\r\n          <div className=\"rounded-2xl border border-gray-200 bg-white p-8 text-center shadow-sm\">\r\n            <div className=\"mb-4 inline-flex h-16 w-16 items-center justify-center rounded-full bg-emerald-50\">\r\n              <CheckCircle2 className=\"h-8 w-8 text-emerald-600\" />\r\n            </div>\r\n            <h2 className=\"mb-2 text-xl font-bold text-gray-900\">\r\n              Order Placed Successfully!\r\n            </h2>\r\n            <p className=\"mb-6 text-sm text-gray-500\">\r\n              Your order has been placed and is now visible in the Orders page.\r\n              You can track its status from there.\r\n            </p>\r\n            <div className=\"flex items-center justify-center gap-3\">\r\n              <Button\r\n                variant=\"secondary\"\r\n                onClick={() => router.push(\"/orders/new\")}\r\n              >\r\n                Create Another Order\r\n              </Button>\r\n              <Button onClick={() => router.push(\"/orders\")}>\r\n                <CheckCircle2 className=\"h-4 w-4\" />\r\n                Go to Orders\r\n              </Button>\r\n            </div>\r\n          </div>\r\n        </div>\r\n      </AdminLayout>\r\n    );\r\n  }\r\n\r\n  return (\r\n    <AdminLayout>\r\n      <div className=\"mx-auto max-w-3xl\">\r\n        {/* Back Button */}\r\n        <button\r\n          onClick={() => router.push(\"/cart\")}\r\n          className=\"mb-6 inline-flex items-center gap-2 text-sm text-gray-500 transition-colors hover:text-gray-900\"\r\n        >\r\n          <ArrowLeft className=\"h-4 w-4\" />\r\n          Back to Cart\r\n        </button>\r\n\r\n        {/* Header */}\r\n        <div className=\"mb-8\">\r\n          <div className=\"flex items-center gap-3\">\r\n            <div className=\"flex h-12 w-12 items-center justify-center rounded-xl bg-emerald-50\">\r\n              <CheckCircle2 className=\"h-6 w-6 text-emerald-600\" />\r\n            </div>\r\n            <div>\r\n              <h1 className=\"text-2xl font-bold text-gray-900\">\r\n                Confirm Your Order\r\n              </h1>\r\n              <p className=\"text-sm text-gray-500\">\r\n                Review your items and confirm the order\r\n              </p>\r\n            </div>\r\n          </div>\r\n        </div>\r\n\r\n        {/* Order Items Summary */}\r\n        <div className=\"mb-6 rounded-xl border border-gray-200 bg-white\">\r\n          <div className=\"border-b border-gray-200 px-6 py-4\">\r\n            <h2 className=\"text-sm font-semibold text-gray-900\">\r\n              Order Items ({items.length})\r\n            </h2>\r\n          </div>\r\n          <div className=\"divide-y divide-gray-100\">\r\n            {items.map((item) => (\r\n              <div\r\n                key={item.id}\r\n                className=\"flex items-center gap-4 px-6 py-4\"\r\n              >\r\n                {item.productImageUrl ? (\r\n                  <img\r\n                    src={item.productImageUrl}\r\n                    alt={item.productName}\r\n                    className=\"h-12 w-12 flex-shrink-0 rounded-lg object-cover\"\r\n                  />\r\n                ) : (\r\n                  <div\r\n                    className={`flex h-12 w-12 flex-shrink-0 items-center justify-center rounded-lg ${\r\n                      item.isBusinessCard\r\n                        ? \"bg-[#1a6b5a]/10\"\r\n                        : \"bg-purple-50\"\r\n                    }`}\r\n                  >\r\n                    {item.isBusinessCard ? (\r\n                      <CreditCard className=\"h-5 w-5 text-[#1a6b5a]\" />\r\n                    ) : (\r\n                      <Package className=\"h-5 w-5 text-purple-600\" />\r\n                    )}\r\n                  </div>\r\n                )}\r\n                <div className=\"flex-1 min-w-0\">\r\n                  <p className=\"text-sm font-medium text-gray-900 truncate\">\r\n                    {item.productName}\r\n                  </p>\r\n                  <div className=\"mt-1 flex flex-wrap gap-1.5\">\r\n                    {item.variantName && (\r\n                      <span className=\"inline-flex items-center gap-0.5 rounded-md bg-amber-50 px-1.5 py-0.5 text-[10px] font-medium text-amber-700\">\r\n                        <Tag className=\"h-2.5 w-2.5\" />\r\n                        {item.variantName}\r\n                      </span>\r\n                    )}\r\n                    {item.size && (\r\n                      <span className=\"inline-flex items-center gap-0.5 rounded-md bg-blue-50 px-1.5 py-0.5 text-[10px] font-medium text-blue-700\">\r\n                        <Ruler className=\"h-2.5 w-2.5\" />\r\n                        {item.size}\r\n                      </span>\r\n                    )}\r\n                    {item.isBusinessCard && (\r\n                      <span className=\"inline-flex items-center gap-0.5 rounded-md bg-pink-50 px-1.5 py-0.5 text-[10px] font-medium text-pink-700\">\r\n                        <CreditCard className=\"h-2.5 w-2.5\" />\r\n                        Business Card\r\n                      </span>\r\n                    )}\r\n                  </div>\r\n                </div>\r\n                <div className=\"text-right\">\r\n                  <p className=\"text-sm font-semibold text-gray-900\">\r\n                    {item.quantity.toLocaleString()}\r\n                  </p>\r\n                  <p className=\"text-[10px] text-gray-400\">qty</p>\r\n                </div>\r\n              </div>\r\n            ))}\r\n          </div>\r\n        </div>\r\n\r\n        {/* Summary */}\r\n        <div className=\"mb-6 rounded-xl border border-gray-200 bg-white p-6\">\r\n          <div className=\"space-y-3\">\r\n            <div className=\"flex items-center justify-between text-sm text-gray-600\">\r\n              <span>Distinct items</span>\r\n              <span>{summary.itemCount}</span>\r\n            </div>\r\n            <div className=\"flex items-center justify-between text-sm text-gray-600\">\r\n              <span>Total quantity</span>\r\n              <span>{summary.totalQuantity.toLocaleString()}</span>\r\n            </div>\r\n            <div className=\"border-t border-gray-100 pt-3\">\r\n              <div className=\"flex items-center justify-between\">\r\n                <span className=\"text-base font-semibold text-gray-900\">\r\n                  Total Units\r\n                </span>\r\n                <span className=\"text-lg font-bold text-navy-900\">\r\n                  {summary.totalQuantity.toLocaleString()}\r\n                </span>\r\n              </div>\r\n            </div>\r\n          </div>\r\n        </div>\r\n\r\n        {/* Actions */}\r\n        <div className=\"flex items-center gap-3\">\r\n          <Button\r\n            variant=\"secondary\"\r\n            onClick={() => router.push(\"/cart\")}\r\n            className=\"flex-1\"\r\n          >\r\n            <ArrowLeft className=\"h-4 w-4\" />\r\n            Back to Cart\r\n          </Button>\r\n          <Button\r\n            onClick={handleConfirm}\r\n            loading={isSubmitting}\r\n            disabled={!isHydrated || isSubmitting || items.length === 0}\r\n            className=\"flex-1 gap-2\"\r\n          >\r\n            <CheckCircle2 className=\"h-4 w-4\" />\r\n            Confirm Order\r\n          </Button>\r\n        </div>\r\n      </div>\r\n    </AdminLayout>\r\n  );\r\n}\r\n","usedDeprecatedRules":[]},{"filePath":"C:\\xampp\\htdocs\\order\\order\\app\\orders\\new\\page.tsx","messages":[{"ruleId":"@typescript-eslint/no-unused-vars","severity":1,"message":"'isAdminUser' is defined but never used.","line":20,"column":33,"nodeType":"Identifier","messageId":"unusedVar","endLine":20,"endColumn":44,"suggestions":[{"messageId":"removeUnusedVar","data":{"varName":"isAdminUser"},"fix":{"range":[619,632],"text":""},"desc":"Remove unused variable \"isAdminUser\"."}]},{"ruleId":"@next/next/no-img-element","severity":1,"message":"Using `<img>` could result in slower LCP and higher bandwidth. Consider using `<Image />` from `next/image` or a custom image loader to automatically optimize images. This may incur additional usage or cost from your provider. See: https://nextjs.org/docs/messages/no-img-element","line":261,"column":23,"nodeType":"JSXOpeningElement","endLine":265,"endColumn":25},{"ruleId":"@next/next/no-img-element","severity":1,"message":"Using `<img>` could result in slower LCP and higher bandwidth. Consider using `<Image />` from `next/image` or a custom image loader to automatically optimize images. This may incur additional usage or cost from your provider. See: https://nextjs.org/docs/messages/no-img-element","line":368,"column":15,"nodeType":"JSXOpeningElement","endLine":372,"endColumn":17}],"suppressedMessages":[{"ruleId":"react-hooks/set-state-in-effect","severity":2,"message":"Error: Calling setState synchronously within an effect can trigger cascading renders\n\nEffects are intended to synchronize state between React and external systems such as manually updating the DOM, state management libraries, or other platform APIs. In general, the body of an effect should do one or both of the following:\n* Update external systems with the latest state from React.\n* Subscribe for updates from some external system, calling setState in a callback function when external state changes.\n\nCalling setState synchronously within an effect body causes cascading renders that can hurt performance, and is not recommended. (https://react.dev/learn/you-might-not-need-an-effect).\n\nC:\\xampp\\htdocs\\order\\order\\app\\orders\\new\\page.tsx:39:5\n  37 |     // Hydrate browser-only user context after SSR.\n  38 |     // eslint-disable-next-line react-hooks/set-state-in-effect\n> 39 |     setMounted(true);\n     |     ^^^^^^^^^^ Avoid calling setState() directly within an effect\n  40 |   }, []);\n  41 |\n  42 |   const userCtx = getCurrentUserContext();","line":39,"column":5,"nodeType":null,"endLine":39,"endColumn":15,"suppressions":[{"kind":"directive","justification":""}]},{"ruleId":"react-hooks/set-state-in-effect","severity":2,"message":"Error: Calling setState synchronously within an effect can trigger cascading renders\n\nEffects are intended to synchronize state between React and external systems such as manually updating the DOM, state management libraries, or other platform APIs. In general, the body of an effect should do one or both of the following:\n* Update external systems with the latest state from React.\n* Subscribe for updates from some external system, calling setState in a callback function when external state changes.\n\nCalling setState synchronously within an effect body causes cascading renders that can hurt performance, and is not recommended. (https://react.dev/learn/you-might-not-need-an-effect).\n\nC:\\xampp\\htdocs\\order\\order\\app\\orders\\new\\page.tsx:54:9\n  52 |         // Restore the persisted checkout selection after SSR.\n  53 |         // eslint-disable-next-line react-hooks/set-state-in-effect\n> 54 |         setCompanyId(saved.companyId ?? \"\");\n     |         ^^^^^^^^^^^^ Avoid calling setState() directly within an effect\n  55 |         setDepartmentId(saved.departmentId ?? \"\");\n  56 |       }\n  57 |     } catch { /* Ignore an invalid draft. */ }","line":54,"column":9,"nodeType":null,"endLine":54,"endColumn":21,"suppressions":[{"kind":"directive","justification":""}]},{"ruleId":"react-hooks/set-state-in-effect","severity":2,"message":"Error: Calling setState synchronously within an effect can trigger cascading renders\n\nEffects are intended to synchronize state between React and external systems such as manually updating the DOM, state management libraries, or other platform APIs. In general, the body of an effect should do one or both of the following:\n* Update external systems with the latest state from React.\n* Subscribe for updates from some external system, calling setState in a callback function when external state changes.\n\nCalling setState synchronously within an effect body causes cascading renders that can hurt performance, and is not recommended. (https://react.dev/learn/you-might-not-need-an-effect).\n\nC:\\xampp\\htdocs\\order\\order\\app\\orders\\new\\page.tsx:72:7\n  70 |       // Hydrate the assigned department from the authenticated session.\n  71 |       // eslint-disable-next-line react-hooks/set-state-in-effect\n> 72 |       setCompanyId(userCtx.companyId ?? \"\");\n     |       ^^^^^^^^^^^^ Avoid calling setState() directly within an effect\n  73 |       setDepartmentId(userCtx.departmentId ?? \"\");\n  74 |     }\n  75 |   }, [mounted, isDeptUser, userCtx.companyId, userCtx.departmentId]);","line":72,"column":7,"nodeType":null,"endLine":72,"endColumn":19,"suppressions":[{"kind":"directive","justification":""}]}],"errorCount":0,"fatalErrorCount":0,"warningCount":3,"fixableErrorCount":0,"fixableWarningCount":0,"source":"\"use client\";\r\n\r\nimport { useState, useEffect } from \"react\";\r\nimport { useRouter } from \"next/navigation\";\r\nimport {\r\n  ShoppingCart,\r\n  ArrowLeft,\r\n  Package,\r\n  Building2,\r\n  CreditCard,\r\n  Trash2,\r\n  X,\r\n  ZoomIn,\r\n} from \"lucide-react\";\r\nimport { Button } from \"@/components/ui/button\";\r\nimport { AdminLayout } from \"@/components/admin-layout\";\r\nimport { useProducts } from \"@/features/products/hooks/use-products\";\r\nimport { useCompanies } from \"@/features/companies/hooks/use-companies\";\r\nimport { useCompanyDepartments } from \"@/features/companies/hooks/use-company-departments\";\r\nimport { getCurrentUserContext, isAdminUser } from \"@/features/auth/user-context\";\r\nimport { ProductGrid } from \"@/features/cart/components/product-grid\";\r\nimport { useCartContext } from \"@/features/cart/components/cart-context\";\r\n\r\n// ============================================\r\n// Storage Keys\r\n// ============================================\r\nconst COMPANY_STORAGE_KEY = \"singh-order-company\";\r\n\r\n// ============================================\r\n// New Order Page (Product Browser + Cart Preview)\r\n// ============================================\r\nexport default function NewOrderPage() {\r\n  const router = useRouter();\r\n  const [mounted, setMounted] = useState(false);\r\n\r\n  useEffect(() => {\r\n    // Hydrate browser-only user context after SSR.\n    // eslint-disable-next-line react-hooks/set-state-in-effect\n    setMounted(true);\r\n  }, []);\r\n\r\n  const userCtx = getCurrentUserContext();\r\n  const isDeptUser = mounted && userCtx.role === \"department_user\";\r\n\r\n  const [companyId, setCompanyId] = useState(\"\");\n  const [departmentId, setDepartmentId] = useState(\"\");\n  const [selectionLoaded, setSelectionLoaded] = useState(false);\n  useEffect(() => {\n    try {\n      const saved = JSON.parse(sessionStorage.getItem(\"order-selection\") ?? \"null\");\n      if (saved?.userId === userCtx.id) {\n        // Restore the persisted checkout selection after SSR.\n        // eslint-disable-next-line react-hooks/set-state-in-effect\n        setCompanyId(saved.companyId ?? \"\");\n        setDepartmentId(saved.departmentId ?? \"\");\n      }\n    } catch { /* Ignore an invalid draft. */ }\n    setSelectionLoaded(true);\n  }, [userCtx.id]);\n  useEffect(() => {\n    if (selectionLoaded) sessionStorage.setItem(\"order-selection\", JSON.stringify({ userId: userCtx.id, companyId, departmentId }));\n  }, [selectionLoaded, userCtx.id, companyId, departmentId]);\r\n\r\n  const [activeTab, setActiveTab] = useState<\"shop\" | \"cart\">(\"shop\");\r\n  const [imageModal, setImageModal] = useState<{ url: string; alt: string } | null>(null);\r\n\r\n  // Set company/department from user context after mount (avoids hydration mismatch)\r\n  useEffect(() => {\r\n    if (mounted && isDeptUser) {\r\n      // Hydrate the assigned department from the authenticated session.\n      // eslint-disable-next-line react-hooks/set-state-in-effect\n      setCompanyId(userCtx.companyId ?? \"\");\r\n      setDepartmentId(userCtx.departmentId ?? \"\");\r\n    }\r\n  }, [mounted, isDeptUser, userCtx.companyId, userCtx.departmentId]);\r\n\r\n  const { products } = useProducts();\r\n  const { companies } = useCompanies();\r\n  const { departments } = useCompanyDepartments(companyId);\r\n  const cart = useCartContext();\r\n\r\n  // Save company info to localStorage for the card design page\r\n  useEffect(() => {\r\n    if (companyId) {\r\n      const company = companies.find((c) => c.id === companyId);\r\n      if (company) {\r\n        localStorage.setItem(\r\n          COMPANY_STORAGE_KEY,\r\n          JSON.stringify({\r\n            name: company.name,\r\n            address: null,\r\n            website: \"\",\r\n          })\r\n        );\r\n      }\r\n    }\r\n  }, [companyId, companies]);\r\n\r\n  return (\r\n    <AdminLayout>\r\n      {/* Header */}\r\n      <div className=\"mb-6\">\r\n        <button\r\n          onClick={() => router.push(\"/orders\")}\r\n          className=\"mb-4 inline-flex items-center gap-1 text-sm text-gray-500 transition-colors hover:text-gray-700\"\r\n        >\r\n          <ArrowLeft className=\"h-4 w-4\" />\r\n          Back to Orders\r\n        </button>\r\n        <div className=\"flex items-center justify-between\">\r\n          <div className=\"flex items-center gap-3\">\r\n            <div className=\"flex h-10 w-10 items-center justify-center rounded-lg bg-indigo-50\">\r\n              <ShoppingCart className=\"h-5 w-5 text-indigo-600\" />\r\n            </div>\r\n            <div>\r\n              <h1 className=\"text-2xl font-bold text-gray-900\">Create New Order</h1>\r\n              <p className=\"text-sm text-gray-500\">Browse products and add to cart</p>\r\n            </div>\r\n          </div>\r\n        </div>\r\n      </div>\r\n\r\n      {/* Company Selection */}\r\n      <div className=\"mb-6 rounded-xl border border-gray-200 bg-white p-6\">\r\n        <h2 className=\"mb-4 text-sm font-semibold text-gray-900\">Order Details</h2>\r\n        <div className=\"grid gap-4 sm:grid-cols-2\">\r\n          <div className=\"space-y-1.5\">\r\n            <label className=\"block text-sm font-medium text-gray-700\">\r\n              Company <span className=\"text-red-500\">*</span>\r\n            </label>\r\n            <div className=\"relative\">\r\n              <Building2 className=\"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400\" />\r\n              <select\r\n                value={companyId}\r\n                onChange={(e) => {\r\n                  const selectedId = e.target.value;\r\n                  setCompanyId(selectedId);\n                  setDepartmentId(\"\");\r\n                  // Save company name to localStorage for business card auto-fill\r\n                  const selectedCompany = companies.find((c) => c.id === selectedId);\r\n                  if (selectedCompany) {\r\n                    localStorage.setItem(\r\n                      COMPANY_STORAGE_KEY,\r\n                      JSON.stringify({\r\n                        name: selectedCompany.name,\r\n                        address: null,\r\n                        website: \"\",\r\n                      })\r\n                    );\r\n                  } else {\r\n                    localStorage.removeItem(COMPANY_STORAGE_KEY);\r\n                  }\r\n                }}\r\n                disabled={isDeptUser}\r\n                className={`block w-full rounded-lg border border-gray-200 bg-gray-50 py-2.5 pl-10 pr-4 text-sm text-gray-900 shadow-sm transition-colors focus:border-blue-500 focus:bg-white focus:outline-none focus:ring-1 focus:ring-blue-500 ${\r\n                isDeptUser ? \"cursor-not-allowed opacity-70\" : \"\"}`}\r\n              >\r\n                <option value=\"\">Select a company</option>\r\n                {companies\r\n                  .filter((c) => c.status === \"active\")\r\n                  .map((c) => (\r\n                    <option key={c.id} value={c.id}>\r\n                      {c.name}\r\n                    </option>\r\n                  ))}\r\n              </select>\r\n            </div>\r\n          </div>\r\n          <div className=\"space-y-1.5\">\r\n            <label className=\"block text-sm font-medium text-gray-700\">\r\n              Department\r\n            </label>\r\n            <div className=\"relative\">\r\n              <Building2 className=\"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400\" />\r\n              <select\r\n                value={departmentId}\r\n                onChange={(e) => setDepartmentId(e.target.value)}\r\n                disabled={isDeptUser}\r\n                className={`block w-full rounded-lg border border-gray-200 bg-gray-50 py-2.5 pl-10 pr-4 text-sm text-gray-900 shadow-sm transition-colors focus:border-blue-500 focus:bg-white focus:outline-none focus:ring-1 focus:ring-blue-500 ${\r\n                  isDeptUser ? \"cursor-not-allowed opacity-70\" : \"\"\r\n                }`}\r\n              >\r\n                <option value=\"\">Select a department</option>\r\n                {departments\r\n                  .filter((d) => d.status === \"active\")\r\n                  .map((d) => (\r\n                    <option key={d.id} value={d.id}>\r\n                      {d.name}\r\n                    </option>\r\n                  ))}\r\n              </select>\r\n            </div>\r\n          </div>\r\n        </div>\r\n      </div>\r\n\r\n      {/* Tab Navigation: Shop / Cart Review */}\r\n      <div className=\"mb-4 flex items-center gap-1 rounded-lg border border-gray-200 bg-white p-1\">\r\n        <button\r\n          onClick={() => setActiveTab(\"shop\")}\r\n          className={`flex-1 rounded-md px-4 py-2 text-sm font-medium transition-colors ${\r\n            activeTab === \"shop\"\r\n              ? \"bg-navy-900 text-white shadow-sm\"\r\n              : \"text-gray-600 hover:bg-gray-50\"\r\n          }`}\r\n        >\r\n          <Package className=\"mr-1.5 inline h-4 w-4\" />\r\n          Browse Products\r\n        </button>\r\n        <button\r\n          onClick={() => setActiveTab(\"cart\")}\r\n          className={`flex-1 rounded-md px-4 py-2 text-sm font-medium transition-colors ${\r\n            activeTab === \"cart\"\r\n              ? \"bg-navy-900 text-white shadow-sm\"\r\n              : \"text-gray-600 hover:bg-gray-50\"\r\n          }`}\r\n        >\r\n          <ShoppingCart className=\"mr-1.5 inline h-4 w-4\" />\r\n          Cart ({cart.itemCount})\r\n        </button>\r\n      </div>\r\n\r\n      {/* Shop Tab - Product Grid */}\r\n      {activeTab === \"shop\" && (\r\n        <div className=\"mb-6\">\r\n          <ProductGrid\r\n            products={products}\r\n            isLoading={products.length === 0}\r\n          />\r\n        </div>\r\n      )}\r\n\r\n      {/* Cart Review Tab - Unified Cart Items */}\r\n      {activeTab === \"cart\" && (\r\n        <div className=\"mb-6 space-y-4\">\r\n          {cart.items.length > 0 ? (\r\n            <div className=\"rounded-xl border border-gray-200 bg-white p-6\">\r\n              <div className=\"mb-4 flex items-center justify-between\">\r\n                <div className=\"flex items-center gap-2\">\r\n                  <div className=\"flex h-7 w-7 items-center justify-center rounded-lg bg-navy-100\">\r\n                    <ShoppingCart className=\"h-3.5 w-3.5 text-navy-600\" />\r\n                  </div>\r\n                  <h2 className=\"text-sm font-semibold text-gray-900\">\r\n                    Cart Items ({cart.itemCount})\r\n                  </h2>\r\n                </div>\r\n                <button\r\n                  onClick={cart.clearCart}\r\n                  className=\"text-xs text-gray-500 hover:text-red-600 transition-colors\"\r\n                >\r\n                  Clear cart\r\n                </button>\r\n              </div>\r\n              <div className=\"space-y-3\">\r\n                {cart.items.map((cartItem) => (\r\n                  <div\r\n                    key={cartItem.id}\r\n                    className=\"flex items-center gap-3 rounded-lg border border-gray-100 bg-gray-50 p-3\"\r\n                  >\r\n                    {cartItem.productImageUrl ? (\r\n                      <img\r\n                        src={cartItem.productImageUrl}\r\n                        alt={cartItem.productName}\r\n                        className=\"h-10 w-10 rounded-lg object-cover\"\r\n                      />\r\n                    ) : (\r\n                      <div\r\n                        className={`flex h-10 w-10 items-center justify-center rounded-lg ${\r\n                          cartItem.isBusinessCard ? \"bg-[#1a6b5a]/10\" : \"bg-purple-50\"\r\n                        }`}\r\n                      >\r\n                        {cartItem.isBusinessCard ? (\r\n                          <CreditCard className=\"h-4 w-4 text-[#1a6b5a]\" />\r\n                        ) : (\r\n                          <Package className=\"h-4 w-4 text-purple-600\" />\r\n                        )}\r\n                      </div>\r\n                    )}\r\n                    <div className=\"flex-1 min-w-0\">\r\n                      <p className=\"text-sm font-medium text-gray-900 truncate\">\r\n                        {cartItem.productName}\r\n                      </p>\r\n                      <div className=\"flex flex-wrap gap-1\">\r\n                        {cartItem.variantName && (\r\n                          <span className=\"text-[10px] text-amber-600\">\r\n                            {cartItem.variantName}\r\n                          </span>\r\n                        )}\r\n                        {cartItem.size && (\r\n                          <span className=\"text-[10px] text-blue-600\">\r\n                            {cartItem.size}\r\n                          </span>\r\n                        )}\r\n                        {cartItem.isBusinessCard && (\r\n                          <span className=\"text-[10px] text-[#1a6b5a] font-medium\">\r\n                            Business Card\r\n                          </span>\r\n                        )}\r\n                      </div>\r\n                      {/* Show BC design count */}\r\n                      {cartItem.isBusinessCard && cartItem.businessCards && cartItem.businessCards.length > 0 && (\r\n                        <p className=\"text-[10px] text-gray-400 mt-0.5\">\r\n                          {cartItem.businessCards.length} design{cartItem.businessCards.length !== 1 ? \"s\" : \"\"} · {cartItem.businessCards.map(bc => bc.name).join(\", \")}\r\n                        </p>\r\n                      )}\r\n                    </div>\r\n                    <div className=\"text-right\">\r\n                      <p className=\"text-sm font-semibold text-navy-900\">\r\n                        {cartItem.quantity.toLocaleString()}\r\n                      </p>\r\n                      <p className=\"text-[10px] text-gray-400\">qty</p>\r\n                    </div>\r\n                    <button\r\n                      onClick={() => cart.removeItem(cartItem.id)}\r\n                      className=\"rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-red-50 hover:text-red-500\"\r\n                    >\r\n                      <Trash2 className=\"h-3.5 w-3.5\" />\r\n                    </button>\r\n                  </div>\r\n                ))}\r\n              </div>\r\n              <div className=\"mt-4 flex items-center justify-between\">\r\n                <p className=\"text-xs text-gray-500\">\r\n                  Total: {cart.summary.totalQuantity.toLocaleString()} units\r\n                </p>\r\n                <Button\r\n                  onClick={() => router.push(\"/cart\")}\r\n                  className=\"gap-1.5\"\r\n                >\r\n                  <ShoppingCart className=\"h-4 w-4\" />\r\n                  Go to Cart ({cart.summary.totalQuantity.toLocaleString()} units)\r\n                </Button>\r\n              </div>\r\n            </div>\r\n          ) : (\r\n            <div className=\"flex flex-col items-center justify-center rounded-xl border-2 border-dashed border-gray-200 py-12\">\r\n              <ShoppingCart className=\"mb-3 h-10 w-10 text-gray-300\" />\r\n              <h3 className=\"text-sm font-medium text-gray-900\">Your cart is empty</h3>\r\n              <p className=\"mt-1 text-xs text-gray-500\">\r\n                Browse products above and add items to your cart\r\n              </p>\r\n            </div>\r\n          )}\r\n        </div>\r\n      )}\r\n\r\n      {/* Image Preview Modal */}\r\n      {imageModal && (\r\n        <div className=\"fixed inset-0 z-50 flex items-center justify-center\">\r\n          <div\r\n            className=\"absolute inset-0 bg-black/60 backdrop-blur-sm\"\r\n            onClick={() => setImageModal(null)}\r\n          />\r\n          <div className=\"relative z-10 mx-4 max-w-3xl overflow-hidden rounded-2xl border border-gray-200 bg-white shadow-2xl\">\r\n            <div className=\"flex items-center justify-between border-b border-gray-200 px-4 py-3\">\r\n              <div className=\"flex items-center gap-2\">\r\n                <ZoomIn className=\"h-4 w-4 text-gray-500\" />\r\n                <span className=\"text-sm font-medium text-gray-700\">{imageModal.alt}</span>\r\n              </div>\r\n              <button\r\n                onClick={() => setImageModal(null)}\r\n                className=\"rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600\"\r\n              >\r\n                <X className=\"h-5 w-5\" />\r\n              </button>\r\n            </div>\r\n            <div className=\"flex items-center justify-center p-4\">\r\n              <img\r\n                src={imageModal.url}\r\n                alt={imageModal.alt}\r\n                className=\"max-h-[70vh] max-w-full rounded-lg object-contain\"\r\n              />\r\n            </div>\r\n          </div>\r\n        </div>\r\n      )}\r\n    </AdminLayout>\r\n  );\r\n}\r\n","usedDeprecatedRules":[]},{"filePath":"C:\\xampp\\htdocs\\order\\order\\features\\business-card\\components\\business-card-config-form.tsx","messages":[{"ruleId":"@typescript-eslint/no-unused-vars","severity":1,"message":"'CreditCard' is defined but never used.","line":5,"column":3,"nodeType":"Identifier","messageId":"unusedVar","endLine":5,"endColumn":13,"suggestions":[{"messageId":"removeUnusedVar","data":{"varName":"CreditCard"},"fix":{"range":[88,99],"text":""},"desc":"Remove unused variable \"CreditCard\"."}]},{"ruleId":"@typescript-eslint/no-unused-vars","severity":1,"message":"'BC_ORDER_STORAGE_KEY' is assigned a value but never used.","line":28,"column":7,"nodeType":"Identifier","messageId":"unusedVar","endLine":28,"endColumn":27}],"suppressedMessages":[{"ruleId":"react-hooks/set-state-in-effect","severity":2,"message":"Error: Calling setState synchronously within an effect can trigger cascading renders\n\nEffects are intended to synchronize state between React and external systems such as manually updating the DOM, state management libraries, or other platform APIs. In general, the body of an effect should do one or both of the following:\n* Update external systems with the latest state from React.\n* Subscribe for updates from some external system, calling setState in a callback function when external state changes.\n\nCalling setState synchronously within an effect body causes cascading renders that can hurt performance, and is not recommended. (https://react.dev/learn/you-might-not-need-an-effect).\n\nC:\\xampp\\htdocs\\order\\order\\features\\business-card\\components\\business-card-config-form.tsx:401:5\n  399 |     // Initialize the draft from the API company and department.\n  400 |     // eslint-disable-next-line react-hooks/set-state-in-effect\n> 401 |     setCards((prev) => {\n      |     ^^^^^^^^ Avoid calling setState() directly within an effect\n  402 |       // Only auto-fill if the first card is empty\n  403 |       if (prev.length > 1 || (prev[0].name.trim() || prev[0].email.trim())) {\n  404 |         return prev;","line":401,"column":5,"nodeType":null,"endLine":401,"endColumn":13,"suppressions":[{"kind":"directive","justification":""}]}],"errorCount":0,"fatalErrorCount":0,"warningCount":2,"fixableErrorCount":0,"fixableWarningCount":0,"source":"\"use client\";\r\n\r\nimport { useState, useEffect, useCallback } from \"react\";\r\nimport {\r\n  CreditCard,\r\n  Plus,\r\n  Trash2,\r\n  User,\r\n  Mail,\r\n  Building2,\r\n  Globe,\r\n  MapPin,\r\n  Hash,\r\n  Check,\r\n  AlertCircle,\r\n  ShoppingCart,\r\n} from \"lucide-react\";\r\nimport { Button } from \"@/components/ui/button\";\r\nimport { BusinessCardPreview } from \"@/features/delivery-management/components/business-card-preview\";\r\nimport { useCartContext } from \"@/features/cart/components/cart-context\";\r\nimport type { ProductResponseDTO } from \"@/features/products/dtos/product.dto\";\nimport type { DeliveryBusinessCardDTO } from \"@/features/delivery-management/dtos/delivery-management.dto\";\r\nimport type { BusinessCardCreateRequestDTO } from \"@/features/orders/dtos/order.dto\";\r\n\r\n// ============================================\r\n// Storage Key Pattern\r\n// ============================================\r\nconst BC_ORDER_STORAGE_KEY = \"singh-order-business-cards\";\r\n\r\nfunction getStorageKey(productId: string): string {\r\n  return `singh-bc-config-${productId}`;\r\n}\r\n\r\n// ============================================\r\n// Card Config Data (form state)\r\n// ============================================\r\ninterface CardConfigData {\r\n  name: string;\r\n  title: string;\r\n  email: string;\r\n  company: string;\r\n  address: string;\r\n  website: string;\r\n  quantity: number;\r\n}\r\n\r\nconst EMPTY_CARD: CardConfigData = {\r\n  name: \"\",\r\n  title: \"\",\r\n  email: \"\",\r\n  company: \"\",\r\n  address: \"\",\r\n  website: \"\",\r\n  quantity: 250,\r\n};\r\n\r\n\r\n// ============================================\r\n// Convert form data to preview card\r\n// ============================================\r\nfunction toPreviewCard(\r\n  card: CardConfigData,\r\n  index: number\r\n): DeliveryBusinessCardDTO {\r\n  return {\r\n    id: `config-${index}`,\r\n    deliveryOrderItemId: \"config\",\r\n    cardNumber: index + 1,\r\n    name: card.name || \"Your Name\",\r\n    title: card.title || null,\r\n    email: card.email || \"email@example.com\",\r\n    company: card.company || null,\r\n    address: card.address || null,\r\n    website: card.website || null,\r\n    quantity: card.quantity || 0,\r\n    createdAt: new Date().toISOString(),\r\n    updatedAt: new Date().toISOString(),\r\n  };\r\n}\r\n\r\n// ============================================\r\n// Validation\r\n// ============================================\r\nfunction validateCard(\r\n  card: CardConfigData,\r\n  index: number\r\n): Record<string, string> {\r\n  const errors: Record<string, string> = {};\r\n  if (!card.name.trim()) {\r\n    errors[`card${index}.name`] = \"Name is required\";\r\n  }\r\n  if (!card.email.trim()) {\r\n    errors[`card${index}.email`] = \"Email is required\";\r\n  } else if (\r\n    !/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(card.email.trim())\r\n  ) {\r\n    errors[`card${index}.email`] = \"Invalid email format\";\r\n  }\r\n  return errors;\r\n}\r\n\r\n// ============================================\r\n// Single Card Config Entry (Preview + Form)\r\n// ============================================\r\nfunction CardConfigEntry({\r\n  card,\r\n  index,\r\n  onChange,\r\n  onRemove,\r\n  onAddToCart,\r\n  canRemove,\r\n  addSuccessIndex,\n  minimumQuantity,\n}: {\r\n  card: CardConfigData;\r\n  index: number;\r\n  onChange: (index: number, field: keyof CardConfigData, value: string) => void;\r\n  onRemove: (index: number) => void;\r\n  onAddToCart: (index: number) => void;\r\n  canRemove: boolean;\r\n  addSuccessIndex: number | null;\n  minimumQuantity: number;\r\n}) {\r\n  const previewCard = toPreviewCard(card, index);\r\n\r\n  const handleChange = useCallback(\r\n    (field: keyof CardConfigData, value: string) => {\r\n      onChange(index, field, value);\r\n    },\r\n    [index, onChange]\r\n  );\r\n\r\n  return (\r\n    <div className=\"rounded-xl border border-gray-200 bg-white p-6\">\r\n      {/* Card Header */}\r\n      <div className=\"mb-4 flex items-center justify-between\">\r\n        <div className=\"flex items-center gap-2\">\r\n          <div className=\"flex h-7 w-7 items-center justify-center rounded-full bg-[#1a6b5a]/10 text-xs font-bold text-[#1a6b5a]\">\r\n            {index + 1}\r\n          </div>\r\n          <h3 className=\"text-sm font-semibold text-gray-900\">\r\n            Design {index + 1}\r\n          </h3>\r\n          {card.quantity > 0 && (\r\n            <span className=\"rounded-full bg-[#1a6b5a]/10 px-2 py-0.5 text-[10px] font-bold text-[#1a6b5a]\">\r\n              ×{card.quantity.toLocaleString()} copies\r\n            </span>\r\n          )}\r\n        </div>\r\n        {canRemove && (\r\n          <button\r\n            type=\"button\"\r\n            onClick={() => onRemove(index)}\r\n            className=\"rounded-lg p-1 text-gray-400 transition-colors hover:bg-red-50 hover:text-red-500\"\r\n          >\r\n            <Trash2 className=\"h-4 w-4\" />\r\n          </button>\r\n        )}\r\n      </div>\r\n\r\n      {/* Content: LHS Preview | RHS Form */}\r\n      <div className=\"grid gap-6 lg:grid-cols-2\">\r\n        {/* LHS: Card Preview */}\r\n        <div className=\"flex flex-col items-center\">\r\n          <p className=\"mb-2 text-[10px] font-medium uppercase tracking-wider text-gray-400\">\r\n            Card Preview\r\n          </p>\r\n          <BusinessCardPreview card={previewCard} format=\"both\" />\r\n        </div>\r\n\r\n        {/* RHS: Form Fields */}\r\n        <div className=\"space-y-4\">\r\n          {/* Name */}\r\n          <div className=\"space-y-1.5\">\r\n            <label className=\"block text-sm font-medium text-gray-700\">\r\n              Full Name <span className=\"text-red-500\">*</span>\r\n            </label>\r\n            <div className=\"relative\">\r\n              <User className=\"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400\" />\r\n              <input\r\n                type=\"text\"\r\n                value={card.name}\r\n                onChange={(e) => handleChange(\"name\", e.target.value)}\r\n                placeholder=\"e.g. Matt Swaney\"\r\n                className=\"block w-full rounded-lg border border-gray-200 bg-gray-50 py-2.5 pl-10 pr-4 text-sm text-gray-900 shadow-sm transition-colors placeholder:text-gray-400 focus:border-blue-500 focus:bg-white focus:outline-none focus:ring-1 focus:ring-blue-500\"\r\n              />\r\n            </div>\r\n          </div>\r\n\r\n          {/* Title */}\r\n          <div className=\"space-y-1.5\">\r\n            <label className=\"block text-sm font-medium text-gray-700\">\r\n              Job Title\r\n            </label>\r\n            <div className=\"relative\">\r\n              <Building2 className=\"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400\" />\r\n              <input\r\n                type=\"text\"\r\n                value={card.title}\r\n                onChange={(e) => handleChange(\"title\", e.target.value)}\r\n                placeholder=\"e.g. Marketing Manager\"\r\n                className=\"block w-full rounded-lg border border-gray-200 bg-gray-50 py-2.5 pl-10 pr-4 text-sm text-gray-900 shadow-sm transition-colors placeholder:text-gray-400 focus:border-blue-500 focus:bg-white focus:outline-none focus:ring-1 focus:ring-blue-500\"\r\n              />\r\n            </div>\r\n          </div>\r\n\r\n          {/* Email */}\r\n          <div className=\"space-y-1.5\">\r\n            <label className=\"block text-sm font-medium text-gray-700\">\r\n              Email <span className=\"text-red-500\">*</span>\r\n            </label>\r\n            <div className=\"relative\">\r\n              <Mail className=\"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400\" />\r\n              <input\r\n                type=\"email\"\r\n                value={card.email}\r\n                onChange={(e) => handleChange(\"email\", e.target.value)}\r\n                placeholder=\"e.g. name@singhmail.com\"\r\n                className=\"block w-full rounded-lg border border-gray-200 bg-gray-50 py-2.5 pl-10 pr-4 text-sm text-gray-900 shadow-sm transition-colors placeholder:text-gray-400 focus:border-blue-500 focus:bg-white focus:outline-none focus:ring-1 focus:ring-blue-500\"\r\n              />\r\n            </div>\r\n          </div>\r\n\r\n          {/* Company */}\r\n          <div className=\"space-y-1.5\">\r\n            <label className=\"block text-sm font-medium text-gray-700\">\r\n              Company\r\n            </label>\r\n            <div className=\"relative\">\r\n              <Building2 className=\"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400\" />\r\n              <input\r\n                type=\"text\"\r\n                value={card.company}\r\n                onChange={(e) => handleChange(\"company\", e.target.value)}\r\n                placeholder=\"e.g. Waltonwood Providence\"\r\n                className=\"block w-full rounded-lg border border-gray-200 bg-gray-50 py-2.5 pl-10 pr-4 text-sm text-gray-900 shadow-sm transition-colors placeholder:text-gray-400 focus:border-blue-500 focus:bg-white focus:outline-none focus:ring-1 focus:ring-blue-500\"\r\n              />\r\n            </div>\r\n          </div>\r\n\r\n          {/* Website */}\r\n          <div className=\"space-y-1.5\">\r\n            <label className=\"block text-sm font-medium text-gray-700\">\r\n              Website\r\n            </label>\r\n            <div className=\"relative\">\r\n              <Globe className=\"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400\" />\r\n              <input\r\n                type=\"url\"\r\n                value={card.website}\r\n                onChange={(e) => handleChange(\"website\", e.target.value)}\r\n                placeholder=\"e.g. waltonwood.com\"\r\n                className=\"block w-full rounded-lg border border-gray-200 bg-gray-50 py-2.5 pl-10 pr-4 text-sm text-gray-900 shadow-sm transition-colors placeholder:text-gray-400 focus:border-blue-500 focus:bg-white focus:outline-none focus:ring-1 focus:ring-blue-500\"\r\n              />\r\n            </div>\r\n          </div>\r\n\r\n          {/* Address */}\r\n          <div className=\"space-y-1.5\">\r\n            <label className=\"block text-sm font-medium text-gray-700\">\r\n              Address\r\n            </label>\r\n            <div className=\"relative\">\r\n              <MapPin className=\"absolute left-3 top-3 h-4 w-4 text-gray-400\" />\r\n              <textarea\r\n                value={card.address}\r\n                onChange={(e) => handleChange(\"address\", e.target.value)}\r\n                placeholder=\"e.g. 11945 Providence Road, Charlotte, NC 28277\"\r\n                rows={2}\r\n                className=\"block w-full resize-none rounded-lg border border-gray-200 bg-gray-50 py-2.5 pl-10 pr-4 text-sm text-gray-900 shadow-sm transition-colors placeholder:text-gray-400 focus:border-blue-500 focus:bg-white focus:outline-none focus:ring-1 focus:ring-blue-500\"\r\n              />\r\n            </div>\r\n          </div>\r\n          {/* Quantity */}\r\n          <div className=\"space-y-1.5\">\r\n            <label className=\"block text-sm font-medium text-gray-700\">\r\n              Quantity <span className=\"text-red-500\">*</span>\r\n            </label>\r\n            <div className=\"relative\">\r\n              <Hash className=\"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400\" />\r\n              <select\r\n                value={card.quantity}\r\n                onChange={(e) => handleChange(\"quantity\", e.target.value)}\r\n                className=\"block w-full rounded-lg border border-gray-200 bg-gray-50 py-2.5 pl-10 pr-4 text-sm text-gray-900 shadow-sm transition-colors focus:border-blue-500 focus:bg-white focus:outline-none focus:ring-1 focus:ring-blue-500\"\r\n              >\r\n                {Array.from({ length: 8 }, (_, index) => minimumQuantity * (index + 1)).map((qty) => (\r\n                  <option key={qty} value={qty}>\r\n                    {qty.toLocaleString()} copies\r\n                  </option>\r\n                ))}\r\n              </select>\r\n            </div>\r\n          </div>\r\n\r\n          {/* Add to Cart + Back to Order Buttons */}\r\n          <div className=\"pt-2 space-y-2\">\r\n            <Button\r\n              type=\"button\"\r\n              variant=\"secondary\"\r\n              size=\"sm\"\r\n              onClick={() => onAddToCart(index)}\r\n              className=\"w-full gap-1.5\"\r\n            >\r\n              {addSuccessIndex === index ? (\r\n                <>\r\n                  <Check className=\"h-4 w-4 text-emerald-600\" />\r\n                  <span className=\"text-emerald-600\">Added to Cart!</span>\r\n                </>\r\n              ) : (\r\n                <>\r\n                  <ShoppingCart className=\"h-4 w-4\" />\r\n                  Add to Cart\r\n                </>\r\n              )}\r\n            </Button>\r\n            <button\r\n              type=\"button\"\r\n              onClick={() => {\r\n                if (typeof window !== \"undefined\") {\r\n                  window.location.href = \"/orders/new\";\r\n                }\r\n              }}\r\n              className=\"flex w-full items-center justify-center gap-1.5 rounded-lg border border-gray-200 bg-white px-3 py-1.5 text-xs font-medium text-gray-600 transition-colors hover:bg-gray-50 hover:text-gray-900\"\r\n            >\r\n              Back to Order\r\n            </button>\r\n          </div>\r\n        </div>\r\n      </div>\r\n    </div>\r\n  );\r\n}\r\n\r\n// ============================================\r\n// Auto-fill data from company/department\r\n// ============================================\r\ninterface AutoFillData {\r\n  companyName: string | null;\r\n  departmentName: string | null;\r\n  departmentEmail: string | null;\r\n  departmentAddress: string | null;\r\n  departmentCity: string | null;\r\n  departmentState: string | null;\r\n  departmentZipCode: string | null;\r\n  departmentCountry: string | null;\r\n  departmentPhone: string | null;\r\n  departmentWebsite: string | null;\r\n}\r\n\r\n// ============================================\r\n// Business Card Config Form Props\r\n// ============================================\r\ninterface BusinessCardConfigFormProps {\n  product: ProductResponseDTO;\r\n  productId: string;\r\n  onSave: () => void;\r\n  onCancel: () => void;\r\n  autoFill?: AutoFillData | null;\r\n}\r\n\r\n// ============================================\r\n// Business Card Config Form Component\r\n// ============================================\r\nexport function BusinessCardConfigForm({\n  product,\r\n  productId,\r\n  onSave,\r\n  onCancel,\r\n  autoFill,\r\n}: BusinessCardConfigFormProps) {\r\n  const [cards, setCards] = useState<CardConfigData[]>(() => {\r\n    if (typeof window !== \"undefined\") {\r\n      try {\r\n        const stored = localStorage.getItem(getStorageKey(productId));\r\n        if (stored) {\r\n          const parsed = JSON.parse(stored) as CardConfigData[];\r\n          if (parsed.length > 0) {\r\n            // Migrate old cards that don't have quantity\r\n            return parsed.map((c) => ({\r\n              ...c,\r\n              quantity: c.quantity ?? product.minimumQuantity,\r\n            }));\r\n          }\r\n        }\r\n      } catch {\r\n        // ignore parse errors\r\n      }\r\n    }\r\n    return [{ ...EMPTY_CARD, quantity: product.minimumQuantity }];\r\n  });\r\n  const [fieldErrors, setFieldErrors] = useState<Record<string, string>>({});\r\n  const [showSuccess, setShowSuccess] = useState(false);\r\n  const [addSuccessIndex, setAddSuccessIndex] = useState<number | null>(null);\r\n  const { addToCart } = useCartContext();\r\n\r\n  // Auto-fill company/department info on first load (only if cards are empty)\r\n  useEffect(() => {\r\n    if (!autoFill) return;\r\n    // Initialize the draft from the API company and department.\n    // eslint-disable-next-line react-hooks/set-state-in-effect\n    setCards((prev) => {\r\n      // Only auto-fill if the first card is empty\r\n      if (prev.length > 1 || (prev[0].name.trim() || prev[0].email.trim())) {\r\n        return prev;\r\n      }\r\n      const addressParts = [\r\n        autoFill.departmentAddress,\r\n        autoFill.departmentCity,\r\n        autoFill.departmentState,\r\n        autoFill.departmentZipCode,\r\n        autoFill.departmentCountry,\r\n      ].filter(Boolean);\r\n      return [\r\n        {\r\n          ...prev[0],\r\n          company: autoFill.departmentName ?? autoFill.companyName ?? \"\",\r\n          email: autoFill.departmentEmail ?? \"\",\r\n          address: addressParts.join(\", \"),\r\n          website: autoFill.departmentWebsite ?? \"\",\r\n        },\r\n      ];\r\n    });\r\n  }, [autoFill]);\r\n\r\n  // Auto-save to localStorage on change\r\n  useEffect(() => {\r\n    const validCards = cards.filter(\r\n      (c) => c.name.trim() || c.email.trim()\r\n    );\r\n    if (validCards.length > 0) {\r\n      localStorage.setItem(\r\n        getStorageKey(productId),\r\n        JSON.stringify(validCards)\r\n      );\r\n    }\r\n  }, [cards, productId]);\r\n\r\n  const handleChange = useCallback(\r\n    (index: number, field: keyof CardConfigData, value: string) => {\r\n      setCards((prev) =>\r\n        prev.map((card, i) => {\r\n          if (i !== index) return card;\r\n          // Convert quantity string to number\r\n          if (field === \"quantity\") {\r\n            const num = parseInt(value);\r\n            return { ...card, quantity: isNaN(num) || num < 1 ? 1 : num };\r\n          }\r\n          return { ...card, [field]: value };\r\n        })\r\n      );\r\n      // Clear field error on change\r\n      const errorKey = `card${index}.${field}`;\r\n      if (fieldErrors[errorKey]) {\r\n        setFieldErrors((prev) => {\r\n          const next = { ...prev };\r\n          delete next[errorKey];\r\n          return next;\r\n        });\r\n      }\r\n    },\r\n    [fieldErrors]\r\n  );\r\n\r\n  const handleAddCard = useCallback(() => {\r\n    setCards((prev) => [...prev, { ...EMPTY_CARD, quantity: product.minimumQuantity }]);\r\n    setTimeout(() => {\r\n      window.scrollTo({\r\n        top: document.body.scrollHeight,\r\n        behavior: \"smooth\",\r\n      });\r\n    }, 100);\r\n  }, [product.minimumQuantity]);\r\n\r\n  const handleRemoveCard = useCallback((index: number) => {\r\n    setCards((prev) => {\r\n      const next = prev.filter((_, i) => i !== index);\r\n      return next.length > 0 ? next : [{ ...EMPTY_CARD, quantity: product.minimumQuantity }];\r\n    });\r\n  }, [product.minimumQuantity]);\r\n\r\n  const handleAddToCart = useCallback(\r\n    (index: number) => {\r\n      const card = cards[index];\r\n      // Validate the card\r\n      const cardErrors = validateCard(card, index);\r\n      if (Object.keys(cardErrors).length > 0) {\r\n        setFieldErrors(cardErrors);\r\n        return;\r\n      }\r\n\r\n      // Convert to BusinessCardCreateRequestDTO\r\n      const bcDTO: BusinessCardCreateRequestDTO = {\r\n        orderItemId: \"\",\r\n        cardNumber: 1,\r\n        name: card.name.trim(),\r\n        title: card.title.trim() || null,\r\n        email: card.email.trim(),\r\n        company: card.company.trim() || null,\r\n        address: card.address.trim() || null,\r\n        website: card.website.trim() || null,\r\n        quantity: card.quantity || product.minimumQuantity,\r\n      };\r\n\r\n      // Add to unified cart system (instead of separate localStorage)\r\n      addToCart({\r\n        productId: product.id,\r\n        productName: product.name,\r\n        productImageUrl: product.imageUrl,\r\n        isBusinessCard: true,\r\n        productVariantId: null,\r\n        variantName: null,\r\n        size: null,\r\n        quantity: bcDTO.quantity,\r\n        minimumQuantity: product.minimumQuantity,\r\n        businessCards: [bcDTO],\r\n      });\r\n\r\n      // Show success feedback\r\n      setAddSuccessIndex(index);\r\n      setTimeout(() => setAddSuccessIndex(null), 2000);\r\n    },\r\n    [cards, addToCart, product]\r\n  );\r\n\r\n  const handleSave = useCallback(() => {\r\n    // Validate all cards\r\n    const allErrors: Record<string, string> = {};\r\n    cards.forEach((card, index) => {\r\n      // Skip empty cards\r\n      if (!card.name.trim() && !card.email.trim()) return;\r\n      const cardErrors = validateCard(card, index);\r\n      Object.assign(allErrors, cardErrors);\r\n    });\r\n\r\n    if (Object.keys(allErrors).length > 0) {\r\n      setFieldErrors(allErrors);\r\n      return;\r\n    }\r\n\r\n    // Save valid cards to config storage (for form draft persistence)\r\n    const validCards = cards.filter(\r\n      (c) => c.name.trim() || c.email.trim()\r\n    );\r\n    localStorage.setItem(\r\n      getStorageKey(productId),\r\n      JSON.stringify(validCards)\r\n    );\r\n\r\n    // Convert to BusinessCardCreateRequestDTO[] and add to unified cart\r\n    const bcDTOs: BusinessCardCreateRequestDTO[] = validCards.map(\r\n      (card, idx) => ({\r\n        orderItemId: \"\",\r\n        cardNumber: idx + 1,\r\n        name: card.name.trim(),\r\n        title: card.title.trim() || null,\r\n        email: card.email.trim(),\r\n        company: card.company.trim() || null,\r\n        address: card.address.trim() || null,\r\n        website: card.website.trim() || null,\r\n        quantity: card.quantity || product.minimumQuantity,\r\n      })\r\n    );\r\n    for (let offset = 0; offset < bcDTOs.length; offset += 3) {\n      const batch = bcDTOs.slice(offset, offset + 3).map((card, index) => ({ ...card, cardNumber: index + 1 }));\r\n      // Calculate total quantity across all designs\r\n      const totalQuantity = batch.reduce((sum, bc) => sum + bc.quantity, 0);\r\n      addToCart({\r\n        productId: product.id,\r\n        productName: product.name,\r\n        productImageUrl: product.imageUrl,\r\n        isBusinessCard: true,\r\n        productVariantId: null,\r\n        variantName: null,\r\n        size: null,\r\n        quantity: totalQuantity,\r\n        minimumQuantity: product.minimumQuantity,\r\n        businessCards: batch,\r\n      });\r\n    }\r\n\r\n    setShowSuccess(true);\r\n    setTimeout(() => {\r\n      setShowSuccess(false);\r\n      onSave();\r\n    }, 1500);\r\n  }, [cards, productId, onSave, addToCart, product]);\r\n\r\n  return (\r\n    <div className=\"space-y-6\">\r\n      {/* Success Toast */}\r\n      {showSuccess && (\r\n        <div className=\"fixed right-4 top-4 z-50 flex items-center gap-2 rounded-lg border border-emerald-200 bg-emerald-50 px-4 py-3 shadow-lg\">\r\n          <Check className=\"h-4 w-4 text-emerald-600\" />\r\n          <span className=\"text-sm font-medium text-emerald-700\">\r\n            Business card designs saved successfully!\r\n          </span>\r\n        </div>\r\n      )}\r\n\r\n      {/* Validation Summary */}\r\n      {Object.keys(fieldErrors).length > 0 && (\r\n        <div className=\"flex items-start gap-2 rounded-lg border border-red-200 bg-red-50 p-3\">\r\n          <AlertCircle className=\"mt-0.5 h-4 w-4 flex-shrink-0 text-red-500\" />\r\n          <div>\r\n            <p className=\"text-sm font-medium text-red-700\">\r\n              Please fix the following errors:\r\n            </p>\r\n            <ul className=\"mt-1 list-inside list-disc text-xs text-red-600\">\r\n              {Object.values(fieldErrors).map((err, i) => (\r\n                <li key={i}>{err}</li>\r\n              ))}\r\n            </ul>\r\n          </div>\r\n        </div>\r\n      )}\r\n\r\n      {/* Cards */}\r\n      <div className=\"space-y-6\">\r\n        {cards.map((card, index) => (\r\n          <CardConfigEntry\r\n            key={index}\r\n            card={card}\n            minimumQuantity={product.minimumQuantity}\r\n            index={index}\r\n            onChange={handleChange}\r\n            onRemove={handleRemoveCard}\r\n            onAddToCart={handleAddToCart}\r\n            canRemove={cards.length > 1}\r\n            addSuccessIndex={addSuccessIndex}\r\n          />\r\n        ))}\r\n      </div>\r\n\r\n      {/* Add Card Button */}\r\n      {cards.length < 10 && (\r\n        <button\r\n          type=\"button\"\r\n          onClick={handleAddCard}\r\n          className=\"flex w-full items-center justify-center gap-2 rounded-lg border-2 border-dashed border-[#1a6b5a]/30 py-4 text-sm font-medium text-[#1a6b5a] transition-colors hover:border-[#1a6b5a] hover:bg-[#1a6b5a]/5\"\r\n        >\r\n          <Plus className=\"h-4 w-4\" />\r\n          Add Another Business Card Design\r\n        </button>\r\n      )}\r\n\r\n      {/* Actions */}\r\n      <div className=\"flex items-center justify-end gap-3 rounded-xl border border-gray-200 bg-white px-6 py-4\">\r\n        <Button type=\"button\" variant=\"ghost\" onClick={onCancel}>\r\n          Cancel\r\n        </Button>\r\n        <Button type=\"button\" onClick={handleSave}>\r\n          <Check className=\"h-4 w-4\" />\r\n          Save Designs\r\n        </Button>\r\n      </div>\r\n    </div>\r\n  );\r\n}\r\n","usedDeprecatedRules":[]},{"filePath":"C:\\xampp\\htdocs\\order\\order\\features\\cart\\components\\cart-context.tsx","messages":[],"suppressedMessages":[{"ruleId":"react-hooks/set-state-in-effect","severity":2,"message":"Error: Calling setState synchronously within an effect can trigger cascading renders\n\nEffects are intended to synchronize state between React and external systems such as manually updating the DOM, state management libraries, or other platform APIs. In general, the body of an effect should do one or both of the following:\n* Update external systems with the latest state from React.\n* Subscribe for updates from some external system, calling setState in a callback function when external state changes.\n\nCalling setState synchronously within an effect body causes cascading renders that can hurt performance, and is not recommended. (https://react.dev/learn/you-might-not-need-an-effect).\n\nC:\\xampp\\htdocs\\order\\order\\features\\cart\\components\\cart-context.tsx:63:5\n  61 |     // Restore the browser cart after SSR.\n  62 |     // eslint-disable-next-line react-hooks/set-state-in-effect\n> 63 |     setData(cartService.getCart());\n     |     ^^^^^^^ Avoid calling setState() directly within an effect\n  64 |     setHydrated(true);\n  65 |     const sync = (event: StorageEvent) => {\n  66 |       if (event.key === \"singh-cart\" || event.key === null) setData(cartService.getCart());","line":63,"column":5,"nodeType":null,"endLine":63,"endColumn":12,"suppressions":[{"kind":"directive","justification":""}]}],"errorCount":0,"fatalErrorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0,"usedDeprecatedRules":[]},{"filePath":"C:\\xampp\\htdocs\\order\\order\\features\\companies\\hooks\\use-companies.ts","messages":[],"suppressedMessages":[{"ruleId":"react-hooks/set-state-in-effect","severity":2,"message":"Error: Calling setState synchronously within an effect can trigger cascading renders\n\nEffects are intended to synchronize state between React and external systems such as manually updating the DOM, state management libraries, or other platform APIs. In general, the body of an effect should do one or both of the following:\n* Update external systems with the latest state from React.\n* Subscribe for updates from some external system, calling setState in a callback function when external state changes.\n\nCalling setState synchronously within an effect body causes cascading renders that can hurt performance, and is not recommended. (https://react.dev/learn/you-might-not-need-an-effect).\n\nC:\\xampp\\htdocs\\order\\order\\features\\companies\\hooks\\use-companies.ts:78:10\n  76 |     // Data fetching on mount — setState in effect is intentional here\n  77 |     // eslint-disable-next-line react-hooks/set-state-in-effect\n> 78 |     void fetchCompanies();\n     |          ^^^^^^^^^^^^^^ Avoid calling setState() directly within an effect\n  79 |   }, [fetchCompanies]);\n  80 |\n  81 |   useApiRefresh(fetchCompanies);","line":78,"column":10,"nodeType":null,"endLine":78,"endColumn":24,"suppressions":[{"kind":"directive","justification":""}]}],"errorCount":0,"fatalErrorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0,"usedDeprecatedRules":[]},{"filePath":"C:\\xampp\\htdocs\\order\\order\\features\\companies\\hooks\\use-company-departments.ts","messages":[{"ruleId":"react-hooks/exhaustive-deps","severity":1,"message":"React Hook useCallback has an unnecessary dependency: 'companyId'. Either exclude it or remove the dependency array.","line":122,"column":5,"nodeType":"ArrayExpression","endLine":122,"endColumn":34,"suggestions":[{"desc":"Update the dependencies array to be: [fetchDepartments]","fix":{"range":[4294,4323],"text":"[fetchDepartments]"}}]}],"suppressedMessages":[{"ruleId":"react-hooks/set-state-in-effect","severity":2,"message":"Error: Calling setState synchronously within an effect can trigger cascading renders\n\nEffects are intended to synchronize state between React and external systems such as manually updating the DOM, state management libraries, or other platform APIs. In general, the body of an effect should do one or both of the following:\n* Update external systems with the latest state from React.\n* Subscribe for updates from some external system, calling setState in a callback function when external state changes.\n\nCalling setState synchronously within an effect body causes cascading renders that can hurt performance, and is not recommended. (https://react.dev/learn/you-might-not-need-an-effect).\n\nC:\\xampp\\htdocs\\order\\order\\features\\companies\\hooks\\use-company-departments.ts:85:10\n  83 |     // Data fetching on mount — setState in effect is intentional here\n  84 |     // eslint-disable-next-line react-hooks/set-state-in-effect\n> 85 |     void fetchDepartments();\n     |          ^^^^^^^^^^^^^^^^ Avoid calling setState() directly within an effect\n  86 |   }, [fetchDepartments]);\n  87 |\n  88 |   useApiRefresh(fetchDepartments);","line":85,"column":10,"nodeType":null,"endLine":85,"endColumn":26,"suppressions":[{"kind":"directive","justification":""}]}],"errorCount":0,"fatalErrorCount":0,"warningCount":1,"fixableErrorCount":0,"fixableWarningCount":0,"source":"\"use client\";\r\n\r\nimport { allApiPages } from \"@/lib/all-api-pages\";\nimport { useApiRefresh } from \"@/lib/api-refresh\";\nimport { useApiFilters } from \"@/lib/use-api-filters\";\n\nimport { useRef, useState, useEffect, useCallback } from \"react\";\r\nimport { departmentService } from \"../services/company.service\";\r\nimport { ApiErrorDTO } from \"@/shared/common\";\r\nimport type { PaginatedResponseDTO } from \"@/shared/common\";\r\nimport type {\r\n  DepartmentResponseDTO,\r\n  DepartmentCreateRequestDTO,\r\n  DepartmentUpdateRequestDTO,\r\n  DepartmentFilterRequestDTO,\r\n} from \"../dtos/company.dto\";\r\n\r\n// H2: State: data, loading (init true), error, refetch.\r\n// H3: After mutation success → refetch relevant list + toast.success(result.message)\r\n// H4: On error → toast.error(error.message) + setError(). Never re-throw.\r\n// H5: Toasts fire in hook only. Never in Page or Service.\r\n// H8: Hooks orchestrate state only. No business logic, response transformation.\r\n\r\ninterface UseCompanyDepartmentsReturn {\r\n  data: PaginatedResponseDTO<DepartmentResponseDTO> | null;\r\n  departments: DepartmentResponseDTO[];\r\n  isLoading: boolean;\r\n  error: string | null;\r\n  refetch: () => Promise<void>;\r\n  clearError: () => void;\r\n  createDepartment: (data: DepartmentCreateRequestDTO) => Promise<boolean>;\r\n  updateDepartment: (\r\n    id: string,\r\n    data: DepartmentUpdateRequestDTO\r\n  ) => Promise<boolean>;\r\n  deleteDepartment: (id: string) => Promise<boolean>;\r\n  toggleDepartmentStatus: (id: string) => Promise<boolean>;\r\n}\r\n\r\nexport function useCompanyDepartments(\r\n  companyId: string,\r\n  initialFilters?: DepartmentFilterRequestDTO\r\n): UseCompanyDepartmentsReturn {\r\n  const [data, setData] =\r\n    useState<PaginatedResponseDTO<DepartmentResponseDTO> | null>(null);\r\n  const [isLoading, setIsLoading] = useState(true);\r\n  const [error, setError] = useState<string | null>(null);\r\n  const filters = useApiFilters<DepartmentFilterRequestDTO>(initialFilters);\r\n\r\n  const requestSequence = useRef(0);\n  const fetchDepartments = useCallback(async () => {\n    if (!companyId || companyId === \"__none__\") {\n      setData(null);\n      setError(null);\n      setIsLoading(false);\n      return;\n    }\n    const requestId = ++requestSequence.current;\n    setIsLoading(true);\r\n    setError(null);\r\n\r\n    try {\r\n      {\r\n        const result = await (filters.page === undefined\n          ? allApiPages((page) => departmentService.listDepartments(companyId, { ...filters, page, perPage: 100 }))\n          : departmentService.listDepartments(companyId, filters));\r\n        if (requestId === requestSequence.current) setData(result);\r\n      }\r\n    } catch (err) {\r\n      const message =\r\n        err instanceof ApiErrorDTO\r\n          ? err.message\r\n          : err instanceof Error\r\n            ? err.message\r\n            : \"Failed to load departments. Please try again.\";\r\n      if (requestId === requestSequence.current) setError(message);\r\n    } finally {\r\n      if (requestId === requestSequence.current) setIsLoading(false);\r\n    }\r\n  }, [companyId, filters]);\r\n\r\n  useEffect(() => {\r\n    // Data fetching on mount — setState in effect is intentional here\r\n    // eslint-disable-next-line react-hooks/set-state-in-effect\r\n    void fetchDepartments();\r\n  }, [fetchDepartments]);\r\n\r\n  useApiRefresh(fetchDepartments);\n\n  const clearError = useCallback(() => {\r\n    setError(null);\r\n  }, []);\r\n\r\n  // --- Create Department ---\r\n  const createDepartment = useCallback(\r\n    async (deptData: DepartmentCreateRequestDTO): Promise<boolean> => {\r\n      try {\r\n        \r\n\r\n        const result = await departmentService.createDepartment(deptData);\r\n        if (typeof window !== \"undefined\" && result.message) {\r\n          const { toast } = await import(\"react-hot-toast\");\r\n          toast.success(result.message);\r\n        }\r\n        await fetchDepartments();\r\n        return true;\r\n      } catch (err) {\r\n        const message =\r\n          err instanceof ApiErrorDTO\r\n            ? err.message\r\n            : err instanceof Error\r\n              ? err.message\r\n              : \"Failed to create department.\";\r\n        setError(message);\r\n        if (typeof window !== \"undefined\") {\r\n          const { toast } = await import(\"react-hot-toast\");\r\n          toast.error(message);\r\n        }\r\n        return false;\r\n      }\r\n    },\r\n    [companyId, fetchDepartments]\r\n  );\r\n\r\n  // --- Update Department ---\r\n  const updateDepartment = useCallback(\r\n    async (\r\n      id: string,\r\n      deptData: DepartmentUpdateRequestDTO\r\n    ): Promise<boolean> => {\r\n      try {\r\n        \r\n\r\n        const result = await departmentService.updateDepartment(\r\n          companyId,\r\n          id,\r\n          deptData\r\n        );\r\n        if (typeof window !== \"undefined\" && result.message) {\r\n          const { toast } = await import(\"react-hot-toast\");\r\n          toast.success(result.message);\r\n        }\r\n        await fetchDepartments();\r\n        return true;\r\n      } catch (err) {\r\n        const message =\r\n          err instanceof ApiErrorDTO\r\n            ? err.message\r\n            : err instanceof Error\r\n              ? err.message\r\n              : \"Failed to update department.\";\r\n        setError(message);\r\n        if (typeof window !== \"undefined\") {\r\n          const { toast } = await import(\"react-hot-toast\");\r\n          toast.error(message);\r\n        }\r\n        return false;\r\n      }\r\n    },\r\n    [companyId, fetchDepartments]\r\n  );\r\n\r\n  // --- Delete Department ---\r\n  const deleteDepartment = useCallback(\r\n    async (id: string): Promise<boolean> => {\r\n      try {\r\n        \r\n\r\n        const result = await departmentService.deleteDepartment(\r\n          companyId,\r\n          id\r\n        );\r\n        if (typeof window !== \"undefined\" && result.message) {\r\n          const { toast } = await import(\"react-hot-toast\");\r\n          toast.success(result.message);\r\n        }\r\n        await fetchDepartments();\r\n        return true;\r\n      } catch (err) {\r\n        const message =\r\n          err instanceof ApiErrorDTO\r\n            ? err.message\r\n            : err instanceof Error\r\n              ? err.message\r\n              : \"Failed to delete department.\";\r\n        setError(message);\r\n        if (typeof window !== \"undefined\") {\r\n          const { toast } = await import(\"react-hot-toast\");\r\n          toast.error(message);\r\n        }\r\n        return false;\r\n      }\r\n    },\r\n    [companyId, fetchDepartments]\r\n  );\r\n\r\n  // --- Toggle Department Status ---\r\n  const toggleDepartmentStatus = useCallback(\r\n    async (id: string): Promise<boolean> => {\r\n      try {\r\n        \r\n\r\n        const result = await departmentService.toggleDepartmentStatus(\r\n          companyId,\r\n          id\r\n        );\r\n        if (typeof window !== \"undefined\" && result.message) {\r\n          const { toast } = await import(\"react-hot-toast\");\r\n          toast.success(result.message);\r\n        }\r\n        await fetchDepartments();\r\n        return true;\r\n      } catch (err) {\r\n        const message =\r\n          err instanceof ApiErrorDTO\r\n            ? err.message\r\n            : err instanceof Error\r\n              ? err.message\r\n              : \"Failed to toggle department status.\";\r\n        setError(message);\r\n        if (typeof window !== \"undefined\") {\r\n          const { toast } = await import(\"react-hot-toast\");\r\n          toast.error(message);\r\n        }\r\n        return false;\r\n      }\r\n    },\r\n    [companyId, fetchDepartments]\r\n  );\r\n\r\n  return {\r\n    data,\r\n    departments: data?.data ?? [],\r\n    isLoading,\r\n    error,\r\n    refetch: fetchDepartments,\r\n    clearError,\r\n    createDepartment,\r\n    updateDepartment,\r\n    deleteDepartment,\r\n    toggleDepartmentStatus,\r\n  };\r\n}\r\n","usedDeprecatedRules":[]},{"filePath":"C:\\xampp\\htdocs\\order\\order\\features\\companies\\hooks\\use-company-users.ts","messages":[],"suppressedMessages":[{"ruleId":"react-hooks/set-state-in-effect","severity":2,"message":"Error: Calling setState synchronously within an effect can trigger cascading renders\n\nEffects are intended to synchronize state between React and external systems such as manually updating the DOM, state management libraries, or other platform APIs. In general, the body of an effect should do one or both of the following:\n* Update external systems with the latest state from React.\n* Subscribe for updates from some external system, calling setState in a callback function when external state changes.\n\nCalling setState synchronously within an effect body causes cascading renders that can hurt performance, and is not recommended. (https://react.dev/learn/you-might-not-need-an-effect).\n\nC:\\xampp\\htdocs\\order\\order\\features\\companies\\hooks\\use-company-users.ts:82:10\n  80 |     // Data fetching on mount — setState in effect is intentional here\n  81 |     // eslint-disable-next-line react-hooks/set-state-in-effect\n> 82 |     void fetchUsers();\n     |          ^^^^^^^^^^ Avoid calling setState() directly within an effect\n  83 |   }, [fetchUsers]);\n  84 |\n  85 |   useApiRefresh(fetchUsers);","line":82,"column":10,"nodeType":null,"endLine":82,"endColumn":20,"suppressions":[{"kind":"directive","justification":""}]}],"errorCount":0,"fatalErrorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0,"usedDeprecatedRules":[]},{"filePath":"C:\\xampp\\htdocs\\order\\order\\features\\delivery-management\\hooks\\use-delivery-management.ts","messages":[],"suppressedMessages":[{"ruleId":"react-hooks/set-state-in-effect","severity":2,"message":"Error: Calling setState synchronously within an effect can trigger cascading renders\n\nEffects are intended to synchronize state between React and external systems such as manually updating the DOM, state management libraries, or other platform APIs. In general, the body of an effect should do one or both of the following:\n* Update external systems with the latest state from React.\n* Subscribe for updates from some external system, calling setState in a callback function when external state changes.\n\nCalling setState synchronously within an effect body causes cascading renders that can hurt performance, and is not recommended. (https://react.dev/learn/you-might-not-need-an-effect).\n\nC:\\xampp\\htdocs\\order\\order\\features\\delivery-management\\hooks\\use-delivery-management.ts:74:10\n  72 |     // Data fetching on mount — setState in effect is intentional here\n  73 |     // eslint-disable-next-line react-hooks/set-state-in-effect\n> 74 |     void fetchDeliveryOrders();\n     |          ^^^^^^^^^^^^^^^^^^^ Avoid calling setState() directly within an effect\n  75 |   }, [fetchDeliveryOrders]);\n  76 |\n  77 |   useApiRefresh(fetchDeliveryOrders);","line":74,"column":10,"nodeType":null,"endLine":74,"endColumn":29,"suppressions":[{"kind":"directive","justification":""}]}],"errorCount":0,"fatalErrorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0,"usedDeprecatedRules":[]},{"filePath":"C:\\xampp\\htdocs\\order\\order\\features\\delivery-management\\hooks\\use-delivery-order-detail.ts","messages":[],"suppressedMessages":[{"ruleId":"react-hooks/set-state-in-effect","severity":2,"message":"Error: Calling setState synchronously within an effect can trigger cascading renders\n\nEffects are intended to synchronize state between React and external systems such as manually updating the DOM, state management libraries, or other platform APIs. In general, the body of an effect should do one or both of the following:\n* Update external systems with the latest state from React.\n* Subscribe for updates from some external system, calling setState in a callback function when external state changes.\n\nCalling setState synchronously within an effect body causes cascading renders that can hurt performance, and is not recommended. (https://react.dev/learn/you-might-not-need-an-effect).\n\nC:\\xampp\\htdocs\\order\\order\\features\\delivery-management\\hooks\\use-delivery-order-detail.ts:56:10\n  54 |     // Data fetching on mount — setState in effect is intentional here\n  55 |     // eslint-disable-next-line react-hooks/set-state-in-effect\n> 56 |     void fetchOrder();\n     |          ^^^^^^^^^^ Avoid calling setState() directly within an effect\n  57 |   }, [fetchOrder]);\n  58 |\n  59 |   // --- Update Order Status ---","line":56,"column":10,"nodeType":null,"endLine":56,"endColumn":20,"suppressions":[{"kind":"directive","justification":""}]}],"errorCount":0,"fatalErrorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0,"usedDeprecatedRules":[]},{"filePath":"C:\\xampp\\htdocs\\order\\order\\features\\notifications\\hooks\\use-notifications.ts","messages":[],"suppressedMessages":[{"ruleId":"react-hooks/set-state-in-effect","severity":2,"message":"Error: Calling setState synchronously within an effect can trigger cascading renders\n\nEffects are intended to synchronize state between React and external systems such as manually updating the DOM, state management libraries, or other platform APIs. In general, the body of an effect should do one or both of the following:\n* Update external systems with the latest state from React.\n* Subscribe for updates from some external system, calling setState in a callback function when external state changes.\n\nCalling setState synchronously within an effect body causes cascading renders that can hurt performance, and is not recommended. (https://react.dev/learn/you-might-not-need-an-effect).\n\nC:\\xampp\\htdocs\\order\\order\\features\\notifications\\hooks\\use-notifications.ts:71:10\n  69 |     // Data fetching on mount — setState in effect is intentional here\n  70 |     // eslint-disable-next-line react-hooks/set-state-in-effect\n> 71 |     void fetchNotifications();\n     |          ^^^^^^^^^^^^^^^^^^ Avoid calling setState() directly within an effect\n  72 |   }, [fetchNotifications]);\n  73 |\n  74 |   useApiRefresh(fetchNotifications);","line":71,"column":10,"nodeType":null,"endLine":71,"endColumn":28,"suppressions":[{"kind":"directive","justification":""}]}],"errorCount":0,"fatalErrorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0,"usedDeprecatedRules":[]},{"filePath":"C:\\xampp\\htdocs\\order\\order\\features\\orders\\hooks\\use-order-detail.ts","messages":[],"suppressedMessages":[{"ruleId":"react-hooks/set-state-in-effect","severity":2,"message":"Error: Calling setState synchronously within an effect can trigger cascading renders\n\nEffects are intended to synchronize state between React and external systems such as manually updating the DOM, state management libraries, or other platform APIs. In general, the body of an effect should do one or both of the following:\n* Update external systems with the latest state from React.\n* Subscribe for updates from some external system, calling setState in a callback function when external state changes.\n\nCalling setState synchronously within an effect body causes cascading renders that can hurt performance, and is not recommended. (https://react.dev/learn/you-might-not-need-an-effect).\n\nC:\\xampp\\htdocs\\order\\order\\features\\orders\\hooks\\use-order-detail.ts:50:10\n  48 |     // Data fetching on mount — setState in effect is intentional here\n  49 |     // eslint-disable-next-line react-hooks/set-state-in-effect\n> 50 |     void fetchOrder();\n     |          ^^^^^^^^^^ Avoid calling setState() directly within an effect\n  51 |   }, [fetchOrder]);\n  52 |\n  53 |   useApiRefresh(fetchOrder);","line":50,"column":10,"nodeType":null,"endLine":50,"endColumn":20,"suppressions":[{"kind":"directive","justification":""}]}],"errorCount":0,"fatalErrorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0,"usedDeprecatedRules":[]},{"filePath":"C:\\xampp\\htdocs\\order\\order\\features\\orders\\hooks\\use-orders.ts","messages":[],"suppressedMessages":[{"ruleId":"react-hooks/set-state-in-effect","severity":2,"message":"Error: Calling setState synchronously within an effect can trigger cascading renders\n\nEffects are intended to synchronize state between React and external systems such as manually updating the DOM, state management libraries, or other platform APIs. In general, the body of an effect should do one or both of the following:\n* Update external systems with the latest state from React.\n* Subscribe for updates from some external system, calling setState in a callback function when external state changes.\n\nCalling setState synchronously within an effect body causes cascading renders that can hurt performance, and is not recommended. (https://react.dev/learn/you-might-not-need-an-effect).\n\nC:\\xampp\\htdocs\\order\\order\\features\\orders\\hooks\\use-orders.ts:81:10\n  79 |     // Data fetching on mount — setState in effect is intentional here\n  80 |     // eslint-disable-next-line react-hooks/set-state-in-effect\n> 81 |     void fetchOrders();\n     |          ^^^^^^^^^^^ Avoid calling setState() directly within an effect\n  82 |   }, [fetchOrders]);\n  83 |\n  84 |   useApiRefresh(fetchOrders);","line":81,"column":10,"nodeType":null,"endLine":81,"endColumn":21,"suppressions":[{"kind":"directive","justification":""}]}],"errorCount":0,"fatalErrorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0,"usedDeprecatedRules":[]},{"filePath":"C:\\xampp\\htdocs\\order\\order\\features\\products\\hooks\\use-products.ts","messages":[],"suppressedMessages":[{"ruleId":"react-hooks/set-state-in-effect","severity":2,"message":"Error: Calling setState synchronously within an effect can trigger cascading renders\n\nEffects are intended to synchronize state between React and external systems such as manually updating the DOM, state management libraries, or other platform APIs. In general, the body of an effect should do one or both of the following:\n* Update external systems with the latest state from React.\n* Subscribe for updates from some external system, calling setState in a callback function when external state changes.\n\nCalling setState synchronously within an effect body causes cascading renders that can hurt performance, and is not recommended. (https://react.dev/learn/you-might-not-need-an-effect).\n\nC:\\xampp\\htdocs\\order\\order\\features\\products\\hooks\\use-products.ts:78:10\n  76 |     // Data fetching on mount — setState in effect is intentional here\n  77 |     // eslint-disable-next-line react-hooks/set-state-in-effect\n> 78 |     void fetchProducts();\n     |          ^^^^^^^^^^^^^ Avoid calling setState() directly within an effect\n  79 |   }, [fetchProducts]);\n  80 |\n  81 |   useApiRefresh(fetchProducts);","line":78,"column":10,"nodeType":null,"endLine":78,"endColumn":23,"suppressions":[{"kind":"directive","justification":""}]}],"errorCount":0,"fatalErrorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0,"usedDeprecatedRules":[]},{"filePath":"C:\\xampp\\htdocs\\order\\order\\lib\\all-api-pages.ts","messages":[],"suppressedMessages":[],"errorCount":0,"fatalErrorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0,"usedDeprecatedRules":[]},{"filePath":"C:\\xampp\\htdocs\\order\\order\\lib\\api-client.ts","messages":[],"suppressedMessages":[],"errorCount":0,"fatalErrorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0,"usedDeprecatedRules":[]},{"filePath":"C:\\xampp\\htdocs\\order\\order\\lib\\api-refresh.ts","messages":[],"suppressedMessages":[],"errorCount":0,"fatalErrorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0,"usedDeprecatedRules":[]},{"filePath":"C:\\xampp\\htdocs\\order\\order\\lib\\use-api-filters.ts","messages":[],"suppressedMessages":[],"errorCount":0,"fatalErrorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0,"usedDeprecatedRules":[]},{"filePath":"C:\\xampp\\htdocs\\order\\order\\lib\\utils.ts","messages":[],"suppressedMessages":[],"errorCount":0,"fatalErrorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0,"usedDeprecatedRules":[]}]
