Browse Source

feat: implement production shop SPA with Flutter WebView bridge and REST API integration

main
sina_sajjadi 3 weeks ago
parent
commit
6f5b9c7176
  1. 3
      .env
  2. 27
      BACKEND_SPEC.md
  3. 301
      index.html
  4. 37
      package-lock.json
  5. 1
      package.json
  6. 206
      src/App.tsx
  7. 9
      src/components/account/AccountMenuRow.tsx
  8. 42
      src/components/account/HabibCoinsBanner.tsx
  9. 15
      src/components/account/OrderCounterCard.tsx
  10. 93
      src/components/bridge/HabibBridgeProviders.tsx
  11. 72
      src/components/checkout/AddressCard.tsx
  12. 20
      src/components/checkout/OrderSummaryRows.tsx
  13. 27
      src/components/common/CategoryCard.tsx
  14. 39
      src/components/common/CompactProductCard.tsx
  15. 40
      src/components/common/GridProductCard.tsx
  16. 51
      src/components/common/SearchBar.tsx
  17. 714
      src/components/common/ShimmerSkeletons.tsx
  18. 58
      src/components/layout/BottomNavBar.tsx
  19. 21
      src/components/layout/TopHeader.tsx
  20. 301
      src/components/modals/AddressFormSheet.tsx
  21. 188
      src/components/modals/LoginRequiredModal.tsx
  22. 195
      src/components/modals/OrderSummarySheet.tsx
  23. 290
      src/components/modals/PaymentMethodsSheet.tsx
  24. 197
      src/components/modals/ShipmentTrackingSheet.tsx
  25. 27
      src/components/orders/OrderListCard.tsx
  26. 720
      src/context/ShopAppContext.tsx
  27. 23
      src/hooks/use-habib-web-ready.ts
  28. 76
      src/hooks/use-hardware-back-handler.ts
  29. 50
      src/hooks/useSmartBack.ts
  30. 114
      src/index.css
  31. 229
      src/lib/auth-bridge.ts
  32. 95
      src/lib/cookies.ts
  33. 166
      src/lib/http.ts
  34. 315
      src/lib/mappers.ts
  35. 45
      src/lib/routes.ts
  36. 660
      src/lib/shopApi.ts
  37. 366
      src/lib/shopQueries.ts
  38. 68
      src/lib/view-paddings.ts
  39. 222
      src/lib/webview-actions.ts
  40. 7
      src/main.tsx
  41. 548
      src/pages/account/LanguageSettingPage.tsx
  42. 416
      src/pages/account/ProviderRequestPage.tsx
  43. 373
      src/pages/account/ShopAccountPage.tsx
  44. 95
      src/pages/account/ShopAddressPage.tsx
  45. 806
      src/pages/catalog/ShopBoothPage.tsx
  46. 185
      src/pages/catalog/ShopCatItemsPage.tsx
  47. 83
      src/pages/catalog/ShopCategoryPage.tsx
  48. 958
      src/pages/catalog/ShopSinglePage.tsx
  49. 1182
      src/pages/chat/ShopChatPage.tsx
  50. 396
      src/pages/checkout/ShopBuy01Page.tsx
  51. 594
      src/pages/checkout/ShopCartPage.tsx
  52. 2
      src/pages/checkout/ShopOrderSummaryPage.tsx
  53. 128
      src/pages/checkout/ShopPayResultPage.tsx
  54. 373
      src/pages/checkout/ShopPaymentPage.tsx
  55. 370
      src/pages/home/ShopHomePage.tsx
  56. 630
      src/pages/orders/ShopOrderDetailPage.tsx
  57. 164
      src/pages/orders/ShopOrdersPage.tsx
  58. 397
      src/pages/orders/ShopSupportPage.tsx
  59. 37
      src/types/window.d.ts
  60. 37
      vite.config.ts

3
.env

@ -0,0 +1,3 @@
# Set to true to fall back to mock data when backend responses are empty or offline
VITE_USE_MOCK_DATA=false

27
BACKEND_SPEC.md

@ -4680,3 +4680,30 @@ node scripts/verify-backend-spec.mjs
3. **20 Canonical Data Entities:** All 20 canonical relational models defined with complete field definitions and PostgreSQL DDL.
4. **Exhaustive REST Endpoints:** At least 62 RESTful endpoint contracts documented across all 13 functional domains with full JSON schemas and examples.
5. **Real Concrete Fixtures:** Every endpoint example and mock schema reflects authentic data from the frontend design tokens and mock catalogs.
### 7.3 Production Integration & Flutter WebView Bridge Module Citations
The production SPA integration inside `src/` adds parameterized routing, live Habib Django REST API bindings (`/api/shop/*`), global shopping cart and account state hydration, interactive overlay bottom sheets, and full `window.FlutterChannel` host bridge parity (`web_ready`, `HABIB_TOKEN`, `HABIB_COINS`, `HABIB_VIEW_PADDINGS`, `handleBackButton`, `buy_coin`, `pick_manual_location`, `upload_file`, and `open_external_url`). Every production source module in `src/` is mapped below:
| Source File Path | Architectural Role & Backend / Host Integration Responsibility |
|---|---|
| `src/types/window.d.ts` | Global TypeScript declarations for `window.FlutterChannel`, `window.HABIB_TOKEN`, `window.HABIB_COINS`, `window.HABIB_VIEW_PADDINGS`, `window.onFlutterResponse`, and `window.handleBackButton`. |
| `src/lib/cookies.ts` | Cookie persistence utilities managing `HABIB_TOKEN`, `USER_LANGUAGE`, and guest cart session token `HABIB_SHOP_GUEST`. |
| `src/lib/auth-bridge.ts` | Habib host authentication token resolver (`getToken`), asynchronous Flutter login handshake (`ensureToken`), and local session sign-out helper (`signOutLocal`). |
| `src/lib/view-paddings.ts` | Safe-area inset listener binding `window.HABIB_VIEW_PADDINGS` and `habib:view-paddings-changed` events to CSS custom properties `--safe-top` through `--safe-left`. |
| `src/lib/webview-actions.ts` | Typed Flutter WebView bridge actions for `close`, `open_external_url`, `copy_to_clipboard`, `download_file`, `buy_coin`, `pick_manual_location`, and `upload_file`. |
| `src/lib/routes.ts` | Parameterized production URL builders (`ROUTES`) and `?bare=1` / `?embed=1` Figma snapshot detection (`isBareMode`). |
| `src/lib/http.ts` | Fetch client (`shopRequest`) injecting `Authorization: Token <HABIB_TOKEN>`, `X-Shop-Session: <HABIB_SHOP_GUEST>`, and `Accept-Language: <USER_LANGUAGE>` headers plus media URL resolution (`resolveMediaUrl`). |
| `src/lib/shopApi.ts` | Strongly typed TypeScript API client covering home feed, categories, products, reviews, store booths, cart, promo codes, shipping/payment methods, orders, shipment tracking, profile, addresses, bookmarks, provider requests, support tickets, and store chat. |
| `src/lib/mappers.ts` | Pure data adapters transforming backend REST DTOs into the UI presentation props consumed by `CompactProductCard`, `GridProductCard`, `CategoryCard`, `AddressCard`, `OrderListCard`, and `ShipmentOrderCard`. |
| `src/hooks/use-hardware-back-handler.ts` | LIFO Android hardware back-button handler stack invoked by `window.handleBackButton()` so open bottom sheets close before route history pops. |
| `src/hooks/use-habib-web-ready.ts` | Lifecycle hook posting `{ action: "web_ready" }` to `window.FlutterChannel` after initial hydration and double `requestAnimationFrame` paint. |
| `src/hooks/useSmartBack.ts` | Safe in-app back navigation hook tracking internal SPA transitions and falling back to deterministic parent routes on deep-linked entry. |
| `src/context/ShopAppContext.tsx` | Application-wide React context hydrating guest/authenticated cart, saved addresses, shipping/payment selections, bookmarks, shopper profile, order counters, Habib Coin balance, language preference, and toast notifications. |
| `src/components/bridge/HabibBridgeProviders.tsx` | Root router-level bridge provider installing global hardware back handling, safe-area padding synchronization, scroll restoration, and status toasts. |
| `src/components/modals/OrderSummarySheet.tsx` | True overlay bottom sheet for `/cart` order pricing breakdown and promo code application, registered on the LIFO hardware back stack. |
| `src/components/modals/PaymentMethodsSheet.tsx` | True overlay bottom sheet for `/checkout/review` payment method selection including live Habib Coins balance validation. |
| `src/components/modals/AddressFormSheet.tsx` | True overlay bottom sheet for `/checkout/shipping` and `/account/addresses` address creation/editing with optional Flutter `pick_manual_location` pin selection. |
| `src/components/modals/ShipmentTrackingSheet.tsx` | True overlay bottom sheet for `/orders/:orderId` carrier tracking code copy and chronological shipment milestone timeline. |
| `src/components/common/ShimmerSkeletons.tsx` | Geometry-matched shimmer skeleton loaders (`HomeFeedShimmer`, `CategoryGridShimmer`, `ProductGridShimmer`, `ProductDetailBodyShimmer`, `StoreBoothBodyShimmer`, `OrdersListShimmer`, `OrderDetailShimmer`, `ChatThreadShimmer`, `CartItemsShimmer`), tactile `InlineSpinner`, and network `RetryBanner`. |

301
index.html

@ -3,14 +3,301 @@
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Habib Shop</title>
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link
href="https://fonts.googleapis.com/css2?family=Cinzel:wght@400;600&family=Inter:wght@400;500;600;700&display=swap"
rel="stylesheet"
<meta
name="viewport"
content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover, interactive-widget=overlays-content"
/>
<title>Habib Shop</title>
<script id="habib-core-bootstrap">
(function () {
var listeners = new Set();
function readCookie(name) {
var match = document.cookie.match(
new RegExp('(?:^|;\\s*)' + name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '=([^;]*)')
);
return match ? decodeURIComponent(match[1]) : '';
}
function sanitizeToken(raw) {
if (typeof raw !== 'string') return '';
var trimmed = raw.trim().replace(/^["']|["']$/g, '');
if (!trimmed || trimmed === 'NO_TOKEN' || trimmed === 'null' || trimmed === 'undefined') {
return '';
}
return trimmed;
}
function resolveInitialToken() {
var urlTok = '';
try {
if (window.location && window.location.search) {
var sp = new URLSearchParams(window.location.search);
urlTok = sanitizeToken(
sp.get('token') ||
sp.get('auth_token') ||
sp.get('habib_token') ||
sp.get('HABIB_TOKEN') ||
''
);
}
} catch (_eUrl) {}
var ssTok = '';
try {
ssTok = sanitizeToken(window.sessionStorage.getItem('HABIB_TOKEN') || '');
} catch (_eSs) {}
return (
sanitizeToken(window.HABIB_TOKEN) ||
urlTok ||
sanitizeToken(readCookie('HABIB_TOKEN')) ||
sanitizeToken(readCookie('habib_token')) ||
ssTok
);
}
var currentToken = resolveInitialToken();
if (currentToken) {
document.cookie = 'HABIB_TOKEN=' + encodeURIComponent(currentToken) + '; path=/; SameSite=Lax';
try {
window.sessionStorage.setItem('HABIB_TOKEN', currentToken);
} catch (_eInitSs) {}
}
var rawCoinsCookie = readCookie('HABIB_COINS');
var currentCoins = rawCoinsCookie !== '' ? Number(rawCoinsCookie) : 21;
if (!Number.isFinite(currentCoins) || currentCoins < 0) {
currentCoins = 21;
}
function getFlutterBridge() {
var ch = window.HabibApp || window.FlutterChannel;
if (ch && typeof ch.postMessage === 'function') {
if (!window.FlutterChannel) window.FlutterChannel = ch;
if (!window.HabibApp) window.HabibApp = ch;
return ch;
}
return null;
}
try {
Object.defineProperty(window, 'HABIB_TOKEN', {
configurable: true,
enumerable: true,
get: function () {
var ssVal = '';
try {
ssVal = sanitizeToken(window.sessionStorage.getItem('HABIB_TOKEN') || '');
} catch (_eGetSs) {}
return (
currentToken ||
sanitizeToken(readCookie('HABIB_TOKEN')) ||
sanitizeToken(readCookie('habib_token')) ||
ssVal
);
},
set: function (nextValue) {
var clean = sanitizeToken(typeof nextValue === 'string' ? nextValue : String(nextValue || ''));
var prev = currentToken;
currentToken = clean;
if (clean) {
document.cookie = 'HABIB_TOKEN=' + encodeURIComponent(clean) + '; path=/; SameSite=Lax';
try {
window.sessionStorage.setItem('HABIB_TOKEN', clean);
} catch (_eSetSs) {}
} else {
document.cookie = 'HABIB_TOKEN=; path=/; max-age=0; SameSite=Lax';
document.cookie = 'habib_token=; path=/; max-age=0; SameSite=Lax';
try {
window.sessionStorage.removeItem('HABIB_TOKEN');
} catch (_eRmSs) {}
}
if (clean !== prev) {
window.dispatchEvent(
new CustomEvent('habib:auth-token-changed', {
detail: { token: clean, previousToken: prev },
})
);
}
},
});
} catch (_err) {
window.HABIB_TOKEN = currentToken;
}
try {
Object.defineProperty(window, 'HABIB_COINS', {
configurable: true,
enumerable: true,
get: function () {
return currentCoins;
},
set: function (nextCoins) {
var parsed = Number(nextCoins);
if (!Number.isFinite(parsed) || parsed < 0) return;
if (parsed !== currentCoins) {
currentCoins = parsed;
window.dispatchEvent(
new CustomEvent('habib:coins-changed', {
detail: { coins: currentCoins },
})
);
}
},
});
} catch (_err2) {
window.HABIB_COINS = currentCoins;
}
window.addFlutterResponseListener = function (fn) {
if (typeof fn !== 'function') {
return function () {};
}
listeners.add(fn);
return function () {
listeners.delete(fn);
};
};
window.onFlutterResponse = function (rawPayload) {
var payload = rawPayload;
if (typeof rawPayload === 'string') {
try {
payload = JSON.parse(rawPayload);
} catch (_e) {
payload = { raw: rawPayload };
}
}
if (payload && typeof payload === 'object') {
var action = String(payload.action || payload.type || '').toLowerCase();
var data = payload.data || payload.payload || payload;
var explicitToken =
typeof data.token === 'string'
? data.token
: typeof data.auth_token === 'string'
? data.auth_token
: typeof data.authToken === 'string'
? data.authToken
: '';
if (explicitToken) {
window.HABIB_TOKEN = explicitToken;
} else if (action === 'login' && payload.success !== false) {
var cookieTokAfterLogin =
sanitizeToken(readCookie('HABIB_TOKEN')) ||
sanitizeToken(readCookie('habib_token'));
if (cookieTokAfterLogin) {
window.HABIB_TOKEN = cookieTokAfterLogin;
}
} else if (action === 'initial_config' || action === 'initialconfig') {
window.__HABIB_BOOTSTRAP__ = data;
var cookieTokFromBootstrap =
sanitizeToken(readCookie('HABIB_TOKEN')) ||
sanitizeToken(readCookie('habib_token'));
if (cookieTokFromBootstrap) {
window.HABIB_TOKEN = cookieTokFromBootstrap;
}
}
var nextCoinVal =
data.coinsBalance !== undefined
? data.coinsBalance
: data.coin_balance !== undefined
? data.coin_balance
: undefined;
if (nextCoinVal !== undefined) {
window.HABIB_COINS = Number(nextCoinVal);
}
}
listeners.forEach(function (listener) {
try {
listener(payload);
} catch (_listenerErr) {
// ignore individual listener errors
}
});
};
var webReadySent = false;
window.HABIB_WEB_READY_SENT = false;
function tryPostWebReady() {
if (webReadySent) return true;
var bridge = getFlutterBridge();
if (bridge) {
webReadySent = true;
window.HABIB_WEB_READY_SENT = true;
try {
bridge.postMessage(
JSON.stringify({
action: 'web_ready',
service: 'shop',
timestamp: Date.now(),
})
);
} catch (_postErr) {
// ignore channel error
}
return true;
}
return false;
}
window.__announceHabibWebReady = function () {
if (tryPostWebReady()) return;
var attempts = 0;
var timer = window.setInterval(function () {
attempts += 1;
if (tryPostWebReady() || attempts >= 25) {
window.clearInterval(timer);
}
}, 120);
};
// Safety fallback so Flutter's reveal cover never hangs permanently
window.setTimeout(function () {
if (!webReadySent) {
tryPostWebReady();
}
}, 3500);
function postClientLog(level, message, details) {
var bridge = getFlutterBridge();
if (!bridge) {
return;
}
try {
bridge.postMessage(
JSON.stringify({
action: 'client_log',
level: level,
message: String(message || 'Shop web error'),
details: details || {},
})
);
} catch (_logErr) {
// ignore logging errors
}
}
window.addEventListener('error', function (event) {
postClientLog('error', event.message || 'Unhandled error', {
filename: event.filename,
lineno: event.lineno,
colno: event.colno,
});
});
window.addEventListener('unhandledrejection', function (event) {
var reason = event.reason;
postClientLog(
'error',
reason && reason.message ? reason.message : String(reason || 'Unhandled promise rejection'),
{}
);
});
})();
</script>
</head>
<body>
<div id="root"></div>

37
package-lock.json

@ -8,6 +8,7 @@
"name": "habib-shop",
"version": "0.0.0",
"dependencies": {
"@tanstack/react-query": "^5.105.1",
"react": "^19.3.1",
"react-dom": "^19.3.1",
"react-router-dom": "^7.18.5"
@ -984,6 +985,38 @@
"dev": true,
"license": "MIT"
},
"node_modules/@tanstack/query-core": {
"version": "5.105.1",
"resolved": "https://registry.npmjs.org/@tanstack/query-core/-/query-core-5.105.1.tgz",
"integrity": "sha512-B/rNlZoZ54w1dlddiUt9oEe1SLM+37c00SKLJEg9YH+7as3Y54P81o9Fh+2ujZ36tXPnQJ5oVe7AcyEWkyFhPg==",
"license": "MIT",
"funding": {
"type": "github",
"url": "https://github.com/sponsors/tannerlinsley"
}
},
"node_modules/@tanstack/react-query": {
"version": "5.105.1",
"resolved": "https://registry.npmjs.org/@tanstack/react-query/-/react-query-5.105.1.tgz",
"integrity": "sha512-qcu+/+PtBOjW8qU4/0l47QVmNG7hPOWsCLzP0bTRhE1X7HYa757C4732wXTUH0QhCjTV1yedX8onsCiEwlNYrA==",
"license": "MIT",
"dependencies": {
"@tanstack/query-core": "5.105.1"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/tannerlinsley"
},
"peerDependencies": {
"@types/react": "^18 || ^19",
"react": "^18 || ^19"
},
"peerDependenciesMeta": {
"@types/react": {
"optional": true
}
}
},
"node_modules/@types/babel__core": {
"version": "7.20.5",
"resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.5.tgz",
@ -1043,7 +1076,7 @@
"version": "19.3.0",
"resolved": "https://registry.npmjs.org/@types/react/-/react-19.3.0.tgz",
"integrity": "sha512-N0rFCuH9YoxG9/m61l9MfpJKfmLOVU0em7ipIz6TRgSSkvReLB9vL85GB+yr8Bs5leqpvg96JSwF4ZS1s4viQg==",
"dev": true,
"devOptional": true,
"license": "MIT",
"dependencies": {
"csstype": "^3.2.2"
@ -1531,7 +1564,7 @@
"version": "3.2.3",
"resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz",
"integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==",
"dev": true,
"devOptional": true,
"license": "MIT"
},
"node_modules/debug": {

1
package.json

@ -10,6 +10,7 @@
"preview": "vite preview"
},
"dependencies": {
"@tanstack/react-query": "^5.105.1",
"react": "^19.3.1",
"react-dom": "^19.3.1",
"react-router-dom": "^7.18.5"

206
src/App.tsx

@ -1,6 +1,11 @@
import React from 'react';
import { QueryClientProvider } from '@tanstack/react-query';
import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom';
import { ShopAppProvider } from './context/ShopAppContext';
import { HabibBridgeProviders } from './components/bridge/HabibBridgeProviders';
import { shopQueryClient } from './lib/shopQueries';
// Home & Discovery
import { ShopHomePage } from './pages/home/ShopHomePage';
import { ShopCategoryPage } from './pages/catalog/ShopCategoryPage';
@ -38,73 +43,140 @@ import { TestDirectoryPage } from './pages/test/TestDirectoryPage';
export const App: React.FC = () => {
return (
<BrowserRouter>
<Routes>
{/* Test & QA Hub */}
<Route path="/test" element={<TestDirectoryPage />} />
{/* 1. Home & Discovery */}
<Route path="/" element={<ShopHomePage />} />
<Route path="/shop-home" element={<ShopHomePage />} />
<Route path="/shop-category" element={<ShopCategoryPage />} />
<Route path="/shop-catitems" element={<ShopCatItemsPage />} />
{/* 2. Product & Store */}
<Route path="/shop-single-page" element={<ShopSinglePage />} />
<Route path="/shop-booth" element={<ShopBoothPage />} />
<Route path="/shop-chat" element={<ShopChatPage />} />
{/* 3. Cart & Checkout */}
<Route path="/shop-cart" element={<ShopCartPage />} />
<Route path="/shop-order-summery" element={<ShopOrderSummaryPage />} />
<Route path="/shop-buy01" element={<ShopBuy01Page />} />
<Route path="/shop-payment" element={<ShopPaymentPage />} />
<Route path="/shop-payment-methods" element={<ShopPaymentMethodsPage />} />
<Route path="/shop-payresult" element={<ShopPayResultPage />} />
{/* 4. Orders & Support */}
<Route path="/shop-orders" element={<ShopOrdersPage />} />
<Route path="/shop-order-detail" element={<ShopOrderDetailPage />} />
<Route path="/shop-support" element={<ShopSupportPage />} />
{/* 5. Account & Settings */}
<Route path="/shop-account" element={<ShopAccountPage />} />
<Route path="/shop-category-4214-345" element={<ShopAccountPage />} />
<Route path="/shop-adreess" element={<ShopAddressPage />} />
<Route path="/provider-requst" element={<ProviderRequestPage />} />
<Route path="/language-setting" element={<LanguageSettingPage />} />
{/* 6. Standalone Nodes */}
<Route
path="/node/boxicons-user-filled"
element={<StandaloneNodesPage nodeSlug="boxicons-user-filled" />}
/>
<Route
path="/node/frame-4175-10154"
element={<StandaloneNodesPage nodeSlug="frame-4175-10154" />}
/>
<Route
path="/node/frame-4175-10157"
element={<StandaloneNodesPage nodeSlug="frame-4175-10157" />}
/>
<Route
path="/node/frame-4175-10160"
element={<StandaloneNodesPage nodeSlug="frame-4175-10160" />}
/>
<Route
path="/node/group-4175-10166"
element={<StandaloneNodesPage nodeSlug="group-4175-10166" />}
/>
<Route
path="/node/shop-home-text"
element={<StandaloneNodesPage nodeSlug="shop-home-text" />}
/>
<Route path="/node/:slug" element={<StandaloneNodesPage />} />
{/* Fallback */}
<Route path="*" element={<Navigate to="/test" replace />} />
</Routes>
</BrowserRouter>
<QueryClientProvider client={shopQueryClient}>
<BrowserRouter>
<ShopAppProvider>
<HabibBridgeProviders>
<Routes>
{/* Test & QA Hub */}
<Route path="/test" element={<TestDirectoryPage />} />
{/* ===================================================== */}
{/* Production Parameterized Routes */}
{/* ===================================================== */}
<Route path="/" element={<ShopHomePage />} />
<Route path="/categories" element={<ShopCategoryPage />} />
<Route
path="/categories/:categorySlug"
element={<ShopCatItemsPage mode="category" />}
/>
<Route
path="/search"
element={<ShopCatItemsPage mode="search" />}
/>
<Route path="/products/:productId" element={<ShopSinglePage />} />
<Route path="/stores" element={<ShopBoothPage />} />
<Route path="/stores/:storeId" element={<ShopBoothPage />} />
<Route path="/chat" element={<ShopChatPage />} />
<Route path="/chat/:conversationId" element={<ShopChatPage />} />
{/* Cart & Checkout */}
<Route path="/cart" element={<ShopCartPage />} />
<Route path="/checkout/shipping" element={<ShopBuy01Page />} />
<Route path="/checkout/review" element={<ShopPaymentPage />} />
<Route
path="/checkout/result/:orderId"
element={<ShopPayResultPage />}
/>
{/* Orders & Support */}
<Route path="/orders" element={<ShopOrdersPage />} />
<Route path="/orders/:orderId" element={<ShopOrderDetailPage />} />
<Route
path="/orders/:orderId/support"
element={<ShopSupportPage />}
/>
<Route path="/support" element={<ShopSupportPage />} />
{/* Account & Settings */}
<Route path="/account" element={<ShopAccountPage />} />
<Route
path="/account/bookmarks"
element={<ShopCatItemsPage mode="bookmarks" />}
/>
<Route path="/account/addresses" element={<ShopAddressPage />} />
<Route path="/account/profile" element={<ProviderRequestPage />} />
<Route path="/account/settings" element={<LanguageSettingPage />} />
{/* ===================================================== */}
{/* Legacy / Figma Design Showcase Routes (?bare=1 QA) */}
{/* ===================================================== */}
{/* 1. Home & Discovery */}
<Route path="/shop-home" element={<ShopHomePage />} />
<Route path="/shop-category" element={<ShopCategoryPage />} />
<Route path="/shop-catitems" element={<ShopCatItemsPage />} />
{/* 2. Product & Store */}
<Route path="/shop-single-page" element={<ShopSinglePage />} />
<Route path="/shop-booth" element={<ShopBoothPage />} />
<Route path="/shop-chat" element={<ShopChatPage />} />
{/* 3. Cart & Checkout */}
<Route path="/shop-cart" element={<ShopCartPage />} />
<Route
path="/shop-order-summery"
element={<ShopOrderSummaryPage />}
/>
<Route path="/shop-buy01" element={<ShopBuy01Page />} />
<Route path="/shop-payment" element={<ShopPaymentPage />} />
<Route
path="/shop-payment-methods"
element={<ShopPaymentMethodsPage />}
/>
<Route path="/shop-payresult" element={<ShopPayResultPage />} />
{/* 4. Orders & Support */}
<Route path="/shop-orders" element={<ShopOrdersPage />} />
<Route
path="/shop-order-detail"
element={<ShopOrderDetailPage />}
/>
<Route path="/shop-support" element={<ShopSupportPage />} />
{/* 5. Account & Settings */}
<Route path="/shop-account" element={<ShopAccountPage />} />
<Route
path="/shop-category-4214-345"
element={<ShopAccountPage />}
/>
<Route path="/shop-adreess" element={<ShopAddressPage />} />
<Route path="/provider-requst" element={<ProviderRequestPage />} />
<Route path="/language-setting" element={<LanguageSettingPage />} />
{/* 6. Standalone Nodes */}
<Route
path="/node/boxicons-user-filled"
element={<StandaloneNodesPage nodeSlug="boxicons-user-filled" />}
/>
<Route
path="/node/frame-4175-10154"
element={<StandaloneNodesPage nodeSlug="frame-4175-10154" />}
/>
<Route
path="/node/frame-4175-10157"
element={<StandaloneNodesPage nodeSlug="frame-4175-10157" />}
/>
<Route
path="/node/frame-4175-10160"
element={<StandaloneNodesPage nodeSlug="frame-4175-10160" />}
/>
<Route
path="/node/group-4175-10166"
element={<StandaloneNodesPage nodeSlug="group-4175-10166" />}
/>
<Route
path="/node/shop-home-text"
element={<StandaloneNodesPage nodeSlug="shop-home-text" />}
/>
<Route path="/node/:slug" element={<StandaloneNodesPage />} />
{/* Fallback */}
<Route path="*" element={<Navigate to="/" replace />} />
</Routes>
</HabibBridgeProviders>
</ShopAppProvider>
</BrowserRouter>
</QueryClientProvider>
);
};

9
src/components/account/AccountMenuRow.tsx

@ -4,19 +4,22 @@ import type { AccountMenuRowItem } from '../../data/accountData';
interface AccountMenuRowProps {
row: AccountMenuRowItem;
onClick?: () => void;
}
/**
* Reusable menu row on `shop-category` Account Overview (4214:345) and `provider requst` (4214:10531).
* - Dimensions: 317×34 at (29, row.y)
*/
export const AccountMenuRow: React.FC<AccountMenuRowProps> = ({ row }) => {
export const AccountMenuRow: React.FC<AccountMenuRowProps> = ({ row, onClick }) => {
const navigate = useNavigate();
return (
<div
onClick={() => {
if (row.targetRoute) {
if (onClick) {
onClick();
} else if (row.targetRoute) {
navigate(row.targetRoute);
}
}}
@ -26,7 +29,7 @@ export const AccountMenuRow: React.FC<AccountMenuRowProps> = ({ row }) => {
display: 'flex',
alignItems: 'center',
gap: 9,
cursor: row.targetRoute ? 'pointer' : 'default',
cursor: onClick || row.targetRoute ? 'pointer' : 'default',
minWidth: 0,
}}
>

42
src/components/account/HabibCoinsBanner.tsx

@ -1,10 +1,45 @@
import React from 'react';
import { useLocation } from 'react-router-dom';
import { useShopApp } from '../../context/ShopAppContext';
import { isBareMode } from '../../lib/routes';
import { buyHabibCoinPackages, isInFlutterWebView } from '../../lib/webview-actions';
interface HabibCoinsBannerProps {
coinsCount?: number;
onBuyCoins?: () => void;
}
/**
* Habib Coins inventory banner on `provider requst` (4214:10558).
* - Dimensions: 343×55 at (16, 692), radius 16.5, fill #fbfbfc, shadow 0px 2px 13px rgba(71, 85, 105, 0.1)
*/
export const HabibCoinsBanner: React.FC = () => {
export const HabibCoinsBanner: React.FC<HabibCoinsBannerProps> = ({
coinsCount,
onBuyCoins,
}) => {
const location = useLocation();
const isBare = isBareMode(location.search);
const { habibCoinsBalance, setHabibCoinsBalance, showToast } = useShopApp();
const resolvedCoins =
coinsCount !== undefined ? coinsCount : isBare ? 21 : habibCoinsBalance;
const handleBuyCoins = async () => {
if (onBuyCoins) {
onBuyCoins();
return;
}
if (isInFlutterWebView()) {
const updated = await buyHabibCoinPackages();
if (typeof updated === 'number') {
setHabibCoinsBalance(updated);
showToast(`Balance updated: ${updated} Habib Coins`);
}
return;
}
showToast('Open Habib mobile app to purchase coin packages');
};
return (
<div
style={{
@ -54,7 +89,7 @@ export const HabibCoinsBanner: React.FC = () => {
color: '#111111',
}}
>
21 Habib Coins
{resolvedCoins} Habib Coins
</div>
</div>
</div>
@ -62,6 +97,9 @@ export const HabibCoinsBanner: React.FC = () => {
{/* "Buy Coins" button */}
<button
type="button"
onClick={() => {
void handleBuyCoins();
}}
style={{
minWidth: 96,
height: 32,

15
src/components/account/OrderCounterCard.tsx

@ -1,9 +1,11 @@
import React from 'react';
import { useNavigate } from 'react-router-dom';
import type { OrderStatusCounterItem } from '../../data/accountData';
import { ROUTES } from '../../lib/routes';
interface OrderCounterCardProps {
counter: OrderStatusCounterItem;
onClick?: () => void;
}
/**
@ -11,12 +13,21 @@ interface OrderCounterCardProps {
* - Dimensions: 106×46 at (counter.relX, 0) inside Frame 2095586833 at (16, 187)
* - Radius: 15, fill: #ffffff, shadow: 0px 2px 13px rgba(180, 187, 200, 0.25)
*/
export const OrderCounterCard: React.FC<OrderCounterCardProps> = ({ counter }) => {
export const OrderCounterCard: React.FC<OrderCounterCardProps> = ({
counter,
onClick,
}) => {
const navigate = useNavigate();
return (
<div
onClick={() => navigate('/shop-orders')}
onClick={() => {
if (onClick) {
onClick();
} else {
navigate(ROUTES.orders());
}
}}
style={{
width: '100%',
minHeight: 46,

93
src/components/bridge/HabibBridgeProviders.tsx

@ -0,0 +1,93 @@
import React, { useEffect, useRef } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
import { initFlutterViewPaddings } from '../../lib/view-paddings';
import { closeService, isInFlutterWebView } from '../../lib/webview-actions';
import {
ensureGlobalHardwareBackInstalled,
useHardwareBackHandler,
} from '../../hooks/use-hardware-back-handler';
import { recordInAppNavigation, useSmartBack } from '../../hooks/useSmartBack';
import { ROUTES } from '../../lib/routes';
import { useShopApp } from '../../context/ShopAppContext';
export const HabibBridgeProviders: React.FC<{ children: React.ReactNode }> = ({
children,
}) => {
const location = useLocation();
const navigate = useNavigate();
const smartBack = useSmartBack(ROUTES.home);
const { toastMessage } = useShopApp();
const isFirstMountRef = useRef(true);
useEffect(() => {
window.__habibNavigate = (to: string) => navigate(to);
return () => {
delete window.__habibNavigate;
};
}, [navigate]);
useEffect(() => {
ensureGlobalHardwareBackInstalled();
const cleanupPaddings = initFlutterViewPaddings();
return cleanupPaddings;
}, []);
useEffect(() => {
if (isFirstMountRef.current) {
isFirstMountRef.current = false;
return;
}
recordInAppNavigation();
if (typeof window !== 'undefined') {
window.scrollTo({ top: 0, behavior: 'auto' });
}
}, [location.pathname, location.search]);
// Base route-level hardware back handler (sits at bottom of LIFO stack below modal sheets)
useHardwareBackHandler(() => {
const isRoot =
location.pathname === '/' || location.pathname === '/shop-home';
if (isRoot) {
if (isInFlutterWebView()) {
closeService();
return true;
}
return false;
}
smartBack(ROUTES.home);
return true;
}, true);
return (
<>
{children}
{toastMessage && (
<div
role="status"
aria-live="polite"
style={{
position: 'fixed',
bottom: 'calc(92px + var(--safe-bottom, 0px))',
left: '50%',
transform: 'translateX(-50%)',
padding: '9px 18px',
borderRadius: '14px',
backgroundColor: 'rgba(17, 17, 17, 0.92)',
color: '#ffffff',
fontFamily: 'var(--font-sans)',
fontSize: '12px',
fontWeight: 600,
lineHeight: '16px',
boxShadow: '0 6px 20px rgba(0, 0, 0, 0.25)',
zIndex: 9999,
pointerEvents: 'none',
whiteSpace: 'nowrap',
}}
>
{toastMessage}
</div>
)}
</>
);
};

72
src/components/checkout/AddressCard.tsx

@ -1,14 +1,25 @@
import React from 'react';
import { useNavigate } from 'react-router-dom';
import type { ShippingAddressOption } from '../../data/checkoutData';
import { ROUTES } from '../../lib/routes';
interface AddressCardProps {
item: ShippingAddressOption;
variant: 'checkout' | 'manage';
onSelect?: () => void;
onEdit?: () => void;
onDelete?: () => void;
onChangeAddressClick?: () => void;
}
export const AddressCard: React.FC<AddressCardProps> = ({ item, variant, onSelect }) => {
export const AddressCard: React.FC<AddressCardProps> = ({
item,
variant,
onSelect,
onEdit,
onDelete,
onChangeAddressClick,
}) => {
const navigate = useNavigate();
return (
@ -91,7 +102,11 @@ export const AddressCard: React.FC<AddressCardProps> = ({ item, variant, onSelec
<span
onClick={(e) => {
e.stopPropagation();
navigate('/shop-adreess');
if (onChangeAddressClick) {
onChangeAddressClick();
} else {
navigate(ROUTES.addresses);
}
}}
style={{
fontFamily: 'var(--font-sans)',
@ -107,15 +122,60 @@ export const AddressCard: React.FC<AddressCardProps> = ({ item, variant, onSelec
Change Adress
</span>
) : (
<img
src="/assets/images/icon-address-delete-edit-pair.svg"
alt="Delete or Edit"
<div
style={{
position: 'relative',
width: '84.66px',
height: '24px',
flexShrink: 0,
}}
/>
>
<img
src="/assets/images/icon-address-delete-edit-pair.svg"
alt="Delete or Edit"
style={{
width: '84.66px',
height: '24px',
display: 'block',
}}
/>
{onDelete && (
<button
type="button"
aria-label="Delete Address"
onClick={(e) => {
e.stopPropagation();
onDelete();
}}
style={{
position: 'absolute',
left: 0,
top: 0,
width: '42px',
height: '24px',
cursor: 'pointer',
}}
/>
)}
{onEdit && (
<button
type="button"
aria-label="Edit Address"
onClick={(e) => {
e.stopPropagation();
onEdit();
}}
style={{
position: 'absolute',
right: 0,
top: 0,
width: '42px',
height: '24px',
cursor: 'pointer',
}}
/>
)}
</div>
)}
</div>

20
src/components/checkout/OrderSummaryRows.tsx

@ -1,15 +1,26 @@
import React from 'react';
import { ORDER_SUMMARY_ROWS } from '../../data/checkoutData';
export interface SummaryLineRow {
id: string;
label: string;
value: string;
}
interface OrderSummaryRowsProps {
left?: number;
top?: number;
width?: number;
valueLeft?: number;
totalValueLeft?: number;
rows?: SummaryLineRow[];
totalText?: string;
}
export const OrderSummaryRows: React.FC<OrderSummaryRowsProps> = () => {
export const OrderSummaryRows: React.FC<OrderSummaryRowsProps> = ({
rows = ORDER_SUMMARY_ROWS,
totalText = '$70.50',
}) => {
return (
<div
style={{
@ -19,7 +30,6 @@ export const OrderSummaryRows: React.FC<OrderSummaryRowsProps> = () => {
gap: '14px',
}}
>
{/* 3 Line Items */}
<div
style={{
width: '100%',
@ -28,7 +38,7 @@ export const OrderSummaryRows: React.FC<OrderSummaryRowsProps> = () => {
gap: '10px',
}}
>
{ORDER_SUMMARY_ROWS.map((row) => (
{rows.map((row) => (
<div
key={row.id}
style={{
@ -67,7 +77,6 @@ export const OrderSummaryRows: React.FC<OrderSummaryRowsProps> = () => {
))}
</div>
{/* Divider */}
<div
style={{
width: '100%',
@ -76,7 +85,6 @@ export const OrderSummaryRows: React.FC<OrderSummaryRowsProps> = () => {
}}
/>
{/* Total Row */}
<div
style={{
width: '100%',
@ -108,7 +116,7 @@ export const OrderSummaryRows: React.FC<OrderSummaryRowsProps> = () => {
flexShrink: 0,
}}
>
$70.50
{totalText}
</span>
</div>
</div>

27
src/components/common/CategoryCard.tsx

@ -1,17 +1,33 @@
import React from 'react';
import { useNavigate } from 'react-router-dom';
import type { CategoryTileItem } from '../../data/catalogData';
import { ROUTES } from '../../lib/routes';
interface CategoryCardProps {
tile: CategoryTileItem;
count?: number | string;
slug?: string;
onClick?: () => void;
}
export const CategoryCard: React.FC<CategoryCardProps> = ({ tile }) => {
export const CategoryCard: React.FC<CategoryCardProps> = ({
tile,
count,
slug,
onClick,
}) => {
const navigate = useNavigate();
return (
<div
onClick={() => navigate('/shop-catitems')}
className={tile.isRightCol ? 'habib-category-card is-right-col' : 'habib-category-card'}
onClick={() => {
if (onClick) {
onClick();
} else {
navigate(ROUTES.category(slug || 'home-living'));
}
}}
style={{
position: 'relative',
width: '100%',
@ -20,7 +36,6 @@ export const CategoryCard: React.FC<CategoryCardProps> = ({ tile }) => {
borderRadius: '15px',
backgroundColor: '#ffffff',
border: tile.isRightCol ? undefined : '1px solid rgba(0, 0, 0, 0.05)',
boxShadow: tile.isRightCol ? '0px 4px 17px rgba(148, 163, 184, 0.05)' : undefined,
cursor: 'pointer',
display: 'flex',
flexDirection: 'column',
@ -30,14 +45,14 @@ export const CategoryCard: React.FC<CategoryCardProps> = ({ tile }) => {
minWidth: 0,
}}
>
{/* Count Badge "24" */}
<div
style={{
position: 'absolute',
right: '10px',
top: '9px',
width: '21px',
minWidth: '21px',
height: '21px',
padding: '0 4px',
borderRadius: '6px',
backgroundColor: 'rgba(215, 142, 6, 0.1)',
display: 'flex',
@ -55,7 +70,7 @@ export const CategoryCard: React.FC<CategoryCardProps> = ({ tile }) => {
textAlign: 'center',
}}
>
24
{count !== undefined ? count : 24}
</span>
</div>

39
src/components/common/CompactProductCard.tsx

@ -1,18 +1,33 @@
import React from 'react';
import { useNavigate } from 'react-router-dom';
import type { CompactProductItem } from '../../data/catalogData';
import { ROUTES } from '../../lib/routes';
interface CompactProductCardProps {
item: CompactProductItem;
slugOrId?: string | number;
onClick?: () => void;
onToggleBookmark?: () => void;
}
export const CompactProductCard: React.FC<CompactProductCardProps> = ({ item }) => {
export const CompactProductCard: React.FC<CompactProductCardProps> = ({
item,
slugOrId,
onClick,
onToggleBookmark,
}) => {
const navigate = useNavigate();
return (
<div
className="habib-compact-card"
onClick={() => navigate('/shop-single-page')}
onClick={() => {
if (onClick) {
onClick();
} else {
navigate(ROUTES.product(slugOrId || 'islam-in-the-bible-book'));
}
}}
style={{
minHeight: '229px',
padding: '12px',
@ -45,8 +60,16 @@ export const CompactProductCard: React.FC<CompactProductCardProps> = ({ item })
/>
{/* Bookmark Pill */}
{item.hasBookmark && (
{(item.hasBookmark || onToggleBookmark) && (
<div
role={onToggleBookmark ? 'button' : undefined}
aria-label={onToggleBookmark ? 'Toggle Bookmark' : undefined}
onClick={(e) => {
if (onToggleBookmark) {
e.stopPropagation();
onToggleBookmark();
}
}}
style={{
position: 'absolute',
right: '6px',
@ -54,11 +77,14 @@ export const CompactProductCard: React.FC<CompactProductCardProps> = ({ item })
width: '18px',
height: '18px',
borderRadius: '6px',
backgroundColor: 'rgba(255, 255, 255, 0.8)',
backgroundColor: item.hasBookmark
? 'rgba(255, 255, 255, 0.92)'
: 'rgba(255, 255, 255, 0.72)',
boxShadow: '0px 1px 2px rgba(0, 0, 0, 0.08)',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
opacity: item.hasBookmark ? 1 : 0.72,
}}
>
<img
@ -125,7 +151,6 @@ export const CompactProductCard: React.FC<CompactProductCardProps> = ({ item })
minWidth: 0,
}}
>
{/* Title */}
<div
style={{
fontFamily: 'var(--font-sans)',
@ -138,7 +163,6 @@ export const CompactProductCard: React.FC<CompactProductCardProps> = ({ item })
{item.title}
</div>
{/* Origin Row */}
<div
style={{
marginTop: '4px',
@ -150,7 +174,7 @@ export const CompactProductCard: React.FC<CompactProductCardProps> = ({ item })
>
<img
src="/assets/images/icon-flag-iran-10.svg"
alt="Iran"
alt="Origin"
style={{
width: '10px',
height: '10px',
@ -173,7 +197,6 @@ export const CompactProductCard: React.FC<CompactProductCardProps> = ({ item })
</span>
</div>
{/* Price Block */}
<div style={{ marginTop: 'auto', paddingTop: '6px' }}>
{item.oldPrice && (
<span

40
src/components/common/GridProductCard.tsx

@ -1,17 +1,35 @@
import React from 'react';
import { useNavigate } from 'react-router-dom';
import type { GridProductItem } from '../../data/catalogData';
import { ROUTES } from '../../lib/routes';
interface GridProductCardProps {
item: GridProductItem;
slugOrId?: string | number;
isBookmarked?: boolean;
onClick?: () => void;
onToggleBookmark?: () => void;
}
export const GridProductCard: React.FC<GridProductCardProps> = ({ item }) => {
export const GridProductCard: React.FC<GridProductCardProps> = ({
item,
slugOrId,
isBookmarked,
onClick,
onToggleBookmark,
}) => {
const navigate = useNavigate();
return (
<div
onClick={() => navigate('/shop-single-page')}
className="habib-grid-card"
onClick={() => {
if (onClick) {
onClick();
} else {
navigate(ROUTES.product(slugOrId || 'islam-in-the-bible-book'));
}
}}
style={{
width: '100%',
minHeight: '241px',
@ -48,6 +66,14 @@ export const GridProductCard: React.FC<GridProductCardProps> = ({ item }) => {
{/* Bookmark Pill */}
<div
role={onToggleBookmark ? 'button' : undefined}
aria-label={onToggleBookmark ? 'Toggle Bookmark' : undefined}
onClick={(e) => {
if (onToggleBookmark) {
e.stopPropagation();
onToggleBookmark();
}
}}
style={{
position: 'absolute',
right: '6px',
@ -55,7 +81,10 @@ export const GridProductCard: React.FC<GridProductCardProps> = ({ item }) => {
width: '20px',
height: '18px',
borderRadius: '6px',
backgroundColor: 'rgba(255, 255, 255, 0.8)',
backgroundColor: isBookmarked
? 'rgba(255, 247, 233, 0.95)'
: 'rgba(255, 255, 255, 0.8)',
border: isBookmarked ? '1px solid #d78e06' : undefined,
boxShadow: '0px 1px 2px rgba(0, 0, 0, 0.08)',
display: 'flex',
alignItems: 'center',
@ -123,7 +152,6 @@ export const GridProductCard: React.FC<GridProductCardProps> = ({ item }) => {
minWidth: 0,
}}
>
{/* Title */}
<div
style={{
fontFamily: 'var(--font-sans)',
@ -136,7 +164,6 @@ export const GridProductCard: React.FC<GridProductCardProps> = ({ item }) => {
{item.title}
</div>
{/* Origin Row */}
<div
style={{
marginTop: '4px',
@ -148,7 +175,7 @@ export const GridProductCard: React.FC<GridProductCardProps> = ({ item }) => {
>
<img
src="/assets/images/icon-flag-iran-10.svg"
alt="Iran"
alt="Origin"
style={{
width: '10px',
height: '10px',
@ -171,7 +198,6 @@ export const GridProductCard: React.FC<GridProductCardProps> = ({ item }) => {
</span>
</div>
{/* Price + Discount Badge */}
<div style={{ marginTop: 'auto', paddingTop: '6px' }}>
{item.oldPrice && (
<span

51
src/components/common/SearchBar.tsx

@ -1,4 +1,6 @@
import React from 'react';
import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { ROUTES } from '../../lib/routes';
interface SearchBarProps {
left?: number;
@ -7,20 +9,48 @@ interface SearchBarProps {
inputWidth?: number;
showFilterButton?: boolean;
onFilterClick?: () => void;
value?: string;
defaultValue?: string;
onChange?: (value: string) => void;
onSubmit?: (value: string) => void;
placeholder?: string;
autoFocus?: boolean;
}
export const SearchBar: React.FC<SearchBarProps> = ({
showFilterButton = false,
onFilterClick,
value,
defaultValue = '',
onChange,
onSubmit,
placeholder = 'Search products, stores, categories...',
autoFocus = false,
}) => {
const navigate = useNavigate();
const [internalVal, setInternalVal] = useState(defaultValue);
const currentValue = value !== undefined ? value : internalVal;
const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
const trimmed = currentValue.trim();
if (onSubmit) {
onSubmit(trimmed);
} else {
navigate(ROUTES.search(trimmed));
}
};
return (
<div
<form
onSubmit={handleSubmit}
style={{
display: 'flex',
alignItems: 'center',
gap: '9px',
width: '100%',
height: '50px',
margin: 0,
}}
>
<div
@ -46,10 +76,19 @@ export const SearchBar: React.FC<SearchBarProps> = ({
}}
/>
<input
type="text"
type="search"
enterKeyHint="search"
autoFocus={autoFocus}
value={currentValue}
onChange={(e) => {
if (value === undefined) {
setInternalVal(e.target.value);
}
onChange?.(e.target.value);
}}
className="habib-search-input"
placeholder="Search products, stores, categories..."
aria-label="Search products, stores, categories..."
placeholder={placeholder}
aria-label={placeholder}
style={{
width: '100%',
height: '100%',
@ -88,6 +127,6 @@ export const SearchBar: React.FC<SearchBarProps> = ({
/>
</button>
)}
</div>
</form>
);
};

714
src/components/common/ShimmerSkeletons.tsx

@ -0,0 +1,714 @@
import React from 'react';
interface ShimmerBoxProps {
width?: number | string;
height?: number | string;
borderRadius?: number | string;
dark?: boolean;
style?: React.CSSProperties;
}
export const ShimmerBox: React.FC<ShimmerBoxProps> = ({
width = '100%',
height = 14,
borderRadius = 8,
dark = false,
style,
}) => (
<div
aria-hidden="true"
className={dark ? 'habib-shimmer-dark' : 'habib-shimmer'}
style={{
width,
height,
borderRadius,
flexShrink: 0,
...style,
}}
/>
);
export const InlineSpinner: React.FC<{
size?: number;
gold?: boolean;
}> = ({ size = 16, gold = false }) => (
<span
aria-hidden="true"
className={`habib-inline-spinner${gold ? ' is-gold' : ''}`}
style={{ width: size, height: size }}
/>
);
export const RetryBanner: React.FC<{
message?: string;
onRetry: () => void;
}> = ({
message = 'Connection took longer than expected. Check your network and try again.',
onRetry,
}) => (
<div
role="alert"
style={{
width: '100%',
padding: '18px 16px',
borderRadius: 16,
background: 'linear-gradient(180deg, #ffffff 0%, #f8f8f8 100%)',
border: '1px solid #e8e4df',
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
textAlign: 'center',
gap: 10,
}}
>
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 600,
fontSize: 13,
lineHeight: '19px',
color: '#292a2e',
}}
>
{message}
</span>
<button
type="button"
onClick={onRetry}
className="habib-cta-btn"
style={{
padding: '8px 18px',
borderRadius: 10,
color: '#ffffff',
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 12,
cursor: 'pointer',
}}
>
Retry
</button>
</div>
);
export const EmptyStateBox: React.FC<{
message: string;
compact?: boolean;
}> = ({ message, compact = false }) => (
<div
style={{
width: '100%',
padding: compact ? '18px 14px' : '32px 16px',
borderRadius: 15,
backgroundColor: '#ffffff',
border: '1px solid #e8e4df',
boxSizing: 'border-box',
textAlign: 'center',
fontFamily: 'var(--font-sans)',
fontWeight: 600,
fontSize: 13,
lineHeight: '19px',
color: '#747474',
}}
>
{message}
</div>
);
export const CompactCarouselShimmer: React.FC<{ count?: number }> = ({
count = 3,
}) => (
<div
className="habib-carousel-scroller habib-scroll-container"
data-testid="shimmer-compact-carousel"
>
<div className="habib-carousel-track">
{Array.from({ length: count }).map((_, idx) => (
<div
key={idx}
className="habib-compact-card"
style={{
padding: 12,
borderRadius: 15,
backgroundColor: '#ffffff',
display: 'flex',
flexDirection: 'column',
gap: 8,
}}
>
<ShimmerBox height={112} borderRadius={10} />
<ShimmerBox width="62%" height={10} borderRadius={5} />
<ShimmerBox width="90%" height={13} borderRadius={6} />
<div
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
marginTop: 2,
}}
>
<ShimmerBox width={54} height={15} borderRadius={6} />
<ShimmerBox width={30} height={12} borderRadius={6} />
</div>
</div>
))}
</div>
</div>
);
export const HomeFeedShimmer: React.FC = () => (
<div
data-testid="shimmer-home-feed"
style={{ display: 'flex', flexDirection: 'column', gap: 20 }}
>
{/* Hero Banner Shimmer */}
<div
className="habib-hero-banner"
style={{
width: '100%',
borderRadius: 15,
backgroundColor: '#182c1f',
padding: '16px 18px',
display: 'flex',
flexDirection: 'column',
justifyContent: 'space-between',
}}
>
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
<ShimmerBox width={68} height={10} borderRadius={5} dark />
<ShimmerBox width="72%" height={18} borderRadius={6} dark />
<ShimmerBox width="56%" height={18} borderRadius={6} dark />
<ShimmerBox width="65%" height={10} borderRadius={5} dark />
</div>
<ShimmerBox width={108} height={30} borderRadius={8} dark />
</div>
{/* 5 Quick Categories Circular Pills Shimmer */}
<div className="habib-quick-cats">
{Array.from({ length: 5 }).map((_, idx) => (
<div
key={idx}
style={{
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
gap: 6,
}}
>
<ShimmerBox width={43} height={43} borderRadius="50%" />
<ShimmerBox width={36} height={9} borderRadius={4} />
</div>
))}
</div>
{/* Populars Section Shimmer */}
<div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
<div
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
padding: '0 2px',
}}
>
<ShimmerBox width={74} height={16} borderRadius={6} />
<ShimmerBox width={56} height={12} borderRadius={6} />
</div>
<CompactCarouselShimmer count={3} />
</div>
{/* New Stores Section Shimmer */}
<div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
<div
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
padding: '0 2px',
}}
>
<ShimmerBox width={86} height={16} borderRadius={6} />
<ShimmerBox width={56} height={12} borderRadius={6} />
</div>
<CompactCarouselShimmer count={3} />
</div>
</div>
);
export const CategoryGridShimmer: React.FC<{ count?: number }> = ({
count = 6,
}) => (
<div className="habib-category-grid" data-testid="shimmer-category-grid">
{Array.from({ length: count }).map((_, idx) => (
<div
key={idx}
style={{
minHeight: 118,
padding: '14px 12px',
borderRadius: 16,
backgroundColor: '#ffffff',
display: 'flex',
flexDirection: 'column',
justifyContent: 'space-between',
}}
>
<div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
<ShimmerBox width="68%" height={14} borderRadius={6} />
<ShimmerBox width="42%" height={10} borderRadius={5} />
</div>
<div style={{ display: 'flex', justifyContent: 'flex-end' }}>
<ShimmerBox width={48} height={48} borderRadius={14} />
</div>
</div>
))}
</div>
);
export const ProductGridShimmer: React.FC<{ count?: number }> = ({
count = 6,
}) => (
<div className="habib-product-grid" data-testid="shimmer-product-grid">
{Array.from({ length: count }).map((_, idx) => (
<div
key={idx}
style={{
padding: 12,
borderRadius: 15,
backgroundColor: '#ffffff',
display: 'flex',
flexDirection: 'column',
gap: 9,
}}
>
<ShimmerBox height={132} borderRadius={11} />
<ShimmerBox width="58%" height={10} borderRadius={5} />
<ShimmerBox width="92%" height={13} borderRadius={6} />
<ShimmerBox width="64%" height={13} borderRadius={6} />
<div
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
marginTop: 2,
}}
>
<ShimmerBox width={62} height={16} borderRadius={6} />
<ShimmerBox width={34} height={13} borderRadius={6} />
</div>
</div>
))}
</div>
);
export const ProductDetailBodyShimmer: React.FC = () => (
<div data-testid="shimmer-product-detail" style={{ display: 'contents' }}>
<div
style={{
position: 'relative',
zIndex: 1,
marginTop: -38,
borderTopLeftRadius: 20,
borderTopRightRadius: 20,
backgroundColor: '#f3f1ef',
padding: '18px var(--page-px) 16px',
display: 'flex',
flexDirection: 'column',
gap: 15,
}}
>
<div
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
}}
>
<ShimmerBox width="54%" height={11} borderRadius={5} />
<ShimmerBox width={56} height={24} borderRadius={8} />
</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: 7 }}>
<ShimmerBox width="82%" height={22} borderRadius={7} />
<ShimmerBox width="38%" height={14} borderRadius={6} />
</div>
<div className="habib-single-attrs-grid" style={{ marginTop: 4 }}>
<ShimmerBox height={48} borderRadius={8} />
<ShimmerBox height={48} borderRadius={8} />
<ShimmerBox height={48} borderRadius={8} />
</div>
<div
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
paddingTop: 4,
}}
>
<div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
<ShimmerBox width={39} height={39} borderRadius="50%" />
<div style={{ display: 'flex', flexDirection: 'column', gap: 5 }}>
<ShimmerBox width={126} height={14} borderRadius={6} />
<ShimmerBox width={74} height={10} borderRadius={5} />
</div>
</div>
<div
style={{
display: 'flex',
flexDirection: 'column',
alignItems: 'flex-end',
gap: 5,
}}
>
<ShimmerBox width={42} height={13} borderRadius={5} />
<ShimmerBox width={54} height={10} borderRadius={5} />
</div>
</div>
<div
style={{
display: 'grid',
gridTemplateColumns: '1fr 1fr',
gap: 16,
marginTop: 8,
paddingBottom: 6,
}}
>
<ShimmerBox height={20} borderRadius={6} />
<ShimmerBox height={20} borderRadius={6} />
</div>
</div>
<div
style={{
flex: 1,
backgroundColor: '#ebe8e5',
padding: '24px var(--page-px) 28px',
display: 'flex',
flexDirection: 'column',
gap: 12,
}}
>
<ShimmerBox width={90} height={14} borderRadius={6} />
<ShimmerBox width="45%" height={13} borderRadius={6} />
<ShimmerBox
width={104}
height={14}
borderRadius={6}
style={{ marginTop: 8 }}
/>
<ShimmerBox width="96%" height={13} borderRadius={6} />
<ShimmerBox width="91%" height={13} borderRadius={6} />
<ShimmerBox width="78%" height={13} borderRadius={6} />
</div>
<div
style={{
position: 'sticky',
bottom: 0,
zIndex: 20,
width: '100%',
minHeight: 87,
padding: '16px var(--page-px) calc(16px + var(--safe-bottom, 0px))',
borderRadius: '17px 17px 0 0',
backgroundColor: '#ffffff',
boxShadow: '0px -7px 12px rgba(103, 110, 124, 0.15)',
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
gap: 12,
}}
>
<div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
<ShimmerBox width={68} height={13} borderRadius={5} />
<ShimmerBox width={88} height={24} borderRadius={7} />
</div>
<ShimmerBox width={176} height={52} borderRadius={11} />
</div>
</div>
);
export const StoreBoothBodyShimmer: React.FC = () => (
<div
data-testid="shimmer-store-booth"
style={{
position: 'relative',
zIndex: 1,
marginTop: -97,
flex: 1,
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
padding: '0 var(--page-px) 32px',
}}
>
<ShimmerBox
width={64}
height={64}
borderRadius={32}
style={{ border: '2px solid #ffffff' }}
/>
<ShimmerBox
width={186}
height={18}
borderRadius={6}
style={{ marginTop: 12 }}
/>
<ShimmerBox
width={104}
height={13}
borderRadius={6}
style={{ marginTop: 8 }}
/>
<div
style={{
marginTop: 14,
width: '100%',
maxWidth: 340,
display: 'flex',
justifyContent: 'space-around',
gap: 10,
}}
>
<ShimmerBox width={64} height={13} borderRadius={5} />
<ShimmerBox width={92} height={13} borderRadius={5} />
<ShimmerBox width={60} height={13} borderRadius={5} />
</div>
<div className="habib-booth-metrics-grid" style={{ marginTop: 21 }}>
<ShimmerBox height={58} borderRadius={8} />
<ShimmerBox height={58} borderRadius={8} />
<ShimmerBox height={58} borderRadius={8} />
</div>
<div
style={{
marginTop: 26,
width: '100%',
display: 'flex',
flexDirection: 'column',
gap: 10,
}}
>
<ShimmerBox width={62} height={16} borderRadius={6} />
<ShimmerBox width="96%" height={13} borderRadius={5} />
<ShimmerBox width="88%" height={13} borderRadius={5} />
<ShimmerBox width="70%" height={13} borderRadius={5} />
</div>
<div
style={{
marginTop: 28,
width: '100%',
display: 'flex',
flexDirection: 'column',
gap: 12,
}}
>
<ShimmerBox width={78} height={16} borderRadius={6} />
<ProductGridShimmer count={4} />
</div>
</div>
);
export const OrdersListShimmer: React.FC<{ count?: number }> = ({
count = 2,
}) => (
<div className="habib-orders-grid" data-testid="shimmer-orders-list">
{Array.from({ length: count }).map((_, idx) => (
<div
key={idx}
style={{
width: '100%',
padding: 14,
borderRadius: 20,
backgroundColor: '#ffffff',
display: 'flex',
flexDirection: 'column',
gap: 14,
}}
>
<div
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
}}
>
<ShimmerBox width={142} height={16} borderRadius={6} />
<ShimmerBox width={86} height={14} borderRadius={6} />
</div>
<div style={{ display: 'flex', gap: 10 }}>
<ShimmerBox width={64} height={64} borderRadius={12} />
<ShimmerBox width={64} height={64} borderRadius={12} />
<ShimmerBox width={64} height={64} borderRadius={12} />
</div>
<ShimmerBox height={38} borderRadius={11} />
<ShimmerBox height={42} borderRadius={11} />
</div>
))}
</div>
);
export const OrderDetailShimmer: React.FC = () => (
<div
data-testid="shimmer-order-detail"
style={{ display: 'flex', flexDirection: 'column', gap: 20 }}
>
<div
style={{
width: '100%',
padding: 14,
borderRadius: 20,
backgroundColor: '#ebe8e5',
display: 'flex',
flexDirection: 'column',
gap: 14,
}}
>
<div
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
}}
>
<ShimmerBox width={146} height={18} borderRadius={6} />
<ShimmerBox width={94} height={14} borderRadius={6} />
</div>
<ShimmerBox height={41} borderRadius={12} />
</div>
<div className="habib-orders-grid">
{Array.from({ length: 2 }).map((_, idx) => (
<div
key={idx}
style={{
width: '100%',
padding: 14,
borderRadius: 20,
backgroundColor: '#ffffff',
display: 'flex',
flexDirection: 'column',
gap: 14,
}}
>
<div
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
}}
>
<ShimmerBox width={132} height={16} borderRadius={6} />
<ShimmerBox width={74} height={22} borderRadius={10} />
</div>
<div style={{ display: 'flex', gap: 10 }}>
<ShimmerBox width={58} height={58} borderRadius={10} />
<div
style={{
flex: 1,
display: 'flex',
flexDirection: 'column',
gap: 8,
justifyContent: 'center',
}}
>
<ShimmerBox width="80%" height={14} borderRadius={6} />
<ShimmerBox width="45%" height={14} borderRadius={6} />
</div>
</div>
<ShimmerBox height={28} borderRadius={10} />
</div>
))}
</div>
</div>
);
export const ChatThreadShimmer: React.FC = () => (
<div
data-testid="shimmer-chat-thread"
style={{
display: 'flex',
flexDirection: 'column',
justifyContent: 'flex-end',
gap: 14,
width: '100%',
}}
>
<div style={{ alignSelf: 'center' }}>
<ShimmerBox width={68} height={14} borderRadius={7} />
</div>
<div style={{ display: 'flex', alignItems: 'flex-start', gap: 9 }}>
<ShimmerBox width={35} height={35} borderRadius="50%" />
<ShimmerBox
width="68%"
height={62}
borderRadius="0px 20px 20px 20px"
/>
</div>
<div style={{ alignSelf: 'flex-end', width: '58%', marginRight: 8 }}>
<ShimmerBox height={48} borderRadius="20px 0px 20px 20px" />
</div>
<div style={{ display: 'flex', alignItems: 'flex-start', gap: 9 }}>
<ShimmerBox width={35} height={35} borderRadius="50%" />
<ShimmerBox
width="74%"
height={54}
borderRadius="0px 20px 20px 20px"
/>
</div>
</div>
);
export const CartItemsShimmer: React.FC<{ count?: number }> = ({
count = 2,
}) => (
<div
data-testid="shimmer-cart-items"
style={{ display: 'flex', flexDirection: 'column', gap: 10 }}
>
{Array.from({ length: count }).map((_, idx) => (
<div
key={idx}
style={{
width: '100%',
minHeight: 121,
padding: 12,
borderRadius: 15,
backgroundColor: '#ffffff',
display: 'flex',
gap: 12,
alignItems: 'center',
}}
>
<ShimmerBox width={86} height={92} borderRadius={11} />
<div
style={{
flex: 1,
display: 'flex',
flexDirection: 'column',
gap: 8,
}}
>
<ShimmerBox width="84%" height={14} borderRadius={6} />
<ShimmerBox width="52%" height={11} borderRadius={5} />
<div
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
marginTop: 6,
}}
>
<ShimmerBox width={64} height={18} borderRadius={6} />
<ShimmerBox width={86} height={30} borderRadius={9} />
</div>
</div>
</div>
))}
</div>
);

58
src/components/layout/BottomNavBar.tsx

@ -1,5 +1,8 @@
import React, { useEffect, useSyncExternalStore } from 'react';
import { useNavigate } from 'react-router-dom';
import { useLocation, useNavigate } from 'react-router-dom';
import { useShopApp } from '../../context/ShopAppContext';
import { isBareMode, ROUTES } from '../../lib/routes';
import { openAiAssistant } from '../../lib/webview-actions';
export type BottomNavTab = 'home' | 'category' | 'account' | 'cart';
@ -37,9 +40,18 @@ const waveListeners = new Set<() => void>();
function tabFromPathname(pathname: string): BottomNavTab | null {
if (pathname === '/' || pathname === '/shop-home') return 'home';
if (pathname === '/shop-category') return 'category';
if (pathname === '/shop-account' || pathname === '/shop-category-4214-345') return 'account';
if (pathname === '/shop-cart') return 'cart';
if (pathname === '/categories' || pathname.startsWith('/categories/') || pathname === '/shop-category') {
return 'category';
}
if (
pathname === '/account' ||
pathname.startsWith('/account/') ||
pathname === '/shop-account' ||
pathname === '/shop-category-4214-345'
) {
return 'account';
}
if (pathname === '/cart' || pathname === '/shop-cart') return 'cart';
return null;
}
@ -157,9 +169,15 @@ const IndicatorWave: React.FC<{
export const BottomNavBar: React.FC<BottomNavBarProps> = ({
activeTab,
showCartBadge = true,
cartBadgeCount = 2,
cartBadgeCount,
}) => {
const navigate = useNavigate();
const location = useLocation();
const { cartItemsCount } = useShopApp();
const isBare = isBareMode(location.search);
const resolvedBadgeCount =
cartBadgeCount !== undefined ? cartBadgeCount : isBare ? 2 : cartItemsCount;
const snapshot = useSyncExternalStore(subscribeWave, getWaveSnapshot, getWaveSnapshot);
useEffect(() => {
@ -202,7 +220,7 @@ export const BottomNavBar: React.FC<BottomNavBarProps> = ({
bottom: 0,
marginTop: 'auto',
width: '100%',
height: '78px',
minHeight: '78px',
flexShrink: 0,
zIndex: 30,
}}
@ -212,7 +230,8 @@ export const BottomNavBar: React.FC<BottomNavBarProps> = ({
style={{
position: 'relative',
width: '100%',
height: '78px',
minHeight: '78px',
paddingBottom: 'var(--safe-bottom, 0px)',
borderRadius: '17px 17px 0 0',
backgroundColor: '#ffffff',
boxShadow: '0px -7px 12px rgba(103, 110, 124, 0.15)',
@ -222,7 +241,7 @@ export const BottomNavBar: React.FC<BottomNavBarProps> = ({
{/* Home Tab */}
<button
type="button"
onClick={() => handleTabNavigate('home', '/shop-home')}
onClick={() => handleTabNavigate('home', ROUTES.home)}
style={{
position: 'relative',
height: '78px',
@ -254,7 +273,7 @@ export const BottomNavBar: React.FC<BottomNavBarProps> = ({
{/* Category Tab */}
<button
type="button"
onClick={() => handleTabNavigate('category', '/shop-category')}
onClick={() => handleTabNavigate('category', ROUTES.categories)}
style={{
position: 'relative',
height: '78px',
@ -283,7 +302,7 @@ export const BottomNavBar: React.FC<BottomNavBarProps> = ({
)}
</button>
{/* Center Habib Emblem Pill */}
{/* Center Habib AI Assistant Button */}
<div
style={{
position: 'relative',
@ -295,9 +314,13 @@ export const BottomNavBar: React.FC<BottomNavBarProps> = ({
>
<img
src="/assets/images/nav-center-habib-pill.svg"
alt="Habib"
alt="Habib AI Assistant"
decoding="sync"
onClick={() => handleTabNavigate('home', '/shop-home')}
onClick={() => {
if (!openAiAssistant()) {
navigate(ROUTES.search());
}
}}
style={{
position: 'absolute',
top: '-7px',
@ -313,7 +336,7 @@ export const BottomNavBar: React.FC<BottomNavBarProps> = ({
{/* Account Tab */}
<button
type="button"
onClick={() => handleTabNavigate('account', '/shop-account')}
onClick={() => handleTabNavigate('account', ROUTES.account)}
style={{
position: 'relative',
height: '78px',
@ -345,7 +368,7 @@ export const BottomNavBar: React.FC<BottomNavBarProps> = ({
{/* Cart Tab */}
<button
type="button"
onClick={() => handleTabNavigate('cart', '/shop-cart')}
onClick={() => handleTabNavigate('cart', ROUTES.cart)}
style={{
position: 'relative',
height: '78px',
@ -365,14 +388,15 @@ export const BottomNavBar: React.FC<BottomNavBarProps> = ({
alt="Cart"
visualClass={cartVisual}
/>
{showCartBadge && cartBadgeCount > 0 && (
{showCartBadge && resolvedBadgeCount > 0 && (
<div
style={{
position: 'absolute',
right: '-6px',
top: '-4px',
width: '16px',
minWidth: '16px',
height: '16px',
padding: '0 3px',
borderRadius: '8px',
backgroundColor: '#d44747',
display: 'flex',
@ -390,7 +414,7 @@ export const BottomNavBar: React.FC<BottomNavBarProps> = ({
color: '#ffffff',
}}
>
{cartBadgeCount}
{resolvedBadgeCount}
</span>
</div>
)}

21
src/components/layout/TopHeader.tsx

@ -1,19 +1,22 @@
import React from 'react';
import { useNavigate } from 'react-router-dom';
import { useSmartBack } from '../../hooks/useSmartBack';
import { ROUTES } from '../../lib/routes';
interface StandardPageHeaderProps {
title: string;
titleTop?: number;
backTo?: string;
showBack?: boolean;
onBackClick?: () => void;
}
export const StandardPageHeader: React.FC<StandardPageHeaderProps> = ({
title,
backTo = '/shop-home',
backTo = ROUTES.home,
showBack = true,
onBackClick,
}) => {
const navigate = useNavigate();
const smartBack = useSmartBack(backTo);
return (
<header
@ -21,7 +24,7 @@ export const StandardPageHeader: React.FC<StandardPageHeaderProps> = ({
position: 'relative',
width: '100%',
minHeight: '61px',
padding: '21px var(--page-px, 16px) 0',
padding: 'calc(21px + var(--safe-top, 0px)) var(--page-px, 16px) 0',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
@ -31,12 +34,18 @@ export const StandardPageHeader: React.FC<StandardPageHeaderProps> = ({
{showBack && (
<button
type="button"
onClick={() => navigate(backTo)}
onClick={() => {
if (onBackClick) {
onBackClick();
} else {
smartBack(backTo);
}
}}
aria-label="Back"
style={{
position: 'absolute',
left: 'var(--page-px, 16px)',
top: '21px',
top: 'calc(21px + var(--safe-top, 0px))',
width: '40px',
height: '40px',
borderRadius: '15px',

301
src/components/modals/AddressFormSheet.tsx

@ -0,0 +1,301 @@
import React, { useEffect, useState } from 'react';
import { useHardwareBackHandler } from '../../hooks/use-hardware-back-handler';
import type { ApiAddress } from '../../lib/shopApi';
import type { SaveAddressInput } from '../../context/ShopAppContext';
import { isInFlutterWebView, pickManualLocation } from '../../lib/webview-actions';
interface AddressFormSheetProps {
isOpen: boolean;
onClose: () => void;
initialAddress?: ApiAddress | null;
onSave: (input: SaveAddressInput) => Promise<ApiAddress | null>;
}
export const AddressFormSheet: React.FC<AddressFormSheetProps> = ({
isOpen,
onClose,
initialAddress,
onSave,
}) => {
const [recipientName, setRecipientName] = useState('');
const [phone, setPhone] = useState('');
const [country, setCountry] = useState('United States');
const [city, setCity] = useState('New York');
const [streetLine, setStreetLine] = useState('');
const [postalCode, setPostalCode] = useState('');
const [lat, setLat] = useState<number | null>(null);
const [lon, setLon] = useState<number | null>(null);
const [isDefault, setIsDefault] = useState(true);
const [saving, setSaving] = useState(false);
useEffect(() => {
if (!isOpen) return;
if (initialAddress) {
setRecipientName(initialAddress.recipient_name || '');
setPhone(initialAddress.phone || '');
setCountry(initialAddress.country || 'United States');
setCity(initialAddress.city || 'New York');
setStreetLine(initialAddress.street_line || '');
setPostalCode(initialAddress.postal_code || '');
setLat(initialAddress.lat !== null ? Number(initialAddress.lat) : null);
setLon(initialAddress.lon !== null ? Number(initialAddress.lon) : null);
setIsDefault(Boolean(initialAddress.is_default));
} else {
setRecipientName('');
setPhone('');
setCountry('United States');
setCity('New York');
setStreetLine('');
setPostalCode('');
setLat(null);
setLon(null);
setIsDefault(true);
}
}, [initialAddress, isOpen]);
useHardwareBackHandler(() => {
if (!saving) onClose();
return true;
}, isOpen);
if (!isOpen) return null;
const handlePickMap = async () => {
const picked = await pickManualLocation();
if (picked) {
setLat(picked.lat);
setLon(picked.lon);
if (picked.city) setCity(picked.city);
if (picked.country) setCountry(picked.country);
if (picked.address) setStreetLine(picked.address);
}
};
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!recipientName.trim() || !streetLine.trim() || saving) return;
setSaving(true);
try {
const saved = await onSave({
id: initialAddress?.id,
recipient_name: recipientName.trim(),
phone: phone.trim(),
country: country.trim() || 'United States',
city: city.trim() || 'New York',
street_line: streetLine.trim(),
postal_code: postalCode.trim(),
lat,
lon,
is_default: isDefault,
});
if (saved) {
onClose();
}
} finally {
setSaving(false);
}
};
const inputStyle: React.CSSProperties = {
width: '100%',
height: '44px',
borderRadius: '12px',
backgroundColor: '#ffffff',
border: '1px solid #d7dbe2',
padding: '0 12px',
fontFamily: 'var(--font-sans)',
fontSize: '13px',
color: '#111111',
};
return (
<div
onClick={() => {
if (!saving) onClose();
}}
style={{
position: 'fixed',
inset: 0,
backgroundColor: 'rgba(17, 17, 17, 0.9)',
zIndex: 60,
display: 'flex',
flexDirection: 'column',
justifyContent: 'flex-end',
}}
>
<form
className="habib-bottom-sheet"
onClick={(e) => e.stopPropagation()}
onSubmit={handleSubmit}
style={{
padding: '22px var(--page-px) calc(24px + var(--safe-bottom, 0px))',
display: 'flex',
flexDirection: 'column',
gap: '14px',
maxHeight: '88dvh',
overflowY: 'auto',
}}
>
<div
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
}}
>
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: '15px',
color: '#111111',
}}
>
{initialAddress ? 'Edit Delivery Address' : 'Add Delivery Address'}
</span>
<button
type="button"
onClick={onClose}
aria-label="Close"
style={{
width: '24px',
height: '24px',
cursor: 'pointer',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
}}
>
<img
src="/assets/images/icon-modal-close-cross.svg"
alt=""
style={{ width: '11.67px', height: '11.67px' }}
/>
</button>
</div>
{isInFlutterWebView() && (
<button
type="button"
onClick={handlePickMap}
style={{
width: '100%',
height: '40px',
borderRadius: '11px',
backgroundColor: 'rgba(215, 142, 6, 0.12)',
border: '1px solid #d78e06',
color: '#d78e06',
fontFamily: 'var(--font-sans)',
fontWeight: 600,
fontSize: '12px',
cursor: 'pointer',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
gap: '6px',
}}
>
<img
src="/assets/images/icon-location-pin-gold.svg"
alt=""
style={{ width: '16px', height: '16px' }}
/>
{lat !== null ? 'Location pinned on map' : 'Pick Location on Map'}
</button>
)}
<input
type="text"
required
placeholder="Recipient full name *"
value={recipientName}
onChange={(e) => setRecipientName(e.target.value)}
style={inputStyle}
/>
<input
type="tel"
placeholder="Phone number"
value={phone}
onChange={(e) => setPhone(e.target.value)}
style={inputStyle}
/>
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '10px' }}>
<input
type="text"
placeholder="Country"
value={country}
onChange={(e) => setCountry(e.target.value)}
style={inputStyle}
/>
<input
type="text"
placeholder="City"
value={city}
onChange={(e) => setCity(e.target.value)}
style={inputStyle}
/>
</div>
<input
type="text"
required
placeholder="Street address, apartment, suite *"
value={streetLine}
onChange={(e) => setStreetLine(e.target.value)}
style={inputStyle}
/>
<input
type="text"
placeholder="Postal / ZIP code"
value={postalCode}
onChange={(e) => setPostalCode(e.target.value)}
style={inputStyle}
/>
<label
style={{
display: 'flex',
alignItems: 'center',
gap: '8px',
fontFamily: 'var(--font-sans)',
fontSize: '12px',
fontWeight: 600,
color: '#292a2e',
cursor: 'pointer',
}}
>
<input
type="checkbox"
checked={isDefault}
onChange={(e) => setIsDefault(e.target.checked)}
style={{ width: '16px', height: '16px', accentColor: '#d78e06' }}
/>
Set as default shipping address
</label>
<button
type="submit"
disabled={saving || !recipientName.trim() || !streetLine.trim()}
className="habib-cta-btn"
style={{
width: '100%',
height: '50px',
borderRadius: '11px',
color: '#fbfbfc',
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: '15px',
cursor: saving ? 'not-allowed' : 'pointer',
opacity: saving || !recipientName.trim() || !streetLine.trim() ? 0.65 : 1,
}}
>
{saving ? 'Saving...' : 'Save Address'}
</button>
</form>
</div>
);
};

188
src/components/modals/LoginRequiredModal.tsx

@ -0,0 +1,188 @@
import React from 'react';
import { useHardwareBackHandler } from '../../hooks/use-hardware-back-handler';
import { InlineSpinner } from '../common/ShimmerSkeletons';
export interface LoginRequiredModalProps {
isOpen: boolean;
title?: string;
description?: string;
isLoggingIn?: boolean;
onConfirmLogin: () => void;
onClose: () => void;
}
/**
* Modal shown when an unauthenticated user triggers a feature that requires
* Habib authentication. Clicking "Log In" invokes the native Flutter login bridge
* (`window.HabibApp.postMessage(JSON.stringify({ action: 'login' }))`).
*/
export const LoginRequiredModal: React.FC<LoginRequiredModalProps> = ({
isOpen,
title = 'Sign in Required',
description = 'Please log in with your Habib account to continue.',
isLoggingIn = false,
onConfirmLogin,
onClose,
}) => {
useHardwareBackHandler(() => {
if (!isLoggingIn) {
onClose();
}
return true;
}, isOpen);
if (!isOpen) return null;
return (
<div
role="dialog"
aria-modal="true"
aria-labelledby="habib-login-modal-title"
onClick={() => {
if (!isLoggingIn) onClose();
}}
style={{
position: 'fixed',
inset: 0,
zIndex: 120,
backgroundColor: 'rgba(21, 28, 49, 0.52)',
backdropFilter: 'blur(3px)',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
padding: '24px 20px',
}}
>
<div
onClick={(e) => e.stopPropagation()}
style={{
width: '100%',
maxWidth: 335,
borderRadius: 20,
backgroundColor: '#ffffff',
boxShadow: '0px 14px 36px rgba(17, 17, 17, 0.24)',
padding: '24px 20px 20px',
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
textAlign: 'center',
gap: 14,
boxSizing: 'border-box',
}}
>
{/* Icon Badge */}
<div
style={{
width: 60,
height: 60,
borderRadius: 20,
backgroundColor: 'rgba(215, 142, 6, 0.14)',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
flexShrink: 0,
}}
>
<img
src="/assets/images/icon-account-avatar-gold.svg"
alt=""
style={{
width: 28,
height: 30,
}}
/>
</div>
{/* Title */}
<h2
id="habib-login-modal-title"
style={{
margin: 0,
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 18,
lineHeight: '24px',
color: '#111111',
}}
>
{title}
</h2>
{/* Description */}
<p
style={{
margin: 0,
fontFamily: 'var(--font-sans)',
fontWeight: 400,
fontSize: 13,
lineHeight: '19px',
color: '#64748b',
}}
>
{description}
</p>
{/* Actions */}
<div
style={{
width: '100%',
display: 'flex',
flexDirection: 'column',
gap: 10,
marginTop: 6,
}}
>
<button
type="button"
disabled={isLoggingIn}
onClick={onConfirmLogin}
className="habib-cta-btn"
style={{
width: '100%',
height: 48,
borderRadius: 12,
backgroundColor: '#d78e06',
border: 'none',
color: '#ffffff',
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 15,
lineHeight: '20px',
cursor: isLoggingIn ? 'wait' : 'pointer',
opacity: isLoggingIn ? 0.8 : 1,
display: 'inline-flex',
alignItems: 'center',
justifyContent: 'center',
gap: 8,
}}
>
{isLoggingIn && <InlineSpinner size={16} />}
<span>{isLoggingIn ? 'Opening Habib Login...' : 'Log In'}</span>
</button>
<button
type="button"
disabled={isLoggingIn}
onClick={onClose}
style={{
width: '100%',
height: 42,
borderRadius: 12,
backgroundColor: '#f3f1ef',
border: 'none',
color: '#3d3d3d',
fontFamily: 'var(--font-sans)',
fontWeight: 600,
fontSize: 13,
lineHeight: '18px',
cursor: isLoggingIn ? 'not-allowed' : 'pointer',
}}
>
Cancel
</button>
</div>
</div>
</div>
);
};

195
src/components/modals/OrderSummarySheet.tsx

@ -0,0 +1,195 @@
import React, { useState } from 'react';
import { useHardwareBackHandler } from '../../hooks/use-hardware-back-handler';
import { InlineSpinner } from '../common/ShimmerSkeletons';
import { OrderSummaryRows, type SummaryLineRow } from '../checkout/OrderSummaryRows';
interface OrderSummarySheetProps {
isOpen: boolean;
onClose: () => void;
rows: SummaryLineRow[];
totalText: string;
promoCode?: string;
onApplyPromo?: (code: string) => Promise<boolean>;
ctaText?: string;
onCtaClick?: () => void;
}
export const OrderSummarySheet: React.FC<OrderSummarySheetProps> = ({
isOpen,
onClose,
rows,
totalText,
promoCode = '',
onApplyPromo,
ctaText = 'Got it',
onCtaClick,
}) => {
const [promoInput, setPromoInput] = useState(promoCode);
const [applying, setApplying] = useState(false);
useHardwareBackHandler(() => {
onClose();
return true;
}, isOpen);
if (!isOpen) return null;
const handlePromoSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!onApplyPromo || applying) return;
setApplying(true);
try {
await onApplyPromo(promoInput.trim());
} finally {
setApplying(false);
}
};
return (
<div
onClick={onClose}
style={{
position: 'fixed',
inset: 0,
backgroundColor: 'rgba(17, 17, 17, 0.9)',
zIndex: 60,
display: 'flex',
flexDirection: 'column',
justifyContent: 'flex-end',
}}
>
<div
className="habib-bottom-sheet"
onClick={(e) => e.stopPropagation()}
style={{
padding: '22px var(--page-px) calc(24px + var(--safe-bottom, 0px))',
display: 'flex',
flexDirection: 'column',
gap: '20px',
}}
>
<div
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
gap: '12px',
}}
>
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: '14px',
lineHeight: '19px',
color: '#111111',
}}
>
Order Summary
</span>
<button
type="button"
onClick={onClose}
aria-label="Close"
style={{
width: '24px',
height: '24px',
cursor: 'pointer',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
}}
>
<img
src="/assets/images/icon-modal-close-cross.svg"
alt=""
style={{ width: '11.67px', height: '11.67px', display: 'block' }}
/>
</button>
</div>
<OrderSummaryRows rows={rows} totalText={totalText} />
{onApplyPromo && (
<form
onSubmit={handlePromoSubmit}
style={{
display: 'flex',
alignItems: 'center',
gap: '8px',
width: '100%',
}}
>
<input
type="text"
value={promoInput}
onChange={(e) => setPromoInput(e.target.value)}
placeholder="Promo code (e.g. HABIB10)"
style={{
flex: 1,
height: '40px',
borderRadius: '11px',
backgroundColor: '#ffffff',
border: '1px solid #d7dbe2',
padding: '0 12px',
fontFamily: 'var(--font-sans)',
fontSize: '12px',
color: '#111111',
}}
/>
<button
type="submit"
disabled={applying}
style={{
height: '40px',
padding: '0 14px',
borderRadius: '11px',
backgroundColor: '#292a2e',
color: '#ffffff',
fontFamily: 'var(--font-sans)',
fontWeight: 600,
fontSize: '12px',
cursor: 'pointer',
opacity: applying ? 0.65 : 1,
display: 'inline-flex',
alignItems: 'center',
justifyContent: 'center',
gap: '6px',
}}
>
{applying ? <InlineSpinner size={13} /> : 'Apply'}
</button>
</form>
)}
<button
type="button"
className="habib-cta-btn"
onClick={() => {
if (onCtaClick) {
onCtaClick();
} else {
onClose();
}
}}
style={{
width: '100%',
height: '52px',
borderRadius: '11px',
cursor: 'pointer',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: '16px',
color: '#fbfbfc',
}}
>
{ctaText}
</button>
</div>
</div>
);
};

290
src/components/modals/PaymentMethodsSheet.tsx

@ -0,0 +1,290 @@
import React from 'react';
import { useHardwareBackHandler } from '../../hooks/use-hardware-back-handler';
import { EmptyStateBox, InlineSpinner } from '../common/ShimmerSkeletons';
import { PaymentMethodCard } from '../checkout/PaymentMethodCard';
import type { PaymentMethodItem } from '../../data/checkoutData';
import { buyHabibCoinPackages, isInFlutterWebView } from '../../lib/webview-actions';
interface PaymentMethodsSheetProps {
isOpen: boolean;
onClose: () => void;
methods: PaymentMethodItem[];
selectedMethodId: string;
onSelectMethod: (id: string) => void;
totalPriceText: string;
onConfirmPurchase: () => void;
isSubmitting?: boolean;
habibCoinsBalance?: number;
requiredCoins?: number;
onCoinsUpdated?: (coins: number) => void;
}
export const PaymentMethodsSheet: React.FC<PaymentMethodsSheetProps> = ({
isOpen,
onClose,
methods,
selectedMethodId,
onSelectMethod,
totalPriceText,
onConfirmPurchase,
isSubmitting = false,
habibCoinsBalance = 21,
requiredCoins = 0,
onCoinsUpdated,
}) => {
useHardwareBackHandler(() => {
if (!isSubmitting) {
onClose();
}
return true;
}, isOpen);
if (!isOpen) return null;
const isHabCoinSelected =
selectedMethodId === 'habcoin' || selectedMethodId === 'pm-habcoin';
const needsMoreCoins =
isHabCoinSelected && requiredCoins > 0 && habibCoinsBalance < requiredCoins;
const handleTopUpCoins = async () => {
if (isInFlutterWebView()) {
const updated = await buyHabibCoinPackages();
if (typeof updated === 'number' && onCoinsUpdated) {
onCoinsUpdated(updated);
}
}
};
return (
<div
onClick={() => {
if (!isSubmitting) onClose();
}}
style={{
position: 'fixed',
inset: 0,
backgroundColor: 'rgba(17, 17, 17, 0.9)',
zIndex: 60,
display: 'flex',
flexDirection: 'column',
justifyContent: 'flex-end',
}}
>
<div
className="habib-bottom-sheet"
onClick={(e) => e.stopPropagation()}
style={{
padding: '22px var(--page-px) calc(24px + var(--safe-bottom, 0px))',
display: 'flex',
flexDirection: 'column',
gap: '20px',
}}
>
{/* Header & Close X Button */}
<div
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
gap: '12px',
}}
>
<div
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: '14px',
lineHeight: '19px',
color: '#111111',
}}
>
Payment Methods
</div>
<button
type="button"
disabled={isSubmitting}
onClick={onClose}
aria-label="Close"
style={{
width: '24px',
height: '24px',
background: 'transparent',
border: 'none',
padding: 0,
cursor: 'pointer',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
}}
>
<img
src="/assets/images/icon-modal-close-cross.svg"
alt=""
style={{
width: '11.67px',
height: '11.67px',
display: 'block',
}}
/>
</button>
</div>
{/* Payment Method Cards */}
<div
style={{
display: 'flex',
flexDirection: 'column',
gap: '12px',
}}
>
{methods.length > 0 ? (
methods.map((method) => (
<PaymentMethodCard
key={method.id}
item={method}
isSelected={method.id === selectedMethodId}
onSelect={() => onSelectMethod(method.id)}
/>
))
) : (
<EmptyStateBox message="No payment methods available." compact />
)}
</div>
{needsMoreCoins && (
<div
style={{
padding: '10px 12px',
borderRadius: '12px',
backgroundColor: 'rgba(212, 71, 71, 0.08)',
border: '1px solid rgba(212, 71, 71, 0.3)',
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
gap: '10px',
}}
>
<span
style={{
fontFamily: 'var(--font-sans)',
fontSize: '12px',
fontWeight: 600,
color: '#d44747',
}}
>
Need {requiredCoins} Habib Coins ({habibCoinsBalance} available)
</span>
{isInFlutterWebView() && (
<button
type="button"
onClick={handleTopUpCoins}
style={{
padding: '6px 12px',
borderRadius: '9px',
backgroundColor: '#292a2e',
color: '#ffffff',
fontFamily: 'var(--font-sans)',
fontSize: '11px',
fontWeight: 600,
cursor: 'pointer',
flexShrink: 0,
}}
>
Buy Coins
</button>
)}
</div>
)}
{/* "Purchase" CTA Button */}
<button
type="button"
disabled={isSubmitting || needsMoreCoins || methods.length === 0}
onClick={onConfirmPurchase}
className="habib-cta-btn"
style={{
position: 'relative',
width: '100%',
height: '52px',
padding: '0 14px',
borderRadius: '11px',
border: 'none',
cursor:
isSubmitting || needsMoreCoins || methods.length === 0
? 'not-allowed'
: 'pointer',
opacity:
isSubmitting || needsMoreCoins || methods.length === 0 ? 0.65 : 1,
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
}}
>
<div
style={{
display: 'inline-flex',
alignItems: 'center',
gap: '6px',
}}
>
{isSubmitting ? (
<InlineSpinner size={18} />
) : (
<img
src="/assets/images/icon-credit-card-white.svg"
alt=""
style={{
width: '24px',
height: '24px',
flexShrink: 0,
}}
/>
)}
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: '16px',
lineHeight: '24px',
color: '#fbfbfc',
}}
>
{isSubmitting ? 'Processing...' : 'Purchase'}
</span>
</div>
<div
style={{
position: 'absolute',
right: '14px',
top: '50%',
transform: 'translateY(-50%)',
minWidth: '56px',
height: '24px',
padding: '0 6px',
borderRadius: '5px',
backgroundColor: 'rgba(255, 255, 255, 0.2)',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
}}
>
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: '14px',
lineHeight: '19px',
color: 'rgba(255, 255, 255, 0.85)',
}}
>
{totalPriceText}
</span>
</div>
</button>
</div>
</div>
);
};

197
src/components/modals/ShipmentTrackingSheet.tsx

@ -0,0 +1,197 @@
import React from 'react';
import { useHardwareBackHandler } from '../../hooks/use-hardware-back-handler';
import type { ApiShipment } from '../../lib/shopApi';
import { copyToClipboard } from '../../lib/webview-actions';
interface ShipmentTrackingSheetProps {
shipment: ApiShipment | null;
onClose: () => void;
onCopied?: () => void;
}
export const ShipmentTrackingSheet: React.FC<ShipmentTrackingSheetProps> = ({
shipment,
onClose,
onCopied,
}) => {
const isOpen = Boolean(shipment);
useHardwareBackHandler(() => {
onClose();
return true;
}, isOpen);
if (!shipment) return null;
const handleCopyTracking = async () => {
if (!shipment.tracking_code) return;
const ok = await copyToClipboard(shipment.tracking_code);
if (ok && onCopied) onCopied();
};
return (
<div
onClick={onClose}
style={{
position: 'fixed',
inset: 0,
backgroundColor: 'rgba(17, 17, 17, 0.9)',
zIndex: 60,
display: 'flex',
flexDirection: 'column',
justifyContent: 'flex-end',
}}
>
<div
className="habib-bottom-sheet"
onClick={(e) => e.stopPropagation()}
style={{
padding: '22px var(--page-px) calc(24px + var(--safe-bottom, 0px))',
display: 'flex',
flexDirection: 'column',
gap: '16px',
maxHeight: '85dvh',
overflowY: 'auto',
}}
>
<div
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
}}
>
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: '15px',
color: '#111111',
}}
>
Shipment Tracking • {shipment.booth_name}
</span>
<button
type="button"
onClick={onClose}
aria-label="Close"
style={{
width: '24px',
height: '24px',
cursor: 'pointer',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
}}
>
<img
src="/assets/images/icon-modal-close-cross.svg"
alt=""
style={{ width: '11.67px', height: '11.67px' }}
/>
</button>
</div>
<div
style={{
padding: '12px',
borderRadius: '12px',
backgroundColor: '#f3f3f3',
display: 'flex',
flexDirection: 'column',
gap: '8px',
}}
>
<div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '12px' }}>
<span style={{ color: '#747474', fontWeight: 600 }}>Carrier</span>
<span style={{ color: '#111111', fontWeight: 700 }}>
{shipment.carrier_name || 'Habib Global Post'}
</span>
</div>
{shipment.tracking_code && (
<div
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
fontSize: '12px',
}}
>
<span style={{ color: '#747474', fontWeight: 600 }}>Tracking Code</span>
<button
type="button"
onClick={handleCopyTracking}
style={{
color: '#d78e06',
fontWeight: 700,
fontSize: '12px',
cursor: 'pointer',
}}
>
{shipment.tracking_code} (Copy)
</button>
</div>
)}
<div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '12px' }}>
<span style={{ color: '#747474', fontWeight: 600 }}>Estimated Delivery</span>
<span style={{ color: '#111111', fontWeight: 700 }}>
{shipment.estimated_delivery_label || '2–3 Business Days'}
</span>
</div>
</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: '12px' }}>
{(shipment.events || []).map((ev, idx) => (
<div
key={ev.id || idx}
style={{
display: 'flex',
alignItems: 'flex-start',
gap: '10px',
}}
>
<div
style={{
width: '12px',
height: '12px',
marginTop: '3px',
borderRadius: '50%',
backgroundColor: idx === 0 ? '#0eb13c' : '#d78e06',
flexShrink: 0,
}}
/>
<div style={{ display: 'flex', flexDirection: 'column', gap: '2px' }}>
<span style={{ fontSize: '13px', fontWeight: 700, color: '#111111' }}>
{ev.title}
</span>
<span style={{ fontSize: '11px', color: '#747474' }}>
{ev.location ? `${ev.location} • ` : ''}
{ev.formatted_time}
</span>
</div>
</div>
))}
</div>
<button
type="button"
className="habib-cta-btn"
onClick={onClose}
style={{
width: '100%',
height: '48px',
borderRadius: '11px',
color: '#fbfbfc',
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: '15px',
cursor: 'pointer',
}}
>
Close
</button>
</div>
</div>
);
};

27
src/components/orders/OrderListCard.tsx

@ -1,17 +1,17 @@
import React from 'react';
import { useNavigate } from 'react-router-dom';
import type { OrderCardData } from '../../data/ordersData';
import { ROUTES } from '../../lib/routes';
interface OrderListCardProps {
order: OrderCardData;
onViewDetails?: () => void;
}
/**
* Order summary card on `shop-orders` (4175:10954 & 4175:10644).
* - Dimensions: 342×233 at (17, order.y), radius 20
* - Gradient: linear-gradient(180deg, #ffffff 0%, #f8f8f8 100%), border 1px solid #ffffff
*/
export const OrderListCard: React.FC<OrderListCardProps> = ({ order }) => {
export const OrderListCard: React.FC<OrderListCardProps> = ({
order,
onViewDetails,
}) => {
const navigate = useNavigate();
return (
@ -29,7 +29,6 @@ export const OrderListCard: React.FC<OrderListCardProps> = ({ order }) => {
gap: 15,
}}
>
{/* Top section */}
<div
style={{
display: 'flex',
@ -37,7 +36,6 @@ export const OrderListCard: React.FC<OrderListCardProps> = ({ order }) => {
gap: 10,
}}
>
{/* Row 1: Order code, dot, price, and date */}
<div
style={{
display: 'flex',
@ -90,7 +88,6 @@ export const OrderListCard: React.FC<OrderListCardProps> = ({ order }) => {
</span>
</div>
{/* Date on right */}
<div
style={{
display: 'inline-flex',
@ -122,7 +119,6 @@ export const OrderListCard: React.FC<OrderListCardProps> = ({ order }) => {
</div>
</div>
{/* Thumbnails row */}
<div
className="habib-scroll-container"
style={{
@ -176,7 +172,6 @@ export const OrderListCard: React.FC<OrderListCardProps> = ({ order }) => {
</div>
</div>
{/* Grey status bar */}
<div
style={{
width: '100%',
@ -257,7 +252,6 @@ export const OrderListCard: React.FC<OrderListCardProps> = ({ order }) => {
</div>
</div>
{/* Right delivery count */}
<div
style={{
display: 'inline-flex',
@ -301,10 +295,15 @@ export const OrderListCard: React.FC<OrderListCardProps> = ({ order }) => {
</div>
</div>
{/* View Details button */}
<button
type="button"
onClick={() => navigate('/shop-order-detail')}
onClick={() => {
if (onViewDetails) {
onViewDetails();
} else {
navigate(ROUTES.orderDetail(order.orderCode || 'ORD-28465'));
}
}}
style={{
width: '100%',
height: 52,

720
src/context/ShopAppContext.tsx

@ -0,0 +1,720 @@
import React, {
createContext,
useCallback,
useContext,
useEffect,
useMemo,
useRef,
useState,
} from 'react';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { useLocation } from 'react-router-dom';
import { LoginRequiredModal } from '../components/modals/LoginRequiredModal';
import { ensureToken, getToken } from '../lib/auth-bridge';
import { ensureGuestToken, getUserLanguage, setUserLanguage } from '../lib/cookies';
import { USE_MOCK_DATA } from '../lib/routes';
import {
type ApiAddress,
type ApiCart,
type ApiOrderCounters,
type ApiProductCard,
type ApiShippingMethod,
type ApiUserProfile,
shopApi,
} from '../lib/shopApi';
import { clearUserScopedCache, shopKeys } from '../lib/shopQueries';
import { useHabibWebReady } from '../hooks/use-habib-web-ready';
export interface SaveAddressInput {
id?: number;
label?: string;
recipient_name: string;
phone?: string;
country?: string;
city?: string;
street_line: string;
postal_code?: string;
lat?: number | null;
lon?: number | null;
is_default?: boolean;
}
export interface LoginModalOptions {
title?: string;
description?: string;
featureName?: string;
onAuthenticated?: () => void;
}
interface ShopAppContextValue {
hydrated: boolean;
isUserAuthenticated: boolean;
openLoginModal: (options?: LoginModalOptions) => void;
closeLoginModal: () => void;
requireAuth: (options?: LoginModalOptions) => Promise<boolean>;
cart: ApiCart | null;
cartItemsCount: number;
cartTotalQuantity: number;
isCartBusy: boolean;
addresses: ApiAddress[];
selectedAddressId: number | null;
selectedAddress: ApiAddress | null;
shippingMethods: ApiShippingMethod[];
selectedShippingMethod: ApiShippingMethod | null;
selectedPaymentMethod: string;
setSelectedPaymentMethod: (code: string) => void;
bookmarkedProducts: ApiProductCard[];
isBookmarked: (productId?: number | null, slug?: string | null) => boolean;
toggleBookmark: (
productRef: string | number,
numericId?: number,
slug?: string
) => Promise<boolean>;
profile: ApiUserProfile | null;
orderCounters: ApiOrderCounters | null;
habibCoinsBalance: number;
setHabibCoinsBalance: (coins: number) => void;
language: string;
changeLanguage: (lang: string) => void;
addToCart: (
productRef: string | number,
quantity?: number,
variantId?: number | null
) => Promise<ApiCart | null>;
updateCartItemQuantity: (itemId: number, quantity: number) => Promise<void>;
removeCartItem: (itemId: number) => Promise<void>;
clearCart: () => Promise<void>;
applyPromoCode: (code: string) => Promise<boolean>;
selectAddress: (id: number) => void;
saveAddress: (input: SaveAddressInput) => Promise<ApiAddress | null>;
deleteAddress: (id: number) => Promise<void>;
selectShippingMethod: (codeOrId: string | number) => void;
refreshCart: () => Promise<void>;
refreshAccountData: () => Promise<void>;
toastMessage: string | null;
showToast: (message: string) => void;
}
const ShopAppContext = createContext<ShopAppContextValue | null>(null);
export const ShopAppProvider: React.FC<{ children: React.ReactNode }> = ({
children,
}) => {
const queryClient = useQueryClient();
const location = useLocation();
const isBare =
location.search.includes('bare=1') || location.search.includes('embed=1');
const [isCartBusy, setIsCartBusy] = useState(false);
const [selectedAddressId, setSelectedAddressId] = useState<number | null>(null);
const [selectedShippingCode, setSelectedShippingCode] = useState<string>('standard');
const [selectedPaymentMethod, setSelectedPaymentMethod] = useState<string>('google_pay');
const [habibCoinsBalance, setHabibCoinsBalance] = useState<number>(() =>
typeof window !== 'undefined' && typeof window.HABIB_COINS === 'number'
? window.HABIB_COINS
: USE_MOCK_DATA
? 21
: 0
);
const [language, setLanguage] = useState<string>(() => getUserLanguage());
const [authToken, setAuthToken] = useState<string>(() => getToken());
const [loginModalState, setLoginModalState] = useState<{
isOpen: boolean;
title: string;
description: string;
onAuthenticated?: () => void;
}>({
isOpen: false,
title: 'Sign in Required',
description: 'Please log in with your Habib account to continue.',
});
const [isLoggingIn, setIsLoggingIn] = useState(false);
const loginResolverRef = useRef<((authenticated: boolean) => void) | null>(null);
const [toastMessage, setToastMessage] = useState<string | null>(null);
const toastTimerRef = useRef<number | undefined>(undefined);
useHabibWebReady(true);
useEffect(() => {
ensureGuestToken();
}, []);
const cartQuery = useQuery({
queryKey: shopKeys.cart(),
queryFn: () => shopApi.fetchCart(false),
enabled: !isBare,
});
const profileQuery = useQuery({
queryKey: shopKeys.profile(),
queryFn: () => shopApi.fetchProfile(),
enabled: !isBare,
});
const addressesQuery = useQuery({
queryKey: shopKeys.addresses(),
queryFn: () => shopApi.fetchAddresses(),
enabled: !isBare,
});
const shippingMethodsQuery = useQuery({
queryKey: shopKeys.shippingMethods(),
queryFn: () => shopApi.fetchShippingMethods(),
enabled: !isBare,
staleTime: 5 * 60_000,
});
const bookmarksQuery = useQuery({
queryKey: shopKeys.bookmarks(),
queryFn: () => shopApi.fetchBookmarks(),
enabled: !isBare,
});
const orderCountersQuery = useQuery({
queryKey: shopKeys.orderCounters(),
queryFn: () => shopApi.fetchOrderCounters(),
enabled: !isBare,
});
const hydrated =
isBare || (!cartQuery.isPending && !bookmarksQuery.isPending);
const cart = cartQuery.data ?? null;
const profile = profileQuery.data ?? null;
const orderCounters = orderCountersQuery.data ?? null;
const isUserAuthenticated = useMemo(() => {
if (isBare) return true;
if (profile !== null) {
return Boolean(profile.is_authenticated);
}
return Boolean(authToken || getToken());
}, [authToken, isBare, profile]);
const addresses = useMemo(
() => addressesQuery.data?.results ?? [],
[addressesQuery.data]
);
const shippingMethods = useMemo(
() => shippingMethodsQuery.data?.results ?? [],
[shippingMethodsQuery.data]
);
const bookmarkedProducts = useMemo(
() =>
(bookmarksQuery.data?.results ?? [])
.map((entry) => entry.product_detail)
.filter((p): p is ApiProductCard => Boolean(p)),
[bookmarksQuery.data]
);
const bookmarkedIdSet = useMemo(
() => new Set(bookmarkedProducts.map((p) => p.id)),
[bookmarkedProducts]
);
const bookmarkedSlugSet = useMemo(
() => new Set(bookmarkedProducts.map((p) => p.slug)),
[bookmarkedProducts]
);
useEffect(() => {
if (typeof profile?.habib_coins_balance === 'number') {
setHabibCoinsBalance(profile.habib_coins_balance);
}
}, [profile?.habib_coins_balance]);
const showToast = useCallback((message: string) => {
setToastMessage(message);
if (typeof window !== 'undefined') {
if (toastTimerRef.current !== undefined) {
window.clearTimeout(toastTimerRef.current);
}
toastTimerRef.current = window.setTimeout(() => {
setToastMessage(null);
}, 2400);
}
}, []);
const refreshCart = useCallback(async () => {
await queryClient.invalidateQueries({ queryKey: shopKeys.cart() });
}, [queryClient]);
const refreshAccountData = useCallback(async () => {
await Promise.allSettled([
queryClient.invalidateQueries({ queryKey: shopKeys.profile() }),
queryClient.invalidateQueries({ queryKey: shopKeys.addresses() }),
queryClient.invalidateQueries({ queryKey: shopKeys.shippingMethods() }),
queryClient.invalidateQueries({ queryKey: shopKeys.bookmarks() }),
queryClient.invalidateQueries({ queryKey: shopKeys.orderCounters() }),
queryClient.invalidateQueries({ queryKey: shopKeys.ordersAll() }),
]);
}, [queryClient]);
useEffect(() => {
if (typeof window === 'undefined') return;
const handleTokenChange = async (
event: WindowEventMap['habib:auth-token-changed']
) => {
const nextToken = event.detail?.token ?? getToken();
setAuthToken(nextToken || '');
clearUserScopedCache(queryClient);
if (nextToken) {
try {
const merged = await shopApi.mergeGuestCart(ensureGuestToken());
queryClient.setQueryData<ApiCart>(shopKeys.cart(), merged);
} catch {
// fallback to query invalidation below
}
}
await queryClient.invalidateQueries({ queryKey: shopKeys.all });
};
const handleCoinsChange = (event: WindowEventMap['habib:coins-changed']) => {
if (typeof event.detail?.coins === 'number') {
setHabibCoinsBalance(event.detail.coins);
}
};
window.addEventListener('habib:auth-token-changed', handleTokenChange);
window.addEventListener('habib:coins-changed', handleCoinsChange);
return () => {
window.removeEventListener('habib:auth-token-changed', handleTokenChange);
window.removeEventListener('habib:coins-changed', handleCoinsChange);
};
}, [queryClient]);
const closeLoginModal = useCallback(() => {
setIsLoggingIn(false);
setLoginModalState((prev) => ({
...prev,
isOpen: false,
onAuthenticated: undefined,
}));
if (loginResolverRef.current) {
const resolve = loginResolverRef.current;
loginResolverRef.current = null;
resolve(false);
}
}, []);
const openLoginModal = useCallback((options?: LoginModalOptions) => {
const title = options?.title || 'Sign in Required';
const description =
options?.description ||
(options?.featureName
? `Please log in with your Habib account to access ${options.featureName}.`
: 'Please log in with your Habib account to continue.');
setLoginModalState({
isOpen: true,
title,
description,
onAuthenticated: options?.onAuthenticated,
});
}, []);
const requireAuth = useCallback(
(options?: LoginModalOptions): Promise<boolean> => {
if (isBare || isUserAuthenticated) {
options?.onAuthenticated?.();
return Promise.resolve(true);
}
openLoginModal(options);
return new Promise<boolean>((resolve) => {
if (loginResolverRef.current) {
loginResolverRef.current(false);
}
loginResolverRef.current = resolve;
});
},
[isBare, isUserAuthenticated, openLoginModal]
);
const handleConfirmModalLogin = useCallback(async () => {
if (isLoggingIn) return;
setIsLoggingIn(true);
try {
const token = await ensureToken(60000, { forceLogin: true });
if (token) {
setAuthToken(token);
await Promise.allSettled([refreshAccountData(), refreshCart()]);
const pendingCallback = loginModalState.onAuthenticated;
setIsLoggingIn(false);
setLoginModalState((prev) => ({
...prev,
isOpen: false,
onAuthenticated: undefined,
}));
if (loginResolverRef.current) {
const resolve = loginResolverRef.current;
loginResolverRef.current = null;
resolve(true);
}
showToast('Signed in with Habib');
pendingCallback?.();
} else {
setIsLoggingIn(false);
showToast('Sign-in canceled');
}
} catch {
setIsLoggingIn(false);
showToast('Could not complete sign-in');
}
}, [
isLoggingIn,
loginModalState.onAuthenticated,
refreshAccountData,
refreshCart,
showToast,
]);
const addToCart = useCallback(
async (
productRef: string | number,
quantity = 1,
variantId?: number | null
): Promise<ApiCart | null> => {
setIsCartBusy(true);
try {
const updated = await shopApi.addCartItem({
product_id: productRef,
quantity,
variant_id: variantId,
});
queryClient.setQueryData<ApiCart>(shopKeys.cart(), updated);
void queryClient.invalidateQueries({ queryKey: shopKeys.home() });
showToast('Added to cart');
return updated;
} catch (err) {
showToast(err instanceof Error ? err.message : 'Could not add item');
return null;
} finally {
setIsCartBusy(false);
}
},
[queryClient, showToast]
);
const updateCartItemQuantity = useCallback(
async (itemId: number, quantity: number) => {
setIsCartBusy(true);
try {
const updated = await shopApi.updateCartItem(itemId, quantity);
queryClient.setQueryData<ApiCart>(shopKeys.cart(), updated);
void queryClient.invalidateQueries({ queryKey: shopKeys.home() });
} catch (err) {
showToast(err instanceof Error ? err.message : 'Could not update cart');
} finally {
setIsCartBusy(false);
}
},
[queryClient, showToast]
);
const removeCartItem = useCallback(
async (itemId: number) => {
setIsCartBusy(true);
try {
const updated = await shopApi.removeCartItem(itemId);
queryClient.setQueryData<ApiCart>(shopKeys.cart(), updated);
void queryClient.invalidateQueries({ queryKey: shopKeys.home() });
} catch (err) {
showToast(err instanceof Error ? err.message : 'Could not remove item');
} finally {
setIsCartBusy(false);
}
},
[queryClient, showToast]
);
const clearCart = useCallback(async () => {
setIsCartBusy(true);
try {
const updated = await shopApi.clearCart();
queryClient.setQueryData<ApiCart>(shopKeys.cart(), updated);
void queryClient.invalidateQueries({ queryKey: shopKeys.home() });
} catch (err) {
showToast(err instanceof Error ? err.message : 'Could not clear cart');
} finally {
setIsCartBusy(false);
}
}, [queryClient, showToast]);
const applyPromoCode = useCallback(
async (code: string): Promise<boolean> => {
setIsCartBusy(true);
try {
const updated = await shopApi.applyPromoCode(code);
queryClient.setQueryData<ApiCart>(shopKeys.cart(), updated);
showToast(code ? `Promo "${code.toUpperCase()}" applied` : 'Promo removed');
return true;
} catch (err) {
showToast(err instanceof Error ? err.message : 'Invalid promo code');
return false;
} finally {
setIsCartBusy(false);
}
},
[queryClient, showToast]
);
const isBookmarked = useCallback(
(productId?: number | null, slug?: string | null): boolean => {
if (productId && bookmarkedIdSet.has(productId)) return true;
if (slug && bookmarkedSlugSet.has(slug)) return true;
return false;
},
[bookmarkedIdSet, bookmarkedSlugSet]
);
const toggleBookmark = useCallback(
async (
productRef: string | number,
numericId?: number,
slug?: string
): Promise<boolean> => {
const currentlySaved = isBookmarked(numericId, slug || String(productRef));
if (!isBare && !isUserAuthenticated) {
const authed = await requireAuth({
featureName: 'saved items',
});
if (!authed) return currentlySaved;
}
try {
if (currentlySaved) {
await shopApi.removeBookmark(productRef);
await queryClient.invalidateQueries({ queryKey: shopKeys.bookmarks() });
void queryClient.invalidateQueries({ queryKey: shopKeys.home() });
void queryClient.invalidateQueries({ queryKey: shopKeys.productsAll() });
void queryClient.invalidateQueries({
queryKey: shopKeys.productDetailsAll(),
});
showToast('Removed from saved items');
return false;
}
await shopApi.addBookmark(productRef);
await queryClient.invalidateQueries({ queryKey: shopKeys.bookmarks() });
void queryClient.invalidateQueries({ queryKey: shopKeys.home() });
void queryClient.invalidateQueries({ queryKey: shopKeys.productsAll() });
void queryClient.invalidateQueries({
queryKey: shopKeys.productDetailsAll(),
});
showToast('Saved to bookmarks');
return true;
} catch (err) {
showToast(err instanceof Error ? err.message : 'Could not update bookmark');
return currentlySaved;
}
},
[isBare, isBookmarked, isUserAuthenticated, queryClient, requireAuth, showToast]
);
const selectAddress = useCallback((id: number) => {
setSelectedAddressId(id);
}, []);
const saveAddress = useCallback(
async (input: SaveAddressInput): Promise<ApiAddress | null> => {
if (!isBare && !isUserAuthenticated) {
const authed = await requireAuth({
featureName: 'delivery addresses',
});
if (!authed) return null;
}
try {
let saved: ApiAddress;
if (input.id) {
saved = await shopApi.updateAddress(input.id, input);
} else {
saved = await shopApi.createAddress(input);
}
await queryClient.invalidateQueries({ queryKey: shopKeys.addresses() });
setSelectedAddressId(saved.id);
showToast(input.id ? 'Address updated' : 'Address added');
return saved;
} catch (err) {
showToast(err instanceof Error ? err.message : 'Could not save address');
return null;
}
},
[isBare, isUserAuthenticated, queryClient, requireAuth, showToast]
);
const deleteAddress = useCallback(
async (id: number) => {
if (!isBare && !isUserAuthenticated) {
const authed = await requireAuth({
featureName: 'delivery addresses',
});
if (!authed) return;
}
try {
await shopApi.deleteAddress(id);
await queryClient.invalidateQueries({ queryKey: shopKeys.addresses() });
setSelectedAddressId((prev) => (prev === id ? null : prev));
showToast('Address deleted');
} catch (err) {
showToast(err instanceof Error ? err.message : 'Could not delete address');
}
},
[isBare, isUserAuthenticated, queryClient, requireAuth, showToast]
);
const selectShippingMethod = useCallback(
(codeOrId: string | number) => {
const found = shippingMethods.find(
(m) => m.code === String(codeOrId) || m.id === Number(codeOrId)
);
if (found) {
setSelectedShippingCode(found.code);
} else {
setSelectedShippingCode(String(codeOrId));
}
},
[shippingMethods]
);
const changeLanguage = useCallback(
(lang: string) => {
setUserLanguage(lang);
setLanguage(lang);
const label =
lang === 'fa' ? 'فارسی' : lang === 'ar' ? 'العربية' : 'English';
showToast(`Language set to ${label}`);
void queryClient.invalidateQueries({ queryKey: shopKeys.all });
},
[queryClient, showToast]
);
const selectedAddress = useMemo(
() =>
addresses.find((a) => a.id === selectedAddressId) ||
addresses.find((a) => a.is_default) ||
addresses[0] ||
null,
[addresses, selectedAddressId]
);
const resolvedSelectedAddressId = selectedAddress?.id ?? null;
const selectedShippingMethod = useMemo(
() =>
shippingMethods.find((m) => m.code === selectedShippingCode) ||
shippingMethods.find((m) => m.is_default) ||
shippingMethods[0] ||
null,
[selectedShippingCode, shippingMethods]
);
const cartItemsCount = cart?.items?.length ?? 0;
const cartTotalQuantity =
cart?.pricing?.total_quantity ??
cart?.items?.reduce((acc, item) => acc + item.quantity, 0) ??
0;
const value = useMemo<ShopAppContextValue>(
() => ({
hydrated,
isUserAuthenticated,
openLoginModal,
closeLoginModal,
requireAuth,
cart,
cartItemsCount,
cartTotalQuantity,
isCartBusy,
addresses,
selectedAddressId: resolvedSelectedAddressId,
selectedAddress,
shippingMethods,
selectedShippingMethod,
selectedPaymentMethod,
setSelectedPaymentMethod,
bookmarkedProducts,
isBookmarked,
toggleBookmark,
profile,
orderCounters,
habibCoinsBalance,
setHabibCoinsBalance,
language,
changeLanguage,
addToCart,
updateCartItemQuantity,
removeCartItem,
clearCart,
applyPromoCode,
selectAddress,
saveAddress,
deleteAddress,
selectShippingMethod,
refreshCart,
refreshAccountData,
toastMessage,
showToast,
}),
[
hydrated,
isUserAuthenticated,
openLoginModal,
closeLoginModal,
requireAuth,
cart,
cartItemsCount,
cartTotalQuantity,
isCartBusy,
addresses,
resolvedSelectedAddressId,
selectedAddress,
shippingMethods,
selectedShippingMethod,
selectedPaymentMethod,
bookmarkedProducts,
isBookmarked,
toggleBookmark,
profile,
orderCounters,
habibCoinsBalance,
language,
changeLanguage,
addToCart,
updateCartItemQuantity,
removeCartItem,
clearCart,
applyPromoCode,
selectAddress,
saveAddress,
deleteAddress,
selectShippingMethod,
refreshCart,
refreshAccountData,
toastMessage,
showToast,
]
);
return (
<ShopAppContext.Provider value={value}>
{children}
<LoginRequiredModal
isOpen={loginModalState.isOpen}
title={loginModalState.title}
description={loginModalState.description}
isLoggingIn={isLoggingIn}
onConfirmLogin={() => {
void handleConfirmModalLogin();
}}
onClose={closeLoginModal}
/>
</ShopAppContext.Provider>
);
};
export function useShopApp(): ShopAppContextValue {
const ctx = useContext(ShopAppContext);
if (!ctx) {
throw new Error('useShopApp must be used inside ShopAppProvider');
}
return ctx;
}

23
src/hooks/use-habib-web-ready.ts

@ -0,0 +1,23 @@
import { useEffect, useRef } from 'react';
export function useHabibWebReady(ready = true): void {
const announcedRef = useRef(false);
useEffect(() => {
if (!ready || announcedRef.current || typeof window === 'undefined') return;
announcedRef.current = true;
let raf2 = 0;
const raf1 = window.requestAnimationFrame(() => {
raf2 = window.requestAnimationFrame(() => {
window.__announceHabibWebReady?.();
});
});
return () => {
window.cancelAnimationFrame(raf1);
if (raf2) window.cancelAnimationFrame(raf2);
};
}, [ready]);
}

76
src/hooks/use-hardware-back-handler.ts

@ -0,0 +1,76 @@
import { useEffect, useRef } from 'react';
type HardwareBackCallback = () => boolean;
interface StackEntry {
id: number;
handler: () => boolean;
}
let nextHandlerId = 1;
const backHandlerStack: StackEntry[] = [];
let globalHandlersInstalled = false;
function runHardwareBackSync(): boolean {
if (typeof document !== 'undefined') {
const active = document.activeElement as HTMLElement | null;
if (
active &&
(active.tagName === 'INPUT' ||
active.tagName === 'TEXTAREA' ||
active.isContentEditable)
) {
active.blur();
return true;
}
}
for (let i = backHandlerStack.length - 1; i >= 0; i -= 1) {
try {
const handled = backHandlerStack[i].handler();
if (handled) {
return true;
}
} catch {
// ignore individual handler errors
}
}
return false;
}
export function ensureGlobalHardwareBackInstalled(): void {
if (typeof window === 'undefined' || globalHandlersInstalled) return;
globalHandlersInstalled = true;
window.__habibHandleHardwareBackSync = () => runHardwareBackSync();
window.__habibHandleHardwareBack = () => Promise.resolve(runHardwareBackSync());
}
export function useHardwareBackHandler(
callback: HardwareBackCallback,
enabled = true
): void {
const callbackRef = useRef<HardwareBackCallback>(callback);
callbackRef.current = callback;
useEffect(() => {
ensureGlobalHardwareBackInstalled();
if (!enabled) return;
const id = nextHandlerId;
nextHandlerId += 1;
const entry: StackEntry = {
id,
handler: () => callbackRef.current(),
};
backHandlerStack.push(entry);
return () => {
const idx = backHandlerStack.findIndex((item) => item.id === id);
if (idx !== -1) {
backHandlerStack.splice(idx, 1);
}
};
}, [enabled]);
}

50
src/hooks/useSmartBack.ts

@ -0,0 +1,50 @@
import { useCallback } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
import { ROUTES } from '../lib/routes';
import { closeService, isInFlutterWebView } from '../lib/webview-actions';
let inAppNavigationCount = 0;
export function recordInAppNavigation(): void {
inAppNavigationCount += 1;
}
export function getInAppNavigationCount(): number {
return inAppNavigationCount;
}
export function useSmartBack(defaultFallback: string = ROUTES.home) {
const navigate = useNavigate();
const location = useLocation();
return useCallback(
(overrideFallback?: string) => {
const targetFallback = overrideFallback || defaultFallback;
const isRoot =
location.pathname === '/' || location.pathname === '/shop-home';
if (isRoot) {
if (isInFlutterWebView()) {
closeService();
return;
}
navigate(ROUTES.test);
return;
}
const historyIdx =
typeof window !== 'undefined' &&
typeof window.history?.state?.idx === 'number'
? window.history.state.idx
: inAppNavigationCount;
if (historyIdx > 0) {
navigate(-1);
} else {
navigate(targetFallback, { replace: true });
}
},
[defaultFallback, location.pathname, navigate]
);
}

114
src/index.css

@ -2,6 +2,11 @@
:root {
--page-px: 16px;
--safe-top: 0px;
--safe-bottom: 0px;
--safe-left: 0px;
--safe-right: 0px;
--kb-height: 0px;
}
@media (max-width: 359.98px) {
@ -34,6 +39,7 @@
box-sizing: border-box;
margin: 0;
padding: 0;
-webkit-tap-highlight-color: transparent;
}
html,
@ -45,6 +51,9 @@ body {
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
color: var(--text-dark-stacked);
-webkit-touch-callout: none;
-webkit-user-select: none;
user-select: none;
}
#root {
@ -63,7 +72,10 @@ textarea {
}
input,
textarea {
textarea,
[contenteditable='true'] {
-webkit-touch-callout: default;
-webkit-user-select: text;
user-select: text;
}
@ -78,6 +90,12 @@ a {
text-decoration: none;
}
img,
svg,
a {
-webkit-user-drag: none;
}
/* Outer Shell: full-bleed responsive on mobile & tablet (<1024px), centered dark frame on desktop (>=1024px) */
.habib-shell-outer {
width: 100%;
@ -117,10 +135,14 @@ a {
.habib-mobile-viewport:not(.is-embed) {
--page-px: 16px;
width: var(--desktop-frame-w, 375px);
min-height: var(--desktop-frame-h, 814px);
border-radius: var(--desktop-frame-r, 0px);
box-shadow: 0 20px 50px rgba(0, 0, 0, 0.45);
}
.habib-mobile-viewport:not(.is-embed) .habib-bottom-sheet {
max-width: var(--desktop-frame-w, 375px);
margin: 0 auto;
}
}
/* Bare/Embed iframe mode for /test Pixel Verification */
@ -184,9 +206,23 @@ a {
width: 100%;
}
.habib-grid-card,
.habib-category-card {
transition: box-shadow 0.18s ease;
}
.habib-category-card.is-right-col {
box-shadow: 0px 4px 17px rgba(148, 163, 184, 0.05);
}
.habib-grid-card:hover,
.habib-category-card:hover {
box-shadow: 0 4px 14px rgba(0, 0, 0, 0.09);
}
.habib-carousel-scroller {
margin: 0 calc(-1 * var(--page-px, 16px));
padding: 0 var(--page-px, 16px);
margin: -10px calc(-1 * var(--page-px, 16px)) -18px;
padding: 10px var(--page-px, 16px) 18px;
overflow-x: auto;
overflow-y: hidden;
}
@ -200,6 +236,11 @@ a {
.habib-compact-card {
width: 152px;
flex: 0 0 152px;
transition: box-shadow 0.18s ease;
}
.habib-compact-card:hover {
box-shadow: 0 4px 14px rgba(0, 0, 0, 0.09);
}
.habib-compact-card-img {
@ -481,6 +522,71 @@ a {
.habib-nav-wave.is-flatten {
display: none;
}
.habib-shimmer,
.habib-shimmer-dark,
.habib-inline-spinner {
animation: none !important;
}
}
/* ========================================================= */
/* Production Shimmer Skeletons & Tactile Loading Spinners */
/* ========================================================= */
@keyframes habib-shimmer-sweep {
0% {
background-position: 180% 0;
}
100% {
background-position: -40% 0;
}
}
@keyframes habib-spin {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
.habib-shimmer {
background: linear-gradient(
90deg,
#e5e1dc 0%,
#f6f4f1 48%,
#e5e1dc 96%
);
background-size: 220% 100%;
animation: habib-shimmer-sweep 1.3s ease-in-out infinite;
}
.habib-shimmer-dark {
background: linear-gradient(
90deg,
rgba(255, 255, 255, 0.09) 0%,
rgba(255, 255, 255, 0.22) 48%,
rgba(255, 255, 255, 0.09) 96%
);
background-size: 220% 100%;
animation: habib-shimmer-sweep 1.3s ease-in-out infinite;
}
.habib-inline-spinner {
display: inline-block;
width: 16px;
height: 16px;
border-radius: 50%;
border: 2px solid rgba(255, 255, 255, 0.35);
border-top-color: #ffffff;
animation: habib-spin 0.7s linear infinite;
flex-shrink: 0;
}
.habib-inline-spinner.is-gold {
border-color: rgba(215, 142, 6, 0.25);
border-top-color: #d78e06;
}
/* Small Phone Refinements (<360px, e.g., 320px iPhone SE) */

229
src/lib/auth-bridge.ts

@ -0,0 +1,229 @@
import { deleteCookie, getCookie, setCookie } from './cookies';
const TOKEN_COOKIE_NAME = 'HABIB_TOKEN';
const REDIRECT_SESSION_KEY = 'redirect';
function cleanToken(raw: string | undefined | null): string {
if (!raw || typeof raw !== 'string') return '';
const trimmed = raw.trim().replace(/^["']|["']$/g, '');
if (!trimmed || trimmed === 'NO_TOKEN' || trimmed === 'null' || trimmed === 'undefined') {
return '';
}
return trimmed;
}
function readTokenFromBootstrap(): string {
if (typeof window === 'undefined') return '';
const win = window as Window & {
__HABIB_BOOTSTRAP__?: Record<string, unknown>;
};
const boot = win.__HABIB_BOOTSTRAP__;
if (!boot || typeof boot !== 'object') return '';
const data = (boot.data as Record<string, unknown> | undefined) || {};
const payload = (boot.payload as Record<string, unknown> | undefined) || {};
const candidate =
boot.token ||
boot.auth_token ||
boot.authToken ||
data.token ||
data.auth_token ||
data.authToken ||
payload.token ||
payload.auth_token ||
payload.authToken;
return typeof candidate === 'string' ? cleanToken(candidate) : '';
}
function readTokenFromUrl(): string {
if (typeof window === 'undefined' || !window.location?.search) return '';
try {
const sp = new URLSearchParams(window.location.search);
return cleanToken(
sp.get('token') ||
sp.get('auth_token') ||
sp.get('habib_token') ||
sp.get(TOKEN_COOKIE_NAME)
);
} catch {
return '';
}
}
function readTokenFromSessionStorage(): string {
if (typeof window === 'undefined') return '';
try {
return cleanToken(window.sessionStorage.getItem(TOKEN_COOKIE_NAME));
} catch {
return '';
}
}
/**
* Reads the authentication token provided by the Habib host app by default:
* 1. `window.HABIB_TOKEN`
* 2. URL query parameters (`token`, `auth_token`, `habib_token`, `HABIB_TOKEN`)
* 3. `window.__HABIB_BOOTSTRAP__` (`initial_config`)
* 4. `HABIB_TOKEN` / `habib_token` cookies set by Flutter `WebAppScreen._setCoockies()`
* 5. `sessionStorage.getItem('HABIB_TOKEN')`
*/
export function getToken(): string {
if (typeof window === 'undefined') return '';
const winToken = cleanToken(window.HABIB_TOKEN);
if (winToken) return winToken;
const urlToken = readTokenFromUrl();
if (urlToken) {
window.HABIB_TOKEN = urlToken;
return urlToken;
}
const bootstrapToken = readTokenFromBootstrap();
if (bootstrapToken) {
window.HABIB_TOKEN = bootstrapToken;
return bootstrapToken;
}
const cookieToken =
cleanToken(getCookie(TOKEN_COOKIE_NAME)) || cleanToken(getCookie('habib_token'));
if (cookieToken) {
return cookieToken;
}
return readTokenFromSessionStorage();
}
export function isAuthenticated(): boolean {
return Boolean(getToken());
}
function postFlutterLoginMessage(): boolean {
if (typeof window === 'undefined') return false;
const channel = window.HabibApp ?? window.FlutterChannel;
if (!channel || typeof channel.postMessage !== 'function') {
return false;
}
try {
channel.postMessage(JSON.stringify({ action: 'login' }));
return true;
} catch {
return false;
}
}
let inflightLoginPromise: Promise<string> | null = null;
/**
* Ensures a valid Habib token exists, or triggers the native Flutter login screen
* via `window.HabibApp.postMessage(JSON.stringify({ action: 'login' }))` (matching Marriage's `authBridge.ensureToken()`).
*/
export function ensureToken(
timeoutMs = 60000,
options?: { forceLogin?: boolean }
): Promise<string> {
if (!options?.forceLogin) {
const existing = getToken();
if (existing) {
return Promise.resolve(existing);
}
}
if (typeof window === 'undefined') {
return Promise.resolve('');
}
if (inflightLoginPromise) {
return inflightLoginPromise;
}
try {
window.sessionStorage.setItem(REDIRECT_SESSION_KEY, 'true');
} catch {
// ignore sessionStorage error
}
inflightLoginPromise = new Promise<string>((resolve) => {
let settled = false;
let timerId: number | undefined;
let removeFlutterListener: (() => void) | undefined;
const finish = (token: string) => {
if (settled) return;
settled = true;
if (timerId !== undefined) window.clearTimeout(timerId);
window.removeEventListener('habib:auth-token-changed', onTokenEvent);
if (removeFlutterListener) removeFlutterListener();
inflightLoginPromise = null;
resolve(token);
};
const syncAfterBridgeLogin = (explicitToken?: string): string => {
const candidate =
cleanToken(explicitToken) ||
cleanToken(getCookie(TOKEN_COOKIE_NAME)) ||
cleanToken(getCookie('habib_token')) ||
getToken();
if (candidate) {
setCookie(TOKEN_COOKIE_NAME, candidate);
window.HABIB_TOKEN = candidate;
}
return candidate;
};
const onTokenEvent = (event: WindowEventMap['habib:auth-token-changed']) => {
const next = cleanToken(event.detail?.token) || getToken();
if (next) {
finish(next);
}
};
window.addEventListener('habib:auth-token-changed', onTokenEvent);
if (typeof window.addFlutterResponseListener === 'function') {
removeFlutterListener = window.addFlutterResponseListener((payload) => {
const action = String(
payload?.action || (payload as Record<string, unknown>)?.type || ''
).toLowerCase();
if (action === 'login') {
if (payload?.success === false) {
finish('');
return;
}
const dataToken =
typeof payload?.data?.token === 'string'
? cleanToken(payload.data.token)
: '';
const resolved = syncAfterBridgeLogin(dataToken);
finish(resolved);
}
});
}
const sent = postFlutterLoginMessage();
if (!sent) {
finish(getToken());
return;
}
timerId = window.setTimeout(() => {
finish(syncAfterBridgeLogin());
}, timeoutMs);
});
return inflightLoginPromise;
}
export function signOutLocal(): void {
deleteCookie(TOKEN_COOKIE_NAME);
deleteCookie('habib_token');
if (typeof window !== 'undefined') {
try {
window.sessionStorage.removeItem(TOKEN_COOKIE_NAME);
} catch {
// ignore
}
window.HABIB_TOKEN = '';
window.dispatchEvent(
new CustomEvent('habib:auth-token-changed', { detail: { token: '' } })
);
}
}

95
src/lib/cookies.ts

@ -0,0 +1,95 @@
const GUEST_COOKIE_NAME = 'HABIB_GUEST_TOKEN';
const SHOP_GUEST_STORAGE_KEY = 'habib_shop_guest_token';
const FLUTTER_LANG_COOKIE_NAME = 'HABIB_LANGUAGE';
const USER_LANG_COOKIE_NAME = 'HABIB_USER_LANGUAGE';
const SHOP_LANG_STORAGE_KEY = 'habib_shop_language';
export function getCookie(name: string): string {
if (typeof document === 'undefined') return '';
const escaped = name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const match = document.cookie.match(new RegExp(`(?:^|;\\s*)${escaped}=([^;]*)`));
return match ? decodeURIComponent(match[1]) : '';
}
export function setCookie(name: string, value: string, maxAgeDays = 365): void {
if (typeof document === 'undefined') return;
const maxAge = Math.floor(maxAgeDays * 86400);
document.cookie = `${name}=${encodeURIComponent(value)}; path=/; max-age=${maxAge}; SameSite=Lax`;
}
export function deleteCookie(name: string): void {
if (typeof document === 'undefined') return;
document.cookie = `${name}=; path=/; max-age=0; SameSite=Lax`;
}
function generateRandomGuestToken(): string {
if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {
return `guest-${crypto.randomUUID()}`;
}
return `guest-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
}
export function ensureGuestToken(): string {
if (typeof window === 'undefined') return 'guest-ssr';
const flutterGuest = getCookie(GUEST_COOKIE_NAME).trim();
if (flutterGuest && flutterGuest !== 'null' && flutterGuest !== 'undefined') {
try {
window.localStorage.setItem(SHOP_GUEST_STORAGE_KEY, flutterGuest);
} catch {
// ignore storage quota errors
}
return flutterGuest;
}
let stored = '';
try {
stored = (window.localStorage.getItem(SHOP_GUEST_STORAGE_KEY) || '').trim();
} catch {
stored = '';
}
if (!stored) {
stored = getCookie(SHOP_GUEST_STORAGE_KEY).trim();
}
if (!stored) {
stored = generateRandomGuestToken();
}
try {
window.localStorage.setItem(SHOP_GUEST_STORAGE_KEY, stored);
} catch {
// ignore storage errors
}
setCookie(SHOP_GUEST_STORAGE_KEY, stored, 365);
return stored;
}
export function getUserLanguage(): string {
if (typeof window === 'undefined') return 'en';
const fromCookie = (
getCookie(FLUTTER_LANG_COOKIE_NAME) ||
getCookie(USER_LANG_COOKIE_NAME) ||
getCookie('USER_LANGUAGE')
).trim();
if (fromCookie) return fromCookie;
try {
const stored = (window.localStorage.getItem(SHOP_LANG_STORAGE_KEY) || '').trim();
if (stored) return stored;
} catch {
// ignore storage errors
}
return 'en';
}
export function setUserLanguage(lang: string): void {
const normalized = (lang || 'en').trim().toLowerCase();
setCookie(FLUTTER_LANG_COOKIE_NAME, normalized, 365);
setCookie(USER_LANG_COOKIE_NAME, normalized, 365);
if (typeof window !== 'undefined') {
try {
window.localStorage.setItem(SHOP_LANG_STORAGE_KEY, normalized);
} catch {
// ignore storage errors
}
}
}

166
src/lib/http.ts

@ -0,0 +1,166 @@
import { getToken } from './auth-bridge';
import { ensureGuestToken, getUserLanguage } from './cookies';
const API_BASE = (import.meta.env.VITE_API_BASE_URL as string | undefined) || '/api/shop';
const THROTTLE_STORAGE_KEY = 'HABIB_SHOP_THROTTLE_MS';
export function resolveClientThrottleMs(): number {
if (typeof window === 'undefined') return 0;
try {
const params = new URLSearchParams(window.location.search);
const paramVal = params.get('throttle') ?? params.get('throttle_ms');
if (paramVal !== null) {
const parsed = Number.parseInt(paramVal, 10);
if (!Number.isFinite(parsed) || parsed <= 0) {
window.sessionStorage.removeItem(THROTTLE_STORAGE_KEY);
return 0;
}
const clamped = Math.min(parsed, 5000);
window.sessionStorage.setItem(THROTTLE_STORAGE_KEY, String(clamped));
return clamped;
}
const stored = window.sessionStorage.getItem(THROTTLE_STORAGE_KEY);
if (stored) {
const parsed = Number.parseInt(stored, 10);
if (Number.isFinite(parsed) && parsed > 0) {
return Math.min(parsed, 5000);
}
}
} catch {
// ignore storage access issues in restricted webviews
}
return 0;
}
export class ShopApiError extends Error {
status: number;
data: unknown;
constructor(message: string, status: number, data?: unknown) {
super(message);
this.name = 'ShopApiError';
this.status = status;
this.data = data;
}
}
export function resolveMediaUrl(url: string | undefined | null, fallback = ''): string {
if (!url) return fallback;
if (
url.startsWith('http://') ||
url.startsWith('https://') ||
url.startsWith('blob:') ||
url.startsWith('data:') ||
url.startsWith('/')
) {
return url;
}
return `/${url}`;
}
interface RequestOptions {
method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
body?: unknown;
query?: Record<string, string | number | boolean | undefined | null>;
signal?: AbortSignal;
}
function buildUrl(
endpoint: string,
query?: Record<string, string | number | boolean | undefined | null>
): string {
const cleanBase = API_BASE.replace(/\/+$/, '');
const cleanPath = endpoint.startsWith('/') ? endpoint : `/${endpoint}`;
let full = `${cleanBase}${cleanPath}`;
if (query) {
const params = new URLSearchParams();
for (const [key, val] of Object.entries(query)) {
if (val !== undefined && val !== null && val !== '') {
params.set(key, String(val));
}
}
const qs = params.toString();
if (qs) {
full += (full.includes('?') ? '&' : '?') + qs;
}
}
return full;
}
export async function shopRequest<T>(
endpoint: string,
options: RequestOptions = {}
): Promise<T> {
const { method = 'GET', body, query, signal } = options;
const headers: Record<string, string> = {
Accept: 'application/json',
};
const token = getToken();
if (token) {
headers.Authorization = `Token ${token}`;
}
const guestToken = ensureGuestToken();
if (guestToken) {
headers['X-Guest-Token'] = guestToken;
}
const lang = getUserLanguage();
if (lang) {
headers['Accept-Language'] = lang;
headers['X-User-Language'] = lang;
}
const throttleMs = resolveClientThrottleMs();
if (throttleMs > 0) {
headers['X-Shop-Throttle-Ms'] = String(throttleMs);
}
let fetchBody: BodyInit | undefined;
if (body !== undefined) {
if (body instanceof FormData) {
fetchBody = body;
} else {
headers['Content-Type'] = 'application/json';
fetchBody = JSON.stringify(body);
}
}
const response = await fetch(buildUrl(endpoint, query), {
method,
headers,
body: fetchBody,
signal,
});
if (response.status === 204) {
return undefined as T;
}
let parsed: unknown = null;
const contentType = response.headers.get('content-type') || '';
if (contentType.includes('application/json')) {
try {
parsed = await response.json();
} catch {
parsed = null;
}
} else {
parsed = await response.text();
}
if (!response.ok) {
const errObj = (parsed && typeof parsed === 'object' ? parsed : {}) as Record<string, unknown>;
const message =
(typeof errObj.error === 'string' && errObj.error) ||
(typeof errObj.detail === 'string' && errObj.detail) ||
(typeof errObj.message === 'string' && errObj.message) ||
`Request failed (${response.status})`;
throw new ShopApiError(message, response.status, parsed);
}
return parsed as T;
}

315
src/lib/mappers.ts

@ -0,0 +1,315 @@
import type {
CategoryTileItem,
CompactProductItem,
GridProductItem,
} from '../data/catalogData';
import type {
CartItemData,
PaymentReviewItem,
ShippingAddressOption,
} from '../data/checkoutData';
import type { OrderCardData, ShipmentCardData } from '../data/ordersData';
import { resolveMediaUrl } from './http';
import type {
ApiAddress,
ApiCartItem,
ApiCategory,
ApiOrderSummary,
ApiProductCard,
ApiShipment,
} from './shopApi';
export function mapProductToCompactItem(
product: ApiProductCard,
bookmarkedOverride?: boolean
): CompactProductItem {
const ratingStr =
product.rating_avg !== undefined && product.rating_avg !== null
? String(Number(product.rating_avg).toFixed(1)).replace(/\.0$/, '')
: undefined;
return {
id: `prod-${product.id}`,
relX: 0,
relY: 28,
imageSrc:
resolveMediaUrl(product.primary_image_url) ||
'/assets/images/product-brown-leather-bag.png',
hasBookmark:
bookmarkedOverride !== undefined
? bookmarkedOverride
: Boolean(product.is_bookmarked),
rating: ratingStr,
ratingPillWidth: ratingStr && ratingStr.length > 1 ? 34 : 28,
title: product.title,
titleLines: product.title.length > 22 ? 2 : 1,
origin: product.origin_label || `${product.store_name || 'Habib Shop'}`,
originRelY: product.title.length > 22 ? 36 : 22,
oldPrice: product.formatted_old_price || undefined,
price: product.formatted_price || `$${product.price}`,
discountBadge: product.discount_badge || undefined,
};
}
export function mapProductToGridItem(product: ApiProductCard): GridProductItem {
const ratingStr =
product.rating_avg !== undefined && product.rating_avg !== null
? String(Number(product.rating_avg).toFixed(1)).replace(/\.0$/, '')
: '5';
return {
id: `grid-${product.id}`,
relX: 0,
relY: 0,
imageSrc:
resolveMediaUrl(product.primary_image_url) ||
'/assets/images/product-brown-leather-bag.png',
imageRadius: 12,
rating: ratingStr,
ratingPillWidth: ratingStr.length > 1 ? 34 : 28,
ratingStarLeft: 4.5,
ratingTextLeft: 16.5,
ratingTextWidth: 15,
title: product.title,
titleLines: product.title.length > 22 ? 2 : 1,
origin: product.origin_label || `${product.store_name || 'Habib Shop'}`,
originRelY: product.title.length > 22 ? 36 : 22,
oldPrice: product.formatted_old_price || undefined,
price: product.formatted_price || `$${product.price}`,
discountBadge: product.discount_badge || undefined,
};
}
export function mapCategoryToTile(
category: ApiCategory,
index: number
): CategoryTileItem {
const isRightCol = index % 2 === 1;
return {
id: `cat-${category.id}`,
x: isRightCol ? 194 : 16,
y: 111 + Math.floor(index / 2) * 132,
width: isRightCol ? 165 : 166,
isRightCol,
countBadgeLeft: isRightCol ? 134 : 135,
innerLeft: isRightCol ? 18 : 16,
label: category.localized_title || category.title,
labelRelY: 47,
iconSrc:
resolveMediaUrl(category.icon_url) ||
'/assets/images/icon-cat-bag-large.svg',
iconLeft: 46.5,
iconWidth: 40,
iconHeight: 40,
};
}
export function mapCartItemToCard(item: ApiCartItem, index: number): CartItemData {
return {
id: String(item.id),
y: 69 + index * 133,
imageSrc:
resolveMediaUrl(item.image_url) ||
'/assets/images/product-brown-leather-bag.png',
title: item.variant_title
? `${item.title} (${item.variant_title})`
: item.title,
titleHeight: item.title.length > 24 ? 28 : 17,
titleLineHeight: item.title.length > 24 ? 14 : 17,
originRelY: item.title.length > 24 ? 34 : 19,
origin: item.origin_label || item.store_name || 'Habib Shop',
quantity: String(item.quantity),
price: item.formatted_unit_price || `$${item.unit_price}`,
};
}
export function mapCartItemToReview(
item: ApiCartItem,
index: number
): PaymentReviewItem {
return {
id: String(item.id),
relY: index * 91,
imageSrc:
resolveMediaUrl(item.image_url) ||
'/assets/images/product-brown-leather-bag.png',
title: item.title,
price: item.formatted_unit_price || `$${item.unit_price}`,
quantity: String(item.quantity),
};
}
export function mapAddressToOption(
addr: ApiAddress,
selectedId: number | null,
index: number
): ShippingAddressOption {
return {
id: String(addr.id),
relY: index * 97,
name: addr.recipient_name || addr.label || 'Recipient',
nameWidth: 90,
address:
addr.full_address ||
[addr.street_line, addr.city, addr.postal_code, addr.country]
.filter(Boolean)
.join(', '),
selected: selectedId !== null ? addr.id === selectedId : addr.is_default,
};
}
export function mapOrderToCardData(
order: ApiOrderSummary,
index: number
): OrderCardData {
const thumbs = (order.thumbnails || []).slice(0, 5).map((src, idx) => ({
src: resolveMediaUrl(src) || '/assets/images/product-brown-leather-bag.png',
relX: idx * 53,
radius: idx === 0 ? 12 : 8,
}));
if (thumbs.length === 0) {
thumbs.push({
src: '/assets/images/product-brown-leather-bag.png',
relX: 0,
radius: 12,
});
}
const extraCount = (order.thumbnails?.length || 0) - 5;
return {
id: `order-${order.id}`,
y: 154 + index * 253,
orderCode: order.order_number,
price: order.formatted_total || `$${order.total_amount}`,
date: order.formatted_date,
thumbnails: thumbs,
moreCountBadge: extraCount > 0 ? `+${extraCount}` : undefined,
itemsCountText: `${order.items_count} item`,
shopsCountText: `${order.shops_count} shop`,
deliveryProgressText: `${order.delivered_shipments_count} / ${Math.max(
1,
order.total_shipments_count
)} Delivery`,
};
}
export function mapShipmentToCardData(
shipment: ApiShipment,
orderDate: string,
index: number
): ShipmentCardData {
const isDelivered = shipment.status === 'delivered';
const isShipping = shipment.status === 'shipping';
const statusType: 'packed' | 'delivered' | 'shipping' = isDelivered
? 'delivered'
: isShipping
? 'shipping'
: 'packed';
const statusLabel = isDelivered
? 'Delivered'
: isShipping
? 'Shiping'
: shipment.status === 'canceled'
? 'Canceled'
: shipment.status === 'ordered'
? 'Ordered'
: 'Packed';
const statusIconSrc = isDelivered
? '/assets/images/icon-status-delivered-green.svg'
: isShipping
? '/assets/images/icon-status-shipping-gold.svg'
: '/assets/images/icon-status-packed-gold.svg';
const statusColor = isDelivered
? '#0eb13c'
: shipment.status === 'canceled'
? '#d44747'
: '#d78e06';
const statusBg = isDelivered
? 'rgba(14, 177, 60, 0.2)'
: shipment.status === 'canceled'
? 'rgba(212, 71, 71, 0.14)'
: 'rgba(239, 196, 126, 0.2)';
const thumbs = (shipment.thumbnails || []).map((src, idx) => ({
src: resolveMediaUrl(src) || '/assets/images/product-brown-leather-bag.png',
relX: idx * 53,
radius: idx === 0 ? 12 : 8,
}));
if (thumbs.length === 0) {
thumbs.push({
src: '/assets/images/product-brown-leather-bag.png',
relX: 0,
radius: 12,
});
}
const infoRows: ShipmentCardData['infoRows'] = isShipping
? [
{
iconSrc: '/assets/images/icon-date-time-grey-18.svg',
label: 'Order',
labelWidth: 32,
value: orderDate || shipment.estimated_delivery_label,
valueLeft: 64,
relY: 10,
},
{
iconSrc: '/assets/images/icon-delivery-truck-grey-18.svg',
label: 'Tracking code',
labelWidth: 76,
value: shipment.tracking_code || 'HBB-TRK-102',
valueLeft: 108,
relY: 38,
},
]
: [
{
iconSrc: isDelivered
? '/assets/images/icon-delivered-box-check-grey-18.svg'
: '/assets/images/icon-delivery-truck-grey-18.svg',
label: 'Delivery',
labelWidth: 45,
value: shipment.estimated_delivery_label || orderDate || '2-4 Days',
valueLeft: 77,
relY: 10,
},
];
return {
id: `shipment-${shipment.id}`,
y: 213 + index * 241,
height: isShipping ? 249 : 221,
innerHeight: isShipping ? 173 : 145,
boothName: shipment.booth_name || 'Al-Hujjah Books',
boothAvatar:
resolveMediaUrl(shipment.booth_avatar) ||
'/assets/images/avatar-al-hujjah-books.png',
statusType,
statusLabel,
statusBadgeLeft: isDelivered ? 233 : 244,
statusBadgeWidth: isDelivered ? 85 : 74,
statusIconSrc,
statusIconLeft: 6.5,
statusIconTop: 5.5,
statusIconSize: isDelivered || isShipping ? 16 : 15,
statusTextLeft: 26.5,
statusTextWidth: 48,
statusColor,
statusBg,
thumbnails: thumbs,
infoBoxHeight: infoRows.length > 1 ? 66 : 38,
infoRows,
stepperRelY: isShipping ? 200 : 172,
greenLineWidth: isDelivered ? 264 : isShipping ? 186 : 84,
completedSteps: shipment.completed_steps || (isDelivered ? 4 : isShipping ? 3 : 2),
deliveryLabelColor: isDelivered ? '#111111' : isShipping ? '#747474' : '#8b8b8b',
};
}

45
src/lib/routes.ts

@ -0,0 +1,45 @@
export const ROUTES = {
home: '/',
categories: '/categories',
category: (slug: string = 'home-living') => `/categories/${encodeURIComponent(slug)}`,
search: (query?: string) =>
query && query.trim()
? `/search?q=${encodeURIComponent(query.trim())}`
: '/search',
product: (idOrSlug: string | number = 'islam-in-the-bible-book') =>
`/products/${encodeURIComponent(String(idOrSlug))}`,
stores: '/stores',
store: (idOrSlug: string | number = 'tashakol-farzandan-rohhallah') =>
`/stores/${encodeURIComponent(String(idOrSlug))}`,
chat: '/chat',
chatThread: (idOrSlug: string | number = 'al-hujjah-books') =>
`/chat/${encodeURIComponent(String(idOrSlug))}`,
cart: '/cart',
checkoutShipping: '/checkout/shipping',
checkoutReview: '/checkout/review',
checkoutResult: (orderNumber: string = 'ORD-28465') =>
`/checkout/result/${encodeURIComponent(orderNumber)}`,
orders: (tab?: 'current' | 'delivered' | 'canceled') =>
tab ? `/orders?tab=${tab}` : '/orders',
orderDetail: (orderNumber: string = 'ORD-28465') =>
`/orders/${encodeURIComponent(orderNumber)}`,
orderSupport: (orderNumber: string = 'ORD-28465') =>
`/orders/${encodeURIComponent(orderNumber)}/support`,
support: '/support',
account: '/account',
bookmarks: '/account/bookmarks',
addresses: '/account/addresses',
profile: '/account/profile',
settings: '/account/settings',
test: '/test',
} as const;
export const USE_MOCK_DATA =
String(import.meta.env.VITE_USE_MOCK_DATA ?? '').trim().toLowerCase() === 'true';
export function isBareMode(search: string): boolean {
if (!search) return false;
const params = new URLSearchParams(search);
return params.get('bare') === '1' || params.get('embed') === '1';
}

660
src/lib/shopApi.ts

@ -0,0 +1,660 @@
import { shopRequest } from './http';
export interface ApiBanner {
id: number;
slug: string;
title: string;
title_i18n?: Record<string, string>;
subtitle: string;
cta_label: string;
image_url: string;
target_route: string;
display_order: number;
}
export interface ApiCategory {
id: number;
parent: number | null;
slug: string;
title: string;
localized_title: string;
title_i18n?: Record<string, string>;
icon_url: string;
small_icon_url: string;
accent_color: string;
display_order: number;
is_quick: boolean;
products_count: number;
}
export interface ApiStoreSummary {
id: number;
slug: string;
name: string;
tagline: string;
country: string;
city: string;
origin_label: string;
logo_url: string;
banner_url: string;
badge: string;
membership_label: string;
sales_label: string;
since_label: string;
avg_response_time: string;
on_time_delivery_rate: number;
satisfaction_rate: number;
rating_avg: string | number;
reviews_count: number;
products_count: number;
is_verified: boolean;
}
export interface ApiProductCard {
id: number;
slug: string;
sku: string;
title: string;
primary_image_url: string;
hero_image_url: string;
price: string;
formatted_price: string;
compare_at_price: string | null;
formatted_old_price: string | null;
discount_badge: string;
coin_price: number;
currency: string;
stock_qty: number;
origin_label: string;
rating_avg: string | number;
reviews_count: number;
store: number;
store_slug: string;
store_name: string;
category: number;
category_slug: string;
category_title: string;
is_popular: boolean;
is_new_store_pick: boolean;
is_bookmarked: boolean;
}
export interface ApiProductMedia {
id: number;
image_url: string;
alt_text: string;
sort_order: number;
}
export interface ApiProductVariant {
id: number;
sku: string;
title: string;
attributes_json: Record<string, string>;
price_override: string | null;
coin_price_override: number | null;
stock_qty: number;
is_active: boolean;
}
export interface ApiReview {
id: number;
product: number;
author_name: string;
rating: number;
comment: string;
image_url: string;
formatted_date: string;
created_at: string;
}
export interface ApiProductDetail extends ApiProductCard {
breadcrumb: string;
description: string;
condition_label: string;
processing_time_label: string;
product_type_label: string;
specs_json: Record<string, string>;
shipping_info_json: Record<string, string>;
store_detail: ApiStoreSummary;
media: ApiProductMedia[];
variants: ApiProductVariant[];
reviews: ApiReview[];
related_products: ApiProductCard[];
}
export interface ApiStoreDetail extends ApiStoreSummary {
description: string;
created_at: string;
products: ApiProductCard[];
}
export interface ApiCartItem {
id: number;
product_id: number;
product_slug: string;
title: string;
image_url: string;
origin_label: string;
store_id: number;
store_slug: string;
store_name: string;
variant: number | null;
variant_title: string;
quantity: number;
unit_price: string;
formatted_unit_price: string;
line_total: string;
formatted_line_total: string;
coin_unit_price: number;
}
export interface ApiCartPricing {
items_count: number;
total_quantity: number;
total_units?: number;
shops_count: number;
subtotal: string;
formatted_subtotal: string;
shipping_fee: string;
formatted_shipping_fee: string;
discount_amount: string;
formatted_discount: string;
formatted_discount_amount?: string;
promo_code: string;
total: string;
total_amount?: string;
formatted_total: string;
coin_total: number;
coins_total?: number;
}
export interface ApiCart {
id: number;
currency: string;
promo_code: string;
items: ApiCartItem[];
pricing: ApiCartPricing;
updated_at: string;
}
export interface ApiAddress {
id: number;
label: string;
recipient_name: string;
phone: string;
country: string;
city: string;
street_line: string;
postal_code: string;
lat: string | number | null;
lon: string | number | null;
is_default: boolean;
full_address: string;
created_at: string;
}
export interface ApiShippingMethod {
id: number;
code: string;
title: string;
title_i18n?: Record<string, string>;
subtitle: string;
price: string;
formatted_price: string;
coin_price: number;
estimated_days_min: number;
estimated_days_max: number;
is_default: boolean;
}
export interface ApiPaymentMethod {
id: string;
code: string;
label: string;
icon_url: string;
is_default: boolean;
balance?: number;
}
export interface ApiShipmentEvent {
id: number;
status: string;
title: string;
location: string;
formatted_time: string;
occurred_at: string;
}
export interface ApiShipment {
id: number;
store: number;
booth_name: string;
booth_slug: string;
booth_avatar: string;
status: 'ordered' | 'packed' | 'shipping' | 'delivered' | 'canceled';
carrier_name: string;
tracking_code: string;
estimated_delivery_label: string;
completed_steps: number;
thumbnails: string[];
events: ApiShipmentEvent[];
}
export interface ApiOrderItem {
id: number;
product: number | null;
product_slug: string;
store: number;
store_name: string;
store_slug: string;
title_snapshot: string;
image_snapshot: string;
origin_snapshot: string;
unit_price: string;
formatted_unit_price: string;
coin_unit_price: number;
quantity: number;
line_total: string;
formatted_line_total: string;
}
export interface ApiOrderSummary {
id: number;
order_number: string;
status: string;
payment_method: string;
payment_method_label: string;
payment_status: string;
currency: string;
total_amount: string;
formatted_total: string;
coins_charged: number;
formatted_date: string;
formatted_datetime: string;
thumbnails: string[];
items_count: number;
shops_count: number;
delivered_shipments_count: number;
total_shipments_count: number;
placed_at: string;
}
export interface ApiOrderDetail extends ApiOrderSummary {
subtotal: string;
formatted_subtotal: string;
shipping_fee: string;
formatted_shipping_fee: string;
discount_amount: string;
formatted_discount: string;
promo_code: string;
shipping_method_title: string;
shipping_address_snapshot: {
recipient_name?: string;
phone?: string;
full_address?: string;
city?: string;
country?: string;
street_line?: string;
};
notes: string;
items: ApiOrderItem[];
shipments: ApiShipment[];
}
export interface ApiOrderCounters {
current: number;
in_progress: number;
delivered: number;
canceled: number;
returned: number;
}
export interface ApiUserProfile {
is_authenticated: boolean;
id?: number;
guest_token?: string;
full_name: string;
email: string;
phone_number: string;
avatar_url: string;
habib_coins_balance: number;
shop_provider: Record<string, unknown> | null;
provider_requests: {
id: number;
service: string;
status: string;
public_name: string;
created_at: string;
}[];
}
export interface ApiSupportSubject {
id: number;
slug: string;
label: string;
title_i18n?: Record<string, string>;
icon_url: string;
display_order: number;
}
export interface ApiSupportTicket {
id: number;
ticket_number: string;
order: number | null;
order_number: string;
subject: number | null;
subject_label: string;
description: string;
attachment_url: string;
status: string;
admin_reply: string;
formatted_date: string;
created_at: string;
}
export interface ApiConversation {
id: number;
store: number;
store_detail: ApiStoreSummary;
last_message_preview: string;
last_message_at: string | null;
formatted_last_time: string;
unread_user_count: number;
created_at: string;
}
export interface ApiChatMessage {
id: number;
conversation: number;
sender_type: 'customer' | 'store' | 'system';
text: string;
attachment_url: string;
product_ref: number | null;
order_ref: number | null;
is_read: boolean;
formatted_time: string;
date_group: string;
created_at: string;
}
export interface HomeFeedResponse {
banners: ApiBanner[];
quick_categories: ApiCategory[];
categories: ApiCategory[];
popular_products: ApiProductCard[];
new_store_products: ApiProductCard[];
featured_stores: ApiStoreSummary[];
cart_items_count: number;
habib_coins_balance: number;
}
export const shopApi = {
// Home & Catalog
fetchHomeFeed: () => shopRequest<HomeFeedResponse>('/home/'),
fetchCategories: (q?: string) =>
shopRequest<{ results: ApiCategory[] }>('/categories/', { query: { q } }),
fetchCategoryDetail: (slug: string, q?: string) =>
shopRequest<{ category: ApiCategory; products: ApiProductCard[] }>(
`/categories/${encodeURIComponent(slug)}/`,
{ query: { q } }
),
fetchProducts: (params?: {
q?: string;
category?: string;
store?: string;
popular?: boolean;
new_store?: boolean;
sort?: 'price_asc' | 'price_desc' | 'rating' | 'newest';
}) =>
shopRequest<{ count: number; results: ApiProductCard[] }>('/products/', {
query: params,
}),
fetchProductDetail: (idOrSlug: string | number) =>
shopRequest<ApiProductDetail>(`/products/${encodeURIComponent(String(idOrSlug))}/`),
fetchProductReviews: (idOrSlug: string | number) =>
shopRequest<{ count: number; results: ApiReview[] }>(
`/products/${encodeURIComponent(String(idOrSlug))}/reviews/`
),
createProductReview: (
idOrSlug: string | number,
payload: { rating: number; comment: string; author_name?: string; image_url?: string }
) =>
shopRequest<ApiReview>(
`/products/${encodeURIComponent(String(idOrSlug))}/reviews/`,
{ method: 'POST', body: payload }
),
fetchStores: (q?: string) =>
shopRequest<{ count: number; results: ApiStoreSummary[] }>('/stores/', {
query: { q },
}),
fetchStoreDetail: (idOrSlug: string | number) =>
shopRequest<ApiStoreDetail>(`/stores/${encodeURIComponent(String(idOrSlug))}/`),
// Cart & Checkout
fetchCart: (includeShipping = false) =>
shopRequest<ApiCart>('/cart/', {
query: { include_shipping: includeShipping ? '1' : undefined },
}),
clearCart: () => shopRequest<ApiCart>('/cart/', { method: 'DELETE' }),
addCartItem: (payload: {
product_id: string | number;
variant_id?: number | null;
quantity?: number;
}) => shopRequest<ApiCart>('/cart/items/', { method: 'POST', body: payload }),
updateCartItem: (itemId: number, quantity: number) =>
shopRequest<ApiCart>(`/cart/items/${itemId}/`, {
method: 'PATCH',
body: { quantity },
}),
removeCartItem: (itemId: number) =>
shopRequest<ApiCart>(`/cart/items/${itemId}/`, { method: 'DELETE' }),
mergeGuestCart: (guestToken?: string) =>
shopRequest<ApiCart>('/cart/merge/', {
method: 'POST',
body: guestToken ? { guest_token: guestToken } : {},
}),
applyPromoCode: (promoCode: string) =>
shopRequest<ApiCart>('/cart/promo/', {
method: 'POST',
body: { promo_code: promoCode },
}),
fetchShippingMethods: () =>
shopRequest<{ results: ApiShippingMethod[] }>('/checkout/shipping-methods/'),
fetchCheckoutSummary: (shippingMethodCodeOrId?: string | number) =>
shopRequest<{
cart: ApiCart;
shipping_method: ApiShippingMethod;
pricing: ApiCartPricing;
habib_coins_balance: number;
}>('/checkout/summary/', {
query: { shipping_method: shippingMethodCodeOrId },
}),
fetchPaymentMethods: () =>
shopRequest<{ habib_coins_balance: number; results: ApiPaymentMethod[] }>(
'/payment/methods/'
),
// Orders & Shipments
fetchOrders: (status?: 'current' | 'delivered' | 'canceled') =>
shopRequest<{ count: number; results: ApiOrderSummary[] }>('/orders/', {
query: { status },
}),
fetchOrderCounters: () => shopRequest<ApiOrderCounters>('/orders/counters/'),
placeOrder: (payload: {
address_id?: number | null;
shipping_address?: Record<string, unknown>;
shipping_method?: string | number;
payment_method: string;
promo_code?: string;
notes?: string;
}) => shopRequest<ApiOrderDetail>('/orders/', { method: 'POST', body: payload }),
fetchOrderDetail: (orderNumber: string) =>
shopRequest<ApiOrderDetail>(`/orders/${encodeURIComponent(orderNumber)}/`),
fetchOrderReceipt: (orderNumber: string) =>
shopRequest<{
order_number: string;
status: string;
payment_status: string;
payment_method: string;
payment_method_label: string;
total_paid: string;
coins_charged: number;
order_date: string;
shipping_address: Record<string, unknown>;
}>(`/orders/${encodeURIComponent(orderNumber)}/receipt/`),
cancelOrder: (orderNumber: string) =>
shopRequest<ApiOrderDetail>(`/orders/${encodeURIComponent(orderNumber)}/cancel/`, {
method: 'POST',
}),
fetchShipmentTracking: (orderNumber: string, shipmentId: number) =>
shopRequest<ApiShipment>(
`/orders/${encodeURIComponent(orderNumber)}/shipments/${shipmentId}/`
),
// Profile, Addresses, Bookmarks & Provider
fetchProfile: () => shopRequest<ApiUserProfile>('/me/profile/'),
updateProfile: (payload: {
full_name?: string;
email?: string;
phone_number?: string;
}) => shopRequest<ApiUserProfile>('/me/profile/', { method: 'PUT', body: payload }),
fetchAddresses: () => shopRequest<{ results: ApiAddress[] }>('/me/addresses/'),
createAddress: (payload: {
label?: string;
recipient_name: string;
phone?: string;
country?: string;
city?: string;
street_line: string;
postal_code?: string;
lat?: number | null;
lon?: number | null;
is_default?: boolean;
}) => shopRequest<ApiAddress>('/me/addresses/', { method: 'POST', body: payload }),
updateAddress: (
id: number,
payload: Partial<{
label: string;
recipient_name: string;
phone: string;
country: string;
city: string;
street_line: string;
postal_code: string;
lat: number | null;
lon: number | null;
is_default: boolean;
}>
) =>
shopRequest<ApiAddress>(`/me/addresses/${id}/`, {
method: 'PATCH',
body: payload,
}),
deleteAddress: (id: number) =>
shopRequest<void>(`/me/addresses/${id}/`, { method: 'DELETE' }),
fetchBookmarks: () =>
shopRequest<{
count: number;
results: { id: number; product: number; product_detail: ApiProductCard }[];
}>('/me/bookmarks/'),
addBookmark: (productIdOrSlug: string | number) =>
shopRequest<{ id: number; product: number; product_detail: ApiProductCard }>(
'/me/bookmarks/',
{ method: 'POST', body: { product_id: productIdOrSlug } }
),
removeBookmark: (productIdOrSlug: string | number) =>
shopRequest<void>(
`/me/bookmarks/${encodeURIComponent(String(productIdOrSlug))}/`,
{ method: 'DELETE' }
),
applyAsProvider: (payload: { store_name: string; description?: string }) =>
shopRequest<{
id?: number;
service: string;
status: string;
public_name: string;
message: string;
}>('/providers/apply/', { method: 'POST', body: payload }),
// Support & Chat
fetchSupportSubjects: () =>
shopRequest<{ results: ApiSupportSubject[] }>('/support/subjects/'),
fetchSupportTickets: () =>
shopRequest<{ count: number; results: ApiSupportTicket[] }>('/support/tickets/'),
createSupportTicket: (payload: {
order_number?: string;
product_id?: string | number;
subject?: string | number;
subject_label?: string;
description: string;
attachment_url?: string;
}) =>
shopRequest<ApiSupportTicket>('/support/tickets/', {
method: 'POST',
body: payload,
}),
fetchChatConversations: () =>
shopRequest<{ count: number; results: ApiConversation[] }>('/chat/conversations/'),
createChatConversation: (storeIdOrSlug: string | number) =>
shopRequest<ApiConversation>('/chat/conversations/', {
method: 'POST',
body: { store_id: storeIdOrSlug },
}),
fetchChatMessages: (pkOrSlug: string | number, afterId?: number) =>
shopRequest<{ conversation: ApiConversation; results: ApiChatMessage[] }>(
`/chat/conversations/${encodeURIComponent(String(pkOrSlug))}/messages/`,
{ query: { after_id: afterId } }
),
sendChatMessage: (
pkOrSlug: string | number,
payload: { text?: string; attachment_url?: string }
) =>
shopRequest<{
conversation: ApiConversation;
message: ApiChatMessage;
new_messages: ApiChatMessage[];
}>(
`/chat/conversations/${encodeURIComponent(String(pkOrSlug))}/messages/`,
{ method: 'POST', body: payload }
),
};

366
src/lib/shopQueries.ts

@ -0,0 +1,366 @@
import {
QueryClient,
useMutation,
useQuery,
useQueryClient,
} from '@tanstack/react-query';
import {
type ApiChatMessage,
type ApiConversation,
type ApiOrderDetail,
type ApiProductDetail,
type ApiUserProfile,
shopApi,
} from './shopApi';
export type ProductsQueryParams = NonNullable<
Parameters<typeof shopApi.fetchProducts>[0]
>;
export const shopQueryClient = new QueryClient({
defaultOptions: {
queries: {
staleTime: 60_000,
gcTime: 15 * 60_000,
retry: 1,
refetchOnWindowFocus: false,
},
},
});
export const shopKeys = {
all: ['shop'] as const,
home: () => ['shop', 'home'] as const,
categoriesAll: () => ['shop', 'categories'] as const,
categories: (q?: string) => ['shop', 'categories', q ?? ''] as const,
categoryDetailsAll: () => ['shop', 'category'] as const,
categoryDetail: (slug: string, q?: string) =>
['shop', 'category', slug, q ?? ''] as const,
productsAll: () => ['shop', 'products'] as const,
products: (params?: ProductsQueryParams) =>
['shop', 'products', params ?? {}] as const,
productDetailsAll: () => ['shop', 'product'] as const,
productDetail: (idOrSlug: string | number) =>
['shop', 'product', String(idOrSlug)] as const,
storeDetailsAll: () => ['shop', 'store'] as const,
storeDetail: (idOrSlug: string | number) =>
['shop', 'store', String(idOrSlug)] as const,
cart: () => ['shop', 'cart'] as const,
shippingMethods: () => ['shop', 'shipping-methods'] as const,
paymentMethods: () => ['shop', 'payment-methods'] as const,
ordersAll: () => ['shop', 'orders'] as const,
orders: (status: 'current' | 'delivered' | 'canceled') =>
['shop', 'orders', status] as const,
orderCounters: () => ['shop', 'order-counters'] as const,
orderDetailsAll: () => ['shop', 'order-detail'] as const,
orderDetail: (orderNumber: string) =>
['shop', 'order-detail', orderNumber] as const,
orderReceiptsAll: () => ['shop', 'order-receipt'] as const,
orderReceipt: (orderNumber: string) =>
['shop', 'order-receipt', orderNumber] as const,
profile: () => ['shop', 'profile'] as const,
addresses: () => ['shop', 'addresses'] as const,
bookmarks: () => ['shop', 'bookmarks'] as const,
supportSubjects: () => ['shop', 'support-subjects'] as const,
supportTickets: () => ['shop', 'support-tickets'] as const,
chatConversations: () => ['shop', 'chat-conversations'] as const,
chatMessagesAll: () => ['shop', 'chat-messages'] as const,
chatMessages: (pkOrSlug: string | number) =>
['shop', 'chat-messages', String(pkOrSlug)] as const,
};
export function clearUserScopedCache(queryClient: QueryClient): void {
queryClient.removeQueries({ queryKey: shopKeys.ordersAll() });
queryClient.removeQueries({ queryKey: shopKeys.orderDetailsAll() });
queryClient.removeQueries({ queryKey: shopKeys.orderReceiptsAll() });
queryClient.removeQueries({ queryKey: shopKeys.chatMessagesAll() });
queryClient.removeQueries({ queryKey: shopKeys.chatConversations() });
queryClient.removeQueries({ queryKey: shopKeys.supportTickets() });
}
export function useHomeFeedQuery(enabled = true) {
return useQuery({
queryKey: shopKeys.home(),
queryFn: () => shopApi.fetchHomeFeed(),
enabled,
});
}
export function useCategoriesQuery(enabled = true, q?: string) {
return useQuery({
queryKey: shopKeys.categories(q),
queryFn: () => shopApi.fetchCategories(q),
enabled,
});
}
export function useCategoryDetailQuery(
slug: string,
enabled = true,
q?: string
) {
return useQuery({
queryKey: shopKeys.categoryDetail(slug, q),
queryFn: () => shopApi.fetchCategoryDetail(slug, q),
enabled: enabled && Boolean(slug),
});
}
export function useProductsQuery(params?: ProductsQueryParams, enabled = true) {
return useQuery({
queryKey: shopKeys.products(params),
queryFn: () => shopApi.fetchProducts(params),
enabled,
});
}
export function useProductDetailQuery(
idOrSlug: string | number,
enabled = true
) {
return useQuery({
queryKey: shopKeys.productDetail(idOrSlug),
queryFn: () => shopApi.fetchProductDetail(idOrSlug),
enabled: enabled && Boolean(idOrSlug),
});
}
export function useStoreDetailQuery(
idOrSlug: string | number,
enabled = true
) {
return useQuery({
queryKey: shopKeys.storeDetail(idOrSlug),
queryFn: () => shopApi.fetchStoreDetail(idOrSlug),
enabled: enabled && Boolean(idOrSlug),
});
}
export function useOrdersQuery(
status: 'current' | 'delivered' | 'canceled',
enabled = true
) {
return useQuery({
queryKey: shopKeys.orders(status),
queryFn: () => shopApi.fetchOrders(status),
enabled,
});
}
export function useOrderDetailQuery(orderNumber: string, enabled = true) {
return useQuery({
queryKey: shopKeys.orderDetail(orderNumber),
queryFn: () => shopApi.fetchOrderDetail(orderNumber),
enabled: enabled && Boolean(orderNumber),
});
}
export function useOrderReceiptQuery(orderNumber: string, enabled = true) {
return useQuery({
queryKey: shopKeys.orderReceipt(orderNumber),
queryFn: () => shopApi.fetchOrderReceipt(orderNumber),
enabled: enabled && Boolean(orderNumber),
});
}
export function usePaymentMethodsQuery(enabled = true) {
return useQuery({
queryKey: shopKeys.paymentMethods(),
queryFn: () => shopApi.fetchPaymentMethods(),
enabled,
});
}
export function useSupportSubjectsQuery(enabled = true) {
return useQuery({
queryKey: shopKeys.supportSubjects(),
queryFn: () => shopApi.fetchSupportSubjects(),
enabled,
staleTime: 5 * 60_000,
});
}
export function useChatMessagesQuery(
pkOrSlug: string | number,
enabled = true
) {
return useQuery({
queryKey: shopKeys.chatMessages(pkOrSlug),
queryFn: () => shopApi.fetchChatMessages(pkOrSlug),
enabled: enabled && Boolean(pkOrSlug),
staleTime: 30_000,
});
}
export function useCreateReviewMutation() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: ({
productRef,
payload,
}: {
productRef: string | number;
routeRef?: string | number;
payload: {
rating: number;
comment: string;
author_name?: string;
image_url?: string;
};
}) => shopApi.createProductReview(productRef, payload),
onSuccess: (created, variables) => {
const refs = new Set(
[variables.productRef, variables.routeRef]
.filter((v): v is string | number => Boolean(v))
.map(String)
);
for (const ref of refs) {
queryClient.setQueryData<ApiProductDetail>(
shopKeys.productDetail(ref),
(old) =>
old
? {
...old,
reviews: [created, ...(old.reviews || [])],
reviews_count: (old.reviews_count || 0) + 1,
}
: old
);
void queryClient.invalidateQueries({
queryKey: shopKeys.productDetail(ref),
});
}
void queryClient.invalidateQueries({ queryKey: shopKeys.home() });
void queryClient.invalidateQueries({ queryKey: shopKeys.productsAll() });
void queryClient.invalidateQueries({
queryKey: shopKeys.storeDetailsAll(),
});
},
});
}
export function usePlaceOrderMutation() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (payload: Parameters<typeof shopApi.placeOrder>[0]) =>
shopApi.placeOrder(payload),
onSuccess: (order) => {
queryClient.setQueryData<ApiOrderDetail>(
shopKeys.orderDetail(order.order_number),
order
);
void queryClient.invalidateQueries({ queryKey: shopKeys.cart() });
void queryClient.invalidateQueries({ queryKey: shopKeys.ordersAll() });
void queryClient.invalidateQueries({
queryKey: shopKeys.orderCounters(),
});
void queryClient.invalidateQueries({ queryKey: shopKeys.profile() });
void queryClient.invalidateQueries({
queryKey: shopKeys.paymentMethods(),
});
void queryClient.invalidateQueries({ queryKey: shopKeys.home() });
void queryClient.invalidateQueries({ queryKey: shopKeys.productsAll() });
void queryClient.invalidateQueries({
queryKey: shopKeys.productDetailsAll(),
});
},
});
}
export function useCancelOrderMutation() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (orderNumber: string) => shopApi.cancelOrder(orderNumber),
onSuccess: (updated, requestedOrderNumber) => {
queryClient.setQueryData<ApiOrderDetail>(
shopKeys.orderDetail(updated.order_number),
updated
);
if (requestedOrderNumber !== updated.order_number) {
queryClient.setQueryData<ApiOrderDetail>(
shopKeys.orderDetail(requestedOrderNumber),
updated
);
}
void queryClient.invalidateQueries({ queryKey: shopKeys.ordersAll() });
void queryClient.invalidateQueries({
queryKey: shopKeys.orderCounters(),
});
void queryClient.invalidateQueries({
queryKey: shopKeys.orderReceipt(updated.order_number),
});
void queryClient.invalidateQueries({ queryKey: shopKeys.profile() });
void queryClient.invalidateQueries({
queryKey: shopKeys.paymentMethods(),
});
},
});
}
export function useCreateSupportTicketMutation() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (payload: Parameters<typeof shopApi.createSupportTicket>[0]) =>
shopApi.createSupportTicket(payload),
onSuccess: () => {
void queryClient.invalidateQueries({
queryKey: shopKeys.supportTickets(),
});
},
});
}
export function useUpdateProfileMutation() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (payload: Parameters<typeof shopApi.updateProfile>[0]) =>
shopApi.updateProfile(payload),
onSuccess: (updated) => {
queryClient.setQueryData<ApiUserProfile>(shopKeys.profile(), updated);
void queryClient.invalidateQueries({ queryKey: shopKeys.profile() });
},
});
}
export function useApplyProviderMutation() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (payload: Parameters<typeof shopApi.applyAsProvider>[0]) =>
shopApi.applyAsProvider(payload),
onSuccess: () => {
void queryClient.invalidateQueries({ queryKey: shopKeys.profile() });
},
});
}
export function useSendChatMessageMutation(resolvedConvRef: string | number) {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (payload: { text?: string; attachment_url?: string }) =>
shopApi.sendChatMessage(resolvedConvRef, payload),
onSuccess: (res) => {
const incomingBatch =
res.new_messages && res.new_messages.length > 0
? res.new_messages
: [res.message];
queryClient.setQueryData<{
conversation: ApiConversation;
results: ApiChatMessage[];
}>(shopKeys.chatMessages(resolvedConvRef), (old) => {
const prevList = old?.results || [];
const seen = new Set(prevList.map((m) => m.id));
const fresh = incomingBatch.filter((m) => m && !seen.has(m.id));
const nextConv = res.conversation || old?.conversation;
if (!nextConv) return old;
return {
conversation: nextConv,
results: [...prevList, ...fresh],
};
});
void queryClient.invalidateQueries({
queryKey: shopKeys.chatConversations(),
});
},
});
}

68
src/lib/view-paddings.ts

@ -0,0 +1,68 @@
import type { FlutterResponsePayload } from '../types/window';
import { postActionToFlutter, isInFlutterWebView } from './webview-actions';
function toLogicalPx(rawPx: unknown, devicePixelRatio: number): number {
const num = Number(rawPx);
if (!Number.isFinite(num) || num <= 0) return 0;
// Flutter MediaQuery padding values may already be logical or physical depending on bridge payload
if (num > 120 && devicePixelRatio > 1) {
return Math.round(num / devicePixelRatio);
}
return Math.round(num);
}
function applySafeCssVars(data: Record<string, unknown>): void {
if (typeof document === 'undefined') return;
const root = document.documentElement;
const dpr = Number(data.devicePixelRatio || window.devicePixelRatio || 1) || 1;
const paddings = (data.viewPadding || data.padding || data) as Record<string, unknown>;
if (paddings.top !== undefined) {
root.style.setProperty('--safe-top', `${toLogicalPx(paddings.top, dpr)}px`);
}
if (paddings.bottom !== undefined) {
root.style.setProperty('--safe-bottom', `${toLogicalPx(paddings.bottom, dpr)}px`);
}
if (paddings.left !== undefined) {
root.style.setProperty('--safe-left', `${toLogicalPx(paddings.left, dpr)}px`);
}
if (paddings.right !== undefined) {
root.style.setProperty('--safe-right', `${toLogicalPx(paddings.right, dpr)}px`);
}
if (data.keyboardHeight !== undefined || paddings.bottomInset !== undefined) {
const rawKb = data.keyboardHeight ?? paddings.bottomInset ?? 0;
root.style.setProperty('--kb-height', `${toLogicalPx(rawKb, dpr)}px`);
}
}
export function initFlutterViewPaddings(): () => void {
if (typeof window === 'undefined') {
return () => {};
}
const handlePayload = (payload: FlutterResponsePayload) => {
if (!payload || typeof payload !== 'object') return;
const action = payload.action;
const data = (payload.data || payload) as Record<string, unknown>;
if (
action === 'initial_config' ||
action === 'get_view_paddings' ||
action === 'view_paddings_changed' ||
action === 'keyboard_changed'
) {
applySafeCssVars(data);
}
};
const unsubscribe =
typeof window.addFlutterResponseListener === 'function'
? window.addFlutterResponseListener(handlePayload)
: () => {};
if (isInFlutterWebView()) {
postActionToFlutter('get_view_paddings');
}
return unsubscribe;
}

222
src/lib/webview-actions.ts

@ -0,0 +1,222 @@
import type { FlutterResponsePayload } from '../types/window';
import { getToken } from './auth-bridge';
function getFlutterChannel() {
if (typeof window === 'undefined') return undefined;
const ch = window.HabibApp ?? window.FlutterChannel;
return ch && typeof ch.postMessage === 'function' ? ch : undefined;
}
export function isInFlutterWebView(): boolean {
return Boolean(getFlutterChannel());
}
export function postActionToFlutter(
action: string,
extraPayload: Record<string, unknown> = {}
): boolean {
const channel = getFlutterChannel();
if (!channel) return false;
try {
channel.postMessage(
JSON.stringify({
action,
...extraPayload,
})
);
return true;
} catch {
return false;
}
}
export function requestFlutterAction(
action: string,
extraPayload: Record<string, unknown> = {},
timeoutMs = 45000
): Promise<FlutterResponsePayload | null> {
if (!isInFlutterWebView()) {
return Promise.resolve(null);
}
return new Promise((resolve) => {
let settled = false;
let unsubscribe: (() => void) | undefined;
const finish = (res: FlutterResponsePayload | null) => {
if (settled) return;
settled = true;
window.clearTimeout(timer);
if (unsubscribe) unsubscribe();
resolve(res);
};
if (typeof window.addFlutterResponseListener === 'function') {
unsubscribe = window.addFlutterResponseListener((payload) => {
if (payload?.action === action) {
finish(payload);
}
});
}
const timer = window.setTimeout(() => {
finish(null);
}, timeoutMs);
const posted = postActionToFlutter(action, extraPayload);
if (!posted) {
finish(null);
}
});
}
export function closeService(): boolean {
return postActionToFlutter('close_service');
}
export function openAiAssistant(): boolean {
return postActionToFlutter('open_ai_assistant');
}
export function openExternalUrl(url: string): void {
if (!url) return;
if (postActionToFlutter('open_external_url', { url, data: { url } })) {
return;
}
if (typeof window !== 'undefined') {
window.open(url, '_blank', 'noopener,noreferrer');
}
}
export async function copyToClipboard(text: string): Promise<boolean> {
if (!text) return false;
if (isInFlutterWebView()) {
postActionToFlutter('copy_to_clipboard', { text, data: { text } });
return true;
}
if (typeof navigator !== 'undefined' && navigator.clipboard?.writeText) {
try {
await navigator.clipboard.writeText(text);
return true;
} catch {
return false;
}
}
return false;
}
export function downloadFile(url: string, filename?: string): void {
if (!url) return;
if (postActionToFlutter('download_file', { url, filename, data: { url, filename } })) {
return;
}
if (typeof document !== 'undefined') {
const a = document.createElement('a');
a.href = url;
if (filename) a.download = filename;
a.target = '_blank';
a.rel = 'noopener noreferrer';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
}
export async function buyHabibCoinPackages(): Promise<number | null> {
if (!isInFlutterWebView()) {
return null;
}
const response = await requestFlutterAction('buy_coin', {}, 120000);
if (!response) return null;
const data = (response.data || response) as Record<string, unknown>;
const rawBalance = data.coinsBalance ?? data.coin_balance;
if (rawBalance !== undefined) {
const parsed = Number(rawBalance);
if (Number.isFinite(parsed) && parsed >= 0) {
window.HABIB_COINS = parsed;
return parsed;
}
}
return typeof window.HABIB_COINS === 'number' ? window.HABIB_COINS : null;
}
export interface PickedLocationResult {
lat: number;
lon: number;
address?: string;
city?: string;
country?: string;
}
export async function pickManualLocation(): Promise<PickedLocationResult | null> {
const response = await requestFlutterAction('pick_manual_location', {}, 90000);
if (!response || response.success === false) return null;
const data = (response.data || response) as Record<string, unknown>;
const lat = Number(data.lat ?? data.latitude);
const lon = Number(data.lon ?? data.lng ?? data.longitude);
if (!Number.isFinite(lat) || !Number.isFinite(lon)) return null;
return {
lat,
lon,
address: typeof data.address === 'string' ? data.address : undefined,
city: typeof data.city === 'string' ? data.city : undefined,
country: typeof data.country === 'string' ? data.country : undefined,
};
}
export async function uploadFileViaFlutterBridge(): Promise<string | null> {
if (!isInFlutterWebView()) return null;
const uploadPayload = {
uploadUrl: '/upload-tmp-media/',
fieldName: 'file',
allowedTypes: ['image', 'video'],
};
const response = await requestFlutterAction(
'upload_file',
{
...uploadPayload,
data: uploadPayload,
},
90000
);
if (!response || response.success === false) return null;
const data = (response.data || response) as Record<string, unknown>;
const url =
(typeof data.url === 'string' && data.url) ||
(typeof data.file_url === 'string' && data.file_url) ||
(typeof data.path === 'string' && data.path) ||
'';
return url || null;
}
export async function uploadBrowserFileToTmpMedia(file: File): Promise<string> {
const formData = new FormData();
formData.append('file', file);
const headers: Record<string, string> = {};
const token = getToken();
if (token) {
headers.Authorization = `Token ${token}`;
}
try {
const resp = await fetch('/upload-tmp-media/', {
method: 'POST',
headers,
body: formData,
});
if (resp.ok) {
const json = (await resp.json()) as Record<string, unknown>;
const resolved =
(typeof json.url === 'string' && json.url) ||
(typeof json.file === 'string' && json.file) ||
(typeof json.path === 'string' && json.path) ||
'';
if (resolved) return resolved;
}
} catch {
// fallback to local object URL for standalone preview
}
return URL.createObjectURL(file);
}

7
src/main.tsx

@ -4,14 +4,15 @@ import './index.css'
import App from './App.tsx'
import { DevClickToComponent } from './components/dev-click-to-component.tsx'
const isBareIframe =
const hideDevOverlay =
typeof window !== 'undefined' &&
(window.location.search.includes('bare=1') ||
window.location.search.includes('embed=1'));
window.location.search.includes('embed=1') ||
Boolean(window.HabibApp || window.FlutterChannel));
createRoot(document.getElementById('root')!).render(
<StrictMode>
<App />
{import.meta.env.DEV && !isBareIframe && <DevClickToComponent />}
{import.meta.env.DEV && !hideDevOverlay && <DevClickToComponent />}
</StrictMode>,
)

548
src/pages/account/LanguageSettingPage.tsx

@ -1,8 +1,19 @@
import React from 'react';
import { useNavigate } from 'react-router-dom';
import React, { useMemo, useState } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
import { MobileShell } from '../../components/layout/MobileShell';
import { AccountMenuRow } from '../../components/account/AccountMenuRow';
import { EmptyStateBox } from '../../components/common/ShimmerSkeletons';
import type { AccountMenuRowItem } from '../../data/accountData';
import { useShopApp } from '../../context/ShopAppContext';
import { useHardwareBackHandler } from '../../hooks/use-hardware-back-handler';
import { useSmartBack } from '../../hooks/useSmartBack';
import { resolveMediaUrl } from '../../lib/http';
import { isBareMode, ROUTES, USE_MOCK_DATA } from '../../lib/routes';
import {
buyHabibCoinPackages,
isInFlutterWebView,
openExternalUrl,
} from '../../lib/webview-actions';
const LANGUAGE_SETTING_MENU_ROWS: AccountMenuRowItem[] = [
{
@ -87,11 +98,147 @@ const LANGUAGE_SETTING_MENU_ROWS: AccountMenuRowItem[] = [
},
];
const LANGUAGE_OPTIONS = [
{ code: 'en', title: 'English', nativeLabel: 'English (US / Global)' },
{ code: 'fa', title: 'فارسی', nativeLabel: 'Persian (ایران)' },
{ code: 'ar', title: 'العربية', nativeLabel: 'Arabic (العراق / الخليج)' },
] as const;
/**
* Node 4214:11018 — `language-setting` (Language Setting & Provider Status, 375×813)
*/
export const LanguageSettingPage: React.FC = () => {
const navigate = useNavigate();
const location = useLocation();
const bare = isBareMode(location.search);
const useMockFallback = bare || USE_MOCK_DATA;
const smartBack = useSmartBack(ROUTES.account);
const {
profile,
selectedAddress,
orderCounters,
habibCoinsBalance,
setHabibCoinsBalance,
language,
changeLanguage,
showToast,
} = useShopApp();
const [langSheetOpen, setLangSheetOpen] = useState(false);
useHardwareBackHandler(() => {
setLangSheetOpen(false);
return true;
}, langSheetOpen);
const displayName = bare
? 'Ahd Art'
: profile?.full_name || (useMockFallback ? 'Ahd Art' : 'Guest');
const displayEmail = bare
? 'Ahdart14@gmail.com'
: profile?.email || (useMockFallback ? 'Ahdart14@gmail.com' : '');
const avatarSrc =
!bare && profile?.avatar_url
? resolveMediaUrl(profile.avatar_url)
: useMockFallback
? '/assets/images/avatar-provider-ahd-art.png'
: '/assets/images/icon-account-avatar-gold.svg';
const providerRows = useMemo(() => {
if (bare || !profile?.provider_requests?.length) {
return useMockFallback
? [
{
id: 'default-meet',
label: 'Provider request on Habib Meet',
statusText: 'Pending',
isRejected: false,
isApproved: false,
},
{
id: 'default-talk',
label: 'Provider request on Habib Talk',
statusText: 'rejected',
isRejected: true,
isApproved: false,
},
]
: [];
}
return profile.provider_requests.map((req) => {
const normalized = (req.status || '').toLowerCase();
const isRejected = normalized.includes('reject') || normalized.includes('deni');
const isApproved = normalized.includes('accept') || normalized.includes('approv');
const serviceLabel =
req.service === 'shop'
? `Habib Shop (${req.public_name || 'Booth'})`
: `Habib ${req.service.charAt(0).toUpperCase()}${req.service.slice(1)}`;
return {
id: `req-${req.id}`,
label: `Provider request on ${serviceLabel}`,
statusText: isApproved ? 'Approved' : isRejected ? 'rejected' : 'Pending',
isRejected,
isApproved,
};
});
}, [bare, profile, useMockFallback]);
const menuRows = useMemo<AccountMenuRowItem[]>(() => {
if (bare) return LANGUAGE_SETTING_MENU_ROWS;
const langLabel =
language === 'fa' ? 'فارسی' : language === 'ar' ? 'العربية' : 'English';
const activeOrders = orderCounters?.in_progress ?? 0;
return LANGUAGE_SETTING_MENU_ROWS.map((row) => {
if (row.id === 'lang-location') {
return {
...row,
subtitle:
selectedAddress?.city || (useMockFallback ? row.subtitle : 'Not set'),
targetRoute: ROUTES.addresses,
};
}
if (row.id === 'lang-language') {
return {
...row,
subtitle: langLabel,
rightIconType: 'edit-path',
targetRoute: '',
};
}
if (row.id === 'lang-notifications') {
return {
...row,
badgeCount: activeOrders > 0 ? String(activeOrders) : undefined,
targetRoute: ROUTES.orders('current'),
};
}
if (row.id === 'lang-notes') {
return {
...row,
targetRoute: ROUTES.bookmarks,
};
}
return {
...row,
targetRoute: ROUTES.account,
};
});
}, [bare, language, orderCounters, selectedAddress, useMockFallback]);
const handleBuyCoins = async () => {
if (bare) return;
if (isInFlutterWebView()) {
const updated = await buyHabibCoinPackages();
if (typeof updated === 'number') {
setHabibCoinsBalance(updated);
showToast(`Balance updated: ${updated} Habib Coins`);
}
return;
}
showToast('Open Habib Shop inside the Habib mobile app to purchase coins');
};
return (
<MobileShell width={375} height={813} backgroundColor="#f5f5f5">
@ -123,7 +270,7 @@ export const LanguageSettingPage: React.FC = () => {
{/* Top Left Back Button */}
<button
type="button"
onClick={() => navigate('/shop-account')}
onClick={() => (bare ? navigate('/shop-account') : smartBack(ROUTES.account))}
aria-label="Back"
style={{
width: 40,
@ -151,8 +298,8 @@ export const LanguageSettingPage: React.FC = () => {
{/* Top Center Avatar */}
<img
src="/assets/images/avatar-provider-ahd-art.png"
alt="Ahd Art"
src={avatarSrc}
alt={displayName}
style={{
marginTop: 5,
width: 84,
@ -163,11 +310,11 @@ export const LanguageSettingPage: React.FC = () => {
}}
/>
{/* Top Right Logout Button */}
{/* Top Right Profile Edit Button */}
<button
type="button"
onClick={() => navigate('/shop-account')}
aria-label="Logout"
onClick={() => navigate(bare ? '/shop-account' : ROUTES.profile)}
aria-label="Edit Profile"
style={{
width: 40,
height: 40,
@ -205,7 +352,7 @@ export const LanguageSettingPage: React.FC = () => {
textAlign: 'center',
}}
>
Ahd Art
{displayName}
</div>
{/* Email "Ahdart14@gmail.com" */}
@ -220,172 +367,119 @@ export const LanguageSettingPage: React.FC = () => {
textAlign: 'center',
}}
>
Ahdart14@gmail.com
{displayEmail}
</div>
</div>
{/* Provider Requests Card (4214:11186) */}
<div
style={{
width: '100%',
padding: '11px 12px',
borderRadius: 15,
backgroundColor: '#ebebeb',
display: 'flex',
flexDirection: 'column',
gap: 20,
}}
>
{/* Row 1: Provider request on Habib Meet -> Pending */}
{providerRows.length > 0 ? (
<div
style={{
width: '100%',
padding: '11px 12px',
borderRadius: 15,
backgroundColor: '#ebebeb',
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
gap: 10,
flexDirection: 'column',
gap: 20,
}}
>
<div style={{ display: 'flex', alignItems: 'center', gap: 10, minWidth: 0, flex: 1 }}>
{providerRows.map((pRow) => (
<div
key={pRow.id}
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
gap: 10,
}}
>
<div
style={{
width: 34,
height: 34,
borderRadius: 11,
backgroundColor: 'rgba(17, 17, 17, 0.1)',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
flexShrink: 0,
gap: 10,
minWidth: 0,
flex: 1,
}}
>
<img
src="/assets/images/icon-menu-bookmark-subtract.svg"
alt=""
<div
style={{
width: 15,
height: 18,
width: 34,
height: 34,
borderRadius: 11,
backgroundColor: 'rgba(17, 17, 17, 0.1)',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
flexShrink: 0,
}}
/>
</div>
<div
style={{
flex: 1,
minWidth: 0,
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 14,
lineHeight: '16px',
color: '#111111',
wordBreak: 'break-word',
}}
>
Provider request on Habib Meet
>
<img
src="/assets/images/icon-menu-bookmark-subtract.svg"
alt=""
style={{
width: 15,
height: 18,
}}
/>
</div>
<div
style={{
flex: 1,
minWidth: 0,
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 14,
lineHeight: '16px',
color: '#111111',
wordBreak: 'break-word',
}}
>
{pRow.label}
</div>
</div>
</div>
<div
style={{
minWidth: 61,
height: 28,
padding: '0 8px',
borderRadius: 8,
backgroundColor: 'rgba(45, 78, 205, 0.2)',
display: 'inline-flex',
alignItems: 'center',
justifyContent: 'center',
flexShrink: 0,
}}
>
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 600,
fontSize: 12,
lineHeight: '14px',
color: '#2d4ecd',
whiteSpace: 'nowrap',
}}
>
Pending
</span>
</div>
</div>
{/* Row 2: Provider request on Habib Talk -> rejected */}
<div
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
gap: 10,
}}
>
<div style={{ display: 'flex', alignItems: 'center', gap: 10, minWidth: 0, flex: 1 }}>
<div
style={{
width: 34,
height: 34,
borderRadius: 11,
backgroundColor: 'rgba(17, 17, 17, 0.1)',
display: 'flex',
minWidth: pRow.isRejected ? 60 : 61,
height: 28,
padding: '0 8px',
borderRadius: 8,
backgroundColor: pRow.isApproved
? 'rgba(14, 177, 60, 0.2)'
: pRow.isRejected
? 'rgba(212, 71, 71, 0.2)'
: 'rgba(45, 78, 205, 0.2)',
display: 'inline-flex',
alignItems: 'center',
justifyContent: 'center',
flexShrink: 0,
}}
>
<img
src="/assets/images/icon-menu-bookmark-subtract.svg"
alt=""
<span
style={{
width: 15,
height: 18,
fontFamily: 'var(--font-sans)',
fontWeight: 600,
fontSize: 12,
lineHeight: '14px',
color: pRow.isApproved
? '#0eb13c'
: pRow.isRejected
? '#d44747'
: '#2d4ecd',
whiteSpace: 'nowrap',
}}
/>
>
{pRow.statusText}
</span>
</div>
<div
style={{
flex: 1,
minWidth: 0,
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 14,
lineHeight: '16px',
color: '#111111',
wordBreak: 'break-word',
}}
>
Provider request on Habib Talk
</div>
</div>
<div
style={{
minWidth: 60,
height: 28,
padding: '0 8px',
borderRadius: 8,
backgroundColor: 'rgba(212, 71, 71, 0.2)',
display: 'inline-flex',
alignItems: 'center',
justifyContent: 'center',
flexShrink: 0,
}}
>
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 600,
fontSize: 12,
lineHeight: '14px',
color: '#d44747',
whiteSpace: 'nowrap',
}}
>
rejected
</span>
</div>
))}
</div>
</div>
) : (
<EmptyStateBox message="No provider requests yet." compact />
)}
{/* Green Donate Card (4214:11115) */}
<div
@ -446,6 +540,11 @@ export const LanguageSettingPage: React.FC = () => {
<button
type="button"
onClick={() => {
if (!bare) {
openExternalUrl('https://habibapp.com');
}
}}
style={{
minWidth: 96,
height: 32,
@ -522,13 +621,14 @@ export const LanguageSettingPage: React.FC = () => {
color: '#151c31',
}}
>
21 Habib Coins
{bare ? '21 Habib Coins' : `${habibCoinsBalance} Habib Coins`}
</div>
</div>
</div>
<button
type="button"
onClick={handleBuyCoins}
style={{
minWidth: 96,
height: 32,
@ -560,7 +660,7 @@ export const LanguageSettingPage: React.FC = () => {
{/* "Apply as Provider" Card */}
<div
onClick={() => navigate('/provider-requst')}
onClick={() => navigate(bare ? '/provider-requst' : ROUTES.profile)}
style={{
width: '100%',
minHeight: 55,
@ -612,6 +712,11 @@ export const LanguageSettingPage: React.FC = () => {
{/* "My Wallet ($24)" / "income from Habib" Card */}
<div
onClick={() => {
if (!bare) {
navigate(ROUTES.orders('delivered'));
}
}}
style={{
width: '100%',
minHeight: 55,
@ -663,7 +768,7 @@ export const LanguageSettingPage: React.FC = () => {
color: '#111111',
}}
>
My Wallet ($24)
{useMockFallback ? 'My Wallet ($24)' : 'My Wallet ($0)'}
</div>
<div
style={{
@ -701,11 +806,156 @@ export const LanguageSettingPage: React.FC = () => {
gap: 19,
}}
>
{LANGUAGE_SETTING_MENU_ROWS.map((row) => (
<AccountMenuRow key={row.id} row={row} />
{menuRows.map((row) => (
<AccountMenuRow
key={row.id}
row={row}
onClick={
!bare && row.id === 'lang-language'
? () => setLangSheetOpen(true)
: undefined
}
/>
))}
</div>
</div>
{/* Language Picker Bottom Sheet */}
{langSheetOpen && (
<div
onClick={() => setLangSheetOpen(false)}
style={{
position: 'fixed',
inset: 0,
backgroundColor: 'rgba(17, 17, 17, 0.9)',
zIndex: 60,
display: 'flex',
flexDirection: 'column',
justifyContent: 'flex-end',
}}
>
<div
className="habib-bottom-sheet"
onClick={(e) => e.stopPropagation()}
style={{
padding: '22px var(--page-px) calc(24px + var(--safe-bottom, 0px))',
display: 'flex',
flexDirection: 'column',
gap: 12,
}}
>
<div
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
marginBottom: 4,
}}
>
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 15,
color: '#111111',
}}
>
Select Shop Language
</span>
<button
type="button"
onClick={() => setLangSheetOpen(false)}
aria-label="Close"
style={{
width: 24,
height: 24,
cursor: 'pointer',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
}}
>
<img
src="/assets/images/icon-modal-close-cross.svg"
alt=""
style={{ width: 11.67, height: 11.67 }}
/>
</button>
</div>
{LANGUAGE_OPTIONS.map((opt) => {
const active = language === opt.code;
return (
<button
key={opt.code}
type="button"
onClick={() => {
changeLanguage(opt.code);
setLangSheetOpen(false);
}}
style={{
width: '100%',
padding: '14px 16px',
borderRadius: 14,
backgroundColor: active ? 'rgba(215, 142, 6, 0.12)' : '#ffffff',
border: active ? '1.5px solid #d78e06' : '1px solid #e5e7eb',
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
cursor: 'pointer',
textAlign: 'left',
}}
>
<div style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 14,
color: '#111111',
}}
>
{opt.title}
</span>
<span
style={{
fontFamily: 'var(--font-sans)',
fontSize: 11,
color: '#73889d',
}}
>
{opt.nativeLabel}
</span>
</div>
<div
style={{
width: 20,
height: 20,
borderRadius: 10,
backgroundColor: active ? '#d78e06' : 'transparent',
border: active ? 'none' : '1px solid #cbd5e1',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
}}
>
{active && (
<div
style={{
width: 8,
height: 8,
borderRadius: '50%',
backgroundColor: '#ffffff',
}}
/>
)}
</div>
</button>
);
})}
</div>
</div>
)}
</MobileShell>
);
};

416
src/pages/account/ProviderRequestPage.tsx

@ -1,23 +1,219 @@
import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import React, { useEffect, useMemo, useState } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
import { MobileShell } from '../../components/layout/MobileShell';
import { HabibCoinsBanner } from '../../components/account/HabibCoinsBanner';
import { ProviderBadgeCard } from '../../components/account/ProviderBadgeCard';
import { AccountMenuRow } from '../../components/account/AccountMenuRow';
import { EmptyStateBox } from '../../components/common/ShimmerSkeletons';
import {
type AccountMenuRowItem,
PROVIDER_BADGE_CARDS,
PROVIDER_SETTINGS_MENU_ROWS,
type ProviderBadgeCardItem,
PROVIDER_INFO_MENU_ROWS,
PROVIDER_SETTINGS_MENU_ROWS,
} from '../../data/accountData';
import { useShopApp } from '../../context/ShopAppContext';
import { useHardwareBackHandler } from '../../hooks/use-hardware-back-handler';
import { useSmartBack } from '../../hooks/useSmartBack';
import { resolveMediaUrl } from '../../lib/http';
import { isBareMode, ROUTES, USE_MOCK_DATA } from '../../lib/routes';
import {
useApplyProviderMutation,
useUpdateProfileMutation,
} from '../../lib/shopQueries';
import { openExternalUrl } from '../../lib/webview-actions';
/**
* Node 4214:10531 — `provider requst` (Provider Request & Profile Settings, 375×1768)
*/
export const ProviderRequestPage: React.FC = () => {
const navigate = useNavigate();
const location = useLocation();
const bare = isBareMode(location.search);
const useMockFallback = bare || USE_MOCK_DATA;
const smartBack = useSmartBack(ROUTES.account);
const {
isUserAuthenticated,
requireAuth,
profile,
language,
orderCounters,
selectedAddress,
showToast,
} = useShopApp();
const updateProfileMutation = useUpdateProfileMutation();
const applyProviderMutation = useApplyProviderMutation();
const [fullName, setFullName] = useState('');
const [email, setEmail] = useState('');
const [phoneNumber, setPhoneNumber] = useState('');
const savingProfile = updateProfileMutation.isPending;
const [applyOpen, setApplyOpen] = useState(false);
const [storeName, setStoreName] = useState('');
const [storeDesc, setStoreDesc] = useState('');
const submittingProvider = applyProviderMutation.isPending;
useEffect(() => {
if (bare || !profile) return;
setFullName((prev) => prev || profile.full_name || '');
setEmail((prev) => prev || profile.email || '');
setPhoneNumber((prev) => prev || profile.phone_number || '');
}, [bare, profile]);
useHardwareBackHandler(() => {
if (!submittingProvider) setApplyOpen(false);
return true;
}, applyOpen);
const providerBadges = useMemo<ProviderBadgeCardItem[]>(() => {
if (bare || !profile?.provider_requests?.length) {
return useMockFallback ? PROVIDER_BADGE_CARDS : [];
}
const mapped = profile.provider_requests.slice(0, 4).map((req, idx): ProviderBadgeCardItem => {
const normalized = (req.status || '').toLowerCase();
const isApproved = normalized.includes('accept') || normalized.includes('approv');
const isDenied = normalized.includes('reject') || normalized.includes('deni');
const svcTitle =
req.service === 'shop'
? req.public_name || 'Habib Shop'
: req.service
? `Habib ${req.service.charAt(0).toUpperCase()}${req.service.slice(1)}`
: req.public_name || 'Habib Shop';
return {
id: `prov-live-${req.id}-${idx}`,
x: idx % 2 === 0 ? 28 : 194,
y: 532 + Math.floor(idx / 2) * 66,
width: 154,
innerLeft: 13,
innerWidth: 128,
statusText: isApproved ? 'Provider in' : isDenied ? 'Request Denied' : 'Under Review',
statusWidth: 96,
title: svcTitle,
titleWidth: 86,
gradientBg: isApproved
? 'linear-gradient(180deg, #203bcc 0%, #9961e7 100%)'
: isDenied
? 'linear-gradient(180deg, #cd4343 0%, #862222 100%)'
: 'linear-gradient(180deg, #eca533 0%, #ffd74b 100%)',
iconSrc: isApproved
? '/assets/images/icon-provider-events-calendar.svg'
: isDenied
? '/assets/images/icon-provider-maukibs-flag.svg'
: '/assets/images/icon-provider-requests-doc.svg',
iconLeft: 9,
iconTop: 12,
iconWidth: 16,
iconHeight: 16,
badgeType: isApproved ? 'approved' : isDenied ? 'denied' : 'review',
};
});
return mapped.length > 0 ? mapped : useMockFallback ? PROVIDER_BADGE_CARDS : [];
}, [bare, profile, useMockFallback]);
const settingsRows = useMemo<AccountMenuRowItem[]>(() => {
if (bare) return PROVIDER_SETTINGS_MENU_ROWS;
const langLabel =
language === 'fa' ? 'فارسی' : language === 'ar' ? 'العربية' : 'English';
const activeOrders = orderCounters?.in_progress ?? 0;
return PROVIDER_SETTINGS_MENU_ROWS.map((row) => {
if (row.id === 'prov-azan') {
return {
...row,
subtitle:
selectedAddress?.city || (useMockFallback ? row.subtitle : 'Not set'),
targetRoute: ROUTES.addresses,
};
}
if (row.id === 'prov-language') {
return {
...row,
subtitle: langLabel,
rightIconType: 'arrow-right',
targetRoute: ROUTES.settings,
};
}
if (row.id === 'prov-notifications') {
return {
...row,
badgeCount: activeOrders > 0 ? String(activeOrders) : undefined,
targetRoute: ROUTES.orders('current'),
};
}
return {
...row,
targetRoute: ROUTES.settings,
};
});
}, [bare, language, orderCounters, selectedAddress, useMockFallback]);
const infoRows = useMemo<AccountMenuRowItem[]>(() => {
if (bare) return PROVIDER_INFO_MENU_ROWS;
return PROVIDER_INFO_MENU_ROWS.map((row) => {
if (row.id === 'info-faqs') {
return { ...row, targetRoute: ROUTES.support };
}
if (row.id === 'info-about') {
return { ...row, targetRoute: ROUTES.stores };
}
return { ...row, targetRoute: '' };
});
}, [bare]);
const handleSaveProfile = async () => {
if (savingProfile) return;
if (!bare && !isUserAuthenticated) {
const authed = await requireAuth({
featureName: 'profile settings',
});
if (!authed) return;
}
try {
await updateProfileMutation.mutateAsync({
full_name: fullName.trim(),
email: email.trim(),
phone_number: phoneNumber.trim(),
});
showToast('Profile saved');
} catch (err) {
showToast(err instanceof Error ? err.message : 'Could not update profile');
}
};
const handleApplyProvider = async (e: React.FormEvent) => {
e.preventDefault();
if (!storeName.trim() || submittingProvider) return;
if (!bare && !isUserAuthenticated) {
const authed = await requireAuth({
featureName: 'provider application',
});
if (!authed) return;
}
try {
const res = await applyProviderMutation.mutateAsync({
store_name: storeName.trim(),
description: storeDesc.trim(),
});
showToast(res.message || 'Provider application submitted');
setApplyOpen(false);
setStoreName('');
setStoreDesc('');
} catch (err) {
showToast(err instanceof Error ? err.message : 'Could not submit application');
}
};
const avatarSrc =
!bare && profile?.avatar_url
? resolveMediaUrl(profile.avatar_url)
: useMockFallback
? '/assets/images/avatar-provider-ahd-art.png'
: '/assets/images/icon-account-avatar-gold.svg';
return (
<MobileShell width={375} height={1768} backgroundColor="#f5f5f5">
@ -30,7 +226,7 @@ export const ProviderRequestPage: React.FC = () => {
gap: 23,
}}
>
{/* Top Bar: Back + Center Avatar + Edit/Camera */}
{/* Top Bar: Back + Center Avatar + Edit/Settings */}
<div
style={{
display: 'flex',
@ -41,7 +237,7 @@ export const ProviderRequestPage: React.FC = () => {
>
<button
type="button"
onClick={() => navigate('/shop-account')}
onClick={() => (bare ? navigate('/shop-account') : smartBack(ROUTES.account))}
aria-label="Back"
style={{
width: 40,
@ -68,7 +264,7 @@ export const ProviderRequestPage: React.FC = () => {
</button>
<img
src="/assets/images/avatar-provider-ahd-art.png"
src={avatarSrc}
alt="Profile"
style={{
marginTop: 5,
@ -82,8 +278,8 @@ export const ProviderRequestPage: React.FC = () => {
<button
type="button"
onClick={() => navigate('/language-setting')}
aria-label="Logout"
onClick={() => navigate(bare ? '/language-setting' : ROUTES.settings)}
aria-label="Settings"
style={{
width: 40,
height: 40,
@ -267,6 +463,28 @@ export const ProviderRequestPage: React.FC = () => {
/>
</div>
</div>
{!bare && (
<button
type="button"
onClick={handleSaveProfile}
disabled={savingProfile}
className="habib-cta-btn"
style={{
width: '100%',
height: 48,
borderRadius: 11,
color: '#fbfbfc',
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 14,
cursor: savingProfile ? 'not-allowed' : 'pointer',
opacity: savingProfile ? 0.7 : 1,
}}
>
{savingProfile ? 'Saving...' : 'Save Profile'}
</button>
)}
</div>
{/* Provider Status Card (4214:10539) */}
@ -295,11 +513,15 @@ export const ProviderRequestPage: React.FC = () => {
Your are a provider in:
</div>
<div className="habib-provider-badges-grid">
{PROVIDER_BADGE_CARDS.map((badge) => (
<ProviderBadgeCard key={badge.id} badge={badge} />
))}
</div>
{providerBadges.length > 0 ? (
<div className="habib-provider-badges-grid">
{providerBadges.map((badge) => (
<ProviderBadgeCard key={badge.id} badge={badge} />
))}
</div>
) : (
<EmptyStateBox message="No active provider roles yet." compact />
)}
</div>
{/* Habib Coins Banner (4214:10558) */}
@ -307,7 +529,13 @@ export const ProviderRequestPage: React.FC = () => {
{/* "Become a provider on Habib" Card (4214:10599) */}
<div
onClick={() => navigate('/language-setting')}
onClick={() => {
if (bare) {
navigate('/language-setting');
} else {
setApplyOpen(true);
}
}}
style={{
width: '100%',
minHeight: 55,
@ -359,6 +587,11 @@ export const ProviderRequestPage: React.FC = () => {
{/* "My Wallet ($24)" Card (4214:10615) */}
<div
onClick={() => {
if (!bare) {
navigate(ROUTES.settings);
}
}}
style={{
width: '100%',
minHeight: 55,
@ -410,7 +643,7 @@ export const ProviderRequestPage: React.FC = () => {
color: '#111111',
}}
>
My Wallet ($24)
{useMockFallback ? 'My Wallet ($24)' : 'My Wallet ($0)'}
</div>
<div
style={{
@ -448,7 +681,7 @@ export const ProviderRequestPage: React.FC = () => {
gap: 19,
}}
>
{PROVIDER_SETTINGS_MENU_ROWS.map((row) => (
{settingsRows.map((row) => (
<AccountMenuRow key={row.id} row={row} />
))}
</div>
@ -466,13 +699,27 @@ export const ProviderRequestPage: React.FC = () => {
gap: 19,
}}
>
{PROVIDER_INFO_MENU_ROWS.map((row) => (
<AccountMenuRow key={row.id} row={row} />
{infoRows.map((row) => (
<AccountMenuRow
key={row.id}
row={row}
onClick={
!bare && row.id === 'info-web'
? () => openExternalUrl('https://habibapp.com')
: undefined
}
/>
))}
</div>
{/* Delete Account Card (4214:10703) */}
<div
onClick={() => {
if (!bare) {
navigate(ROUTES.support);
showToast('Submit an account deletion request to Habib Support');
}
}}
style={{
width: '100%',
minHeight: 55,
@ -575,6 +822,9 @@ export const ProviderRequestPage: React.FC = () => {
<img
src="/assets/images/icon-social-instagram.svg"
alt="Instagram"
onClick={() => {
if (!bare) openExternalUrl('https://habibapp.com');
}}
style={{
width: 32,
height: 31,
@ -584,6 +834,9 @@ export const ProviderRequestPage: React.FC = () => {
<img
src="/assets/images/icon-social-telegram.svg"
alt="Telegram"
onClick={() => {
if (!bare) openExternalUrl('https://habibapp.com');
}}
style={{
width: 32,
height: 31,
@ -593,6 +846,9 @@ export const ProviderRequestPage: React.FC = () => {
<img
src="/assets/images/icon-social-youtube.svg"
alt="WhatsApp"
onClick={() => {
if (!bare) openExternalUrl('https://habibapp.com');
}}
style={{
width: 30.25,
height: 30.28,
@ -602,6 +858,130 @@ export const ProviderRequestPage: React.FC = () => {
</div>
</div>
</div>
{/* Provider Application Bottom Sheet */}
{applyOpen && (
<div
onClick={() => {
if (!submittingProvider) setApplyOpen(false);
}}
style={{
position: 'fixed',
inset: 0,
backgroundColor: 'rgba(17, 17, 17, 0.9)',
zIndex: 60,
display: 'flex',
flexDirection: 'column',
justifyContent: 'flex-end',
}}
>
<form
className="habib-bottom-sheet"
onClick={(e) => e.stopPropagation()}
onSubmit={handleApplyProvider}
style={{
padding: '22px var(--page-px) calc(24px + var(--safe-bottom, 0px))',
display: 'flex',
flexDirection: 'column',
gap: 14,
}}
>
<div
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
}}
>
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 15,
color: '#111111',
}}
>
Open a Habib Shop Booth
</span>
<button
type="button"
onClick={() => setApplyOpen(false)}
aria-label="Close"
style={{
width: 24,
height: 24,
cursor: 'pointer',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
}}
>
<img
src="/assets/images/icon-modal-close-cross.svg"
alt=""
style={{ width: 11.67, height: 11.67 }}
/>
</button>
</div>
<input
type="text"
required
placeholder="Store / Booth public name *"
value={storeName}
onChange={(e) => setStoreName(e.target.value)}
style={{
width: '100%',
height: 46,
borderRadius: 12,
backgroundColor: '#ffffff',
border: '1px solid #d7dbe2',
padding: '0 12px',
fontFamily: 'var(--font-sans)',
fontSize: 13,
color: '#111111',
}}
/>
<textarea
rows={3}
placeholder="Tell us about your products, craftsmanship, or bookstore"
value={storeDesc}
onChange={(e) => setStoreDesc(e.target.value)}
style={{
width: '100%',
borderRadius: 12,
backgroundColor: '#ffffff',
border: '1px solid #d7dbe2',
padding: '10px 12px',
fontFamily: 'var(--font-sans)',
fontSize: 13,
color: '#111111',
resize: 'none',
}}
/>
<button
type="submit"
disabled={submittingProvider || !storeName.trim()}
className="habib-cta-btn"
style={{
width: '100%',
height: 50,
borderRadius: 11,
color: '#fbfbfc',
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 15,
cursor: submittingProvider ? 'not-allowed' : 'pointer',
opacity: submittingProvider || !storeName.trim() ? 0.65 : 1,
}}
>
{submittingProvider ? 'Submitting...' : 'Submit Provider Request'}
</button>
</form>
</div>
)}
</MobileShell>
);
};

373
src/pages/account/ShopAccountPage.tsx

@ -1,19 +1,173 @@
import React from 'react';
import { useNavigate } from 'react-router-dom';
import React, { useMemo } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
import { MobileShell } from '../../components/layout/MobileShell';
import { BottomNavBar } from '../../components/layout/BottomNavBar';
import { OrderCounterCard } from '../../components/account/OrderCounterCard';
import { AccountMenuRow } from '../../components/account/AccountMenuRow';
import {
ACCOUNT_ORDER_COUNTERS,
type AccountMenuRowItem,
SHOP_ACCOUNT_MENU_ROWS,
} from '../../data/accountData';
import { useShopApp } from '../../context/ShopAppContext';
import { resolveMediaUrl } from '../../lib/http';
import { isBareMode, ROUTES, USE_MOCK_DATA } from '../../lib/routes';
/**
* Node 4214:345 — `shop-category` (Shop Account Overview, 375×814)
*/
export const ShopAccountPage: React.FC = () => {
const navigate = useNavigate();
const location = useLocation();
const bare = isBareMode(location.search);
const useMockFallback = bare || USE_MOCK_DATA;
const {
isUserAuthenticated,
openLoginModal,
requireAuth,
profile,
orderCounters,
selectedAddress,
language,
bookmarkedProducts,
cartItemsCount,
} = useShopApp();
const counters = useMemo(() => {
if (bare || (!orderCounters && useMockFallback)) return ACCOUNT_ORDER_COUNTERS;
if (!isUserAuthenticated) {
return [
{ ...ACCOUNT_ORDER_COUNTERS[0], countText: '0 Orders' },
{ ...ACCOUNT_ORDER_COUNTERS[1], countText: '0 Orders' },
{ ...ACCOUNT_ORDER_COUNTERS[2], countText: '0 Orders' },
];
}
return [
{
...ACCOUNT_ORDER_COUNTERS[0],
countText: `${orderCounters?.in_progress ?? 0} Orders`,
},
{
...ACCOUNT_ORDER_COUNTERS[1],
countText: `${orderCounters?.delivered ?? 0} Orders`,
},
{
...ACCOUNT_ORDER_COUNTERS[2],
countText: `${orderCounters?.returned ?? 0} Orders`,
},
];
}, [bare, isUserAuthenticated, orderCounters, useMockFallback]);
const menuRows = useMemo<AccountMenuRowItem[]>(() => {
if (bare) return SHOP_ACCOUNT_MENU_ROWS;
const langLabel =
language === 'fa' ? 'فارسی' : language === 'ar' ? 'العربية' : 'English';
const mapped = SHOP_ACCOUNT_MENU_ROWS.map((row): AccountMenuRowItem => {
if (row.id === 'acc-addresses') {
return {
...row,
subtitle: isUserAuthenticated
? selectedAddress?.full_address ||
(useMockFallback ? row.subtitle : 'No saved address')
: 'Sign in to manage addresses',
targetRoute: ROUTES.addresses,
};
}
if (row.id === 'acc-language') {
return {
...row,
subtitle: langLabel,
rightIconType: 'arrow-right',
targetRoute: ROUTES.settings,
};
}
if (row.id === 'acc-notifications') {
const activeCount = isUserAuthenticated
? orderCounters?.in_progress ?? 0
: 0;
return {
...row,
badgeCount: activeCount > 0 ? String(activeCount) : undefined,
targetRoute: ROUTES.orders('current'),
};
}
if (row.id === 'acc-support') {
return {
...row,
targetRoute: ROUTES.support,
};
}
if (row.id === 'acc-faq') {
return {
...row,
targetRoute: ROUTES.profile,
};
}
return row;
});
const bookmarksRow: AccountMenuRowItem = {
id: 'acc-bookmarks',
y: 250,
title: 'Saved Items',
titleWidth: 110,
titleColor: '#151c31',
subtitle: isUserAuthenticated
? `${bookmarkedProducts.length} bookmarked products`
: 'Sign in to view saved items',
subtitleWidth: 180,
iconBoxBg: 'rgba(215, 142, 6, 0.14)',
iconSrc: '/assets/images/icon-menu-bookmark-subtract.svg',
iconLeft: 10,
iconTop: 8,
iconWidth: 14,
iconHeight: 18,
rightIconType: 'arrow-right',
targetRoute: ROUTES.bookmarks,
};
return [mapped[0], bookmarksRow, ...mapped.slice(1)];
}, [
bare,
bookmarkedProducts.length,
isUserAuthenticated,
language,
orderCounters,
selectedAddress,
useMockFallback,
]);
const displayName = bare
? 'Habib shoper'
: isUserAuthenticated
? profile?.full_name || 'Habib Shopper'
: useMockFallback
? 'Habib shoper'
: 'Guest';
const displaySub = bare
? '09102036523'
: isUserAuthenticated
? profile?.phone_number || profile?.email || 'Verified Habib Account'
: useMockFallback
? '09102036523'
: 'Sign in with your Habib account';
const avatarUrl =
!bare && isUserAuthenticated && profile?.avatar_url
? resolveMediaUrl(profile.avatar_url)
: '';
const handleProtectedNavigate = (targetRoute: string, featureName: string) => {
if (bare) {
navigate(targetRoute);
return;
}
void requireAuth({
featureName,
onAuthenticated: () => navigate(targetRoute),
});
};
return (
<MobileShell width={375} height={814} backgroundColor="#f3f1ef">
@ -38,7 +192,12 @@ export const ShopAccountPage: React.FC = () => {
{/* Right Edit Profile Button (4214:11436) */}
<button
type="button"
onClick={() => navigate('/provider-requst')}
onClick={() =>
handleProtectedNavigate(
bare ? '/provider-requst' : ROUTES.profile,
'your profile settings'
)
}
aria-label="Edit Profile"
style={{
position: 'absolute',
@ -76,16 +235,29 @@ export const ShopAccountPage: React.FC = () => {
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
overflow: 'hidden',
}}
>
<img
src="/assets/images/icon-account-avatar-gold.svg"
alt="Habib shoper"
style={{
width: 31,
height: 33.04,
}}
/>
{avatarUrl ? (
<img
src={avatarUrl}
alt={displayName}
style={{
width: '100%',
height: '100%',
objectFit: 'cover',
}}
/>
) : (
<img
src="/assets/images/icon-account-avatar-gold.svg"
alt={displayName}
style={{
width: 31,
height: 33.04,
}}
/>
)}
</div>
{/* User Name "Habib shoper" (4214:366) */}
@ -100,7 +272,7 @@ export const ShopAccountPage: React.FC = () => {
textAlign: 'center',
}}
>
Habib shoper
{displayName}
</div>
{/* Phone "09102036523" (4214:367) */}
@ -115,18 +287,34 @@ export const ShopAccountPage: React.FC = () => {
textAlign: 'center',
}}
>
09102036523
{displaySub}
</div>
</div>
{/* 3 Order Status Counter Cards (4215:11563) */}
<div className="habib-counters-grid" style={{ marginBottom: 24 }}>
{ACCOUNT_ORDER_COUNTERS.map((counter) => (
<OrderCounterCard key={counter.id} counter={counter} />
{counters.map((counter) => (
<OrderCounterCard
key={counter.id}
counter={counter}
onClick={() => {
if (bare) {
navigate('/shop-orders');
return;
}
const target =
counter.id === 'cnt-delivered'
? ROUTES.orders('delivered')
: counter.id === 'cnt-returned'
? ROUTES.orders('canceled')
: ROUTES.orders('current');
handleProtectedNavigate(target, 'your orders');
}}
/>
))}
</div>
{/* White Menu Card (4214:364) with 5 Account Menu Rows */}
{/* White Menu Card (4214:364) with Account Menu Rows */}
<div
style={{
width: '100%',
@ -140,84 +328,127 @@ export const ShopAccountPage: React.FC = () => {
marginBottom: 15,
}}
>
{SHOP_ACCOUNT_MENU_ROWS.map((row) => (
<AccountMenuRow key={row.id} row={row} />
{menuRows.map((row) => (
<AccountMenuRow
key={row.id}
row={row}
onClick={() => {
if (bare || row.id === 'acc-language') {
if (row.targetRoute) navigate(row.targetRoute);
return;
}
const labelMap: Record<string, string> = {
'acc-addresses': 'your saved addresses',
'acc-bookmarks': 'your saved items',
'acc-notifications': 'order notifications',
'acc-support': 'support requests',
'acc-faq': 'provider & account settings',
};
if (row.targetRoute) {
handleProtectedNavigate(
row.targetRoute,
labelMap[row.id] || row.title.toLowerCase()
);
}
}}
/>
))}
</div>
{/* Sign Out Card (4214:464) */}
<div
onClick={() => navigate('/shop-home')}
style={{
width: '100%',
minHeight: 55,
padding: '10px 13px',
borderRadius: 15,
backgroundColor: '#ffffff',
cursor: 'pointer',
display: 'flex',
alignItems: 'center',
gap: 10,
}}
>
{/* Sign In Prompt Card when no authentication is provided by HabibApp (4214:464) */}
{(bare || !isUserAuthenticated) && (
<div
style={{
width: 34,
height: 34,
borderRadius: 11,
backgroundColor: 'rgba(17, 17, 17, 0.1)',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
flexShrink: 0,
onClick={() => {
if (bare) {
navigate('/shop-home');
return;
}
openLoginModal({
title: 'Sign in with Habib',
description:
'Log in with your Habib account to access orders, saved items, addresses, and checkout.',
});
}}
>
<img
src="/assets/images/icon-exit-booth-red.svg"
alt=""
style={{
width: 19,
height: 19,
}}
/>
</div>
<div
style={{
flex: 1,
minWidth: 0,
width: '100%',
minHeight: 55,
padding: '10px 13px',
borderRadius: 15,
backgroundColor: '#ffffff',
cursor: 'pointer',
display: 'flex',
flexDirection: 'column',
gap: 2,
alignItems: 'center',
gap: 10,
}}
>
<div
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 600,
fontSize: 14,
lineHeight: '16px',
color: '#d44747',
width: 34,
height: 34,
borderRadius: 11,
backgroundColor: bare
? 'rgba(17, 17, 17, 0.1)'
: 'rgba(215, 142, 6, 0.14)',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
flexShrink: 0,
}}
>
Sign out
<img
src={
bare
? '/assets/images/icon-exit-booth-red.svg'
: '/assets/images/icon-account-avatar-gold.svg'
}
alt=""
style={{
width: 19,
height: 19,
}}
/>
</div>
<div
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 600,
fontSize: 10,
lineHeight: '12.9px',
color: '#8b8b8b',
flex: 1,
minWidth: 0,
display: 'flex',
flexDirection: 'column',
gap: 2,
}}
>
sign out from account
<div
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 600,
fontSize: 14,
lineHeight: '16px',
color: bare ? '#d44747' : '#d78e06',
}}
>
{bare ? 'Sign out' : 'Log in with Habib'}
</div>
<div
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 600,
fontSize: 10,
lineHeight: '12.9px',
color: '#8b8b8b',
}}
>
{bare ? 'sign out from account' : 'connect your Habib account'}
</div>
</div>
</div>
</div>
)}
</div>
{/* Bottom Navigation Bar (4214:470) */}
<BottomNavBar activeTab="account" showCartBadge={true} />
<BottomNavBar
activeTab="account"
showCartBadge={bare ? true : cartItemsCount > 0}
/>
</MobileShell>
);
};

95
src/pages/account/ShopAddressPage.tsx

@ -1,21 +1,40 @@
import React, { useState } from 'react';
import { useLocation } from 'react-router-dom';
import { MobileShell } from '../../components/layout/MobileShell';
import { StandardPageHeader } from '../../components/layout/TopHeader';
import {
AddressCard,
AddNewAddressCard,
} from '../../components/checkout/AddressCard';
import { AddressFormSheet } from '../../components/modals/AddressFormSheet';
import { BUY01_ADDRESSES } from '../../data/checkoutData';
import { useShopApp } from '../../context/ShopAppContext';
import { mapAddressToOption } from '../../lib/mappers';
import { isBareMode, ROUTES } from '../../lib/routes';
import type { ApiAddress } from '../../lib/shopApi';
/**
* Node 4182:13316 — `shop-adreess` (My Addresses, 375×814)
*/
export const ShopAddressPage: React.FC = () => {
const [selectedId, setSelectedId] = useState('addr-1');
const location = useLocation();
const bare = isBareMode(location.search);
const addresses = BUY01_ADDRESSES.map((addr) => ({
const {
addresses: apiAddresses,
selectedAddressId,
selectAddress,
saveAddress,
deleteAddress,
} = useShopApp();
const [bareSelectedId, setBareSelectedId] = useState('addr-1');
const [sheetOpen, setSheetOpen] = useState(false);
const [editingAddress, setEditingAddress] = useState<ApiAddress | null>(null);
const bareAddresses = BUY01_ADDRESSES.map((addr) => ({
...addr,
selected: addr.id === selectedId,
selected: addr.id === bareSelectedId,
}));
return (
@ -24,7 +43,7 @@ export const ShopAddressPage: React.FC = () => {
<StandardPageHeader
title="My Adresses"
titleTop={29}
backTo="/shop-account"
backTo={bare ? '/shop-account' : ROUTES.account}
/>
<div
@ -44,19 +63,69 @@ export const ShopAddressPage: React.FC = () => {
gap: 10,
}}
>
{addresses.map((address) => (
<AddressCard
key={address.id}
item={address}
variant="manage"
onSelect={() => setSelectedId(address.id)}
/>
))}
{bare ? (
bareAddresses.map((address) => (
<AddressCard
key={address.id}
item={address}
variant="manage"
onSelect={() => setBareSelectedId(address.id)}
/>
))
) : apiAddresses.length > 0 ? (
apiAddresses.map((addr, index) => (
<AddressCard
key={addr.id}
item={mapAddressToOption(addr, selectedAddressId, index)}
variant="manage"
onSelect={() => selectAddress(addr.id)}
onEdit={() => {
setEditingAddress(addr);
setSheetOpen(true);
}}
onDelete={() => {
void deleteAddress(addr.id);
}}
/>
))
) : (
<div
style={{
padding: '22px 16px',
borderRadius: 15,
backgroundColor: '#ffffff',
textAlign: 'center',
fontFamily: 'var(--font-sans)',
fontSize: 13,
color: '#73889d',
}}
>
No saved delivery addresses yet. Tap below to add your first address.
</div>
)}
</div>
{/* Add New Address Card (4182:13457) */}
<AddNewAddressCard />
<AddNewAddressCard
onClick={
bare
? undefined
: () => {
setEditingAddress(null);
setSheetOpen(true);
}
}
/>
</div>
{!bare && (
<AddressFormSheet
isOpen={sheetOpen}
onClose={() => setSheetOpen(false)}
initialAddress={editingAddress}
onSave={saveAddress}
/>
)}
</MobileShell>
);
};

806
src/pages/catalog/ShopBoothPage.tsx

@ -1,27 +1,52 @@
import React, { useEffect, useRef, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import React from 'react';
import { useLocation, useNavigate, useParams } from 'react-router-dom';
import { MobileShell } from '../../components/layout/MobileShell';
import { GridProductCard } from '../../components/common/GridProductCard';
import {
EmptyStateBox,
RetryBanner,
ShimmerBox,
StoreBoothBodyShimmer,
} from '../../components/common/ShimmerSkeletons';
import { TWO_COLUMN_GRID_PRODUCTS } from '../../data/catalogData';
import { useShopApp } from '../../context/ShopAppContext';
import { useSmartBack } from '../../hooks/useSmartBack';
import { resolveMediaUrl } from '../../lib/http';
import { mapProductToGridItem } from '../../lib/mappers';
import { isBareMode, ROUTES, USE_MOCK_DATA } from '../../lib/routes';
import { useStoreDetailQuery } from '../../lib/shopQueries';
import { copyToClipboard } from '../../lib/webview-actions';
/**
* Node 4129:15733 — `shop-Booth` (375×1233)
*/
export const ShopBoothPage: React.FC = () => {
const navigate = useNavigate();
const [copied, setCopied] = useState(false);
const copyTimerRef = useRef<number | undefined>(undefined);
const location = useLocation();
const isBare = isBareMode(location.search);
const useMockFallback = isBare || USE_MOCK_DATA;
const { storeId } = useParams<{ storeId?: string }>();
const smartBack = useSmartBack(ROUTES.home);
const { requireAuth, isBookmarked, toggleBookmark, showToast } = useShopApp();
useEffect(() => () => window.clearTimeout(copyTimerRef.current), []);
const resolvedSlug = storeId || 'tashakol-farzandan-rohhallah';
const storeQuery = useStoreDetailQuery(resolvedSlug, !isBare);
const store = storeQuery.data ?? null;
const loading =
!isBare && (storeQuery.isPending || (!store && storeQuery.isFetching));
const loadError = !isBare && storeQuery.isError;
const liveStore = !isBare ? store : null;
const handleShare = async () => {
const url = window.location.href;
const shareData: ShareData = {
title: 'TashakolFarzandan Rohhallah',
title: liveStore?.name || 'TashakolFarzandan Rohhallah',
url,
};
if (
typeof navigator !== 'undefined' &&
typeof navigator.share === 'function' &&
(!navigator.canShare || navigator.canShare(shareData))
) {
@ -38,39 +63,8 @@ export const ShopBoothPage: React.FC = () => {
}
}
let didCopy = false;
if (navigator.clipboard?.writeText) {
try {
await navigator.clipboard.writeText(url);
didCopy = true;
} catch {
// Fall through to legacy copy for non-secure contexts
}
}
if (!didCopy) {
const textarea = document.createElement('textarea');
textarea.value = url;
textarea.setAttribute('readonly', '');
textarea.style.position = 'fixed';
textarea.style.opacity = '0';
document.body.appendChild(textarea);
textarea.select();
try {
didCopy = document.execCommand('copy');
} catch {
didCopy = false;
}
document.body.removeChild(textarea);
}
if (didCopy) {
setCopied(true);
window.clearTimeout(copyTimerRef.current);
copyTimerRef.current = window.setTimeout(() => setCopied(false), 2000);
} else {
window.prompt('Share link:', url);
}
const didCopy = await copyToClipboard(url);
showToast(didCopy ? 'Store link copied' : 'Could not copy link');
};
return (
@ -85,22 +79,29 @@ export const ShopBoothPage: React.FC = () => {
flexShrink: 0,
}}
>
<img
src="/assets/images/bg-booth-calligraphy-header.png"
alt=""
style={{
width: '100%',
height: '100%',
objectFit: 'cover',
display: 'block',
pointerEvents: 'none',
}}
/>
{!isBare && loading ? (
<ShimmerBox width="100%" height="100%" borderRadius={0} />
) : (
<img
src={
resolveMediaUrl(liveStore?.banner_url) ||
'/assets/images/bg-booth-calligraphy-header.png'
}
alt=""
style={{
width: '100%',
height: '100%',
objectFit: 'cover',
display: 'block',
pointerEvents: 'none',
}}
/>
)}
<div
style={{
position: 'absolute',
top: 35,
top: 'calc(35px + var(--safe-top, 0px))',
left: 'var(--page-px)',
right: 'var(--page-px)',
display: 'flex',
@ -110,7 +111,7 @@ export const ShopBoothPage: React.FC = () => {
>
<button
type="button"
onClick={() => navigate('/shop-home')}
onClick={() => smartBack(ROUTES.home)}
aria-label="Back"
style={{
width: 40,
@ -168,7 +169,7 @@ export const ShopBoothPage: React.FC = () => {
/>
<button
type="button"
onClick={() => navigate('/shop-cart')}
onClick={() => navigate(ROUTES.cart)}
aria-label="Cart"
style={{
position: 'absolute',
@ -187,425 +188,474 @@ export const ShopBoothPage: React.FC = () => {
</div>
</div>
{/* Store Profile & Products Body */}
<div
style={{
position: 'relative',
zIndex: 1,
marginTop: -97,
flex: 1,
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
padding: '0 var(--page-px) 32px',
}}
>
{/* Circular Store Avatar */}
<img
src="/assets/images/avatar-tashakol-booth.png"
alt="TashakolFarzandan Rohhallah"
style={{
width: 64,
height: 64,
borderRadius: 32,
border: '1px solid #ffffff',
objectFit: 'cover',
boxSizing: 'border-box',
}}
/>
{/* Store Title */}
<h1
{!isBare && loading ? (
<StoreBoothBodyShimmer />
) : !liveStore && !useMockFallback ? (
<div
style={{
marginTop: 12,
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 16,
lineHeight: '20px',
color: '#151c31',
textAlign: 'center',
width: '100%',
flex: 1,
display: 'flex',
flexDirection: 'column',
gap: 14,
padding: '24px var(--page-px) 32px',
}}
>
TashakolFarzandan Rohhallah
</h1>
{/* Iran Flag + "Iran | Tehran" */}
{loadError && (
<RetryBanner
message="Could not load store booth details. Tap Retry to refresh."
onRetry={() => void storeQuery.refetch()}
/>
)}
<EmptyStateBox message="Store booth not found." />
</div>
) : (
<div
style={{
marginTop: 6,
display: 'inline-flex',
position: 'relative',
zIndex: 1,
marginTop: -97,
flex: 1,
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
gap: 4,
padding: '0 var(--page-px) 32px',
}}
>
{/* Circular Store Avatar */}
<img
src="/assets/images/icon-flag-iran-19.svg"
alt="Iran"
src={
resolveMediaUrl(liveStore?.logo_url) ||
'/assets/images/avatar-tashakol-booth.png'
}
alt={liveStore?.name || 'TashakolFarzandan Rohhallah'}
style={{
width: 19,
height: 19,
width: 64,
height: 64,
borderRadius: 32,
border: '1px solid #ffffff',
objectFit: 'cover',
boxSizing: 'border-box',
}}
/>
<span
{/* Store Title */}
<h1
style={{
marginTop: 12,
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 12,
lineHeight: '17px',
color: '#8b8b8b',
whiteSpace: 'nowrap',
fontSize: 16,
lineHeight: '20px',
color: '#151c31',
textAlign: 'center',
width: '100%',
}}
>
Iran | Tehran
</span>
</div>
{liveStore?.name || 'TashakolFarzandan Rohhallah'}
</h1>
{/* Store Stats Row */}
<div
style={{
marginTop: 12,
width: '100%',
maxWidth: 460,
minHeight: 31,
display: 'flex',
alignItems: 'center',
justifyContent: 'space-around',
gap: 6,
}}
>
<div style={{ display: 'inline-flex', alignItems: 'center', gap: 3 }}>
{/* Iran Flag + Origin */}
<div
style={{
marginTop: 6,
display: 'inline-flex',
alignItems: 'center',
gap: 4,
}}
>
<img
src="/assets/images/icon-star-rating-16.svg"
alt=""
src="/assets/images/icon-flag-iran-19.svg"
alt="Origin"
style={{
width: 16,
height: 15,
flexShrink: 0,
width: 19,
height: 19,
}}
/>
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 600,
fontSize: 10,
lineHeight: '12.9px',
color: '#747474',
fontWeight: 700,
fontSize: 12,
lineHeight: '17px',
color: '#8b8b8b',
whiteSpace: 'nowrap',
}}
>
4.4 (608)
{liveStore
? [liveStore.country, liveStore.city].filter(Boolean).join(' | ')
: 'Iran | Tehran'}
</span>
</div>
<div
style={{
width: 1,
height: 12,
backgroundColor: '#d7dbe2',
flexShrink: 0,
}}
/>
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 600,
fontSize: 10,
lineHeight: '12.9px',
color: '#747474',
textAlign: 'center',
whiteSpace: 'nowrap',
}}
>
+1 year membership
</span>
<div
style={{
width: 1,
height: 12,
backgroundColor: '#d7dbe2',
flexShrink: 0,
}}
/>
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 600,
fontSize: 10,
lineHeight: '12.9px',
color: '#747474',
textAlign: 'center',
whiteSpace: 'nowrap',
}}
>
+60 sales
</span>
</div>
{!isBare && loadError && !store && (
<div style={{ width: '100%', marginTop: 14 }}>
<RetryBanner
message="Could not load store booth details. Tap Retry to refresh."
onRetry={() => void storeQuery.refetch()}
/>
</div>
)}
{/* 3 Store Metric Cards */}
<div className="habib-booth-metrics-grid" style={{ marginTop: 21 }}>
{/* Card 1: 2h Avg. Response */}
{/* Store Stats Row */}
<div
onClick={() => navigate('/shop-chat')}
style={{
minHeight: 58,
padding: '8px',
borderRadius: 8,
backgroundColor: '#efece9',
border: '1px solid #e8e4df',
cursor: 'pointer',
marginTop: 12,
width: '100%',
maxWidth: 460,
minHeight: 31,
display: 'flex',
flexDirection: 'column',
justifyContent: 'space-between',
minWidth: 0,
alignItems: 'center',
justifyContent: 'space-around',
gap: 6,
}}
>
<div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
<div style={{ display: 'inline-flex', alignItems: 'center', gap: 3 }}>
<img
src="/assets/images/icon-booth-chat-dots.svg"
src="/assets/images/icon-star-rating-16.svg"
alt=""
style={{
width: 24,
height: 24,
width: 16,
height: 15,
flexShrink: 0,
}}
/>
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 'clamp(14px, 4.3vw, 16px)',
lineHeight: '20px',
background: 'linear-gradient(195deg, #eaba73 0%, #d78e06 100%)',
WebkitBackgroundClip: 'text',
WebkitTextFillColor: 'transparent',
fontWeight: 600,
fontSize: 10,
lineHeight: '12.9px',
color: '#747474',
whiteSpace: 'nowrap',
}}
>
2h
{liveStore
? `${Number(
useMockFallback
? liveStore.rating_avg || 4.4
: liveStore.rating_avg ?? 0
).toFixed(1)} (${
liveStore.reviews_count ?? (useMockFallback ? 608 : 0)
})`
: '4.4 (608)'}
</span>
</div>
<div
style={{
width: 1,
height: 12,
backgroundColor: '#d7dbe2',
flexShrink: 0,
}}
/>
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 'clamp(8.5px, 2.7vw, 10px)',
lineHeight: '13.9px',
color: '#1f1f1f',
fontWeight: 600,
fontSize: 10,
lineHeight: '12.9px',
color: '#747474',
textAlign: 'center',
whiteSpace: 'nowrap',
overflow: 'hidden',
textOverflow: 'ellipsis',
}}
>
Avg. Response
{liveStore?.membership_label || '+1 year membership'}
</span>
<div
style={{
width: 1,
height: 12,
backgroundColor: '#d7dbe2',
flexShrink: 0,
}}
/>
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 600,
fontSize: 10,
lineHeight: '12.9px',
color: '#747474',
textAlign: 'center',
whiteSpace: 'nowrap',
}}
>
{liveStore?.sales_label || '+60 sales'}
</span>
</div>
{/* Card 2: 87% On-time Delivery */}
<div
style={{
minHeight: 58,
padding: '8px',
borderRadius: 8,
backgroundColor: '#efece9',
border: '1px solid #e8e4df',
display: 'flex',
flexDirection: 'column',
justifyContent: 'space-between',
minWidth: 0,
}}
>
<div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
<img
src="/assets/images/icon-booth-delivery-truck.svg"
alt=""
style={{
width: 24,
height: 24,
flexShrink: 0,
}}
/>
{/* 3 Store Metric Cards */}
<div className="habib-booth-metrics-grid" style={{ marginTop: 21 }}>
{/* Card 1: Avg. Response -> Opens Store Chat */}
<div
onClick={() => {
const target = ROUTES.chatThread(liveStore?.slug || resolvedSlug);
if (isBare) {
navigate(target);
return;
}
void requireAuth({
featureName: 'booth chat',
onAuthenticated: () => navigate(target),
});
}}
style={{
minHeight: 58,
padding: '8px',
borderRadius: 8,
backgroundColor: '#efece9',
border: '1px solid #e8e4df',
cursor: 'pointer',
display: 'flex',
flexDirection: 'column',
justifyContent: 'space-between',
minWidth: 0,
}}
>
<div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
<img
src="/assets/images/icon-booth-chat-dots.svg"
alt=""
style={{
width: 24,
height: 24,
flexShrink: 0,
}}
/>
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 'clamp(14px, 4.3vw, 16px)',
lineHeight: '20px',
background: 'linear-gradient(195deg, #eaba73 0%, #d78e06 100%)',
WebkitBackgroundClip: 'text',
WebkitTextFillColor: 'transparent',
whiteSpace: 'nowrap',
}}
>
{liveStore?.avg_response_time || '2h'}
</span>
</div>
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 'clamp(14px, 4.3vw, 16px)',
lineHeight: '20px',
background: 'linear-gradient(195deg, #eaba73 0%, #d78e06 100%)',
WebkitBackgroundClip: 'text',
WebkitTextFillColor: 'transparent',
fontSize: 'clamp(8.5px, 2.7vw, 10px)',
lineHeight: '13.9px',
color: '#1f1f1f',
whiteSpace: 'nowrap',
overflow: 'hidden',
textOverflow: 'ellipsis',
}}
>
87%
Avg. Response
</span>
</div>
<span
{/* Card 2: On-time Delivery */}
<div
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 'clamp(8.5px, 2.7vw, 10px)',
lineHeight: '13.9px',
color: '#1f1f1f',
whiteSpace: 'nowrap',
overflow: 'hidden',
textOverflow: 'ellipsis',
minHeight: 58,
padding: '8px',
borderRadius: 8,
backgroundColor: '#efece9',
border: '1px solid #e8e4df',
display: 'flex',
flexDirection: 'column',
justifyContent: 'space-between',
minWidth: 0,
}}
>
On-time Delivery
</span>
</div>
{/* Card 3: 98% Satisfaction */}
<div
style={{
minHeight: 58,
padding: '8px',
borderRadius: 8,
backgroundColor: '#efece9',
border: '1px solid #e8e4df',
display: 'flex',
flexDirection: 'column',
justifyContent: 'space-between',
minWidth: 0,
}}
>
<div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
<img
src="/assets/images/icon-booth-shield-protect.svg"
alt=""
style={{
width: 24,
height: 24,
flexShrink: 0,
}}
/>
<div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
<img
src="/assets/images/icon-booth-delivery-truck.svg"
alt=""
style={{
width: 24,
height: 24,
flexShrink: 0,
}}
/>
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 'clamp(14px, 4.3vw, 16px)',
lineHeight: '20px',
background: 'linear-gradient(195deg, #eaba73 0%, #d78e06 100%)',
WebkitBackgroundClip: 'text',
WebkitTextFillColor: 'transparent',
whiteSpace: 'nowrap',
}}
>
{liveStore
? `${String(liveStore.on_time_delivery_rate).replace(/%+$/, '')}%`
: '87%'}
</span>
</div>
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 'clamp(14px, 4.3vw, 16px)',
lineHeight: '20px',
background: 'linear-gradient(195deg, #eaba73 0%, #d78e06 100%)',
WebkitBackgroundClip: 'text',
WebkitTextFillColor: 'transparent',
fontSize: 'clamp(8.5px, 2.7vw, 10px)',
lineHeight: '13.9px',
color: '#1f1f1f',
whiteSpace: 'nowrap',
overflow: 'hidden',
textOverflow: 'ellipsis',
}}
>
98%
On-time Delivery
</span>
</div>
<span
{/* Card 3: Satisfaction */}
<div
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 'clamp(8.5px, 2.7vw, 10px)',
lineHeight: '13.9px',
color: '#1f1f1f',
whiteSpace: 'nowrap',
overflow: 'hidden',
textOverflow: 'ellipsis',
minHeight: 58,
padding: '8px',
borderRadius: 8,
backgroundColor: '#efece9',
border: '1px solid #e8e4df',
display: 'flex',
flexDirection: 'column',
justifyContent: 'space-between',
minWidth: 0,
}}
>
Satisfaction
</span>
<div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
<img
src="/assets/images/icon-booth-shield-protect.svg"
alt=""
style={{
width: 24,
height: 24,
flexShrink: 0,
}}
/>
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 'clamp(14px, 4.3vw, 16px)',
lineHeight: '20px',
background: 'linear-gradient(195deg, #eaba73 0%, #d78e06 100%)',
WebkitBackgroundClip: 'text',
WebkitTextFillColor: 'transparent',
whiteSpace: 'nowrap',
}}
>
{liveStore
? `${String(liveStore.satisfaction_rate).replace(/%+$/, '')}%`
: '98%'}
</span>
</div>
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 'clamp(8.5px, 2.7vw, 10px)',
lineHeight: '13.9px',
color: '#1f1f1f',
whiteSpace: 'nowrap',
overflow: 'hidden',
textOverflow: 'ellipsis',
}}
>
Satisfaction
</span>
</div>
</div>
</div>
{/* About Section */}
<section
style={{
marginTop: 26,
width: '100%',
display: 'flex',
flexDirection: 'column',
gap: 14,
}}
>
<div
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 14,
lineHeight: '19px',
color: '#292a2e',
}}
>
About
</div>
<div
{/* About Section */}
<section
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 400,
fontSize: 12,
lineHeight: '18px',
color: '#747474',
whiteSpace: 'pre-wrap',
marginTop: 26,
width: '100%',
display: 'flex',
flexDirection: 'column',
gap: 14,
}}
>
{
'In this room, we are going to talk about raising children from the perspective of Islam In this room, we are going to talk about raising children from the perspective of Islam of Islam In this room, we are going to talk about raising children from about the perspective talk about of Islam room.'
}
</div>
</section>
<div
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 14,
lineHeight: '19px',
color: '#292a2e',
}}
>
About
</div>
<div
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 400,
fontSize: 12,
lineHeight: '18px',
color: '#747474',
whiteSpace: 'pre-wrap',
}}
>
{liveStore?.description ||
(useMockFallback
? 'In this room, we are going to talk about raising children from the perspective of Islam In this room, we are going to talk about raising children from the perspective of Islam of Islam In this room, we are going to talk about raising children from about the perspective talk about of Islam room.'
: 'No description available.')}
</div>
</section>
{/* Products Section */}
<section
style={{
marginTop: 28,
width: '100%',
display: 'flex',
flexDirection: 'column',
gap: 12,
}}
>
<div
{/* Products Section */}
<section
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 14,
lineHeight: '19px',
color: '#292a2e',
marginTop: 28,
width: '100%',
display: 'flex',
flexDirection: 'column',
gap: 12,
}}
>
Products
</div>
<div className="habib-product-grid">
{TWO_COLUMN_GRID_PRODUCTS.map((product) => (
<GridProductCard key={product.id} item={product} />
))}
</div>
</section>
</div>
<div
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 14,
lineHeight: '19px',
color: '#292a2e',
}}
>
Products
</div>
{copied && (
<div
role="status"
aria-live="polite"
style={{
position: 'fixed',
bottom: 24,
left: '50%',
transform: 'translateX(-50%)',
zIndex: 50,
padding: '8px 16px',
borderRadius: 999,
backgroundColor: '#151c31',
color: '#ffffff',
fontFamily: 'var(--font-sans)',
fontWeight: 600,
fontSize: 12,
lineHeight: '16px',
boxShadow: '0 4px 14px rgba(0, 0, 0, 0.2)',
pointerEvents: 'none',
whiteSpace: 'nowrap',
}}
>
Link copied
{liveStore?.products?.length ? (
<div className="habib-product-grid">
{liveStore.products.map((product) => (
<GridProductCard
key={product.id}
item={mapProductToGridItem(product)}
slugOrId={product.slug}
isBookmarked={isBookmarked(product.id, product.slug)}
onToggleBookmark={() => {
void toggleBookmark(product.slug, product.id, product.slug);
}}
/>
))}
</div>
) : useMockFallback ? (
<div className="habib-product-grid">
{TWO_COLUMN_GRID_PRODUCTS.map((product) => (
<GridProductCard key={product.id} item={product} />
))}
</div>
) : (
<EmptyStateBox message="No products in this store yet." />
)}
</section>
</div>
)}
</MobileShell>

185
src/pages/catalog/ShopCatItemsPage.tsx

@ -1,17 +1,120 @@
import React from 'react';
import React, { useEffect, useMemo, useState } from 'react';
import { useLocation, useParams, useSearchParams } from 'react-router-dom';
import { MobileShell } from '../../components/layout/MobileShell';
import { StandardPageHeader } from '../../components/layout/TopHeader';
import { SearchBar } from '../../components/common/SearchBar';
import { GridProductCard } from '../../components/common/GridProductCard';
import {
EmptyStateBox,
ProductGridShimmer,
RetryBanner,
} from '../../components/common/ShimmerSkeletons';
import { TWO_COLUMN_GRID_PRODUCTS } from '../../data/catalogData';
import { useShopApp } from '../../context/ShopAppContext';
import { mapProductToGridItem } from '../../lib/mappers';
import { isBareMode, ROUTES, USE_MOCK_DATA } from '../../lib/routes';
import {
useCategoryDetailQuery,
useProductsQuery,
} from '../../lib/shopQueries';
interface ShopCatItemsPageProps {
mode?: 'category' | 'search' | 'bookmarks';
}
function humanizeSlug(slug?: string): string {
if (!slug) return 'Category';
return slug
.replace(/-/g, ' ')
.replace(/\b\w/g, (ch) => ch.toUpperCase());
}
/**
* Node 4181:12817 — `shop-catitems` (Home & Living Category Items, 375×814)
* Node 4181:12817 — `shop-catitems` (Category Items, Search Results, Bookmarks, 375×814)
*/
export const ShopCatItemsPage: React.FC = () => {
export const ShopCatItemsPage: React.FC<ShopCatItemsPageProps> = ({
mode = 'category',
}) => {
const location = useLocation();
const isBare = isBareMode(location.search);
const useMockFallback = isBare || USE_MOCK_DATA;
const { categorySlug } = useParams<{ categorySlug?: string }>();
const [searchParams, setSearchParams] = useSearchParams();
const initialQ = searchParams.get('q') || '';
const { hydrated, bookmarkedProducts, isBookmarked, toggleBookmark } =
useShopApp();
const [query, setQuery] = useState(initialQ);
const isSearchOrAll = mode === 'search' || !categorySlug;
const shouldFetchLive = !isBare && mode !== 'bookmarks';
const productsQuery = useProductsQuery(
{ q: initialQ || undefined },
shouldFetchLive && isSearchOrAll
);
const categoryQuery = useCategoryDetailQuery(
categorySlug || '',
shouldFetchLive && !isSearchOrAll
);
const products = !shouldFetchLive
? null
: isSearchOrAll
? productsQuery.data?.results ?? null
: categoryQuery.data?.products ?? null;
const activeQuery = isSearchOrAll ? productsQuery : categoryQuery;
const loading =
shouldFetchLive &&
(activeQuery.isPending || (!products && activeQuery.isFetching));
const loadError = shouldFetchLive && activeQuery.isError;
const headerTitle = useMemo(() => {
if (mode === 'bookmarks') return 'Saved Items';
if (isSearchOrAll) {
return initialQ ? `Results for "${initialQ}"` : 'Explore Products';
}
const cat = categoryQuery.data?.category;
return (
cat?.localized_title ||
cat?.title ||
(categorySlug ? humanizeSlug(categorySlug) : 'Home & Living')
);
}, [categoryQuery.data?.category, categorySlug, initialQ, isSearchOrAll, mode]);
useEffect(() => {
setQuery(initialQ);
}, [initialQ]);
const displayedProducts = useMemo(() => {
const source = mode === 'bookmarks' ? bookmarkedProducts : products;
if (!source) return null;
const trimmed = query.trim().toLowerCase();
if (!trimmed) return source;
return source.filter(
(p) =>
p.title.toLowerCase().includes(trimmed) ||
(p.store_name || '').toLowerCase().includes(trimmed) ||
(p.category_title || '').toLowerCase().includes(trimmed)
);
}, [bookmarkedProducts, mode, products, query]);
const backFallback =
mode === 'bookmarks'
? ROUTES.account
: mode === 'search'
? ROUTES.home
: ROUTES.categories;
const isBookmarksLoading = !isBare && mode === 'bookmarks' && !hydrated;
return (
<MobileShell width={375} height={814} backgroundColor="#f3f1ef">
<StandardPageHeader title="Home & Living" backTo="/shop-category" />
<StandardPageHeader
title={isBare ? 'Home & Living' : headerTitle}
backTo={backFallback}
/>
<div
style={{
@ -22,13 +125,75 @@ export const ShopCatItemsPage: React.FC = () => {
gap: 23,
}}
>
<SearchBar showFilterButton={false} />
<SearchBar
showFilterButton={false}
value={isBare ? undefined : query}
onChange={isBare ? undefined : setQuery}
onSubmit={
isBare
? undefined
: (val) => {
if (mode === 'search') {
setSearchParams(val ? { q: val } : {});
} else {
setQuery(val);
}
}
}
/>
<div className="habib-product-grid">
{TWO_COLUMN_GRID_PRODUCTS.map((product) => (
<GridProductCard key={product.id} item={product} />
))}
</div>
{!isBare && (loading || isBookmarksLoading) ? (
<ProductGridShimmer count={6} />
) : !isBare && displayedProducts ? (
displayedProducts.length > 0 ? (
<div className="habib-product-grid">
{displayedProducts.map((product) => (
<GridProductCard
key={product.id}
item={mapProductToGridItem(product)}
slugOrId={product.slug}
isBookmarked={isBookmarked(product.id, product.slug)}
onToggleBookmark={() => {
void toggleBookmark(product.slug, product.id, product.slug);
}}
/>
))}
</div>
) : (
<div
style={{
padding: '48px 16px',
textAlign: 'center',
fontFamily: 'var(--font-sans)',
color: '#747474',
fontSize: '13px',
fontWeight: 600,
}}
>
{mode === 'bookmarks'
? 'No saved items yet. Tap the bookmark icon on any product to save it here.'
: 'No matching products found.'}
</div>
)
) : (
<>
{!isBare && loadError && (
<RetryBanner
message="Could not load products. Tap Retry to refresh."
onRetry={() => void activeQuery.refetch()}
/>
)}
{useMockFallback ? (
<div className="habib-product-grid">
{TWO_COLUMN_GRID_PRODUCTS.map((product) => (
<GridProductCard key={product.id} item={product} />
))}
</div>
) : (
<EmptyStateBox message="No products available." />
)}
</>
)}
</div>
</MobileShell>
);

83
src/pages/catalog/ShopCategoryPage.tsx

@ -1,14 +1,46 @@
import React from 'react';
import React, { useMemo, useState } from 'react';
import { useLocation } from 'react-router-dom';
import { MobileShell } from '../../components/layout/MobileShell';
import { BottomNavBar } from '../../components/layout/BottomNavBar';
import { SearchBar } from '../../components/common/SearchBar';
import { CategoryCard } from '../../components/common/CategoryCard';
import {
CategoryGridShimmer,
EmptyStateBox,
RetryBanner,
} from '../../components/common/ShimmerSkeletons';
import { CATEGORY_GRID_TILES } from '../../data/catalogData';
import { mapCategoryToTile } from '../../lib/mappers';
import { isBareMode, USE_MOCK_DATA } from '../../lib/routes';
import { useCategoriesQuery } from '../../lib/shopQueries';
/**
* Node 4181:12170 — `shop-category` (Category Grid, 375×814)
*/
export const ShopCategoryPage: React.FC = () => {
const location = useLocation();
const isBare = isBareMode(location.search);
const useMockFallback = isBare || USE_MOCK_DATA;
const [searchQuery, setSearchQuery] = useState('');
const categoriesQuery = useCategoriesQuery(!isBare);
const categories = categoriesQuery.data?.results ?? null;
const loading =
!isBare &&
(categoriesQuery.isPending || (!categories && categoriesQuery.isFetching));
const loadError = !isBare && categoriesQuery.isError;
const filteredCategories = useMemo(() => {
if (!categories) return null;
const q = searchQuery.trim().toLowerCase();
if (!q) return categories;
return categories.filter(
(cat) =>
cat.title.toLowerCase().includes(q) ||
(cat.localized_title || '').toLowerCase().includes(q) ||
cat.slug.toLowerCase().includes(q)
);
}, [categories, searchQuery]);
return (
<MobileShell width={375} height={814} backgroundColor="#f3f1ef">
<div
@ -16,17 +48,52 @@ export const ShopCategoryPage: React.FC = () => {
flex: 1,
display: 'flex',
flexDirection: 'column',
padding: '38px var(--page-px) 24px',
padding: 'calc(38px + var(--safe-top, 0px)) var(--page-px) 24px',
gap: 20,
}}
>
<SearchBar showFilterButton={false} />
<SearchBar
showFilterButton={false}
value={isBare ? undefined : searchQuery}
onChange={isBare ? undefined : setSearchQuery}
/>
<div className="habib-category-grid">
{CATEGORY_GRID_TILES.map((tile) => (
<CategoryCard key={tile.id} tile={tile} />
))}
</div>
{!isBare && loading && !categories ? (
<CategoryGridShimmer count={6} />
) : (
<>
{!isBare && loadError && !categories && (
<RetryBanner
message="Could not load categories. Tap Retry to refresh."
onRetry={() => void categoriesQuery.refetch()}
/>
)}
{!isBare && filteredCategories ? (
filteredCategories.length > 0 || USE_MOCK_DATA ? (
<div className="habib-category-grid">
{filteredCategories.map((cat, idx) => (
<CategoryCard
key={cat.id}
tile={mapCategoryToTile(cat, idx)}
count={cat.products_count}
slug={cat.slug}
/>
))}
</div>
) : (
<EmptyStateBox message="No categories found." />
)
) : useMockFallback ? (
<div className="habib-category-grid">
{CATEGORY_GRID_TILES.map((tile) => (
<CategoryCard key={tile.id} tile={tile} />
))}
</div>
) : (
<EmptyStateBox message="No categories available." />
)}
</>
)}
</div>
<BottomNavBar activeTab="category" showCartBadge={true} />

958
src/pages/catalog/ShopSinglePage.tsx
File diff suppressed because it is too large
View File

1182
src/pages/chat/ShopChatPage.tsx
File diff suppressed because it is too large
View File

396
src/pages/checkout/ShopBuy01Page.tsx

@ -1,26 +1,94 @@
import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import React, { useMemo, useState } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
import { MobileShell } from '../../components/layout/MobileShell';
import { StandardPageHeader } from '../../components/layout/TopHeader';
import { StickyFooterBar } from '../../components/layout/StickyFooterBar';
import { AddressCard, AddNewAddressCard } from '../../components/checkout/AddressCard';
import { EmptyStateBox } from '../../components/common/ShimmerSkeletons';
import { AddressFormSheet } from '../../components/modals/AddressFormSheet';
import { useShopApp } from '../../context/ShopAppContext';
import { BUY01_ADDRESSES } from '../../data/checkoutData';
import { mapAddressToOption } from '../../lib/mappers';
import { isBareMode, ROUTES, USE_MOCK_DATA } from '../../lib/routes';
import type { ApiAddress } from '../../lib/shopApi';
/**
* Node 4159:367 — `shop-buy01` (Shipping Details, 375×814)
*/
export const ShopBuy01Page: React.FC = () => {
const navigate = useNavigate();
const [selectedId, setSelectedId] = useState('addr-1');
const location = useLocation();
const isBare = isBareMode(location.search);
const useMockFallback = isBare || USE_MOCK_DATA;
const addresses = BUY01_ADDRESSES.map((addr) => ({
...addr,
selected: addr.id === selectedId,
}));
const {
isUserAuthenticated,
requireAuth,
addresses,
selectedAddressId,
selectAddress,
saveAddress,
shippingMethods,
selectedShippingMethod,
selectShippingMethod,
cart,
showToast,
} = useShopApp();
const [bareSelectedId, setBareSelectedId] = useState('addr-1');
const [addressModalOpen, setAddressModalOpen] = useState(false);
const [editingAddress, setEditingAddress] = useState<ApiAddress | null>(null);
const bareAddresses = useMemo(
() =>
BUY01_ADDRESSES.map((addr) => ({
...addr,
selected: addr.id === bareSelectedId,
})),
[bareSelectedId]
);
const liveAddressOptions = useMemo(
() =>
addresses.map((addr, idx) =>
mapAddressToOption(addr, selectedAddressId, idx)
),
[addresses, selectedAddressId]
);
const computedTotalText = useMemo(() => {
if (isBare || !cart?.pricing) return useMockFallback ? '$24.00' : '$0.00';
const subtotalNum = Number(cart.pricing.subtotal) || 0;
const discountNum = Number(cart.pricing.discount_amount) || 0;
const shipNum = Number(selectedShippingMethod?.price || 0);
const total = Math.max(0, subtotalNum - discountNum + shipNum);
return `$${total.toFixed(2)}`;
}, [cart?.pricing, isBare, selectedShippingMethod?.price, useMockFallback]);
const handleContinue = () => {
if (!isBare && !isUserAuthenticated) {
void requireAuth({
featureName: 'checkout',
onAuthenticated: () => navigate(ROUTES.checkoutReview),
});
return;
}
if (!isBare && addresses.length === 0) {
showToast('Please add a delivery address to continue');
setEditingAddress(null);
setAddressModalOpen(true);
return;
}
navigate(ROUTES.checkoutReview);
};
return (
<MobileShell width={375} height={814} backgroundColor="#f3f1ef">
<StandardPageHeader title="Shipping Details" titleTop={30} backTo="/shop-cart" />
<StandardPageHeader
title="Shipping Details"
titleTop={30}
backTo={ROUTES.cart}
/>
{/* Shipping Details Body */}
<div
@ -58,16 +126,42 @@ export const ShopBuy01Page: React.FC = () => {
</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
{addresses.map((address) => (
<AddressCard
key={address.id}
item={address}
variant="checkout"
onSelect={() => setSelectedId(address.id)}
/>
))}
{isBare ? (
bareAddresses.map((address) => (
<AddressCard
key={address.id}
item={address}
variant="checkout"
onSelect={() => setBareSelectedId(address.id)}
/>
))
) : liveAddressOptions.length > 0 ? (
liveAddressOptions.map((option, idx) => (
<AddressCard
key={option.id}
item={option}
variant="checkout"
onSelect={() => selectAddress(addresses[idx].id)}
onChangeAddressClick={() => {
setEditingAddress(addresses[idx]);
setAddressModalOpen(true);
}}
/>
))
) : !useMockFallback ? (
<EmptyStateBox message="No saved delivery addresses yet." compact />
) : null}
<AddNewAddressCard onClick={() => navigate('/shop-adreess')} />
<AddNewAddressCard
onClick={() => {
if (isBare) {
navigate(ROUTES.addresses);
} else {
setEditingAddress(null);
setAddressModalOpen(true);
}
}}
/>
</div>
</section>
@ -96,103 +190,211 @@ export const ShopBuy01Page: React.FC = () => {
</span>
</div>
{/* Standard Shipping Card */}
<div
style={{
width: '100%',
minHeight: 56,
padding: 12,
borderRadius: 15,
background: 'linear-gradient(180deg, #fff7e9 0%, #fdf9f4 100%)',
border: '1px solid #d78e06',
boxSizing: 'border-box',
display: 'flex',
alignItems: 'center',
gap: 14,
}}
>
{/* Selected Radio */}
{!isBare && shippingMethods.length > 0 ? (
<div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
{shippingMethods.map((method) => {
const isSelected = selectedShippingMethod?.code === method.code;
return (
<div
key={method.id}
onClick={() => selectShippingMethod(method.code)}
style={{
width: '100%',
minHeight: 56,
padding: 12,
borderRadius: 15,
background: isSelected
? 'linear-gradient(180deg, #fff7e9 0%, #fdf9f4 100%)'
: '#ffffff',
border: isSelected ? '1px solid #d78e06' : '1px solid transparent',
boxSizing: 'border-box',
display: 'flex',
alignItems: 'center',
gap: 14,
cursor: 'pointer',
}}
>
<div
style={{
width: 20,
height: 20,
borderRadius: 10,
backgroundColor: isSelected ? '#d78e06' : 'transparent',
border: isSelected ? undefined : '1px solid #dbdbdb',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
flexShrink: 0,
}}
>
{isSelected && (
<div
style={{
width: 8,
height: 8,
borderRadius: '50%',
backgroundColor: '#ffffff',
}}
/>
)}
</div>
<img
src="/assets/images/icon-delivery-truck-grey-24.svg"
alt=""
style={{
width: 24,
height: 24,
flexShrink: 0,
}}
/>
<div
style={{
flex: 1,
minWidth: 0,
display: 'flex',
flexDirection: 'column',
gap: 2,
}}
>
<div
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 12,
lineHeight: '17px',
color: '#36363c',
}}
>
{method.title}
</div>
<div
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 400,
fontSize: 10,
lineHeight: '12.9px',
color: '#747474',
}}
>
{method.subtitle ||
`${method.estimated_days_min}-${method.estimated_days_max} business days`}
</div>
</div>
<div
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 14,
lineHeight: '19px',
color: '#292a2e',
flexShrink: 0,
}}
>
{method.formatted_price}
</div>
</div>
);
})}
</div>
) : useMockFallback ? (
<div
style={{
width: 20,
height: 20,
borderRadius: 10,
backgroundColor: '#d78e06',
width: '100%',
minHeight: 56,
padding: 12,
borderRadius: 15,
background: 'linear-gradient(180deg, #fff7e9 0%, #fdf9f4 100%)',
border: '1px solid #d78e06',
boxSizing: 'border-box',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
flexShrink: 0,
gap: 14,
}}
>
<div
style={{
width: 8,
height: 8,
borderRadius: '50%',
backgroundColor: '#ffffff',
width: 20,
height: 20,
borderRadius: 10,
backgroundColor: '#d78e06',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
flexShrink: 0,
}}
/>
</div>
>
<div
style={{
width: 8,
height: 8,
borderRadius: '50%',
backgroundColor: '#ffffff',
}}
/>
</div>
{/* Truck Icon */}
<img
src="/assets/images/icon-delivery-truck-grey-24.svg"
alt=""
style={{
width: 24,
height: 24,
flexShrink: 0,
}}
/>
<img
src="/assets/images/icon-delivery-truck-grey-24.svg"
alt=""
style={{
width: 24,
height: 24,
flexShrink: 0,
}}
/>
{/* "Standard shiping" & "2-3 business day" */}
<div
style={{
flex: 1,
minWidth: 0,
display: 'flex',
flexDirection: 'column',
gap: 2,
}}
>
<div
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 12,
lineHeight: '17px',
color: '#36363c',
flex: 1,
minWidth: 0,
display: 'flex',
flexDirection: 'column',
gap: 2,
}}
>
Standard shiping
<div
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 12,
lineHeight: '17px',
color: '#36363c',
}}
>
Standard shiping
</div>
<div
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 400,
fontSize: 10,
lineHeight: '12.9px',
color: '#747474',
}}
>
2-3 business day
</div>
</div>
<div
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 400,
fontSize: 10,
lineHeight: '12.9px',
color: '#747474',
fontWeight: 700,
fontSize: 14,
lineHeight: '19px',
color: '#292a2e',
flexShrink: 0,
}}
>
2-3 business day
$5,00
</div>
</div>
{/* Price "$5,00" */}
<div
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 14,
lineHeight: '19px',
color: '#292a2e',
flexShrink: 0,
}}
>
$5,00
</div>
</div>
) : (
<EmptyStateBox message="No delivery methods available." compact />
)}
</section>
{/* Green Encryption Banner */}
@ -229,13 +431,21 @@ export const ShopBuy01Page: React.FC = () => {
{/* Bottom Sticky Continue Bar */}
<StickyFooterBar
height={90}
price="$24.00"
price={computedTotalText}
topLabel="Total Cost"
buttonText="Continue"
buttonFontWeight={700}
iconSrc="/assets/images/icon-arrow-right-white.svg"
iconPosition="right"
targetRoute="/shop-payment"
targetRoute={ROUTES.checkoutReview}
onButtonClick={handleContinue}
/>
<AddressFormSheet
isOpen={addressModalOpen}
onClose={() => setAddressModalOpen(false)}
initialAddress={editingAddress}
onSave={saveAddress}
/>
</MobileShell>
);

594
src/pages/checkout/ShopCartPage.tsx

@ -1,10 +1,19 @@
import React, { useState } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import React, { useMemo, useState } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
import { MobileShell } from '../../components/layout/MobileShell';
import { BottomNavBar } from '../../components/layout/BottomNavBar';
import { StickyFooterBar } from '../../components/layout/StickyFooterBar';
import { MainCartItemCard } from '../../components/checkout/CartItemCard';
import type { SummaryLineRow } from '../../components/checkout/OrderSummaryRows';
import {
CartItemsShimmer,
InlineSpinner,
} from '../../components/common/ShimmerSkeletons';
import { OrderSummarySheet } from '../../components/modals/OrderSummarySheet';
import { useShopApp } from '../../context/ShopAppContext';
import { CART_ITEMS_MAIN, type CartItemData } from '../../data/checkoutData';
import { mapCartItemToCard } from '../../lib/mappers';
import { isBareMode, ROUTES, USE_MOCK_DATA } from '../../lib/routes';
interface InteractiveCartItem extends CartItemData {
qty: number;
@ -12,7 +21,7 @@ interface InteractiveCartItem extends CartItemData {
oldUnitPrice: number;
}
const createInitialItems = (): InteractiveCartItem[] =>
const createInitialBareItems = (): InteractiveCartItem[] =>
CART_ITEMS_MAIN.map((item) => {
const unitPrice = parseFloat(item.price.replace(/[^0-9.]/g, '')) || 24;
return {
@ -29,80 +38,139 @@ const createInitialItems = (): InteractiveCartItem[] =>
export const ShopCartPage: React.FC = () => {
const navigate = useNavigate();
const location = useLocation();
const searchParams = new URLSearchParams(location.search);
const isBare =
searchParams.get('bare') === '1' || searchParams.get('embed') === '1';
const isBare = isBareMode(location.search);
const useMockFallback = isBare || USE_MOCK_DATA;
const [items, setItems] = useState<InteractiveCartItem[]>(createInitialItems);
const [hasInteracted, setHasInteracted] = useState(false);
const [isSummaryOpen, setIsSummaryOpen] = useState(false);
const handleIncrement = (id: string) => {
setHasInteracted(true);
setItems((prev) =>
prev.map((item) =>
item.id === id ? { ...item, qty: item.qty + 1 } : item
)
);
};
const {
hydrated,
requireAuth,
cart,
isCartBusy,
updateCartItemQuantity,
removeCartItem,
clearCart,
applyPromoCode,
addToCart,
} = useShopApp();
const handleDecrement = (id: string) => {
setHasInteracted(true);
setItems((prev) =>
prev
.map((item) =>
item.id === id ? { ...item, qty: item.qty - 1 } : item
)
.filter((item) => item.qty > 0)
);
};
const [bareItems, setBareItems] = useState<InteractiveCartItem[]>(
createInitialBareItems
);
const [hasInteractedBare, setHasInteractedBare] = useState(false);
const [isSummaryOpen, setIsSummaryOpen] = useState(false);
const handleRemove = (id: string) => {
setHasInteracted(true);
setItems((prev) => prev.filter((item) => item.id !== id));
};
const liveItems = cart?.items || [];
const livePricing = cart?.pricing;
const resolvedLiveQty =
livePricing?.total_quantity ??
livePricing?.total_units ??
liveItems.reduce((sum, item) => sum + item.quantity, 0);
const resolvedShopsCount =
livePricing?.shops_count ||
new Set(liveItems.map((item) => item.store_id)).size;
const handleClearOrRestore = () => {
setHasInteracted(true);
if (items.length > 0) {
setItems([]);
} else {
setItems(createInitialItems());
}
};
const totalQuantity = items.reduce((sum, item) => sum + item.qty, 0);
const shopsCount = items.length;
const totalPrice = items.reduce(
const bareTotalQty = bareItems.reduce((sum, item) => sum + item.qty, 0);
const bareTotalPrice = bareItems.reduce(
(sum, item) => sum + item.unitPrice * item.qty,
0
);
const totalOldPrice = items.reduce(
const bareTotalOldPrice = bareItems.reduce(
(sum, item) => sum + item.oldUnitPrice * item.qty,
0
);
const useFigmaSnapshot = isBare && !hasInteracted;
const useFigmaSnapshot = isBare && !hasInteractedBare;
const hasAnyItems = isBare ? bareItems.length > 0 : liveItems.length > 0;
const topInfoText = useFigmaSnapshot
? '3 item from 2 Shops'
: `${totalQuantity} item from ${shopsCount} ${
shopsCount === 1 ? 'Shop' : 'Shops'
: isBare
? `${bareTotalQty} item from ${bareItems.length} ${
bareItems.length === 1 ? 'Shop' : 'Shops'
}`
: `${resolvedLiveQty} item from ${resolvedShopsCount} ${
resolvedShopsCount === 1 ? 'Shop' : 'Shops'
}`;
const footerPrice = useFigmaSnapshot
? '$24.00'
: `$${totalPrice.toFixed(2)}`;
: isBare
? `$${bareTotalPrice.toFixed(2)}`
: livePricing?.formatted_total || '$0.00';
const footerOldPrice = useFigmaSnapshot
? '$28.50'
: totalQuantity > 0
? `$${totalOldPrice.toFixed(2)}`
: undefined;
: isBare
? bareTotalQty > 0
? `$${bareTotalOldPrice.toFixed(2)}`
: undefined
: livePricing && Number(livePricing.discount_amount) > 0
? livePricing.formatted_subtotal
: undefined;
const footerTotalItemsLabel = useFigmaSnapshot
? 'Total 4 item'
: `Total ${totalQuantity} item`;
: isBare
? `Total ${bareTotalQty} item`
: `Total ${resolvedLiveQty} item`;
const summaryRows = useMemo<SummaryLineRow[]>(() => {
if (isBare) {
return [
{
id: 'row-items',
label: `Items (${bareTotalQty})`,
value: `$${bareTotalPrice.toFixed(2)}`,
},
...bareItems.map((it) => ({
id: `row-${it.id}`,
label: `${it.title} (×${it.qty})`,
value: `$${(it.unitPrice * it.qty).toFixed(2)}`,
})),
];
}
const rows: SummaryLineRow[] = [
{
id: 'row-items',
label: `Items (${resolvedLiveQty})`,
value: livePricing?.formatted_subtotal || '$0.00',
},
...liveItems.map((it) => ({
id: `row-${it.id}`,
label: `${it.title} (×${it.quantity})`,
value: it.formatted_line_total,
})),
];
if (livePricing && Number(livePricing.discount_amount) > 0) {
rows.push({
id: 'row-discount',
label: `Promo (${livePricing.promo_code})`,
value: `-${livePricing.formatted_discount}`,
});
}
return rows;
}, [bareItems, bareTotalPrice, bareTotalQty, isBare, liveItems, livePricing]);
const summaryTotalText = isBare
? `$${bareTotalPrice.toFixed(2)}`
: livePricing?.formatted_total || '$0.00';
const handleClearOrRestore = async () => {
if (isBare) {
setHasInteractedBare(true);
setBareItems((prev) => (prev.length > 0 ? [] : createInitialBareItems()));
return;
}
if (liveItems.length > 0) {
await clearCart();
} else {
await addToCart('islam-in-the-bible-book', 1);
}
};
return (
<MobileShell width={375} height={814} backgroundColor="#f3f1ef">
@ -112,7 +180,7 @@ export const ShopCartPage: React.FC = () => {
flex: 1,
display: 'flex',
flexDirection: 'column',
padding: '42px var(--page-px) 24px',
padding: 'calc(42px + var(--safe-top, 0px)) var(--page-px) 24px',
gap: 13,
}}
>
@ -128,6 +196,9 @@ export const ShopCartPage: React.FC = () => {
>
<div
style={{
display: 'inline-flex',
alignItems: 'center',
gap: 6,
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 10,
@ -135,31 +206,40 @@ export const ShopCartPage: React.FC = () => {
color: '#292a2e',
}}
>
{topInfoText}
<span>{topInfoText}</span>
{!isBare && isCartBusy && <InlineSpinner size={12} gold />}
</div>
<div
onClick={handleClearOrRestore}
role="button"
aria-label={items.length > 0 ? 'Clear all' : 'Restore'}
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 10,
lineHeight: '13.9px',
color: items.length > 0 ? '#d44747' : '#d78e06',
textAlign: 'right',
cursor: 'pointer',
whiteSpace: 'nowrap',
userSelect: 'none',
}}
>
{items.length > 0 ? 'Clear all' : 'Restore'}
</div>
{(hasAnyItems || useMockFallback) && (
<div
onClick={() => {
if (!isCartBusy) {
void handleClearOrRestore();
}
}}
role="button"
aria-label={hasAnyItems ? 'Clear all' : 'Add sample item'}
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 10,
lineHeight: '13.9px',
color: hasAnyItems ? '#d44747' : '#d78e06',
textAlign: 'right',
cursor: 'pointer',
whiteSpace: 'nowrap',
userSelect: 'none',
}}
>
{hasAnyItems ? 'Clear all' : isBare ? 'Restore' : '+ Add Sample'}
</div>
)}
</div>
{/* Cart Item Cards */}
{items.length > 0 ? (
{!isBare && !hydrated ? (
<CartItemsShimmer count={2} />
) : hasAnyItems ? (
<div
style={{
display: 'flex',
@ -167,27 +247,72 @@ export const ShopCartPage: React.FC = () => {
gap: 10,
}}
>
{items.map((item, idx) => {
const displayCardItem: CartItemData = {
...item,
y: 69 + idx * 133,
quantity: String(item.qty),
price: useFigmaSnapshot
? item.price
: `$${(item.unitPrice * item.qty).toFixed(2)}`,
};
return (
<MainCartItemCard
key={item.id}
item={displayCardItem}
onIncrement={handleIncrement}
onDecrement={handleDecrement}
onRemove={handleRemove}
onClickItem={() => navigate('/shop-single-page')}
onClickOrigin={() => navigate('/shop-booth')}
/>
);
})}
{isBare
? bareItems.map((item, idx) => {
const displayCardItem: CartItemData = {
...item,
y: 69 + idx * 133,
quantity: String(item.qty),
price: useFigmaSnapshot
? item.price
: `$${(item.unitPrice * item.qty).toFixed(2)}`,
};
return (
<MainCartItemCard
key={item.id}
item={displayCardItem}
onIncrement={(id) => {
setHasInteractedBare(true);
setBareItems((prev) =>
prev.map((it) =>
it.id === id ? { ...it, qty: it.qty + 1 } : it
)
);
}}
onDecrement={(id) => {
setHasInteractedBare(true);
setBareItems((prev) =>
prev
.map((it) =>
it.id === id ? { ...it, qty: it.qty - 1 } : it
)
.filter((it) => it.qty > 0)
);
}}
onRemove={(id) => {
setHasInteractedBare(true);
setBareItems((prev) => prev.filter((it) => it.id !== id));
}}
onClickItem={() => navigate(ROUTES.product())}
onClickOrigin={() => navigate(ROUTES.store())}
/>
);
})
: liveItems.map((item, idx) => (
<MainCartItemCard
key={item.id}
item={mapCartItemToCard(item, idx)}
onIncrement={() => {
void updateCartItemQuantity(item.id, item.quantity + 1);
}}
onDecrement={() => {
if (item.quantity <= 1) {
void removeCartItem(item.id);
} else {
void updateCartItemQuantity(item.id, item.quantity - 1);
}
}}
onRemove={() => {
void removeCartItem(item.id);
}}
onClickItem={() =>
navigate(ROUTES.product(item.product_slug || item.product_id))
}
onClickOrigin={() =>
navigate(ROUTES.store(item.store_slug || item.store_id))
}
/>
))}
</div>
) : (
<div
@ -224,12 +349,20 @@ export const ShopCartPage: React.FC = () => {
color: '#747474',
}}
>
Looks like you removed all items from your shopping cart.
Browse verified Muslim booths and add products to start your order.
</div>
<div style={{ display: 'flex', flexWrap: 'wrap', justifyContent: 'center', gap: 10, marginTop: 8 }}>
<div
style={{
display: 'flex',
flexWrap: 'wrap',
justifyContent: 'center',
gap: 10,
marginTop: 8,
}}
>
<button
type="button"
onClick={handleClearOrRestore}
onClick={() => navigate(ROUTES.home)}
style={{
padding: '10px 18px',
borderRadius: 11,
@ -242,11 +375,11 @@ export const ShopCartPage: React.FC = () => {
cursor: 'pointer',
}}
>
Restore Items
Browse Shop
</button>
<button
type="button"
onClick={() => navigate('/shop-home')}
onClick={() => navigate(ROUTES.categories)}
style={{
padding: '10px 18px',
borderRadius: 11,
@ -259,7 +392,7 @@ export const ShopCartPage: React.FC = () => {
cursor: 'pointer',
}}
>
Browse Shop
Explore Categories
</button>
</div>
</div>
@ -286,250 +419,35 @@ export const ShopCartPage: React.FC = () => {
buttonText="checkout"
buttonFontWeight={700}
iconSrc="/assets/images/icon-credit-card-white.svg"
targetRoute="/shop-buy01"
disabled={items.length === 0}
targetRoute={ROUTES.checkoutShipping}
onButtonClick={() => {
if (isBare) {
navigate(ROUTES.checkoutShipping);
return;
}
void requireAuth({
featureName: 'checkout',
onAuthenticated: () => navigate(ROUTES.checkoutShipping),
});
}}
disabled={!hasAnyItems || isCartBusy}
/>
<BottomNavBar
activeTab="cart"
showCartBadge={items.length > 0}
cartBadgeCount={items.length}
showCartBadge={hasAnyItems}
cartBadgeCount={isBare ? bareItems.length : liveItems.length}
/>
</div>
{/* Interactive Order Summary Bottom Sheet Modal */}
{isSummaryOpen && (
<div
onClick={() => setIsSummaryOpen(false)}
style={{
position: 'absolute',
inset: 0,
backgroundColor: 'rgba(17, 17, 17, 0.9)',
zIndex: 40,
display: 'flex',
flexDirection: 'column',
justifyContent: 'flex-end',
}}
>
<div
className="habib-bottom-sheet"
onClick={(e) => e.stopPropagation()}
style={{
padding: '22px var(--page-px) 24px',
display: 'flex',
flexDirection: 'column',
gap: 24,
}}
>
{/* Header Row */}
<div
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
gap: 12,
}}
>
<div
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 14,
lineHeight: '19px',
color: '#111111',
}}
>
Orded Summery
</div>
<button
type="button"
onClick={() => setIsSummaryOpen(false)}
aria-label="Close"
style={{
width: 24,
height: 24,
background: 'transparent',
border: 'none',
padding: 0,
cursor: 'pointer',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
}}
>
<img
src="/assets/images/icon-modal-close-cross.svg"
alt=""
style={{
width: 11.67,
height: 11.67,
display: 'block',
}}
/>
</button>
</div>
{/* Dynamic Breakdown Rows */}
<div
style={{
display: 'flex',
flexDirection: 'column',
gap: 14,
}}
>
<div
style={{
display: 'flex',
flexDirection: 'column',
gap: 10,
}}
>
<div
style={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
gap: 12,
}}
>
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 600,
fontSize: 14,
lineHeight: '20px',
color: '#747474',
}}
>
Items ({totalQuantity})
</span>
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 600,
fontSize: 14,
lineHeight: '20px',
color: '#747474',
}}
>
${totalPrice.toFixed(2)}
</span>
</div>
{items.map((item) => (
<div
key={item.id}
style={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
gap: 12,
}}
>
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 600,
fontSize: 14,
lineHeight: '20px',
color: '#747474',
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
minWidth: 0,
}}
>
{item.title} (×{item.qty})
</span>
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 600,
fontSize: 14,
lineHeight: '20px',
color: '#747474',
flexShrink: 0,
}}
>
${(item.unitPrice * item.qty).toFixed(2)}
</span>
</div>
))}
</div>
<div
style={{
width: '100%',
height: 1,
backgroundColor: '#d7dbe2',
}}
/>
<div
style={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
gap: 12,
}}
>
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 16,
lineHeight: '20px',
color: '#111111',
}}
>
Total
</span>
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 16,
lineHeight: '20px',
color: 'var(--color-text-charcoal)',
}}
>
${totalPrice.toFixed(2)}
</span>
</div>
</div>
<button
type="button"
onClick={() => setIsSummaryOpen(false)}
style={{
width: '100%',
height: 52,
borderRadius: 11,
backgroundColor: '#d78e06',
border: 'none',
padding: 0,
cursor: 'pointer',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
}}
>
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 16,
lineHeight: '24px',
color: '#fbfbfc',
}}
>
Got it
</span>
</button>
</div>
</div>
)}
<OrderSummarySheet
isOpen={isSummaryOpen}
onClose={() => setIsSummaryOpen(false)}
rows={summaryRows}
totalText={summaryTotalText}
promoCode={cart?.promo_code || ''}
onApplyPromo={isBare ? undefined : applyPromoCode}
/>
</MobileShell>
);
};

2
src/pages/checkout/ShopOrderSummaryPage.tsx

@ -158,12 +158,12 @@ export const ShopOrderSummaryPage: React.FC = () => {
{/* "Got it" CTA Button */}
<button
type="button"
className="habib-cta-btn"
onClick={() => navigate('/shop-buy01')}
style={{
width: '100%',
height: 52,
borderRadius: 11,
backgroundColor: '#d78e06',
border: 'none',
padding: 0,
cursor: 'pointer',

128
src/pages/checkout/ShopPayResultPage.tsx

@ -1,13 +1,37 @@
import React from 'react';
import { useNavigate } from 'react-router-dom';
import { useLocation, useNavigate, useParams } from 'react-router-dom';
import { MobileShell } from '../../components/layout/MobileShell';
import { StandardPageHeader } from '../../components/layout/TopHeader';
import { EmptyStateBox, ShimmerBox } from '../../components/common/ShimmerSkeletons';
import { isBareMode, ROUTES, USE_MOCK_DATA } from '../../lib/routes';
import { useOrderReceiptQuery } from '../../lib/shopQueries';
/**
* Node 4162:11664 — `shop-payresult` (Payment Successful Result, 375×814)
*/
export const ShopPayResultPage: React.FC = () => {
const navigate = useNavigate();
const location = useLocation();
const isBare = isBareMode(location.search);
const useMockFallback = isBare || USE_MOCK_DATA;
const { orderId } = useParams<{ orderId?: string }>();
const resolvedOrderNumber = orderId || 'ORD-28465';
const receiptQuery = useOrderReceiptQuery(resolvedOrderNumber, !isBare);
const receipt = receiptQuery.data
? {
orderNumber: receiptQuery.data.order_number,
totalPaid: receiptQuery.data.total_paid,
paymentMethodLabel: receiptQuery.data.payment_method_label,
orderDate: receiptQuery.data.order_date,
}
: null;
const loading =
!isBare &&
(receiptQuery.isPending || (!receipt && receiptQuery.isFetching));
const activeOrderCode =
!isBare && receipt ? receipt.orderNumber : resolvedOrderNumber;
return (
<MobileShell width={375} height={814} backgroundColor="#f3f1ef">
@ -22,10 +46,16 @@ export const ShopPayResultPage: React.FC = () => {
flex: 1,
display: 'flex',
flexDirection: 'column',
padding: '20px var(--page-px) 24px',
padding: '20px var(--page-px) calc(24px + var(--safe-bottom, 0px))',
gap: 18,
}}
>
{!isBare && !loading && !receipt && !useMockFallback ? (
<div style={{ flex: 1, display: 'flex', alignItems: 'center' }}>
<EmptyStateBox message="Order receipt not found." />
</div>
) : (
<>
{/* Success Hero Block */}
<div
style={{
@ -134,17 +164,21 @@ export const ShopPayResultPage: React.FC = () => {
</span>
</div>
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 14,
lineHeight: '19px',
color: '#292a2e',
}}
>
$70.50
</span>
{!isBare && loading && !receipt ? (
<ShimmerBox width={68} height={18} borderRadius={6} />
) : (
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 14,
lineHeight: '19px',
color: '#292a2e',
}}
>
{!isBare && receipt ? receipt.totalPaid : '$70.50'}
</span>
)}
</div>
{/* Horizontal Divider */}
@ -158,7 +192,7 @@ export const ShopPayResultPage: React.FC = () => {
{/* 3 Metadata Rows */}
<div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
{/* Row 1: Order Code -> ORD-28465 */}
{/* Row 1: Order Code */}
<div
style={{
display: 'flex',
@ -213,12 +247,12 @@ export const ShopPayResultPage: React.FC = () => {
whiteSpace: 'nowrap',
}}
>
ORD-28465
{isBare ? 'ORD-28465' : activeOrderCode}
</span>
</div>
</div>
{/* Row 2: Payment method -> PayPal */}
{/* Row 2: Payment method */}
<div
style={{
display: 'flex',
@ -250,20 +284,24 @@ export const ShopPayResultPage: React.FC = () => {
</span>
</div>
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 400,
fontSize: 12,
lineHeight: '18px',
color: '#292a2e',
}}
>
PayPal
</span>
{!isBare && loading && !receipt ? (
<ShimmerBox width={82} height={15} borderRadius={5} />
) : (
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 400,
fontSize: 12,
lineHeight: '18px',
color: '#292a2e',
}}
>
{!isBare && receipt ? receipt.paymentMethodLabel : 'PayPal'}
</span>
)}
</div>
{/* Row 3: Order Date -> Mar 15,2025 | 9:41 PM */}
{/* Row 3: Order Date */}
<div
style={{
display: 'flex',
@ -296,25 +334,29 @@ export const ShopPayResultPage: React.FC = () => {
</span>
</div>
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 400,
fontSize: 12,
lineHeight: '18px',
color: '#292a2e',
whiteSpace: 'nowrap',
}}
>
Mar 15,2025 | 9:41 PM
</span>
{!isBare && loading && !receipt ? (
<ShimmerBox width={118} height={15} borderRadius={5} />
) : (
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 400,
fontSize: 12,
lineHeight: '18px',
color: '#292a2e',
whiteSpace: 'nowrap',
}}
>
{!isBare && receipt ? receipt.orderDate : 'Mar 15,2025 | 9:41 PM'}
</span>
)}
</div>
</div>
{/* "track Order" Secondary Button */}
<button
type="button"
onClick={() => navigate('/shop-order-detail')}
onClick={() => navigate(ROUTES.orderDetail(activeOrderCode))}
style={{
marginTop: 2,
width: '100%',
@ -353,11 +395,13 @@ export const ShopPayResultPage: React.FC = () => {
</span>
</button>
</div>
</>
)}
{/* "Continue Shoping" Primary CTA Button */}
<button
type="button"
onClick={() => navigate('/shop-home')}
onClick={() => navigate(ROUTES.home)}
style={{
width: '100%',
height: 52,

373
src/pages/checkout/ShopPaymentPage.tsx

@ -1,21 +1,193 @@
import React from 'react';
import React, { useEffect, useMemo, useState } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
import { MobileShell } from '../../components/layout/MobileShell';
import { StandardPageHeader } from '../../components/layout/TopHeader';
import { StickyFooterBar } from '../../components/layout/StickyFooterBar';
import { ReviewItemCard } from '../../components/checkout/ReviewItemCard';
import { OrderSummaryRows } from '../../components/checkout/OrderSummaryRows';
import { PAYMENT_REVIEW_ITEMS } from '../../data/checkoutData';
import {
OrderSummaryRows,
type SummaryLineRow,
} from '../../components/checkout/OrderSummaryRows';
import { EmptyStateBox } from '../../components/common/ShimmerSkeletons';
import { PaymentMethodsSheet } from '../../components/modals/PaymentMethodsSheet';
import { useShopApp } from '../../context/ShopAppContext';
import {
PAYMENT_METHODS_LIST,
PAYMENT_REVIEW_ITEMS,
type PaymentMethodItem,
} from '../../data/checkoutData';
import { resolveMediaUrl } from '../../lib/http';
import { mapCartItemToReview } from '../../lib/mappers';
import { isBareMode, ROUTES, USE_MOCK_DATA } from '../../lib/routes';
import {
usePaymentMethodsQuery,
usePlaceOrderMutation,
} from '../../lib/shopQueries';
/**
* Node 4160:11203 — `shop-payment` (Review & Confirm, 375×814)
*/
export const ShopPaymentPage: React.FC = () => {
const navigate = useNavigate();
const location = useLocation();
const isBare = isBareMode(location.search);
const useMockFallback = isBare || USE_MOCK_DATA;
const {
isUserAuthenticated,
requireAuth,
cart,
selectedAddress,
selectedShippingMethod,
selectedPaymentMethod,
setSelectedPaymentMethod,
habibCoinsBalance,
setHabibCoinsBalance,
showToast,
} = useShopApp();
const [paymentSheetOpen, setPaymentSheetOpen] = useState(false);
const paymentMethodsQuery = usePaymentMethodsQuery(!isBare);
const placeOrderMutation = usePlaceOrderMutation();
const paymentMethodsData = paymentMethodsQuery.data;
const submitting = placeOrderMutation.isPending;
useEffect(() => {
if (!isBare && typeof paymentMethodsData?.habib_coins_balance === 'number') {
setHabibCoinsBalance(paymentMethodsData.habib_coins_balance);
}
}, [isBare, paymentMethodsData?.habib_coins_balance, setHabibCoinsBalance]);
const paymentMethods = useMemo<PaymentMethodItem[]>(() => {
if (!isBare && paymentMethodsData?.results?.length) {
const coins = paymentMethodsData.habib_coins_balance ?? habibCoinsBalance;
return paymentMethodsData.results.map((pm, idx) => ({
id: pm.code || pm.id,
relY: idx * 69,
label:
pm.code === 'habcoin'
? `Habib Coins (${coins} available)`
: pm.label,
iconSrc:
resolveMediaUrl(pm.icon_url) ||
'/assets/images/icon-payment-google.svg',
selected: (pm.code || pm.id) === selectedPaymentMethod,
}));
}
return useMockFallback ? PAYMENT_METHODS_LIST : [];
}, [
habibCoinsBalance,
isBare,
paymentMethodsData,
selectedPaymentMethod,
useMockFallback,
]);
const livePricing = cart?.pricing;
const { rows, totalText, requiredCoins } = useMemo(() => {
if (isBare || !livePricing) {
return useMockFallback
? {
rows: undefined,
totalText: '$24.00',
requiredCoins: 0,
}
: {
rows: [],
totalText: '$0.00',
requiredCoins: 0,
};
}
const subtotalNum = Number(livePricing.subtotal) || 0;
const discountNum = Number(livePricing.discount_amount) || 0;
const shipNum = Number(selectedShippingMethod?.price || 0);
const totalNum = Math.max(0, subtotalNum - discountNum + shipNum);
const coins =
(livePricing.coin_total || Math.ceil(subtotalNum)) +
(selectedShippingMethod?.coin_price || Math.ceil(shipNum));
const computedRows: SummaryLineRow[] = [
{
id: 'row-items',
label: `Items (${livePricing.total_quantity ?? livePricing.total_units ?? 0})`,
value: livePricing.formatted_subtotal,
},
{
id: 'row-shipping',
label:
selectedShippingMethod?.title ||
(useMockFallback ? 'Standard shipping' : 'Shipping'),
value:
selectedShippingMethod?.formatted_price ||
(useMockFallback ? '$5.00' : '$0.00'),
},
];
if (discountNum > 0) {
computedRows.push({
id: 'row-discount',
label: `Promo (${livePricing.promo_code})`,
value: `-${livePricing.formatted_discount}`,
});
}
return {
rows: computedRows,
totalText: `$${totalNum.toFixed(2)}`,
requiredCoins: coins,
};
}, [isBare, livePricing, selectedShippingMethod, useMockFallback]);
const handleConfirmPurchase = async () => {
if (isBare) {
setPaymentSheetOpen(false);
navigate(ROUTES.checkoutResult('ORD-28465'));
return;
}
if (!isUserAuthenticated) {
setPaymentSheetOpen(false);
const authed = await requireAuth({
featureName: 'order payment',
});
if (!authed) return;
}
if (!selectedAddress && !useMockFallback) {
showToast('Please select a delivery address');
return;
}
if (submitting) return;
try {
const order = await placeOrderMutation.mutateAsync({
address_id: selectedAddress?.id ?? null,
shipping_address: selectedAddress
? undefined
: {
recipient_name: 'Ali Ghaderi',
street_line: '250 Park Avenue South',
city: 'New York',
postal_code: '10003',
country: 'United States',
},
shipping_method: selectedShippingMethod?.code || 'standard',
payment_method: selectedPaymentMethod || 'google_pay',
promo_code: cart?.promo_code || undefined,
});
setPaymentSheetOpen(false);
navigate(ROUTES.checkoutResult(order.order_number), { replace: true });
} catch (err) {
showToast(err instanceof Error ? err.message : 'Could not complete order');
}
};
return (
<MobileShell width={375} height={814} backgroundColor="#f3f1ef">
<StandardPageHeader
title="Review & Confirm"
titleTop={29}
showBack={false}
showBack={!isBare}
backTo={ROUTES.checkoutShipping}
/>
{/* Review Sections Body */}
@ -54,77 +226,128 @@ export const ShopPaymentPage: React.FC = () => {
</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
{PAYMENT_REVIEW_ITEMS.map((item) => (
<ReviewItemCard key={item.id} item={item} />
))}
{!isBare && cart?.items?.length ? (
cart.items.map((item, idx) => (
<ReviewItemCard
key={item.id}
item={mapCartItemToReview(item, idx)}
/>
))
) : useMockFallback ? (
PAYMENT_REVIEW_ITEMS.map((item) => (
<ReviewItemCard key={item.id} item={item} />
))
) : (
<EmptyStateBox message="Your cart is empty." compact />
)}
</div>
</section>
{/* Delivery Address Section */}
<section style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
<div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
<img
src="/assets/images/icon-location-pin-gold.svg"
alt=""
style={{
width: 24,
height: 24,
flexShrink: 0,
}}
/>
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 16,
lineHeight: '20px',
color: '#111111',
}}
>
Delivery Address
</span>
</div>
{/* Read-only Address Card */}
<div
style={{
width: '100%',
minHeight: 74,
padding: 12,
borderRadius: 15,
backgroundColor: '#ffffff',
display: 'flex',
flexDirection: 'column',
gap: 8,
alignItems: 'center',
justifyContent: 'space-between',
gap: 6,
}}
>
<div
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 12,
lineHeight: '17px',
color: '#292a2e',
}}
>
Ali Ghaderi
<div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
<img
src="/assets/images/icon-location-pin-gold.svg"
alt=""
style={{
width: 24,
height: 24,
flexShrink: 0,
}}
/>
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 16,
lineHeight: '20px',
color: '#111111',
}}
>
Delivery Address
</span>
</div>
{!isBare && (
<span
onClick={() => navigate(ROUTES.checkoutShipping)}
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 600,
fontSize: 11,
color: '#d78e06',
cursor: 'pointer',
}}
>
Edit
</span>
)}
</div>
{/* Read-only Address Card */}
{!isBare && !selectedAddress && !useMockFallback ? (
<EmptyStateBox message="No delivery address selected." compact />
) : (
<div
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 400,
fontSize: 12,
lineHeight: '18px',
color: '#3d3d3d',
wordBreak: 'break-word',
width: '100%',
minHeight: 74,
padding: 12,
borderRadius: 15,
backgroundColor: '#ffffff',
display: 'flex',
flexDirection: 'column',
gap: 8,
}}
>
250 Park Avenue South, New York, NY 10003 United States
<div
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 12,
lineHeight: '17px',
color: '#292a2e',
}}
>
{!isBare && selectedAddress
? selectedAddress.recipient_name
: 'Ali Ghaderi'}
</div>
<div
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 400,
fontSize: 12,
lineHeight: '18px',
color: '#3d3d3d',
wordBreak: 'break-word',
}}
>
{!isBare && selectedAddress
? selectedAddress.full_address ||
[
selectedAddress.street_line,
selectedAddress.city,
selectedAddress.postal_code,
selectedAddress.country,
]
.filter(Boolean)
.join(', ')
: '250 Park Avenue South, New York, NY 10003 United States'}
</div>
</div>
</div>
)}
</section>
{/* Orded Summery Section */}
{/* Order Summary Section */}
<section style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
<div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
<img
@ -158,7 +381,10 @@ export const ShopPaymentPage: React.FC = () => {
backgroundColor: '#ffffff',
}}
>
<OrderSummaryRows />
<OrderSummaryRows
rows={rows}
totalText={isBare ? '$70.50' : totalText}
/>
</div>
</section>
</div>
@ -166,12 +392,39 @@ export const ShopPaymentPage: React.FC = () => {
{/* Bottom Sticky Payment Bar */}
<StickyFooterBar
height={90}
price="$24.00"
price={isBare ? '$24.00' : totalText}
topLabel="Total Cost"
buttonText="Payment"
buttonFontWeight={700}
iconSrc="/assets/images/icon-credit-card-white.svg"
targetRoute="/shop-payment-methods"
targetRoute={ROUTES.checkoutReview}
disabled={!isBare && (!cart?.items || cart.items.length === 0)}
onButtonClick={() => {
if (isBare) {
setPaymentSheetOpen(true);
return;
}
void requireAuth({
featureName: 'payment and checkout',
onAuthenticated: () => setPaymentSheetOpen(true),
});
}}
/>
<PaymentMethodsSheet
isOpen={paymentSheetOpen}
onClose={() => setPaymentSheetOpen(false)}
methods={paymentMethods}
selectedMethodId={selectedPaymentMethod}
onSelectMethod={setSelectedPaymentMethod}
totalPriceText={totalText}
onConfirmPurchase={() => {
void handleConfirmPurchase();
}}
isSubmitting={submitting}
habibCoinsBalance={habibCoinsBalance}
requiredCoins={requiredCoins}
onCoinsUpdated={setHabibCoinsBalance}
/>
</MobileShell>
);

370
src/pages/home/ShopHomePage.tsx

@ -1,16 +1,39 @@
import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import React, { useEffect, useMemo, useRef, useState } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
import { MobileShell } from '../../components/layout/MobileShell';
import { BottomNavBar } from '../../components/layout/BottomNavBar';
import { SearchBar } from '../../components/common/SearchBar';
import { CompactProductCard } from '../../components/common/CompactProductCard';
import {
EmptyStateBox,
HomeFeedShimmer,
RetryBanner,
} from '../../components/common/ShimmerSkeletons';
import {
HOME_QUICK_CATEGORIES,
HOME_POPULAR_PRODUCTS,
HOME_NEW_STORES_PRODUCTS,
} from '../../data/catalogData';
import { useShopApp } from '../../context/ShopAppContext';
import { useSmartBack } from '../../hooks/useSmartBack';
import { resolveMediaUrl } from '../../lib/http';
import { mapProductToCompactItem } from '../../lib/mappers';
import { isBareMode, ROUTES, USE_MOCK_DATA } from '../../lib/routes';
import { useHomeFeedQuery } from '../../lib/shopQueries';
interface HeroSlideView {
id: string;
imageSrc: string;
objectPosition: string;
imageScale?: string;
tag: string;
title: string;
subtitle: string;
ctaLabel: string;
ctaRoute: string;
}
const HERO_BANNER_SLIDES = [
const DEFAULT_HERO_SLIDES: HeroSlideView[] = [
{
id: 'global-marketplace',
imageSrc: '/assets/images/banner-habib-marketplace-relatable.jpg',
@ -20,7 +43,7 @@ const HERO_BANNER_SLIDES = [
title: 'Global Marketplace for the Muslim Community',
subtitle: 'Diverse stores, products, and cultures united in one shared marketplace.',
ctaLabel: 'Explore Products',
ctaRoute: '/shop-catitems',
ctaRoute: ROUTES.search(),
},
{
id: 'trusted-booths',
@ -31,25 +54,219 @@ const HERO_BANNER_SLIDES = [
title: 'Authentic Crafts from Trusted Muslim Sellers',
subtitle: 'Curated books, handicrafts, modest fashion, and home essentials worldwide.',
ctaLabel: 'Browse Booths',
ctaRoute: '/shop-booth',
ctaRoute: ROUTES.store('al-hujjah-books'),
},
] as const;
];
/**
* Node 4080:9587 — `shop-home` (375×1074)
*/
export const ShopHomePage: React.FC = () => {
const navigate = useNavigate();
const location = useLocation();
const isBare = isBareMode(location.search);
const useMockFallback = isBare || USE_MOCK_DATA;
const smartBack = useSmartBack(ROUTES.test);
const { isBookmarked, toggleBookmark } = useShopApp();
const homeQuery = useHomeFeedQuery(!isBare);
const feed = homeQuery.data ?? null;
const loading =
!isBare && (homeQuery.isPending || (!feed && homeQuery.isFetching));
const loadError = !isBare && homeQuery.isError;
const [activeSlide, setActiveSlide] = useState(0);
const [isPaused, setIsPaused] = useState(false);
const [dragOffset, setDragOffset] = useState(0);
const [isDragging, setIsDragging] = useState(false);
const [bannerEl, setBannerEl] = useState<HTMLDivElement | null>(null);
const dragStartRef = useRef<{
id: number;
x: number;
y: number;
lastX: number;
time: number;
locked: 'x' | null;
} | null>(null);
const suppressClickRef = useRef(false);
const wheelCooldownRef = useRef(0);
const heroSlides = useMemo<HeroSlideView[]>(() => {
if (isBare || !feed?.banners?.length) {
return useMockFallback ? DEFAULT_HERO_SLIDES : [];
}
return feed.banners.map((b, idx) => ({
id: b.slug || `banner-${b.id}`,
imageSrc:
resolveMediaUrl(b.image_url) ||
DEFAULT_HERO_SLIDES[idx % DEFAULT_HERO_SLIDES.length].imageSrc,
objectPosition: idx === 0 ? 'center 68%' : 'center center',
imageScale: idx === 1 ? 'scale(1.03)' : undefined,
tag: 'Habib Shop',
title: b.title,
subtitle: b.subtitle,
ctaLabel: b.cta_label || 'Explore Products',
ctaRoute: b.target_route || ROUTES.search(),
}));
}, [feed, isBare, useMockFallback]);
const quickCategories = useMemo(() => {
if (isBare || !feed?.quick_categories?.length) {
return useMockFallback
? HOME_QUICK_CATEGORIES.map((cat) => ({
id: cat.id,
label: cat.label,
iconSrc: cat.iconSrc,
targetRoute:
cat.id === 'cat-more'
? ROUTES.categories
: cat.id === 'cat-bag'
? ROUTES.category('bag')
: cat.id === 'cat-beauty'
? ROUTES.category('beauty')
: cat.id === 'cat-art'
? ROUTES.category('art-handicrafts')
: ROUTES.category('home-living'),
}))
: [];
}
const items = feed.quick_categories.slice(0, 4).map((cat) => ({
id: `qcat-${cat.id}`,
label: cat.localized_title || cat.title,
iconSrc:
resolveMediaUrl(cat.small_icon_url || cat.icon_url) ||
'/assets/images/icon-cat-bag-small.svg',
targetRoute: ROUTES.category(cat.slug),
}));
items.push({
id: 'cat-more',
label: 'More',
iconSrc: '/assets/images/icon-cat-more-dots.svg',
targetRoute: ROUTES.categories,
});
return items;
}, [feed, isBare, useMockFallback]);
useEffect(() => {
if (isPaused) return;
if (isPaused || isDragging || heroSlides.length <= 1) return;
const timer = window.setTimeout(() => {
setActiveSlide((prev) => (prev + 1) % HERO_BANNER_SLIDES.length);
setActiveSlide((prev) => (prev + 1) % heroSlides.length);
}, 3800);
return () => window.clearTimeout(timer);
}, [activeSlide, isPaused]);
}, [activeSlide, heroSlides.length, isPaused, isDragging]);
useEffect(() => {
if (!bannerEl) return;
// Consume horizontal touchmove so Android WebView / Flutter does not cancel the swipe
const onTouchMove = (e: TouchEvent) => {
if (dragStartRef.current?.locked === 'x' && e.cancelable) {
e.preventDefault();
}
};
bannerEl.addEventListener('touchmove', onTouchMove, { passive: false });
return () => {
bannerEl.removeEventListener('touchmove', onTouchMove);
};
}, [bannerEl]);
const handlePointerDown = (e: React.PointerEvent<HTMLDivElement>) => {
if (!e.isPrimary || heroSlides.length <= 1) return;
if (e.pointerType === 'mouse' && e.button !== 0) return;
suppressClickRef.current = false;
if (e.pointerType !== 'mouse') setIsPaused(true);
dragStartRef.current = {
id: e.pointerId,
x: e.clientX,
y: e.clientY,
lastX: e.clientX,
time: Date.now(),
locked: null,
};
};
const handlePointerMove = (e: React.PointerEvent<HTMLDivElement>) => {
const start = dragStartRef.current;
if (!start || start.id !== e.pointerId) return;
start.lastX = e.clientX;
const dx = e.clientX - start.x;
const dy = e.clientY - start.y;
if (!start.locked) {
const absX = Math.abs(dx);
const absY = Math.abs(dy);
if (absX < 6 && absY < 8) return;
if (absY > absX) {
dragStartRef.current = null;
if (e.pointerType !== 'mouse') setIsPaused(false);
return;
}
start.locked = 'x';
suppressClickRef.current = true;
// Touch already has implicit pointer capture; stealing it fires a bubbling lostpointercapture on e.target
if (e.pointerType === 'mouse') {
e.currentTarget.setPointerCapture(e.pointerId);
}
setIsDragging(true);
}
const atEdge =
(activeSlide === 0 && dx > 0) ||
(activeSlide === heroSlides.length - 1 && dx < 0);
setDragOffset(atEdge ? dx * 0.3 : dx);
};
const finishDrag = (e: React.PointerEvent<HTMLDivElement>, cancelled = false) => {
if (e.pointerType !== 'mouse') setIsPaused(false);
const start = dragStartRef.current;
if (!start || start.id !== e.pointerId) return;
dragStartRef.current = null;
if (e.currentTarget.hasPointerCapture(e.pointerId)) {
e.currentTarget.releasePointerCapture(e.pointerId);
}
if (start.locked === 'x' && !cancelled) {
const endX = Number.isFinite(e.clientX) ? e.clientX : start.lastX;
const dx = endX - start.x;
const elapsed = Date.now() - start.time;
const threshold = Math.min(50, (e.currentTarget.clientWidth || 343) * 0.16);
const isQuickFlick = elapsed < 250 && Math.abs(dx) > 20;
if (dx <= -threshold || (isQuickFlick && dx < 0)) {
setActiveSlide((prev) => Math.min(heroSlides.length - 1, prev + 1));
} else if (dx >= threshold || (isQuickFlick && dx > 0)) {
setActiveSlide((prev) => Math.max(0, prev - 1));
}
window.setTimeout(() => {
suppressClickRef.current = false;
}, 80);
}
setIsDragging(false);
setDragOffset(0);
};
const handleWheel = (e: React.WheelEvent<HTMLDivElement>) => {
if (Math.abs(e.deltaX) <= Math.abs(e.deltaY) || Math.abs(e.deltaX) < 20) return;
const now = Date.now();
if (now - wheelCooldownRef.current < 450) return;
wheelCooldownRef.current = now;
setActiveSlide((prev) =>
e.deltaX > 0
? Math.min(heroSlides.length - 1, prev + 1)
: Math.max(0, prev - 1)
);
};
const livePopulars = !isBare && feed?.popular_products?.length ? feed.popular_products : null;
const liveNewStores =
!isBare && feed?.new_store_products?.length ? feed.new_store_products : null;
const featuredStoreRoute =
!isBare && feed?.featured_stores?.[0]?.slug
? ROUTES.store(feed.featured_stores[0].slug)
: useMockFallback
? ROUTES.store('tashakol-farzandan-rohhallah')
: ROUTES.search();
return (
<MobileShell width={375} height={1074} backgroundColor="#f3f1ef">
@ -137,7 +354,7 @@ export const ShopHomePage: React.FC = () => {
flex: 1,
display: 'flex',
flexDirection: 'column',
padding: '37px var(--page-px) 22px',
padding: 'calc(37px + var(--safe-top, 0px)) var(--page-px) 22px',
gap: 20,
}}
>
@ -153,7 +370,7 @@ export const ShopHomePage: React.FC = () => {
>
<button
type="button"
onClick={() => navigate('/test')}
onClick={() => smartBack()}
aria-label="Back"
style={{
width: 40,
@ -194,7 +411,7 @@ export const ShopHomePage: React.FC = () => {
<button
type="button"
onClick={() => navigate('/shop-orders')}
onClick={() => navigate(ROUTES.orders())}
aria-label="Notifications"
style={{
width: 40,
@ -224,36 +441,71 @@ export const ShopHomePage: React.FC = () => {
{/* Search Bar & Filter Button */}
<SearchBar
showFilterButton={true}
onFilterClick={() => navigate('/shop-category')}
onFilterClick={() => navigate(ROUTES.categories)}
onSubmit={(q) => navigate(ROUTES.search(q))}
/>
{/* Hero Green Marketplace Card */}
{!isBare && loading && !feed ? (
<HomeFeedShimmer />
) : (
<>
{!isBare && loadError && !feed && (
<RetryBanner
message="Could not load live marketplace feed. Tap Retry to refresh."
onRetry={() => void homeQuery.refetch()}
/>
)}
{/* Hero Green Marketplace Card */}
{heroSlides.length > 0 && (
<div
ref={setBannerEl}
className="habib-hero-banner"
onMouseEnter={() => setIsPaused(true)}
onMouseLeave={() => setIsPaused(false)}
onFocusCapture={() => setIsPaused(true)}
onBlurCapture={() => setIsPaused(false)}
onWheel={handleWheel}
style={{
position: 'relative',
width: '100%',
borderRadius: 15,
overflow: 'hidden',
backgroundColor: '#182c1f',
touchAction: 'pan-y',
}}
>
{/* Horizontal sliding track */}
<div
onPointerDown={handlePointerDown}
onPointerMove={handlePointerMove}
onPointerUp={(e) => finishDrag(e)}
onPointerCancel={(e) => finishDrag(e, true)}
onLostPointerCapture={(e) => {
if (e.target === e.currentTarget) finishDrag(e, true);
}}
onClickCapture={(e) => {
if (suppressClickRef.current) {
e.preventDefault();
e.stopPropagation();
suppressClickRef.current = false;
}
}}
style={{
display: 'flex',
width: '100%',
height: '100%',
transform: `translateX(-${activeSlide * 100}%)`,
transition: 'transform 550ms cubic-bezier(0.22, 1, 0.36, 1)',
transform: `translateX(calc(-${activeSlide * 100}% + ${dragOffset}px))`,
transition: isDragging
? 'none'
: 'transform 550ms cubic-bezier(0.22, 1, 0.36, 1)',
willChange: 'transform',
touchAction: 'pan-y',
userSelect: 'none',
cursor: isDragging ? 'grabbing' : 'grab',
}}
>
{HERO_BANNER_SLIDES.map((slide) => (
{heroSlides.map((slide) => (
<div
key={slide.id}
style={{
@ -262,11 +514,13 @@ export const ShopHomePage: React.FC = () => {
width: '100%',
height: '100%',
overflow: 'hidden',
touchAction: 'pan-y',
}}
>
<img
src={slide.imageSrc}
alt=""
draggable={false}
style={{
position: 'absolute',
inset: 0,
@ -275,6 +529,7 @@ export const ShopHomePage: React.FC = () => {
objectFit: 'cover',
objectPosition: slide.objectPosition,
transform: slide.imageScale,
pointerEvents: 'none',
}}
/>
@ -380,7 +635,7 @@ export const ShopHomePage: React.FC = () => {
zIndex: 2,
}}
>
{HERO_BANNER_SLIDES.map((slide, idx) => {
{heroSlides.map((slide, idx) => {
const isActive = activeSlide === idx;
return (
<button
@ -404,10 +659,12 @@ export const ShopHomePage: React.FC = () => {
})}
</div>
</div>
)}
{/* 5 Quick Category Circular Pills */}
{quickCategories.length > 0 && (
<div className="habib-quick-cats">
{HOME_QUICK_CATEGORIES.map((cat) => (
{quickCategories.map((cat) => (
<div
key={cat.id}
onClick={() => navigate(cat.targetRoute)}
@ -462,6 +719,7 @@ export const ShopHomePage: React.FC = () => {
</div>
))}
</div>
)}
{/* Populars Section */}
<section style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
@ -485,7 +743,7 @@ export const ShopHomePage: React.FC = () => {
Populars
</div>
<div
onClick={() => navigate('/shop-catitems')}
onClick={() => navigate(ROUTES.search())}
style={{
display: 'inline-flex',
alignItems: 'center',
@ -516,13 +774,35 @@ export const ShopHomePage: React.FC = () => {
</div>
</div>
<div className="habib-carousel-scroller habib-scroll-container">
<div className="habib-carousel-track">
{HOME_POPULAR_PRODUCTS.map((product) => (
<CompactProductCard key={product.id} item={product} />
))}
{livePopulars ? (
<div className="habib-carousel-scroller habib-scroll-container">
<div className="habib-carousel-track">
{livePopulars.map((prod) => (
<CompactProductCard
key={prod.id}
item={mapProductToCompactItem(
prod,
isBookmarked(prod.id, prod.slug)
)}
slugOrId={prod.slug}
onToggleBookmark={() => {
void toggleBookmark(prod.slug, prod.id, prod.slug);
}}
/>
))}
</div>
</div>
</div>
) : useMockFallback ? (
<div className="habib-carousel-scroller habib-scroll-container">
<div className="habib-carousel-track">
{HOME_POPULAR_PRODUCTS.map((product) => (
<CompactProductCard key={product.id} item={product} />
))}
</div>
</div>
) : (
<EmptyStateBox message="No popular products yet." compact />
)}
</section>
{/* New Stores Section */}
@ -548,7 +828,7 @@ export const ShopHomePage: React.FC = () => {
New Stores
</div>
<div
onClick={() => navigate('/shop-booth')}
onClick={() => navigate(featuredStoreRoute)}
style={{
display: 'inline-flex',
alignItems: 'center',
@ -579,14 +859,38 @@ export const ShopHomePage: React.FC = () => {
</div>
</div>
<div className="habib-carousel-scroller habib-scroll-container">
<div className="habib-carousel-track">
{HOME_NEW_STORES_PRODUCTS.map((product) => (
<CompactProductCard key={product.id} item={product} />
))}
{liveNewStores ? (
<div className="habib-carousel-scroller habib-scroll-container">
<div className="habib-carousel-track">
{liveNewStores.map((prod) => (
<CompactProductCard
key={prod.id}
item={mapProductToCompactItem(
prod,
isBookmarked(prod.id, prod.slug)
)}
slugOrId={prod.slug}
onToggleBookmark={() => {
void toggleBookmark(prod.slug, prod.id, prod.slug);
}}
/>
))}
</div>
</div>
</div>
) : useMockFallback ? (
<div className="habib-carousel-scroller habib-scroll-container">
<div className="habib-carousel-track">
{HOME_NEW_STORES_PRODUCTS.map((product) => (
<CompactProductCard key={product.id} item={product} />
))}
</div>
</div>
) : (
<EmptyStateBox message="No new store products yet." compact />
)}
</section>
</>
)}
</div>
{/* Bottom Navigation Bar */}

630
src/pages/orders/ShopOrderDetailPage.tsx

@ -1,15 +1,60 @@
import React from 'react';
import { useNavigate } from 'react-router-dom';
import React, { useState } from 'react';
import { useLocation, useNavigate, useParams } from 'react-router-dom';
import { MobileShell } from '../../components/layout/MobileShell';
import { StandardPageHeader } from '../../components/layout/TopHeader';
import {
EmptyStateBox,
InlineSpinner,
OrderDetailShimmer,
RetryBanner,
} from '../../components/common/ShimmerSkeletons';
import { ShipmentStatusCard } from '../../components/orders/ShipmentStatusCard';
import { ShipmentTrackingSheet } from '../../components/modals/ShipmentTrackingSheet';
import { useShopApp } from '../../context/ShopAppContext';
import { ORDER_DETAIL_SHIPMENTS } from '../../data/ordersData';
import { mapShipmentToCardData } from '../../lib/mappers';
import { isBareMode, ROUTES, USE_MOCK_DATA } from '../../lib/routes';
import type { ApiShipment } from '../../lib/shopApi';
import {
useCancelOrderMutation,
useOrderDetailQuery,
} from '../../lib/shopQueries';
/**
* Node 4175:10421 — `shop-order detail` (Order Details & Multi-Shipment Stepper, 375×1061)
*/
export const ShopOrderDetailPage: React.FC = () => {
const navigate = useNavigate();
const location = useLocation();
const isBare = isBareMode(location.search);
const useMockFallback = isBare || USE_MOCK_DATA;
const { orderId } = useParams<{ orderId?: string }>();
const resolvedOrderNumber = orderId || 'ORD-28465';
const { showToast } = useShopApp();
const orderQuery = useOrderDetailQuery(resolvedOrderNumber, !isBare);
const cancelOrderMutation = useCancelOrderMutation();
const order = orderQuery.data ?? null;
const loading =
!isBare && (orderQuery.isPending || (!order && orderQuery.isFetching));
const loadError = !isBare && orderQuery.isError;
const [activeShipment, setActiveShipment] = useState<ApiShipment | null>(null);
const canceling = cancelOrderMutation.isPending;
const liveOrder = !isBare ? order : null;
const canCancel =
liveOrder &&
(liveOrder.status === 'processing' || liveOrder.status === 'pending_payment');
const handleCancelOrder = async () => {
if (!liveOrder || canceling) return;
try {
await cancelOrderMutation.mutateAsync(liveOrder.order_number);
showToast('Order canceled');
} catch (err) {
showToast(err instanceof Error ? err.message : 'Could not cancel order');
}
};
return (
<MobileShell width={375} height={1061} backgroundColor="#f3f1ef">
@ -17,7 +62,7 @@ export const ShopOrderDetailPage: React.FC = () => {
<StandardPageHeader
title="Order Details"
titleTop={29}
backTo="/shop-orders"
backTo={ROUTES.orders()}
/>
<div
@ -25,285 +70,392 @@ export const ShopOrderDetailPage: React.FC = () => {
display: 'flex',
flexDirection: 'column',
flex: 1,
padding: '26px var(--page-px) 20px',
padding: '26px var(--page-px) calc(20px + var(--safe-bottom, 0px))',
gap: 20,
}}
>
{/* Top Order Summary Card (4175:11005) */}
<div
style={{
width: '100%',
padding: 12,
borderRadius: 20,
backgroundColor: '#ebe8e5',
display: 'flex',
flexDirection: 'column',
gap: 15,
}}
>
{/* Row 1: Order code, dot, price, and date */}
<div
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
gap: 8,
flexWrap: 'wrap',
minHeight: 26,
}}
>
<div
style={{
display: 'flex',
alignItems: 'center',
gap: 6,
flexWrap: 'wrap',
}}
>
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 600,
fontSize: 14,
lineHeight: '24px',
color: '#111111',
whiteSpace: 'nowrap',
}}
>
ORD-28465
</span>
<span
style={{
width: 6,
height: 6,
borderRadius: '50%',
backgroundColor: '#bcbcbc',
flexShrink: 0,
}}
{!isBare && loading ? (
<OrderDetailShimmer />
) : !liveOrder && !useMockFallback ? (
<>
{loadError && (
<RetryBanner
message="Could not load order details. Tap Retry to refresh."
onRetry={() => void orderQuery.refetch()}
/>
)}
<EmptyStateBox message="Order not found." />
</>
) : (
<>
{!isBare && loadError && !order && (
<RetryBanner
message="Could not load order details. Tap Retry to refresh."
onRetry={() => void orderQuery.refetch()}
/>
)}
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 600,
fontSize: 14,
lineHeight: '24px',
color: '#111111',
whiteSpace: 'nowrap',
}}
>
$24.00
</span>
</div>
{/* Date on right */}
{/* Top Order Summary Card */}
<div
style={{
display: 'inline-flex',
alignItems: 'center',
gap: 4,
width: '100%',
padding: 12,
borderRadius: 20,
backgroundColor: '#ebe8e5',
display: 'flex',
flexDirection: 'column',
gap: 15,
}}
>
<img
src="/assets/images/icon-date-time-grey-18.svg"
alt=""
style={{
width: 18,
height: 18,
flexShrink: 0,
}}
/>
<span
{/* Row 1: Order code, dot, price, and date */}
<div
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 600,
fontSize: 14,
lineHeight: '14px',
color: '#747474',
whiteSpace: 'nowrap',
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
gap: 8,
flexWrap: 'wrap',
minHeight: 26,
}}
>
Mar 15,2025
</span>
</div>
</div>
{/* Grey Status Bar */}
<div
style={{
width: '100%',
minHeight: 41,
padding: '10px',
borderRadius: 12,
backgroundColor: '#f3f3f3',
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
gap: 8,
flexWrap: 'wrap',
}}
>
<div
style={{
display: 'flex',
alignItems: 'center',
gap: 9,
}}
>
<div style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}>
<img
src="/assets/images/icon-shipping-box-grey-18.svg"
alt=""
style={{
width: 18,
height: 18,
flexShrink: 0,
}}
/>
<span
<div
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 600,
fontSize: 14,
lineHeight: '14px',
color: '#111111',
whiteSpace: 'nowrap',
display: 'flex',
alignItems: 'center',
gap: 6,
flexWrap: 'wrap',
}}
>
3 item
</span>
</div>
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 600,
fontSize: 14,
lineHeight: '24px',
color: '#111111',
whiteSpace: 'nowrap',
}}
>
{liveOrder?.order_number || resolvedOrderNumber}
</span>
{/* Vertical divider */}
<div
style={{
width: 1,
height: 17,
backgroundColor: '#dbdbdb',
flexShrink: 0,
}}
/>
<span
style={{
width: 6,
height: 6,
borderRadius: '50%',
backgroundColor: '#bcbcbc',
flexShrink: 0,
}}
/>
<div style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}>
<img
src="/assets/images/icon-order-item-next-circle.svg"
alt=""
style={{
width: 16,
height: 16,
flexShrink: 0,
}}
/>
<span
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 600,
fontSize: 14,
lineHeight: '24px',
color: '#111111',
whiteSpace: 'nowrap',
}}
>
{liveOrder?.formatted_total || '$24.00'}
</span>
</div>
{/* Date on right */}
<div
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 600,
fontSize: 14,
lineHeight: '14px',
color: '#111111',
whiteSpace: 'nowrap',
display: 'inline-flex',
alignItems: 'center',
gap: 4,
}}
>
1 shop
</span>
<img
src="/assets/images/icon-date-time-grey-18.svg"
alt=""
style={{
width: 18,
height: 18,
flexShrink: 0,
}}
/>
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 600,
fontSize: 14,
lineHeight: '14px',
color: '#747474',
whiteSpace: 'nowrap',
}}
>
{liveOrder?.formatted_date || 'Mar 15,2025'}
</span>
</div>
</div>
</div>
{/* Right delivery count */}
<div
style={{
display: 'inline-flex',
alignItems: 'center',
gap: 4,
}}
>
{/* Grey Status Bar */}
<div
style={{
width: 16,
height: 16,
borderRadius: 10,
backgroundColor: '#0eb13c',
width: '100%',
minHeight: 41,
padding: '10px',
borderRadius: 12,
backgroundColor: '#f3f3f3',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
flexShrink: 0,
justifyContent: 'space-between',
gap: 8,
flexWrap: 'wrap',
}}
>
<img
src="/assets/images/icon-check-white-tiny.svg"
alt=""
<div
style={{
width: 8,
height: 6,
display: 'flex',
alignItems: 'center',
gap: 9,
}}
/>
>
<div style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}>
<img
src="/assets/images/icon-shipping-box-grey-18.svg"
alt=""
style={{
width: 18,
height: 18,
flexShrink: 0,
}}
/>
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 600,
fontSize: 14,
lineHeight: '14px',
color: '#111111',
whiteSpace: 'nowrap',
}}
>
{liveOrder ? `${liveOrder.items_count} item` : '3 item'}
</span>
</div>
{/* Vertical divider */}
<div
style={{
width: 1,
height: 17,
backgroundColor: '#dbdbdb',
flexShrink: 0,
}}
/>
<div style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}>
<img
src="/assets/images/icon-order-item-next-circle.svg"
alt=""
style={{
width: 16,
height: 16,
flexShrink: 0,
}}
/>
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 600,
fontSize: 14,
lineHeight: '14px',
color: '#111111',
whiteSpace: 'nowrap',
}}
>
{liveOrder ? `${liveOrder.shops_count} shop` : '1 shop'}
</span>
</div>
</div>
{/* Right delivery count */}
<div
style={{
display: 'inline-flex',
alignItems: 'center',
gap: 4,
}}
>
<div
style={{
width: 16,
height: 16,
borderRadius: 10,
backgroundColor:
liveOrder?.status === 'canceled' ? '#d44747' : '#0eb13c',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
flexShrink: 0,
}}
>
<img
src="/assets/images/icon-check-white-tiny.svg"
alt=""
style={{
width: 8,
height: 6,
}}
/>
</div>
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 600,
fontSize: 12,
lineHeight: '14px',
color: '#111111',
whiteSpace: 'nowrap',
}}
>
{liveOrder
? liveOrder.status === 'canceled'
? 'Canceled'
: `${liveOrder.delivered_shipments_count} / ${Math.max(
1,
liveOrder.total_shipments_count
)} Delivery`
: '1 / 3 Delivery'}
</span>
</div>
</div>
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 600,
fontSize: 12,
lineHeight: '14px',
color: '#111111',
whiteSpace: 'nowrap',
}}
>
1 / 3 Delivery
</span>
</div>
</div>
</div>
{/* 3 Shipment Cards (Packed, Delivered, Shiping) */}
<div className="habib-orders-grid">
{ORDER_DETAIL_SHIPMENTS.map((shipment) => (
<ShipmentStatusCard key={shipment.id} shipment={shipment} />
))}
</div>
{/* Shipment Cards */}
{liveOrder?.shipments?.length ? (
<div className="habib-orders-grid">
{liveOrder.shipments.map((shipment, idx) => (
<div
key={shipment.id}
onClick={() => setActiveShipment(shipment)}
style={{ cursor: 'pointer' }}
>
<ShipmentStatusCard
shipment={mapShipmentToCardData(
shipment,
liveOrder.formatted_date,
idx
)}
/>
</div>
))}
</div>
) : useMockFallback ? (
<div className="habib-orders-grid">
{ORDER_DETAIL_SHIPMENTS.map((shipment) => (
<ShipmentStatusCard key={shipment.id} shipment={shipment} />
))}
</div>
) : (
<EmptyStateBox message="No shipments for this order yet." compact />
)}
</>
)}
{/* Bottom CTA Button "Order support" (4175:10432) */}
<button
type="button"
onClick={() => navigate('/shop-support')}
{/* Bottom Actions */}
<div
style={{
marginTop: 'auto',
width: '100%',
height: 52,
borderRadius: 11,
backgroundColor: '#d78e06',
border: 'none',
padding: '0 16px',
cursor: 'pointer',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
gap: 6,
flexDirection: 'column',
gap: 10,
}}
>
<img
src="/assets/images/icon-customer-support-headset-white.svg"
alt=""
style={{
width: 24,
height: 24,
flexShrink: 0,
}}
/>
<span
{canCancel && (
<button
type="button"
disabled={canceling}
onClick={() => {
void handleCancelOrder();
}}
style={{
width: '100%',
height: 44,
borderRadius: 11,
backgroundColor: 'transparent',
border: '1px solid rgba(212, 71, 71, 0.45)',
color: '#d44747',
fontFamily: 'var(--font-sans)',
fontWeight: 600,
fontSize: 14,
cursor: canceling ? 'not-allowed' : 'pointer',
display: 'inline-flex',
alignItems: 'center',
justifyContent: 'center',
gap: 8,
}}
>
{canceling && <InlineSpinner size={14} gold />}
{canceling ? 'Canceling...' : 'Cancel Order'}
</button>
)}
{/* Bottom CTA Button "Order support" */}
<button
type="button"
onClick={() =>
navigate(
liveOrder?.order_number
? ROUTES.orderSupport(liveOrder.order_number)
: orderId
? ROUTES.orderSupport(orderId)
: useMockFallback
? ROUTES.orderSupport(resolvedOrderNumber)
: ROUTES.support
)
}
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 600,
fontSize: 16,
lineHeight: '24px',
color: '#fbfbfc',
whiteSpace: 'nowrap',
width: '100%',
height: 52,
borderRadius: 11,
backgroundColor: '#d78e06',
border: 'none',
padding: '0 16px',
cursor: 'pointer',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
gap: 6,
}}
>
Order support
</span>
</button>
<img
src="/assets/images/icon-customer-support-headset-white.svg"
alt=""
style={{
width: 24,
height: 24,
flexShrink: 0,
}}
/>
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 600,
fontSize: 16,
lineHeight: '24px',
color: '#fbfbfc',
whiteSpace: 'nowrap',
}}
>
Order support
</span>
</button>
</div>
</div>
<ShipmentTrackingSheet
shipment={activeShipment}
onClose={() => setActiveShipment(null)}
onCopied={() => showToast('Tracking code copied')}
/>
</MobileShell>
);
};

164
src/pages/orders/ShopOrdersPage.tsx

@ -1,48 +1,186 @@
import React, { useState } from 'react';
import React, { useEffect, useMemo, useState } from 'react';
import { useLocation, useNavigate, useSearchParams } from 'react-router-dom';
import { MobileShell } from '../../components/layout/MobileShell';
import { StandardPageHeader } from '../../components/layout/TopHeader';
import {
EmptyStateBox,
OrdersListShimmer,
RetryBanner,
} from '../../components/common/ShimmerSkeletons';
import { OrderFilterTabs } from '../../components/orders/OrderFilterTabs';
import { OrderListCard } from '../../components/orders/OrderListCard';
import { useShopApp } from '../../context/ShopAppContext';
import {
ORDER_FILTER_TABS,
ORDERS_LIST_CARDS,
type OrderFilterTabItem,
} from '../../data/ordersData';
import { mapOrderToCardData } from '../../lib/mappers';
import { isBareMode, ROUTES, USE_MOCK_DATA } from '../../lib/routes';
import { useOrdersQuery } from '../../lib/shopQueries';
/**
* Node 4175:9811 — `shop-orders` (Orders List, 375×814)
*/
export const ShopOrdersPage: React.FC = () => {
const navigate = useNavigate();
const location = useLocation();
const isBare = isBareMode(location.search);
const useMockFallback = isBare || USE_MOCK_DATA;
const [searchParams, setSearchParams] = useSearchParams();
const { orderCounters } = useShopApp();
const paramTab = searchParams.get('tab');
const initialTab: OrderFilterTabItem['id'] =
paramTab === 'delivered' || paramTab === 'canceled' ? paramTab : 'current';
const [activeTabId, setActiveTabId] =
useState<OrderFilterTabItem['id']>('current');
useState<OrderFilterTabItem['id']>(initialTab);
useEffect(() => {
if (
paramTab === 'current' ||
paramTab === 'delivered' ||
paramTab === 'canceled'
) {
setActiveTabId(paramTab);
}
}, [paramTab]);
const ordersQuery = useOrdersQuery(activeTabId, !isBare);
const orders = ordersQuery.data?.results ?? null;
const loading =
!isBare && (ordersQuery.isPending || (!orders && ordersQuery.isFetching));
const loadError = !isBare && ordersQuery.isError;
const tabs = useMemo<OrderFilterTabItem[]>(() => {
if (isBare) return ORDER_FILTER_TABS;
if (!orderCounters) {
return useMockFallback
? ORDER_FILTER_TABS
: ORDER_FILTER_TABS.map((tab) => ({ ...tab, count: '0' }));
}
return ORDER_FILTER_TABS.map((tab) => ({
...tab,
count:
tab.id === 'current'
? String(orderCounters.current)
: tab.id === 'delivered'
? String(orderCounters.delivered)
: String(orderCounters.canceled),
}));
}, [isBare, orderCounters, useMockFallback]);
const handleSelectTab = (id: OrderFilterTabItem['id']) => {
setActiveTabId(id);
if (!isBare) {
setSearchParams({ tab: id }, { replace: true });
}
};
return (
<MobileShell width={375} height={814} backgroundColor="#f3f1ef">
{/* Top Header: Back button + "Orders" */}
<StandardPageHeader title="Orders" titleTop={29} backTo="/shop-account" />
<StandardPageHeader
title="Orders"
titleTop={29}
backTo={ROUTES.account}
/>
<div
style={{
display: 'flex',
flexDirection: 'column',
flex: 1,
padding: '26px var(--page-px) 28px',
padding: '26px var(--page-px) calc(28px + var(--safe-bottom, 0px))',
gap: 22,
}}
>
{/* Segmented Filter Tabs (4175:9880 + 4175:9892) */}
{/* Segmented Filter Tabs */}
<OrderFilterTabs
tabs={ORDER_FILTER_TABS}
tabs={tabs}
activeTabId={activeTabId}
onSelectTab={(id) => setActiveTabId(id)}
onSelectTab={handleSelectTab}
/>
{/* Order Cards (4175:10954 & 4175:10644) */}
<div className="habib-orders-grid">
{ORDERS_LIST_CARDS.map((order) => (
<OrderListCard key={order.id} order={order} />
))}
</div>
{/* Order Cards */}
{!isBare && loading ? (
<OrdersListShimmer count={2} />
) : !isBare && orders ? (
orders.length > 0 ? (
<div className="habib-orders-grid">
{orders.map((order, idx) => (
<OrderListCard
key={order.id}
order={mapOrderToCardData(order, idx)}
onViewDetails={() =>
navigate(ROUTES.orderDetail(order.order_number))
}
/>
))}
</div>
) : (
<div
style={{
padding: '42px 20px',
borderRadius: 20,
background: 'linear-gradient(180deg, #ffffff 0%, #f8f8f8 100%)',
border: '1px solid #ffffff',
textAlign: 'center',
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
gap: 10,
}}
>
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 15,
color: '#111111',
}}
>
{`No ${activeTabId} orders`}
</span>
<button
type="button"
onClick={() => navigate(ROUTES.home)}
style={{
marginTop: 4,
padding: '9px 18px',
borderRadius: 11,
backgroundColor: '#d78e06',
color: '#ffffff',
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 12,
cursor: 'pointer',
}}
>
Browse Shop
</button>
</div>
)
) : (
<>
{!isBare && loadError && (
<RetryBanner
message="Could not load orders. Tap Retry to refresh."
onRetry={() => void ordersQuery.refetch()}
/>
)}
{useMockFallback ? (
<div className="habib-orders-grid">
{ORDERS_LIST_CARDS.map((order) => (
<OrderListCard key={order.id} order={order} />
))}
</div>
) : (
<EmptyStateBox message={`No ${activeTabId} orders`} />
)}
</>
)}
</div>
</MobileShell>
);

397
src/pages/orders/ShopSupportPage.tsx

@ -1,24 +1,165 @@
import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import React, { useEffect, useRef, useState } from 'react';
import { useLocation, useNavigate, useParams } from 'react-router-dom';
import { MobileShell } from '../../components/layout/MobileShell';
import { StandardPageHeader } from '../../components/layout/TopHeader';
import { EmptyStateBox } from '../../components/common/ShimmerSkeletons';
import { useShopApp } from '../../context/ShopAppContext';
import { SUPPORT_SUBJECT_OPTIONS } from '../../data/ordersData';
import { resolveMediaUrl } from '../../lib/http';
import { isBareMode, ROUTES, USE_MOCK_DATA } from '../../lib/routes';
import {
useCreateSupportTicketMutation,
useOrderDetailQuery,
useSupportSubjectsQuery,
} from '../../lib/shopQueries';
import {
isInFlutterWebView,
uploadBrowserFileToTmpMedia,
uploadFileViaFlutterBridge,
} from '../../lib/webview-actions';
/**
* Node 4177:11244 — `shop-support` (Order Support Request Form, 375×1061)
*/
export const ShopSupportPage: React.FC = () => {
const navigate = useNavigate();
const location = useLocation();
const isBare = isBareMode(location.search);
const useMockFallback = isBare || USE_MOCK_DATA;
const { orderId } = useParams<{ orderId?: string }>();
const { isUserAuthenticated, requireAuth, showToast } = useShopApp();
const [selectedSubjectId, setSelectedSubjectId] = useState('subj-counterfeit');
const [description, setDescription] = useState('');
const [attachmentUrl, setAttachmentUrl] = useState('');
const [uploading, setUploading] = useState(false);
const fileInputRef = useRef<HTMLInputElement | null>(null);
const subjectsQuery = useSupportSubjectsQuery(!isBare);
const orderDetailQuery = useOrderDetailQuery(
orderId || '',
!isBare && Boolean(orderId)
);
const createTicketMutation = useCreateSupportTicketMutation();
const subjects = subjectsQuery.data?.results ?? null;
const orderDetail = orderDetailQuery.data ?? null;
const submitting = createTicketMutation.isPending;
useEffect(() => {
if (isBare || !subjects?.length) return;
setSelectedSubjectId((prev) => {
if (subjects.some((s) => s.slug === prev)) return prev;
const def =
subjects.find((s) => s.slug.includes('counterfeit')) || subjects[0];
return def ? def.slug : prev;
});
}, [isBare, subjects]);
const handleUploadClick = async () => {
if (isBare || uploading) return;
if (isInFlutterWebView()) {
setUploading(true);
try {
const url = await uploadFileViaFlutterBridge();
if (url) {
setAttachmentUrl(url);
showToast('Evidence attached');
}
} finally {
setUploading(false);
}
return;
}
fileInputRef.current?.click();
};
const handleFileChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (!file) return;
e.target.value = '';
setUploading(true);
try {
const url = await uploadBrowserFileToTmpMedia(file);
setAttachmentUrl(url);
showToast('Evidence attached');
} finally {
setUploading(false);
}
};
const handleSubmit = async () => {
if (isBare) {
navigate(ROUTES.orders());
return;
}
if (!isUserAuthenticated) {
const authed = await requireAuth({
featureName: 'order support requests',
});
if (!authed) return;
}
if (!description.trim()) {
showToast('Please enter a description for your support request');
return;
}
if (submitting) return;
try {
const chosenApiSubj = subjects?.find((s) => s.slug === selectedSubjectId);
const chosenStaticSubj = SUPPORT_SUBJECT_OPTIONS.find(
(s) => s.id === selectedSubjectId
);
const ticket = await createTicketMutation.mutateAsync({
order_number: orderDetail?.order_number || orderId || undefined,
product_id: orderDetail?.items?.[0]?.product ?? undefined,
subject: chosenApiSubj?.slug || undefined,
subject_label:
chosenApiSubj?.label || chosenStaticSubj?.label || 'Order Support',
description: description.trim(),
attachment_url: attachmentUrl || undefined,
});
showToast(`Support ticket ${ticket.ticket_number} submitted`);
navigate(orderId ? ROUTES.orderDetail(orderId) : ROUTES.orders());
} catch (err) {
showToast(err instanceof Error ? err.message : 'Could not submit request');
}
};
const firstItem = !isBare ? orderDetail?.items?.[0] : null;
const backTarget = orderId ? ROUTES.orderDetail(orderId) : ROUTES.account;
const displaySubjects =
!isBare && subjects?.length
? subjects.map((s) => ({
id: s.slug,
label: s.label,
iconSrc:
resolveMediaUrl(s.icon_url) ||
'/assets/images/icon-support-other-dots.svg',
}))
: useMockFallback
? SUPPORT_SUBJECT_OPTIONS.map((s) => ({
id: s.id,
label: s.label,
iconSrc: s.iconSrc,
}))
: [];
return (
<MobileShell width={375} height={1061} backgroundColor="#f3f1ef">
<input
ref={fileInputRef}
type="file"
accept="image/*,video/*"
onChange={handleFileChange}
style={{ display: 'none' }}
/>
{/* Top Header: Back button + "Support" */}
<StandardPageHeader
title="Support"
titleTop={29}
backTo="/shop-order-detail"
backTo={backTarget}
/>
<div
@ -26,11 +167,11 @@ export const ShopSupportPage: React.FC = () => {
display: 'flex',
flexDirection: 'column',
flex: 1,
padding: '29px var(--page-px) 20px',
padding: '29px var(--page-px) calc(20px + var(--safe-bottom, 0px))',
gap: 20,
}}
>
{/* Main White Support Card (4177:11307) */}
{/* Main White Support Card */}
<div
style={{
width: '100%',
@ -44,7 +185,8 @@ export const ShopSupportPage: React.FC = () => {
gap: 20,
}}
>
{/* Product Box (4177:11308) */}
{/* Product Box */}
{(useMockFallback || Boolean(firstItem || orderDetail)) && (
<div
style={{
width: '100%',
@ -58,8 +200,11 @@ export const ShopSupportPage: React.FC = () => {
}}
>
<img
src="/assets/images/product-grey-tshirt-model.png"
alt="Islam in the Bible Book"
src={
resolveMediaUrl(firstItem?.image_snapshot) ||
'/assets/images/product-grey-tshirt-model.png'
}
alt={firstItem?.title_snapshot || 'Islam in the Bible Book'}
style={{
width: 59.3,
height: 57,
@ -89,7 +234,12 @@ export const ShopSupportPage: React.FC = () => {
wordBreak: 'break-word',
}}
>
Islam in the Bible Book
{firstItem?.title_snapshot ||
(orderId
? `Order ${orderId}`
: isBare
? 'Islam in the Bible Book'
: 'Habib Shop Support Desk')}
</div>
<div
@ -110,10 +260,12 @@ export const ShopSupportPage: React.FC = () => {
whiteSpace: 'nowrap',
}}
>
$24.00
{firstItem?.formatted_unit_price ||
orderDetail?.formatted_total ||
(useMockFallback ? '$24.00' : '$0.00')}
</span>
{/* Quantity Badge (35×34) */}
{/* Quantity Badge */}
<div
style={{
width: 35,
@ -136,14 +288,15 @@ export const ShopSupportPage: React.FC = () => {
color: '#151c31',
}}
>
1
{firstItem?.quantity ?? 1}
</span>
</div>
</div>
</div>
</div>
)}
{/* Amber Notice Box (4178:11668) */}
{/* Amber Notice Box */}
<div
style={{
width: '100%',
@ -158,7 +311,6 @@ export const ShopSupportPage: React.FC = () => {
gap: 3,
}}
>
{/* Header Row */}
<div
style={{
display: 'inline-flex',
@ -189,7 +341,6 @@ export const ShopSupportPage: React.FC = () => {
</span>
</div>
{/* Body Text */}
<div
style={{
fontFamily: 'var(--font-sans)',
@ -204,7 +355,7 @@ export const ShopSupportPage: React.FC = () => {
</div>
</div>
{/* Request Subject Section (4178:11682) */}
{/* Request Subject Section */}
<div
style={{
display: 'flex',
@ -225,61 +376,65 @@ export const ShopSupportPage: React.FC = () => {
</div>
{/* 6 Subject Tiles Grid */}
<div className="habib-support-subjects-grid">
{SUPPORT_SUBJECT_OPTIONS.map((option) => {
const isSelected = option.id === selectedSubjectId;
{displaySubjects.length > 0 ? (
<div className="habib-support-subjects-grid">
{displaySubjects.map((option) => {
const isSelected = option.id === selectedSubjectId;
return (
<button
key={option.id}
type="button"
onClick={() => setSelectedSubjectId(option.id)}
style={{
width: '100%',
minHeight: 63,
padding: '8px 4px',
borderRadius: 15,
background: isSelected
? 'linear-gradient(180deg, #fff7e9 0%, #fdf9f4 100%)'
: '#ffffff',
border: `1px solid ${isSelected ? '#d78e06' : '#bcbcbc'}`,
boxSizing: 'border-box',
cursor: 'pointer',
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',
gap: 4,
}}
>
<img
src={option.iconSrc}
alt={option.label}
return (
<button
key={option.id}
type="button"
onClick={() => setSelectedSubjectId(option.id)}
style={{
width: 28,
height: 28,
flexShrink: 0,
}}
/>
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: isSelected ? 700 : 600,
fontSize: 10,
lineHeight: '12.9px',
color: isSelected ? '#111111' : '#3d3d3d',
textAlign: 'center',
width: '100%',
minHeight: 63,
padding: '8px 4px',
borderRadius: 15,
background: isSelected
? 'linear-gradient(180deg, #fff7e9 0%, #fdf9f4 100%)'
: '#ffffff',
border: `1px solid ${isSelected ? '#d78e06' : '#bcbcbc'}`,
boxSizing: 'border-box',
cursor: 'pointer',
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',
gap: 4,
}}
>
{option.label}
</span>
</button>
);
})}
</div>
<img
src={option.iconSrc}
alt={option.label}
style={{
width: 28,
height: 28,
flexShrink: 0,
}}
/>
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: isSelected ? 700 : 600,
fontSize: 10,
lineHeight: '12.9px',
color: isSelected ? '#111111' : '#3d3d3d',
textAlign: 'center',
}}
>
{option.label}
</span>
</button>
);
})}
</div>
) : (
<EmptyStateBox message="No support subjects available." compact />
)}
</div>
{/* Description* Section (4178:11675) */}
{/* Description* Section */}
<div
style={{
display: 'flex',
@ -324,7 +479,7 @@ export const ShopSupportPage: React.FC = () => {
/>
</div>
{/* Add Evidence or Image(Optional) Section (4178:11683) */}
{/* Add Evidence or Image(Optional) Section */}
<div
style={{
display: 'flex',
@ -345,61 +500,94 @@ export const ShopSupportPage: React.FC = () => {
</div>
<div
onClick={() => {
void handleUploadClick();
}}
style={{
width: '100%',
minHeight: 100,
padding: '16px 12px',
borderRadius: 15,
border: '1px dashed #bcbcbc',
border: `1px dashed ${attachmentUrl ? '#0eb13c' : '#bcbcbc'}`,
boxSizing: 'border-box',
cursor: 'pointer',
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',
gap: 2,
gap: 4,
}}
>
<img
src="/assets/images/icon-upload-image-placeholder.svg"
alt=""
style={{
width: 24,
height: 24,
}}
/>
<div
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 400,
fontSize: 14,
lineHeight: '20px',
color: '#111111',
textAlign: 'center',
}}
>
+ Upload Image
</div>
<div
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 12,
lineHeight: '17px',
color: '#bcbcbc',
textAlign: 'center',
}}
>
mp4, mpeg, h24
</div>
{attachmentUrl ? (
<>
<img
src={resolveMediaUrl(attachmentUrl)}
alt="Uploaded evidence"
style={{
width: 56,
height: 56,
borderRadius: 10,
objectFit: 'cover',
}}
/>
<div
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 600,
fontSize: 12,
color: '#0eb13c',
}}
>
Attachment ready (tap to replace)
</div>
</>
) : (
<>
<img
src="/assets/images/icon-upload-image-placeholder.svg"
alt=""
style={{
width: 24,
height: 24,
}}
/>
<div
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 400,
fontSize: 14,
lineHeight: '20px',
color: '#111111',
textAlign: 'center',
}}
>
{uploading ? 'Uploading...' : '+ Upload Image'}
</div>
<div
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 12,
lineHeight: '17px',
color: '#bcbcbc',
textAlign: 'center',
}}
>
mp4, mpeg, h24
</div>
</>
)}
</div>
</div>
</div>
{/* Bottom CTA Button "Submit Order" (4177:11292) */}
{/* Bottom CTA Button "Submit Order" */}
<button
type="button"
onClick={() => navigate('/shop-orders')}
disabled={submitting}
onClick={() => {
void handleSubmit();
}}
style={{
marginTop: 'auto',
width: '100%',
@ -408,7 +596,8 @@ export const ShopSupportPage: React.FC = () => {
backgroundColor: '#d78e06',
border: 'none',
padding: '0 16px',
cursor: 'pointer',
cursor: submitting ? 'not-allowed' : 'pointer',
opacity: submitting ? 0.65 : 1,
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
@ -434,7 +623,7 @@ export const ShopSupportPage: React.FC = () => {
whiteSpace: 'nowrap',
}}
>
Submit Order
{submitting ? 'Submitting...' : 'Submit Order'}
</span>
</button>
</div>

37
src/types/window.d.ts

@ -0,0 +1,37 @@
export interface FlutterResponsePayload {
action?: string;
success?: boolean;
error?: string;
data?: Record<string, unknown>;
[key: string]: unknown;
}
export type FlutterResponseListener = (payload: FlutterResponsePayload) => void;
declare global {
interface Window {
HabibApp?: {
postMessage: (message: string) => void;
};
FlutterChannel?: {
postMessage: (message: string) => void;
};
HABIB_TOKEN?: string;
HABIB_COINS?: number;
HABIB_WEB_READY_SENT?: boolean;
__announceHabibWebReady?: () => void;
onFlutterResponse?: (payload: FlutterResponsePayload | string) => void;
addFlutterResponseListener?: (listener: FlutterResponseListener) => () => void;
__habibHandleHardwareBack?: () => Promise<boolean> | boolean;
__habibHandleHardwareBackSync?: () => boolean;
__habibNavigate?: (to: string) => void;
}
interface WindowEventMap {
'habib:auth-token-changed': CustomEvent<{ token: string; previousToken: string }>;
'habib:coins-changed': CustomEvent<{ coins: number }>;
}
}
export {};

37
vite.config.ts

@ -49,7 +49,6 @@ function clickToComponentServerPlugin(): Plugin {
return
}
// Alt + Right Click -> Open in Antigravity Desktop App's Auxiliary Panel (right split)
if (target === 'app') {
try {
const result = await openInAntigravityApp(locator)
@ -66,7 +65,6 @@ function clickToComponentServerPlugin(): Plugin {
return
}
// Alt + Left Click (default) -> Open in Antigravity IDE (or fallback to VS Code / Cursor)
const isWindows = os.platform() === 'win32'
const bin = isWindows ? 'antigravity-ide.cmd' : 'antigravity-ide'
const cmd = `${bin} -r -g "${locator}"`
@ -116,6 +114,27 @@ function clickToComponentServerPlugin(): Plugin {
}
}
const backendOrigin = process.env.VITE_BACKEND_ORIGIN || 'http://127.0.0.1:9000'
const apiProxy = {
'/api/shop': {
target: backendOrigin,
changeOrigin: true,
},
'/habcoin': {
target: backendOrigin,
changeOrigin: true,
},
'/upload-tmp-media': {
target: backendOrigin,
changeOrigin: true,
},
'/media': {
target: backendOrigin,
changeOrigin: true,
},
}
// https://vite.dev/config/
export default defineConfig(({ command }) => ({
plugins: [
@ -126,4 +145,18 @@ export default defineConfig(({ command }) => ({
}),
clickToComponentServerPlugin(),
],
server: {
host: '0.0.0.0',
port: 5173,
strictPort: true,
allowedHosts: true,
proxy: apiProxy,
},
preview: {
host: '0.0.0.0',
port: 5178,
strictPort: true,
allowedHosts: true,
proxy: apiProxy,
},
}))
Loading…
Cancel
Save