"use client";

import { useEffect, useMemo, useState, type ReactNode } from "react";
import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";
import Sidebar from "@/components/Sidebar";
import Footer from "@/components/Footer";
import BackgroundGradients from "@/components/BackgroundGradients";
import staticCopy from "@/i18n/staticCopy.json";
import {
  DEFAULT_LOCALE,
  getStoredLocale,
  LOCALE_CHANGE_EVENT,
  type LocaleCode,
} from "@/i18n/localeSwitcher";

const STATUS_STYLES: Record<string, string> = {
  Delivered: "bg-[#008000]/10 border border-[#008000]/50 text-[#008000]",
  "In Transit": "bg-[#155DFC]/10 border border-[#155DFC]/50 text-[#155DFC]",
  "Out for Delivery": "bg-[#155DFC]/10 border border-[#155DFC]/50 text-[#155DFC]",
  Pending: "bg-[#CB8601]/10 border border-[#CB8601]/50 text-[#CB8601]",
  Confirmed: "bg-[#F7FAF8] border border-[#053F31]/50 text-[#053F31]",
  Cancelled: "bg-[#FE3D45]/10 border border-[#FE3D45]/50 text-[#FE3D45]",
};

type StoreOrderRow = {
  id: string;
  order_no: string;
  product_name: string;
  buyer_location: string;
  quantity_label: string;
  amount_label: string;
  date_label: string;
  status_label: string;
  derived_status?: string;
  status?: string;
  detail_id?: string;
};

const PER_PAGE = 8;

const ORDERS_LIST_PATH = "/store/customers/my-orders";

function normalizeDerived(o: StoreOrderRow) {
  return (o.derived_status || o.status || "").toLowerCase();
}

function extractOrdersPayload(json: unknown): StoreOrderRow[] {
  if (!json || typeof json !== "object") return [];
  const o = json as Record<string, unknown>;
  const raw = o.orders ?? (o.data as Record<string, unknown> | undefined)?.orders;
  return Array.isArray(raw) ? (raw as StoreOrderRow[]) : [];
}

type StatusFilterOption = { value: string; label: string };

function parseStatusFilterItems(raw: unknown): StatusFilterOption[] {
  if (!Array.isArray(raw)) return [];
  return raw.filter(
    (item): item is StatusFilterOption =>
      !!item &&
      typeof item === "object" &&
      typeof (item as StatusFilterOption).value === "string" &&
      typeof (item as StatusFilterOption).label === "string"
  );
}

function extractStatusFilters(json: unknown): StatusFilterOption[] {
  if (!json || typeof json !== "object") return [];
  const o = json as Record<string, unknown>;
  const dataVal = o.data;
  const data =
    dataVal && typeof dataVal === "object" && !Array.isArray(dataVal)
      ? (dataVal as Record<string, unknown>)
      : undefined;

  const fromFilters = (filters: unknown) =>
    filters && typeof filters === "object" && !Array.isArray(filters)
      ? parseStatusFilterItems((filters as Record<string, unknown>).statuses)
      : [];

  const candidates: unknown[] = [
    o.filters && typeof o.filters === "object" ? (o.filters as Record<string, unknown>).statuses : undefined,
    data?.filters && typeof data.filters === "object"
      ? (data.filters as Record<string, unknown>).statuses
      : undefined,
    o.statuses,
    data?.statuses,
  ];

  for (const raw of candidates) {
    const parsed = parseStatusFilterItems(raw);
    if (parsed.length > 0) return parsed;
  }

  return [];
}

function parseProductFilterItems(raw: unknown): string[] {
  if (!Array.isArray(raw)) return [];
  return raw.filter((item): item is string => typeof item === "string" && item.trim().length > 0);
}

function extractProductFilters(json: unknown): string[] {
  if (!json || typeof json !== "object") return [];
  const o = json as Record<string, unknown>;
  const dataVal = o.data;
  const data =
    dataVal && typeof dataVal === "object" && !Array.isArray(dataVal)
      ? (dataVal as Record<string, unknown>)
      : undefined;

  const candidates: unknown[] = [
    o.filters && typeof o.filters === "object" ? (o.filters as Record<string, unknown>).products : undefined,
    data?.filters && typeof data.filters === "object"
      ? (data.filters as Record<string, unknown>).products
      : undefined,
    o.products,
    data?.products,
  ];

  for (const raw of candidates) {
    const parsed = parseProductFilterItems(raw);
    if (parsed.length > 0) return parsed;
  }

  return [];
}

type DayFilterOption = { value: string; label: string };

function parseDayFilterItems(raw: unknown): DayFilterOption[] {
  if (!Array.isArray(raw)) return [];
  return raw.filter(
    (item): item is DayFilterOption =>
      !!item &&
      typeof item === "object" &&
      typeof (item as DayFilterOption).value === "string" &&
      typeof (item as DayFilterOption).label === "string"
  );
}

function extractDayFilters(json: unknown): DayFilterOption[] {
  if (!json || typeof json !== "object") return [];
  const o = json as Record<string, unknown>;
  const dataVal = o.data;
  const data =
    dataVal && typeof dataVal === "object" && !Array.isArray(dataVal)
      ? (dataVal as Record<string, unknown>)
      : undefined;

  const candidates: unknown[] = [
    o.filters && typeof o.filters === "object" ? (o.filters as Record<string, unknown>).days : undefined,
    data?.filters && typeof data.filters === "object"
      ? (data.filters as Record<string, unknown>).days
      : undefined,
    o.days,
    data?.days,
  ];

  for (const raw of candidates) {
    const parsed = parseDayFilterItems(raw);
    if (parsed.length > 0) return parsed;
  }

  return [];
}

function IconSearch() {
  return (
    <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <circle cx="11" cy="11" r="8" />
      <path d="m21 21-4.35-4.35" />
    </svg>
  );
}

function IconChevronDown() {
  return (
    <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
      <path d="m6 9 6 6 6-6" />
    </svg>
  );
}

function IconLocation() {
  return (
    <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" className="text-[#757575] shrink-0">
      <path d="M20 10c0 6-8 12-8 12s-8-6-8-12a8 8 0 0 1 16 0Z" />
      <circle cx="12" cy="10" r="3" />
    </svg>
  );
}

function IconChevronLeft() {
  return (
    <svg xmlns="http://www.w3.org/2000/svg" width="10" height="18" viewBox="0 0 10 18" fill="none" stroke="currentColor" strokeWidth="2">
      <path d="M8 1L2 9l6 8" />
    </svg>
  );
}

function IconChevronRight() {
  return (
    <svg xmlns="http://www.w3.org/2000/svg" width="10" height="18" viewBox="0 0 10 18" fill="none" stroke="currentColor" strokeWidth="2">
      <path d="M2 1l6 8-6 8" />
    </svg>
  );
}

function IconChevronRightSmall() {
  return (
    <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" className="shrink-0 text-[#757575]">
      <path d="m9 18 6-6-6-6" />
    </svg>
  );
}

function formatStatCount(n: number) {
  return n >= 100 ? String(n) : String(n).padStart(2, "0");
}

function IconStatTotal() {
  return (
    <svg width="69" height="69" viewBox="0 0 69 69" fill="none" xmlns="http://www.w3.org/2000/svg">
      <circle cx="34.5" cy="34.5" r="34" fill="#053F31" fillOpacity="0.06" stroke="#053F31" strokeOpacity="0.3" strokeDasharray="1.84 1.84" />
      <circle cx="34.5" cy="34.5" r="28" fill="#053F31" fillOpacity="0.06" stroke="#053F31" strokeOpacity="0.3" strokeDasharray="1.84 1.84" />
      <circle opacity="0.08" cx="35" cy="35" r="21.5" fill="#053F31" />
      <path d="M13.6751 37.7384C14.1998 41.8245 15.8874 45.6739 18.5371 48.8284C21.1868 51.9829 24.687 54.3097 28.6212 55.532C32.5554 56.7542 36.758 56.8204 40.7287 55.7227C44.6995 54.625 48.2713 52.4096 51.019 49.3402C53.7668 46.2707 55.5749 42.4764 56.228 38.4089C56.8812 34.3413 56.352 30.1717 54.7034 26.3962C53.0548 22.6208 50.3563 19.3985 46.9288 17.1128C43.5014 14.827 39.4894 13.5742 35.3703 13.5032" stroke="#053F31" strokeWidth="1.10732" strokeLinecap="round" />
      <path fillRule="evenodd" clipRule="evenodd" d="M34.3241 37.7758V39.7523C34.3245 39.7791 34.3176 39.8055 34.3042 39.8287C34.2908 39.8519 34.2713 39.8711 34.2479 39.8842L32.7011 40.7773C32.5992 40.8361 32.4726 40.763 32.4726 40.6453V38.0061L26.088 34.32L24.0753 35.482C23.9138 35.5752 23.8214 35.7353 23.8214 35.9217V42.7077C23.8214 42.8941 23.9138 43.0542 24.0753 43.1474L29.9521 46.5404C30.1136 46.6336 30.2985 46.6336 30.4599 46.5404L36.3368 43.1474C36.4982 43.0542 36.5907 42.8941 36.5907 42.7077V36.5668L34.7773 37.6137C34.6374 37.6949 34.4838 37.7498 34.3241 37.7758ZM33.8632 22.4586C34.0247 22.3654 34.2096 22.3654 34.371 22.4586L40.2479 25.8516C40.4094 25.9448 40.5018 26.1049 40.5018 26.2914V33.0773C40.5018 33.2638 40.4094 33.4238 40.2479 33.5171L34.3711 36.9101C34.2096 37.0033 34.0247 37.0033 33.8632 36.9101L27.9864 33.5171C27.8249 33.4238 27.7325 33.2638 27.7325 33.0773V26.2914C27.7325 26.1049 27.8249 25.9448 27.9864 25.8516L29.9991 24.6896L36.3837 28.3758V31.015C36.3837 31.1326 36.5103 31.2057 36.6122 31.1469L38.159 30.2538C38.1824 30.2407 38.2019 30.2216 38.2153 30.1983C38.2287 30.1751 38.2356 30.1487 38.2352 30.1219V27.3068L31.8506 23.6206L33.8632 22.4586ZM41.3143 31.0641L42.9054 31.9828V34.7979C42.9057 34.8247 42.8988 34.8511 42.8854 34.8743C42.872 34.8976 42.8526 34.9167 42.8292 34.9298L41.2823 35.8229C41.1805 35.8818 41.0538 35.8086 41.0538 35.691V33.8675C40.9459 34.0111 40.8099 34.1312 40.6542 34.2207L37.4032 36.0977V40.9335L38.5334 41.5861C38.6949 41.6793 38.8798 41.6793 39.0413 41.5861L44.918 38.1931C45.0795 38.0999 45.1719 37.9398 45.1719 37.7534V30.9674C45.1719 30.7809 45.0795 30.6208 44.918 30.5276L41.3143 28.447V31.0641Z" fill="#053F31" />
    </svg>

  );
}

function IconStatPending() {
  return (
    <svg width="69" height="69" viewBox="0 0 69 69" fill="none" xmlns="http://www.w3.org/2000/svg">
      <circle cx="34.5" cy="34.5" r="34" fill="#CD8600" fillOpacity="0.06" stroke="#CD8600" strokeOpacity="0.3" strokeDasharray="1.84 1.84" />
      <circle cx="34.5" cy="34.5" r="28" fill="#CD8600" fillOpacity="0.06" stroke="#CD8600" strokeOpacity="0.3" strokeDasharray="1.84 1.84" />
      <circle opacity="0.08" cx="35" cy="35" r="21.5" fill="#CD8600" />
      <path d="M13.6751 37.7384C14.1998 41.8245 15.8874 45.6739 18.5371 48.8284C21.1868 51.9829 24.687 54.3097 28.6212 55.532C32.5554 56.7542 36.758 56.8204 40.7287 55.7227C44.6995 54.625 48.2713 52.4096 51.019 49.3402C53.7668 46.2707 55.5749 42.4764 56.228 38.4089C56.8812 34.3413 56.352 30.1717 54.7034 26.3962C53.0548 22.6208 50.3563 19.3985 46.9288 17.1128C43.5014 14.827 39.4894 13.5742 35.3703 13.5032" stroke="#CD8600" strokeWidth="1.10732" strokeLinecap="round" />
      <g clipPath="url(#clip0_1094_59440)">
        <path d="M42.1641 35.3864V28.383C42.1639 28.3203 42.1472 28.2587 42.1156 28.2044C42.0841 28.1502 42.0388 28.1053 41.9843 28.0741L32.2363 22.4461C32.1823 22.4149 32.121 22.3984 32.0586 22.3984C31.9962 22.3984 31.9349 22.4149 31.8809 22.4461L22.1374 28.0715C22.0816 28.1021 22.035 28.1472 22.0026 28.202C21.9702 28.2568 21.9531 28.3193 21.9531 28.383V40.6162C21.9531 40.6786 21.9696 40.7399 22.0008 40.7939C22.0319 40.848 22.0768 40.8928 22.1309 40.924L31.8809 46.5531C31.9349 46.5843 31.9962 46.6008 32.0586 46.6008C32.121 46.6008 32.1823 46.5843 32.2363 46.5531L37.473 43.5301C37.9694 44.2659 38.6449 44.8633 39.4359 45.266C40.2269 45.6687 41.1073 45.8634 41.9943 45.832C42.8814 45.8005 43.7458 45.5438 44.5063 45.0861C45.2667 44.6284 45.8982 43.9847 46.3412 43.2155C46.7842 42.4464 47.0243 41.5772 47.0387 40.6898C47.0531 39.8023 46.8415 38.9258 46.4236 38.1427C46.0058 37.3596 45.3956 36.6957 44.6504 36.2135C43.9052 35.7313 43.0496 35.4467 42.1641 35.3864ZM37.7017 26.4224L28.6634 31.6406L26.8896 30.6164L35.9277 25.3982L37.7017 26.4224ZM28.3008 32.2461V38.7618L27.6305 38.0063C27.5799 37.9506 27.5135 37.9117 27.4402 37.8949C27.3668 37.8782 27.2901 37.8843 27.2204 37.9126L26.5234 38.1973V31.2317L28.3008 32.2461ZM32.0586 23.1644L35.2167 24.9877L26.1784 30.206L23.0205 28.3825L32.0586 23.1644ZM31.7031 45.6296L22.6641 40.411V28.9977L25.8125 30.8216V38.7287C25.8136 38.7874 25.8291 38.845 25.8575 38.8965C25.8859 38.948 25.9263 38.9918 25.9754 39.0241C26.0245 39.0565 26.0807 39.0764 26.1392 39.0822C26.1977 39.0879 26.2568 39.0794 26.3112 39.0572L27.2585 38.6667L28.3786 39.9385C28.4121 39.9764 28.4532 40.0068 28.4992 40.0276C28.5453 40.0484 28.5953 40.0591 28.6458 40.0591C28.6904 40.0591 28.7346 40.0514 28.7766 40.0362C28.8447 40.011 28.9036 39.9657 28.9456 39.9063C28.9876 39.847 29.0106 39.7763 29.0117 39.7037V32.6566L31.7031 34.2163V45.6296ZM32.0586 33.6008L29.3743 32.051L38.4126 26.8329L41.0966 28.3825L32.0586 33.6008ZM32.4141 45.6298V34.2163L41.4531 28.9976V35.3864C40.5964 35.4449 39.7672 35.7134 39.0388 36.1682C38.3104 36.623 37.7052 37.2501 37.2765 37.9942C36.8478 38.7383 36.6089 39.5764 36.5809 40.4347C36.5529 41.293 36.7366 42.1449 37.1157 42.9154L32.4141 45.6298ZM41.8086 45.1242C40.9147 45.1242 40.0409 44.8591 39.2977 44.3625C38.5544 43.8659 37.9752 43.1601 37.6331 42.3342C37.291 41.5084 37.2015 40.5997 37.3759 39.723C37.5503 38.8463 37.9807 38.041 38.6128 37.4089C39.2449 36.7768 40.0502 36.3464 40.9269 36.172C41.8036 35.9976 42.7123 36.0871 43.5381 36.4292C44.364 36.7712 45.0698 37.3505 45.5664 38.0938C46.0631 38.837 46.3281 39.7108 46.3281 40.6047C46.3238 41.802 45.8462 42.949 44.9996 43.7956C44.153 44.6423 43.0059 45.1198 41.8086 45.1241V45.1242Z" fill="#CB8601" />
        <path d="M35.0439 34.2267C35.0052 34.1858 34.9574 34.1546 34.9043 34.1357C34.8512 34.1169 34.7944 34.1109 34.7385 34.1183C34.6827 34.1257 34.6293 34.1462 34.583 34.1782C34.5366 34.2102 34.4985 34.2528 34.4718 34.3024L33.6136 35.899C33.5845 35.9531 33.5699 36.0138 33.5712 36.0753C33.5726 36.1367 33.5899 36.1968 33.6214 36.2496C33.6529 36.3023 33.6976 36.346 33.751 36.3764C33.8044 36.4068 33.8648 36.4228 33.9263 36.4228C33.9914 36.423 34.0554 36.4057 34.1116 36.3728C34.1677 36.3398 34.2141 36.2925 34.2458 36.2356L34.4414 35.8828V38.9385C34.4414 39.0328 34.4789 39.1232 34.5455 39.1898C34.6122 39.2565 34.7026 39.2939 34.7969 39.2939C34.8912 39.2939 34.9816 39.2565 35.0482 39.1898C35.1149 39.1232 35.1523 39.0328 35.1523 38.9385V35.365L35.4413 35.6776C35.473 35.7115 35.5112 35.7388 35.5535 35.7579C35.5958 35.777 35.6416 35.7875 35.688 35.7889C35.7344 35.7902 35.7807 35.7824 35.824 35.7657C35.8674 35.7491 35.9071 35.7241 35.9407 35.692C35.9746 35.6599 36.0018 35.6214 36.0208 35.5787C36.0398 35.536 36.0502 35.49 36.0514 35.4433C36.0526 35.3967 36.0446 35.3502 36.0278 35.3066C36.011 35.263 35.9858 35.2231 35.9537 35.1893L35.0439 34.2267ZM23.5742 38.6861C23.4799 38.6861 23.3895 38.7235 23.3229 38.7902C23.2562 38.8569 23.2188 38.9473 23.2188 39.0416V40.3578C23.2188 40.4521 23.2562 40.5425 23.3229 40.6092C23.3895 40.6758 23.4799 40.7133 23.5742 40.7133C23.6685 40.7133 23.7589 40.6758 23.8256 40.6092C23.8922 40.5425 23.9297 40.4521 23.9297 40.3578V39.0416C23.9297 38.9473 23.8922 38.8569 23.8256 38.7902C23.7589 38.7235 23.6685 38.6861 23.5742 38.6861ZM24.9961 39.6611C24.9018 39.6611 24.8114 39.6985 24.7447 39.7652C24.6781 39.8319 24.6406 39.9223 24.6406 40.0166V41.2023C24.6406 41.2966 24.6781 41.387 24.7447 41.4537C24.8114 41.5203 24.9018 41.5578 24.9961 41.5578C25.0904 41.5578 25.1808 41.5203 25.2474 41.4537C25.3141 41.387 25.3516 41.2966 25.3516 41.2023V40.0166C25.3516 39.9223 25.3141 39.8319 25.2474 39.7652C25.1808 39.6985 25.0904 39.6611 24.9961 39.6611ZM26.4687 40.6361C26.3745 40.6361 26.2841 40.6735 26.2174 40.7402C26.1507 40.8069 26.1133 40.8973 26.1133 40.9916V42.0356C26.1133 42.1299 26.1507 42.2203 26.2174 42.287C26.2841 42.3536 26.3745 42.3911 26.4687 42.3911C26.563 42.3911 26.6534 42.3536 26.7201 42.287C26.7868 42.2203 26.8242 42.1299 26.8242 42.0356V40.9916C26.8242 40.8973 26.7868 40.8069 26.7201 40.7402C26.6534 40.6735 26.563 40.6361 26.4687 40.6361ZM27.8906 41.6111C27.7963 41.6111 27.7059 41.6485 27.6393 41.7152C27.5726 41.7819 27.5352 41.8723 27.5352 41.9666V42.8689C27.5352 42.9632 27.5726 43.0536 27.6393 43.1203C27.7059 43.187 27.7963 43.2244 27.8906 43.2244C27.9849 43.2244 28.0753 43.187 28.142 43.1203C28.2086 43.0536 28.2461 42.9632 28.2461 42.8689V41.9666C28.2461 41.8723 28.2086 41.7819 28.142 41.7152C28.0753 41.6485 27.9849 41.6111 27.8906 41.6111ZM29.0078 43.7216C29.0078 43.8158 29.0453 43.9062 29.1119 43.9729C29.1786 44.0396 29.269 44.077 29.3633 44.077C29.4576 44.077 29.548 44.0396 29.6146 43.9729C29.6813 43.9062 29.7187 43.8158 29.7187 43.7216V42.9416C29.7187 42.8473 29.6813 42.7569 29.6146 42.6902C29.548 42.6235 29.4576 42.5861 29.3633 42.5861C29.269 42.5861 29.1786 42.6235 29.1119 42.6902C29.0453 42.7569 29.0078 42.8473 29.0078 42.9416V43.7216ZM35.5159 39.4487L33.8965 40.3836C33.8149 40.4307 33.7553 40.5083 33.7309 40.5994C33.7065 40.6905 33.7193 40.7875 33.7664 40.8692C33.8135 40.9508 33.8912 41.0104 33.9822 41.0348C34.0733 41.0592 34.1703 41.0464 34.252 40.9993L35.8714 40.0644C35.9531 40.0173 36.0126 39.9396 36.037 39.8485C36.0614 39.7575 36.0487 39.6604 36.0015 39.5788C35.9544 39.4972 35.8768 39.4376 35.7857 39.4132C35.6946 39.3888 35.5976 39.4015 35.5159 39.4487ZM42.1602 40.45V37.443C42.1602 37.3487 42.1227 37.2583 42.056 37.1916C41.9894 37.1249 41.899 37.0875 41.8047 37.0875C41.7104 37.0875 41.62 37.1249 41.5533 37.1916C41.4867 37.2583 41.4492 37.3487 41.4492 37.443V40.6041C41.4492 40.6528 41.4592 40.7009 41.4786 40.7455C41.4979 40.7902 41.5262 40.8303 41.5617 40.8636L43.1888 42.387C43.2577 42.4509 43.3491 42.4849 43.443 42.4816C43.5369 42.4782 43.6257 42.4378 43.6899 42.3693C43.7541 42.3007 43.7886 42.2094 43.7857 42.1155C43.7829 42.0216 43.7429 41.9326 43.6747 41.868L42.1602 40.45Z" fill="#CB8601" />
      </g>
      <defs>
        <clipPath id="clip0_1094_59440">
          <rect width="26" height="26" fill="white" transform="translate(21.5 21.5)" />
        </clipPath>
      </defs>
    </svg>

  );
}

function IconStatTransit() {
  return (
    <svg width="69" height="69" viewBox="0 0 69 69" fill="none" xmlns="http://www.w3.org/2000/svg">
      <circle cx="34.5" cy="34.5" r="34" fill="#155DFC" fillOpacity="0.06" stroke="#155DFC" strokeOpacity="0.3" strokeDasharray="1.84 1.84" />
      <circle cx="34.5" cy="34.5" r="28" fill="#155DFC" fillOpacity="0.06" stroke="#155DFC" strokeOpacity="0.3" strokeDasharray="1.84 1.84" />
      <circle opacity="0.08" cx="35" cy="35" r="21.5" fill="#155DFC" />
      <path d="M13.6751 37.7384C14.1998 41.8245 15.8874 45.6739 18.5371 48.8284C21.1868 51.9829 24.687 54.3097 28.6212 55.532C32.5554 56.7542 36.758 56.8204 40.7287 55.7227C44.6995 54.625 48.2713 52.4096 51.019 49.3402C53.7668 46.2707 55.5749 42.4764 56.228 38.4089C56.8812 34.3413 56.352 30.1717 54.7034 26.3962C53.0548 22.6208 50.3563 19.3985 46.9288 17.1128C43.5014 14.827 39.4894 13.5742 35.3703 13.5032" stroke="#155DFC" strokeWidth="1.10732" strokeLinecap="round" />
      <path d="M32.5971 30.0195H35.4768V30.7838H32.5971V30.0195ZM36.5562 30.0195H39.4367V30.7838H36.5562V30.0195ZM40.5161 30.0195H43.3958V30.7838H40.5161V30.0195ZM36.401 33.5193C36.2053 33.5191 36.0176 33.5966 35.879 33.7347C35.7404 33.8728 35.6624 34.0603 35.662 34.256V37.4492C35.662 37.8566 35.9937 38.1875 36.401 38.1875H39.5935C40.0008 38.1875 40.3309 37.8566 40.3309 37.4492V34.256C40.3307 34.0605 40.2529 33.8731 40.1147 33.735C39.9764 33.5969 39.7889 33.5193 39.5935 33.5193H38.2115V35.4709H37.7814V33.5193H36.401ZM38.9758 36.2343V34.2827H39.5667V37.4217H36.401V34.2827H37.0179V36.2343H38.9758ZM37.1518 38.3781H35.7699V40.3289H35.3397V38.3781H33.9594C33.7638 38.3781 33.5763 38.4557 33.4379 38.5938C33.2995 38.7319 33.2215 38.9193 33.2211 39.1148V42.3081C33.2211 42.7146 33.552 43.0463 33.9594 43.0463H37.1518C37.3474 43.0459 37.5349 42.968 37.6731 42.8296C37.8113 42.6912 37.8891 42.5037 37.8893 42.3081V39.1148C37.8891 38.9194 37.8113 38.732 37.673 38.5939C37.5347 38.4557 37.3473 38.3781 37.1518 38.3781ZM37.1251 42.2813H33.9594V39.1424H34.5755V41.0932H36.5334V39.1424H37.1243V42.2813H37.1251ZM42.0343 38.3781H40.6524V40.3289H40.223V38.3781H38.8426C38.647 38.3779 38.4592 38.4554 38.3207 38.5935C38.1821 38.7317 38.104 38.9191 38.1036 39.1148V42.3081C38.1036 42.7146 38.4345 43.0463 38.8426 43.0463H42.0343C42.23 43.0461 42.4176 42.9682 42.5558 42.8298C42.6941 42.6914 42.7718 42.5037 42.7718 42.3081V39.1148C42.7716 38.9194 42.6938 38.732 42.5555 38.5939C42.4172 38.4557 42.2298 38.3781 42.0343 38.3781ZM42.0083 42.2813H38.8426V39.1424H39.4587V41.0932H41.4166V39.1424H42.0075L42.0083 42.2813ZM32.7287 36.9891L28.6656 34.642C27.9794 34.2481 27.286 34.6688 27.286 35.4401V37.4027H21.8906V38.167H27.286V40.1296C27.286 40.6937 27.6272 41.0869 28.1164 41.0869C28.2969 41.0869 28.4812 41.0341 28.6664 40.9269L32.7295 38.5814C33.062 38.3892 33.2526 38.0992 33.2526 37.7841C33.2518 37.4713 33.0612 37.1806 32.7287 36.9891ZM32.3466 37.9212L28.2843 40.2659C28.2342 40.2993 28.1764 40.3193 28.1164 40.3242C28.0511 40.3242 28.0503 40.1327 28.0503 40.1304V35.4409C28.0503 35.4386 28.0511 35.2479 28.1164 35.2479C28.1361 35.2479 28.1929 35.2526 28.2843 35.3046L32.3474 37.6509C32.464 37.7187 32.4892 37.777 32.4892 37.7864C32.4884 37.7943 32.464 37.8534 32.3466 37.9212ZM31.3034 42.2813H29.6544V40.9537L28.8901 41.3941V43.0455H32.0677V39.5607L31.3034 40.002V42.2813Z" fill="#165DFA" />
      <path d="M37.9969 25.9551C32.5251 25.9551 28.8906 30.0064 28.8906 30.977V34.1742L29.6541 34.6154L29.6525 31.003C29.7746 30.416 32.7835 26.7193 37.9969 26.7193C43.2095 26.7193 46.2192 30.4153 46.339 30.977V42.2815H44.6892V32.3739H31.3039V35.5688L32.0681 36.01V33.1382H43.9265V43.0457H47.1032V30.977C47.1032 30.0064 43.4687 25.9551 37.9969 25.9551Z" fill="#165DFA" />
    </svg>

  );
}

function IconStatDelivered() {
  return (
    <svg width="69" height="69" viewBox="0 0 69 69" fill="none" xmlns="http://www.w3.org/2000/svg">
      <circle cx="34.5" cy="34.5" r="34" fill="#008000" fillOpacity="0.06" stroke="#008000" strokeOpacity="0.3" strokeDasharray="1.84 1.84" />
      <circle cx="34.5" cy="34.5" r="28" fill="#008000" fillOpacity="0.06" stroke="#008000" strokeOpacity="0.3" strokeDasharray="1.84 1.84" />
      <circle opacity="0.08" cx="35" cy="35" r="21.5" fill="#008000" />
      <path d="M13.6751 37.7384C14.1998 41.8245 15.8874 45.6739 18.5371 48.8284C21.1868 51.9829 24.687 54.3097 28.6212 55.532C32.5554 56.7542 36.758 56.8204 40.7287 55.7227C44.6995 54.625 48.2713 52.4096 51.019 49.3402C53.7668 46.2707 55.5749 42.4764 56.228 38.4089C56.8812 34.3413 56.352 30.1717 54.7034 26.3962C53.0548 22.6208 50.3563 19.3985 46.9288 17.1128C43.5014 14.827 39.4894 13.5742 35.3703 13.5032" stroke="#008000" strokeWidth="1.10732" strokeLinecap="round" />
      <g clipPath="url(#clip0_1094_59471)">
        <path d="M36.2845 44.6562H22.3125V28.7603L26.611 22.3125H31.4531V23.3281H27.1546L23.3281 29.0678V43.6406H36.2845V44.6562ZM42.625 35.6172V29.0678L38.7985 23.3281H35.0078V22.3125H39.3421L43.6406 28.7603V35.6167L42.625 35.6172Z" fill="#018001" />
        <path d="M36.0234 28.4062H43.1328V29.4219H36.0234V28.4062ZM22.8203 28.4062H29.9297V29.4219H22.8203V28.4062Z" fill="#018001" />
        <path d="M30.4223 29.0373L29.4371 28.7909L31.0566 22.3125H35.438L36.5243 28.8306L35.5225 28.9975L34.5776 23.3281H31.8496L30.4223 29.0373ZM31.4531 42.625H24.3438V35.5156H31.4531V42.625ZM25.3594 41.6094H30.4375V36.5312H25.3594V41.6094Z" fill="#018001" />
        <path d="M26.375 37.5469H29.4219V38.5625H26.375V37.5469ZM26.375 39.5781H29.4219V40.5938H26.375V39.5781ZM40.5938 46.6875C37.1923 46.6875 34.5 43.9241 34.5 40.5938C34.5 37.2337 37.2337 34.5 40.5938 34.5C41.5696 34.5 42.5016 34.7236 43.364 35.1646L43.364 35.1645C45.414 36.2126 46.6875 38.2929 46.6875 40.5938C46.6875 43.9538 43.9538 46.6875 40.5938 46.6875ZM40.5938 35.5156C37.7936 35.5156 35.5156 37.7936 35.5156 40.5938C35.5156 43.379 37.7694 45.6719 40.5938 45.6719C43.3939 45.6719 45.6719 43.3939 45.6719 40.5938C45.6719 38.6762 44.6104 36.9424 42.9017 36.0689L42.9016 36.0688C42.1838 35.7017 41.4073 35.5156 40.5938 35.5156ZM36.5312 34.4333L34.5 33.0791L32.9766 34.0947L31.4531 33.0791L29.4219 34.4333V28.4062H36.5312V34.4333ZM31.4531 31.8584L32.9766 32.874L34.5 31.8584L35.5156 32.5355V29.4219H30.4375V32.5355L31.4531 31.8584Z" fill="#018001" />
        <path d="M39.5778 42.8351L37.6953 40.9525L38.4135 40.2344L39.5778 41.3987L42.2656 38.7109L42.9838 39.4291L39.5778 42.8351Z" fill="#018001" />
      </g>
      <defs>
        <clipPath id="clip0_1094_59471">
          <rect width="26" height="26" fill="white" transform="translate(21.5 21.5)" />
        </clipPath>
      </defs>
    </svg>

  );
}

function IconStatCancelled() {
  return (
    <svg width="69" height="69" viewBox="0 0 69 69" fill="none" xmlns="http://www.w3.org/2000/svg">
      <circle cx="34.5" cy="34.5" r="34" fill="#FE3D45" fillOpacity="0.06" stroke="#FE3D45" strokeOpacity="0.3" strokeDasharray="1.84 1.84" />
      <circle cx="34.5" cy="34.5" r="28" fill="#FE3D45" fillOpacity="0.06" stroke="#FE3D45" strokeOpacity="0.3" strokeDasharray="1.84 1.84" />
      <circle opacity="0.08" cx="35" cy="35" r="21.5" fill="#FE3D45" />
      <path d="M13.6751 37.7384C14.1998 41.8245 15.8874 45.6739 18.5371 48.8284C21.1868 51.9829 24.687 54.3097 28.6212 55.532C32.5554 56.7542 36.758 56.8204 40.7287 55.7227C44.6995 54.625 48.2713 52.4096 51.019 49.3402C53.7668 46.2707 55.5749 42.4764 56.228 38.4089C56.8812 34.3413 56.352 30.1717 54.7034 26.3962C53.0548 22.6208 50.3563 19.3985 46.9288 17.1128C43.5014 14.827 39.4894 13.5742 35.3703 13.5032" stroke="#FE3D45" strokeWidth="1.10732" strokeLinecap="round" />
      <path d="M34.4969 47.1148C34.4445 47.1147 34.3928 47.103 34.3455 47.0805L23.6141 41.912C23.5542 41.8834 23.5036 41.8384 23.4682 41.7823C23.4328 41.7262 23.4141 41.6612 23.4141 41.5948V30.0434C23.4154 29.9857 23.4313 29.9292 23.4602 29.8793C23.4892 29.8293 23.5303 29.7875 23.5798 29.7577C23.6301 29.7258 23.6877 29.7072 23.7472 29.7037C23.8067 29.7002 23.8661 29.7119 23.9198 29.7377L34.6398 34.8948C34.6997 34.9234 34.7502 34.9684 34.7856 35.0245C34.821 35.0806 34.8398 35.1456 34.8398 35.212V46.7634C34.8379 46.821 34.8218 46.8773 34.7929 46.9271C34.764 46.977 34.7232 47.0189 34.6741 47.0491C34.6223 47.087 34.5609 47.1098 34.4969 47.1148ZM24.1198 41.372L34.1455 46.2005V35.4348L24.1198 30.6062V41.372Z" fill="#FE3D45" />
      <path d="M34.4969 35.5575C34.4445 35.5574 34.3928 35.5457 34.3455 35.5232L23.6141 30.3575C23.5542 30.3289 23.5036 30.2839 23.4682 30.2278C23.4328 30.1717 23.4141 30.1067 23.4141 30.0403C23.4139 29.9736 23.4325 29.9081 23.4679 29.8515C23.5033 29.7949 23.554 29.7494 23.6141 29.7203L29.5712 26.8632C29.6135 26.839 29.6603 26.8238 29.7087 26.8184C29.7571 26.8131 29.8061 26.8179 29.8526 26.8323C29.8991 26.8468 29.9421 26.8707 29.9789 26.9025C30.0158 26.9344 30.0457 26.9734 30.0667 27.0173C30.0878 27.0613 30.0996 27.109 30.1014 27.1577C30.1031 27.2064 30.0949 27.2549 30.0771 27.3002C30.0592 27.3455 30.0323 27.3867 29.9978 27.4211C29.9634 27.4556 29.9222 27.4825 29.8769 27.5003L24.5826 30.0375L34.4969 34.8118L44.4169 30.0489L39.0512 27.4775C38.9669 27.4368 38.9021 27.3643 38.8711 27.276C38.84 27.1876 38.8452 27.0906 38.8855 27.0061C38.9274 26.9221 39.0004 26.8577 39.0889 26.8268C39.1775 26.7958 39.2747 26.8007 39.3598 26.8403L45.3883 29.7289C45.448 29.7585 45.4983 29.8041 45.5336 29.8606C45.5689 29.9171 45.5879 29.9823 45.5883 30.0489C45.5862 30.114 45.5661 30.1773 45.5303 30.2317C45.4945 30.2862 45.4444 30.3297 45.3855 30.3575L34.6398 35.5232C34.595 35.5444 34.5464 35.5561 34.4969 35.5575Z" fill="#FE3D45" />
      <path d="M34.4973 47.1145C34.4314 47.1151 34.3668 47.0962 34.3116 47.0602C34.2625 47.03 34.2217 46.9881 34.1928 46.9382C34.1638 46.8884 34.1477 46.8321 34.1459 46.7745V35.2145C34.1459 35.1482 34.1647 35.0832 34.2001 35.027C34.2355 34.9709 34.286 34.926 34.3459 34.8974L45.0773 29.7259C45.1311 29.7005 45.1904 29.689 45.2497 29.6926C45.3091 29.6961 45.3666 29.7145 45.417 29.7461C45.4674 29.7777 45.509 29.8214 45.538 29.8733C45.567 29.9252 45.5825 29.9836 45.583 30.0431V41.5945C45.583 41.6609 45.5643 41.7259 45.5289 41.782C45.4935 41.8381 45.4429 41.8831 45.383 41.9117L34.6402 47.0802C34.5955 47.1014 34.5468 47.1131 34.4973 47.1145ZM34.8516 35.4345V46.2002L44.8773 41.3717V30.6059L34.8516 35.4345ZM31.2116 40.0717C31.1562 40.0717 31.1015 40.0587 31.0519 40.0339C31.0023 40.0092 30.9592 39.9732 30.9259 39.9288L28.7116 36.9545L26.9973 37.9117C26.9439 37.9425 26.8833 37.9587 26.8216 37.9587C26.7599 37.9587 26.6993 37.9425 26.6459 37.9117C26.5922 37.8807 26.5476 37.8361 26.5165 37.7825C26.4854 37.7288 26.4689 37.6679 26.4688 37.6059V31.5002C26.4691 31.4339 26.488 31.3691 26.5234 31.313C26.5587 31.257 26.6091 31.2119 26.6688 31.1831L30.4716 29.3402C30.5557 29.2993 30.6526 29.2935 30.7411 29.324C30.8295 29.3546 30.9021 29.419 30.943 29.5031C30.984 29.5872 30.9898 29.6841 30.9592 29.7725C30.9287 29.8609 30.8643 29.9336 30.7802 29.9745L27.183 31.7317V37.0002L28.6402 36.1859C28.715 36.1433 28.803 36.1296 28.8872 36.1475C28.9715 36.1654 29.0463 36.2137 29.0973 36.2831L30.8459 38.6431V33.6145C30.8459 33.5482 30.8647 33.4832 30.9001 33.427C30.9355 33.3709 30.986 33.326 31.0459 33.2974L35.4659 31.1602C35.5075 31.1311 35.5548 31.1113 35.6047 31.1021C35.6546 31.0929 35.7059 31.0945 35.7551 31.1068C35.8044 31.1192 35.8504 31.142 35.89 31.1736C35.9297 31.2053 35.9621 31.2451 35.985 31.2903C36.008 31.3356 36.0209 31.3853 36.023 31.436C36.0251 31.4867 36.0162 31.5372 35.9971 31.5842C35.9779 31.6312 35.9489 31.6735 35.912 31.7083C35.8751 31.7431 35.8311 31.7696 35.783 31.7859L31.5516 33.8374V39.7231C31.5542 39.7996 31.532 39.875 31.4882 39.9378C31.4444 40.0007 31.3815 40.0476 31.3088 40.0717C31.2765 40.076 31.2438 40.076 31.2116 40.0717Z" fill="#FE3D45" />
      <path d="M36.7636 43.4805C36.6968 43.4807 36.6313 43.462 36.5747 43.4266C36.5181 43.3913 36.4726 43.3406 36.4436 43.2805C36.4232 43.2387 36.4114 43.1933 36.4087 43.1469C36.4061 43.1005 36.4126 43.054 36.428 43.0102C36.4435 42.9664 36.4674 42.926 36.4985 42.8915C36.5296 42.857 36.5673 42.8289 36.6093 42.8091L40.9293 40.7262C41.0143 40.6866 41.1115 40.6817 41.2001 40.7127C41.2887 40.7436 41.3617 40.8079 41.4036 40.8919C41.4439 40.9765 41.449 41.0735 41.418 41.1618C41.3869 41.2502 41.3222 41.3226 41.2379 41.3633L36.9293 43.4462C36.8776 43.4709 36.8208 43.4826 36.7636 43.4805ZM36.7636 41.2691C36.684 41.2683 36.6071 41.2407 36.5451 41.1908C36.4831 41.141 36.4397 41.0717 36.4219 40.9941C36.4041 40.9166 36.4129 40.8353 36.4469 40.7634C36.4809 40.6915 36.5381 40.6331 36.6093 40.5976L38.9293 39.5005C39.0138 39.4602 39.1109 39.455 39.1992 39.4861C39.2875 39.5171 39.36 39.5819 39.4007 39.6662C39.436 39.7515 39.4363 39.8473 39.4016 39.9329C39.3668 40.0184 39.2998 40.0868 39.215 40.1234L36.9293 41.2348C36.8776 41.2594 36.8208 41.2712 36.7636 41.2691ZM34.4693 31.9776C33.4617 31.9776 32.4768 31.6789 31.6391 31.1191C30.8013 30.5593 30.1484 29.7637 29.7628 28.8328C29.3772 27.902 29.2763 26.8777 29.4729 25.8895C29.6695 24.9013 30.1546 23.9936 30.8671 23.2811C31.5795 22.5687 32.4872 22.0835 33.4754 21.887C34.4636 21.6904 35.4879 21.7913 36.4188 22.1768C37.3496 22.5624 38.1453 23.2154 38.705 24.0531C39.2648 24.8909 39.5636 25.8758 39.5636 26.8834C39.5621 28.234 39.0249 29.5288 38.0698 30.4839C37.1148 31.4389 35.8199 31.9761 34.4693 31.9776ZM34.4693 22.4976C33.6019 22.4976 32.7539 22.7549 32.0327 23.2368C31.3115 23.7187 30.7494 24.4036 30.4174 25.205C30.0855 26.0064 29.9986 26.8882 30.1678 27.739C30.3371 28.5897 30.7548 29.3712 31.3681 29.9845C31.9815 30.5979 32.7629 31.0156 33.6137 31.1848C34.4644 31.354 35.3462 31.2672 36.1476 30.9352C36.949 30.6033 37.634 30.0412 38.1159 29.3199C38.5978 28.5987 38.855 27.7508 38.855 26.8834C38.8535 25.7207 38.3909 24.606 37.5688 23.7839C36.7466 22.9617 35.632 22.4991 34.4693 22.4976Z" fill="#FE3D45" />
      <path d="M36.8799 27.2379H32.1199C32.0259 27.2379 31.9358 27.2005 31.8694 27.1341C31.803 27.0677 31.7656 26.9775 31.7656 26.8836C31.7656 26.7896 31.803 26.6995 31.8694 26.6331C31.9358 26.5666 32.0259 26.5293 32.1199 26.5293H36.8799C36.9739 26.5293 37.064 26.5666 37.1304 26.6331C37.1969 26.6995 37.2342 26.7896 37.2342 26.8836C37.2342 26.9775 37.1969 27.0677 37.1304 27.1341C37.064 27.2005 36.9739 27.2379 36.8799 27.2379Z" fill="#FE3D45" />
      <path d="M34.5027 29.617C34.409 29.6163 34.3193 29.5787 34.253 29.5124C34.1868 29.4461 34.1492 29.3565 34.1484 29.2627V24.5027C34.1484 24.4562 34.1576 24.4101 34.1754 24.3671C34.1932 24.3242 34.2193 24.2851 34.2522 24.2522C34.2851 24.2193 34.3242 24.1932 34.3671 24.1754C34.4101 24.1576 34.4562 24.1484 34.5027 24.1484C34.5492 24.1484 34.5953 24.1576 34.6383 24.1754C34.6813 24.1932 34.7203 24.2193 34.7532 24.2522C34.7861 24.2851 34.8122 24.3242 34.83 24.3671C34.8478 24.4101 34.857 24.4562 34.857 24.5027V29.2627C34.857 29.3567 34.8197 29.4468 34.7532 29.5132C34.6868 29.5797 34.5967 29.617 34.5027 29.617Z" fill="#FE3D45" />
    </svg>

  );
}

function OrderStatCard({
  title,
  value,
  classNameBg,
  classNameBorder,
  titleClass,
  icon,
}: {
  title: string;
  value: string;
  classNameBg: string;
  classNameBorder: string;
  titleClass: string;
  icon: ReactNode;
}) {
  return (
    <div
      className={`flex min-w-0 flex-1 justify-between gap-3 rounded-2xl border p-5 font-outfit shadow-[0_1px_3px_rgba(0,0,0,0.04)] ${classNameBg} ${classNameBorder}`}
    >
      <div className="flex min-w-0 flex-col justify-between gap-5">
        <span className={`text-[16px] font-light leading-[150%] ${titleClass}`}>{title}</span>
        <span className="text-[32px] font-semibold leading-[150%] text-[#000000]">{value}</span>
      </div>
      <div className="relative flex h-[72px] w-[72px] shrink-0 items-center justify-center sm:h-[76px] sm:w-[76px]">
        <div className="relative z-[1] flex items-center justify-center">{icon}</div>
      </div>
    </div>
  );
}

const MARKETPLACE_ZIGZAG_COUNT = 3;

const OrdersPage = () => {
  const router = useRouter();
  const pathname = usePathname();
  const [search, setSearch] = useState("");
  const [statusFilter, setStatusFilter] = useState("all");
  const [statusFilterOptions, setStatusFilterOptions] = useState<StatusFilterOption[]>([]);
  const [productFilter, setProductFilter] = useState("all");
  const [productFilterOptions, setProductFilterOptions] = useState<string[]>([]);
  const [dateFilter, setDateFilter] = useState("all");
  const [dateFilterOptions, setDateFilterOptions] = useState<DayFilterOption[]>([]);
  const [page, setPage] = useState(1);
  const [expandedIndex, setExpandedIndex] = useState<number>(0);
  const [orders, setOrders] = useState<StoreOrderRow[]>([]);
  const [ordersLoading, setOrdersLoading] = useState(true);
  const [cardsData, setCardsData] = useState<Record<string, { label: string; value: number }>>({});
  const [uiLocale, setUiLocale] = useState<LocaleCode>(DEFAULT_LOCALE);

  useEffect(() => {
    const syncLocale = () => setUiLocale(getStoredLocale());
    syncLocale();
    window.addEventListener("storage", syncLocale);
    window.addEventListener(LOCALE_CHANGE_EVENT, syncLocale);
    return () => {
      window.removeEventListener("storage", syncLocale);
      window.removeEventListener(LOCALE_CHANGE_EVENT, syncLocale);
    };
  }, []);

  const t =
    staticCopy.ordersPage[uiLocale as keyof typeof staticCopy.ordersPage] ??
    staticCopy.ordersPage["en-EN"];

  useEffect(() => {
    const base = process.env.NEXT_PUBLIC_MEDUSA_BACKEND_URL;
    if (!base) {
      setOrders([]);
      setOrdersLoading(false);
      return;
    }

    const qs = new URLSearchParams();
    if (dateFilter && dateFilter !== "all") qs.set("days", dateFilter);
    if (statusFilter && statusFilter !== "all") qs.set("status", statusFilter);
    if (productFilter && productFilter !== "all") qs.set("product", productFilter);
    const q = search.trim();
    if (q) {
      qs.set("q", q);
      const hasOtherFilter = qs.has("days") || qs.has("status") || qs.has("product");
      qs.set("limit", hasOtherFilter ? "5" : "10");
    }

    const queryString = qs.toString();
    const pageUrl = queryString ? `${pathname}?${queryString}` : pathname;
    router.replace(pageUrl, { scroll: false });

    let cancelled = false;
    const load = async () => {
      setOrdersLoading(true);
      try {
        const headers: Record<string, string> = {
          "Content-Type": "application/json",
          "x-publishable-api-key": process.env.NEXT_PUBLIC_MEDUSA_PUBLISHABLE_API_KEY || "",
        };
        try {
          const raw = typeof window !== "undefined" ? localStorage.getItem("currentUser") : null;
          const user = raw ? JSON.parse(raw) : null;
          const authTok = String(user?.token ?? user?.access_token ?? "").trim();
          if (authTok) headers.Authorization = `Bearer ${authTok}`;
        } catch {
        }
        const apiUrl = queryString ? `${base}${ORDERS_LIST_PATH}?${queryString}` : `${base}${ORDERS_LIST_PATH}`;
        const res = await fetch(apiUrl, {
          method: "GET",
          headers,
          credentials: "include",
          cache: "no-store",
        });
        const json = await res.json().catch(() => ({}));
        if (cancelled) return;
        const list = res.ok ? extractOrdersPayload(json) : [];
        const statuses = res.ok ? extractStatusFilters(json) : [];
        const products = res.ok ? extractProductFilters(json) : [];
        const days = res.ok ? extractDayFilters(json) : [];
        const cards = res.ok ? (json.cards as Record<string, { label: string; value: number }>) || {} : {};
        setOrders(list);
        setCardsData(cards);
        setStatusFilterOptions(
          statuses.length > 0 ? statuses : [{ value: "all", label: t.allStatus }]
        );
        setProductFilterOptions(products);
        setDateFilterOptions(
          days.length > 0
            ? days
            : [
                { value: "7", label: t.last7Days },
                { value: "15", label: t.last15Days },
                { value: "30", label: t.last30Days },
                { value: "all", label: t.allTime },
              ]
        );
        setPage(1);
      } catch {
        if (!cancelled) {
          setOrders([]);
          setPage(1);
        }
      } finally {
        if (!cancelled) setOrdersLoading(false);
      }
    };
    void load();
    return () => {
      cancelled = true;
    };
  }, [dateFilter, statusFilter, productFilter, search, pathname, router, uiLocale]);

  const orderSummary = useMemo(() => {
    if (cardsData && Object.keys(cardsData).length > 0) {
      return {
        total: cardsData.total_orders?.value || 0,
        pending: cardsData.pending?.value || 0,
        inTransit: cardsData.in_transit?.value || 0,
        delivered: cardsData.delivered?.value || 0,
        cancelled: cardsData.cancelled?.value || 0,
      };
    }

    const list = orders;
    const pending = list.filter((o) => {
      const n = normalizeDerived(o);
      return n === "pending" || n === "confirmed" || n === "processing";
    }).length;
    const inTransit = list.filter((o) => {
      const n = normalizeDerived(o);
      return n.includes("transit") || n === "shipped" || n === "fulfilling";
    }).length;
    const delivered = list.filter((o) => {
      const n = normalizeDerived(o);
      return n === "delivered" || n === "completed";
    }).length;
    const cancelled = list.filter((o) => {
      const n = normalizeDerived(o);
      return n === "cancelled" || n === "canceled";
    }).length;
    return {
      total: list.length,
      pending,
      inTransit,
      delivered,
      cancelled,
    };
  }, [orders, cardsData]);

  const totalOrdersCount = orders.length;
  const totalPages = Math.max(1, Math.ceil(totalOrdersCount / PER_PAGE));
  const start = totalOrdersCount === 0 ? 0 : (page - 1) * PER_PAGE + 1;
  const end = Math.min(page * PER_PAGE, totalOrdersCount);

  const paginatedOrders = useMemo(
    () => orders.slice((page - 1) * PER_PAGE, page * PER_PAGE),
    [orders, page]
  );

  const paginationSlots: (number | "ellipsis")[] = (() => {
    if (totalPages <= 7) return Array.from({ length: totalPages }, (_, i) => i + 1);
    const slots: (number | "ellipsis")[] = [];
    if (page <= 4) {
      for (let p = 1; p <= 5; p++) slots.push(p);
      slots.push("ellipsis");
      slots.push(totalPages);
    } else if (page >= totalPages - 3) {
      slots.push(1);
      slots.push("ellipsis");
      for (let p = totalPages - 4; p <= totalPages; p++) slots.push(p);
    } else {
      slots.push(1);
      slots.push("ellipsis");
      for (let p = page - 1; p <= page + 1; p++) slots.push(p);
      slots.push("ellipsis");
      slots.push(totalPages);
    }
    return slots;
  })();

  const showingOrdersText = t.showingOrders
    .replace("{start}", String(start))
    .replace("{end}", String(end))
    .replace("{count}", String(totalOrdersCount));

  return (
    <>
      <main className="px-4 pt-6 pb-20 md:pr-8">
        <div className="min-h-screen flex items-start gap-6 xl:max-w-[1240px] 2xl:max-w-[1440px] sm:mx-auto">
          <BackgroundGradients count={MARKETPLACE_ZIGZAG_COUNT} />
          <Sidebar />

          <div className="w-full pb-0 md:pb-28">
            <div className="mb-3 font-lexend text-[18px] mb-10 md:mb-12 border-b border-[#DDDDDD] pb-[20px] mb-[20px] xl:pb-[30px] xl:mb-[30px] text-[#053F31]">{t.pageTitle}</div>

            <div className="mb-8 grid md:grid-cols-1 gap-4 lg:grid-cols-2 xl:grid-cols-5">
              <OrderStatCard
                title={t.statTotalOrders}
                value={formatStatCount(orderSummary.total)}
                classNameBg="bg-[#F7FAF8]"
                classNameBorder="border-[#053F31]/50"
                titleClass="text-[#757575]"
                icon={<IconStatTotal />}
              />
              <OrderStatCard
                title={t.statPending}
                value={formatStatCount(orderSummary.pending)}
                classNameBg="bg-[#FAF3E6]"
                classNameBorder="border-[#CD8600]/50"
                titleClass="text-[#CC8602]"
                icon={<IconStatPending />}
              />
              <OrderStatCard
                title={t.statInTransit}
                value={formatStatCount(orderSummary.inTransit)}
                classNameBg="bg-[#E8EFFE]"
                classNameBorder="border-[#155DFC]/37"
                titleClass="text-[#165EFC]"
                icon={<IconStatTransit />}
              />
              <OrderStatCard
                title={t.statDelivered}
                value={formatStatCount(orderSummary.delivered)}
                classNameBg="bg-[#E5F2E5]"
                classNameBorder="border-[#008000]/50"
                titleClass="text-[#018001]"
                icon={<IconStatDelivered />}
              />
              <OrderStatCard
                title={t.statCancelled}
                value={formatStatCount(orderSummary.cancelled)}
                classNameBg="bg-[#FDEAEB]"
                classNameBorder="border-[#FE3D45]/50"
                titleClass="text-[#FE3D45]"
                icon={<IconStatCancelled />}
              />
            </div>

            <div className="flex flex-col sm:flex-row gap-4 mb-6">
              <div className="flex flex-1 min-w-0">
                <input
                  type="text"
                  placeholder={t.searchPlaceholder}
                  value={search}
                  onChange={(e) => setSearch(e.target.value)}
                  className="flex-1 min-w-0 rounded-l-[10px] border border-[#E6E6E6] bg-white px-4 py-3 font-outfit text-[#424242] placeholder:text-[#757575] focus:outline-none focus:ring-2 focus:ring-[#053F31]/20 focus:border-[#053F31]"
                />
                <button
                  type="button"
                  className="flex items-center justify-center w-12 rounded-r-[10px] bg-[#053F31] text-white cursor-pointer hover:opacity-90 transition-opacity shrink-0"
                  aria-label={t.searchAriaLabel}
                >
                  <IconSearch />
                </button>
              </div>
              <div className="flex flex-col md:flex-row gap-3">
                <select
                  value={
                    statusFilterOptions.some((s) => s.value === statusFilter)
                      ? statusFilter
                      : statusFilterOptions[0]?.value ?? "all"
                  }
                  onChange={(e) => setStatusFilter(e.target.value)}
                  className="min-w-[140px] rounded-[10px] border border-[#E6E6E6] bg-white pl-4 pr-10 py-3 font-outfit text-[#424242] focus:outline-none appearance-none cursor-pointer bg-no-repeat bg-[length:16px] bg-[right_12px_center]"
                  style={{ backgroundImage: `url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 24 24' fill='none' stroke='%23424242' strokeWidth='2'%3E%3Cpath d='m6 9 6 6 6-6'/%3E%3C/svg%3E")` }}
                >
                  {(statusFilterOptions.length > 0
                    ? statusFilterOptions
                    : [{ value: "all", label: t.allStatus }]
                  ).map((opt) => (
                    <option key={opt.value} value={opt.value}>
                      {opt.label}
                    </option>
                  ))}
                </select>
                <select
                  value={productFilterOptions.some((p) => p === productFilter) || productFilter === "all" ? productFilter : "all"}
                  onChange={(e) => setProductFilter(e.target.value)}
                  className="min-w-[140px] rounded-[10px] border border-[#E6E6E6] bg-white pl-4 pr-10 py-3 font-outfit text-[#424242] focus:outline-none appearance-none cursor-pointer bg-no-repeat bg-[length:16px] bg-[right_12px_center]"
                  style={{ backgroundImage: `url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 24 24' fill='none' stroke='%23424242' strokeWidth='2'%3E%3Cpath d='m6 9 6 6 6-6'/%3E%3C/svg%3E")` }}
                >
                  <option value="all">{t.allProducts}</option>
                  {productFilterOptions.map((p) => (
                    <option key={p} value={p}>
                      {p}
                    </option>
                  ))}
                </select>
                <select
                  value={
                    dateFilterOptions.some((d) => d.value === dateFilter)
                      ? dateFilter
                      : dateFilterOptions[0]?.value ?? "all"
                  }
                  onChange={(e) => setDateFilter(e.target.value)}
                  className="min-w-[180px] rounded-[10px] border border-[#E6E6E6] bg-white pl-4 pr-10 py-3 font-outfit text-[#424242] focus:outline-none appearance-none cursor-pointer bg-no-repeat bg-[length:16px] bg-[right_12px_center]"
                  style={{ backgroundImage: `url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 24 24' fill='none' stroke='%23424242' strokeWidth='2'%3E%3Cpath d='m6 9 6 6 6-6'/%3E%3C/svg%3E")` }}
                >
                  {(dateFilterOptions.length > 0
                    ? dateFilterOptions
                    : [
                        { value: "7", label: t.last7Days },
                        { value: "15", label: t.last15Days },
                        { value: "30", label: t.last30Days },
                        { value: "all", label: t.allTime },
                      ]
                  ).map((opt) => (
                    <option key={opt.value} value={opt.value}>
                      {opt.label}
                    </option>
                  ))}
                </select>
              </div>
            </div>

            <div className="md:hidden rounded-[20px] overflow-hidden shadow-[0_4px_20px_rgba(0,0,0,0.06)] bg-white">
              <div className="bg-[#DAE6DC] text-[#053F31] font-outfit font-semibold flex justify-between items-center py-3 px-4 rounded-t-[20px]">
                <span>{t.colOrderNumber}</span>
                <span>{t.colProduct}</span>
              </div>
              <div className="divide-y divide-[#E6E6E6]">
                {ordersLoading ? (
                  <div className="py-8 px-4 text-center font-outfit text-[#757575]">{t.loadingOrders}</div>
                ) : paginatedOrders.length === 0 ? (
                  <div className="py-8 px-4 text-center font-outfit text-[#757575]">{t.noOrdersFound}</div>
                ) : (
                  paginatedOrders.map((order, i) => (
                    <div key={order.id} className="bg-white">
                      <button
                        type="button"
                        onClick={() => setExpandedIndex(expandedIndex === i ? -1 : i)}
                        className="w-full flex justify-between items-end py-3 px-4 text-right font-outfit"
                      >
                        <span className="flex items-center gap-2">
                          {expandedIndex === i ? (
                            <span className="text-[#053F31]">
                              <IconChevronDown />
                            </span>
                          ) : (
                            <IconChevronRightSmall />
                          )}
                          <span className="text-[#424242]">
                            {expandedIndex === i ? order.order_no : `${String(i + 1).padStart(2, "0")}.`}
                          </span>
                          {expandedIndex === i && <span className="text-[#000000] font-medium sr-only md:not-sr-only" />}
                        </span>
                        <span className="text-[#000000]">{order.product_name}</span>
                      </button>
                      {expandedIndex === i && (
                        <div className="px-4 pb-4 pt-0 space-y-2 font-outfit border-t border-[#E6E6E6]">
                          <div className="flex justify-between">
                            <span className="text-[#053F31] font-medium shrink-0">{t.labelLocation}</span>
                            <span className="flex items-end gap-1.5 text-[#757575]">
                              <IconLocation />
                              {order.buyer_location}
                            </span>
                          </div>
                          <div className="flex justify-between">
                            <span className="text-[#053F31] font-medium">{t.labelQuantity}</span>
                            <span className="text-[#757575]">{order.quantity_label}</span>
                          </div>
                          <div className="flex justify-between">
                            <span className="text-[#053F31] font-medium">{t.labelAmount}</span>
                            <span className="text-[#757575]">{order.amount_label}</span>
                          </div>
                          <div className="flex justify-between">
                            <span className="text-[#053F31] font-medium">{t.labelDate}</span>
                            <span className="text-[#757575]">{order.date_label}</span>
                          </div>
                          <div className="flex justify-between items-center">
                            <span className="text-[#053F31] font-medium">{t.labelStatus}</span>
                            <span className={`inline-block rounded-[10px] px-[15px] py-[5px] text-sm font-medium ${STATUS_STYLES[order.status_label] ?? "bg-[#f97316]/10 border border-[#f97316]/50 text-[#f97316]"}`}>
                              {order.status_label === "Out for Delivery" ? t.statusOutForDeliveryAs : order.status_label}
                            </span>
                          </div>
                          <div className="flex justify-between items-center">
                          <span className="text-[#053F31] font-medium">{t.labelAction}</span>
                            <Link
                              href={`/orders/${order.detail_id ?? order.id}`}
                              className="inline-block rounded-[10px] border border-[#053F31]/50 bg-[#F7FAF8] px-[15px] py-[5px] font-outfit text-sm font-medium text-[#424242] hover:bg-[#F7FAF8] hover:border-[#053F31]/30 transition"
                            >
                              {t.viewDetails}
                            </Link>
                          </div>
                        </div>
                      )}
                    </div>
                  ))
                )}
              </div>
              {totalOrdersCount > 0 ? (
                <div className="flex flex-col sm:flex-row items-center justify-between gap-4 bg-[#DAE6DC] px-4 py-4 text-[#053F31] font-outfit">
                  <p className="text-sm font-medium">
                    {showingOrdersText}
                  </p>
                  <div className="flex items-center gap-2">
                    <button
                      type="button"
                      onClick={() => setPage((p) => Math.max(1, p - 1))}
                      disabled={page <= 1}
                      className="flex h-10 w-10 items-center justify-center rounded-[8px] border border-[#053F31]/30 bg-white text-[#053F31] disabled:opacity-50 cursor-pointer hover:bg-[#053F31]/10"
                      aria-label={t.ariaPreviousPage}
                    >
                      <IconChevronLeft />
                    </button>
                    <div className="flex items-center gap-1">
                      {paginationSlots.map((slot, i) =>
                        slot === "ellipsis" ? (
                          <span key={`e-${i}`} className="flex h-10 w-10 items-center justify-center text-[#053F31]">
                            …
                          </span>
                        ) : (
                          <button
                            key={slot}
                            type="button"
                            onClick={() => setPage(slot)}
                            className={`flex h-10 w-10 items-center justify-center rounded-[8px] font-semibold text-sm transition cursor-pointer ${page === slot
                              ? "bg-[#053F31] text-white"
                              : "border border-[#053F31]/30 bg-white text-[#053F31] hover:bg-[#053F31]/10"
                              }`}
                          >
                            {slot}
                          </button>
                        )
                      )}
                    </div>
                    <button
                      type="button"
                      onClick={() => setPage((p) => Math.min(totalPages, p + 1))}
                      disabled={page >= totalPages}
                      className="flex h-10 w-10 items-center justify-center rounded-[8px] border border-[#053F31]/30 bg-white text-[#053F31] disabled:opacity-50 cursor-pointer hover:bg-[#053F31]/10"
                      aria-label={t.ariaNextPage}
                    >
                      <IconChevronRight />
                    </button>
                  </div>
                </div>
              ) : null}
            </div>

            <div className="hidden md:block rounded-[20px] overflow-hidden shadow-[0_4px_20px_rgba(0,0,0,0.06)] bg-white">
              <div className="overflow-x-auto">
                <table className="w-full font-outfit text-center">
                  <thead>
                    <tr className="bg-[#DAE6DC] text-[#053F31] font-semibold whitespace-nowrap">
                      <th className="py-4 px-4">{t.colOrderNumber}</th>
                      <th className="py-4 px-4 min-w-[180px]">{t.colProduct}</th>
                      <th className="py-4 px-4 min-w-[250px]">{t.colLocation}</th>
                      <th className="py-4 px-4">{t.colQuantity}</th>
                      <th className="py-4 px-4">{t.colAmount}</th>
                      <th className="py-4 px-4">{t.colDate}</th>
                      <th className="py-4 px-4">{t.colStatus}</th>
                      <th className="py-4 px-4">{t.colActions}</th>
                    </tr>
                  </thead>
                  <tbody>
                    {ordersLoading ? (
                      <tr>
                        <td colSpan={8} className="py-10 px-4 text-center font-outfit text-[#757575]">
                          {t.loadingOrders}
                        </td>
                      </tr>
                    ) : paginatedOrders.length === 0 ? (
                      <tr>
                        <td colSpan={8} className="py-10 px-4 text-center font-outfit text-[#757575]">
                          {t.noOrdersFound}
                        </td>
                      </tr>
                    ) : (
                      paginatedOrders.map((order) => (
                        <tr key={order.id} className="border-b border-[#E6E6E6] last:border-b-0 hover:bg-[#F7FAF8]/80 transition-colors">
                          <td className="py-5 px-3 text-[#000000] font-medium whitespace-nowrap">{order.order_no}</td>
                          <td className="py-5 px-4 text-[#000000] min-w-[180px] break-words">{order.product_name}</td>
                          <td className="py-5 px-4 text-[#000000] min-w-[250px] max-w-[400px]">
                            <span className="flex items-start gap-2 break-words">
                              <span className="mt-1 shrink-0"><IconLocation /></span>
                              {order.buyer_location}
                            </span>
                          </td>
                          <td className="py-5 px-4 text-[#000000] whitespace-nowrap">{order.quantity_label}</td>
                          <td className="py-5 px-4 text-[#000000] whitespace-nowrap">{order.amount_label}</td>
                          <td className="py-5 px-4 text-[#000000] whitespace-nowrap">{order.date_label}</td>
                          <td className="py-5 px-4">
                            <span className={`inline-block rounded-[10px] px-[15px] py-[5px] text-sm font-medium break-words max-w-[120px] text-center ${STATUS_STYLES[order.status_label] ?? "bg-[#f97316]/10 border border-[#f97316]/50 text-[#f97316]"}`}>
                              {order.status_label === "Out for Delivery" ? t.statusOutForDeliveryAs : order.status_label}
                            </span>
                          </td>
                          <td className="py-5 px-4 whitespace-nowrap">
                            <Link
                              href={`/orders/${order.detail_id ?? order.id}`}
                              className="inline-block rounded-[10px] border border-[#053F31]/50 bg-[#F7FAF8] px-[15px] py-[5px] font-outfit text-sm font-medium text-[#424242] hover:bg-white hover:border-[#053F31] transition shadow-sm"
                            >
                              {t.viewDetails}
                            </Link>
                          </td>
                        </tr>
                      ))
                    )}
                  </tbody>
                </table>
              </div>

              {totalOrdersCount > 0 ? (
                <div className="flex flex-col sm:flex-row items-center justify-between gap-4 bg-[#DAE6DC] px-4 py-4 text-[#053F31] font-outfit">
                  <p className="text-sm font-medium">
                    {showingOrdersText}
                  </p>
                  <div className="flex items-center gap-2">
                    <button
                      type="button"
                      onClick={() => setPage((p) => Math.max(1, p - 1))}
                      disabled={page <= 1}
                      className="flex h-10 w-10 items-center justify-center rounded-[8px] border border-[#053F31]/30 bg-white text-[#053F31] disabled:opacity-50 cursor-pointer hover:bg-[#053F31]/10"
                      aria-label={t.ariaPreviousPage}
                    >
                      <IconChevronLeft />
                    </button>
                    <div className="flex items-center gap-1">
                      {paginationSlots.map((slot, i) =>
                        slot === "ellipsis" ? (
                          <span key={`e-${i}`} className="flex h-10 w-10 items-center justify-center text-[#053F31]">
                            …
                          </span>
                        ) : (
                          <button
                            key={slot}
                            type="button"
                            onClick={() => setPage(slot)}
                            className={`flex h-10 w-10 items-center justify-center rounded-[8px] font-semibold text-sm transition cursor-pointer ${page === slot
                              ? "bg-[#053F31] text-white"
                              : "border border-[#053F31]/30 bg-white text-[#053F31] hover:bg-[#053F31]/10"
                              }`}
                          >
                            {slot}
                          </button>
                        )
                      )}
                    </div>
                    <button
                      type="button"
                      onClick={() => setPage((p) => Math.min(totalPages, p + 1))}
                      disabled={page >= totalPages}
                      className="flex h-10 w-10 items-center justify-center rounded-[8px] border border-[#053F31]/30 bg-white text-[#053F31] disabled:opacity-50 cursor-pointer hover:bg-[#053F31]/10"
                      aria-label={t.ariaNextPage}
                    >
                      <IconChevronRight />
                    </button>
                  </div>
                </div>
              ) : null}
            </div>
          </div>
        </div>
      </main>
      <Footer />

    </>
  );
};

export default OrdersPage;
