Browse Source

feat: implement mobile-first shop interface with pages, components, and api integration

main
sina_sajjadi 2 weeks ago
parent
commit
a91aa43bb6
  1. 2
      .env
  2. 139
      index.html
  3. 18
      package-lock.json
  4. 4
      package.json
  5. 11
      src/components/account/HabibCoinsBanner.tsx
  6. 1
      src/components/bridge/HabibBridgeProviders.tsx
  7. 2
      src/components/checkout/AddressCard.tsx
  8. 3
      src/components/checkout/CartItemCard.tsx
  9. 2
      src/components/checkout/PaymentMethodCard.tsx
  10. 669
      src/components/common/PhoneNumberInput.tsx
  11. 407
      src/components/common/ShimmerSkeletons.tsx
  12. 2
      src/components/layout/BottomNavBar.tsx
  13. 68
      src/components/layout/MobileShell.tsx
  14. 1
      src/components/layout/TopHeader.tsx
  15. 67
      src/components/modals/AddressFormSheet.tsx
  16. 7
      src/components/modals/LoginRequiredModal.tsx
  17. 81
      src/components/modals/OrderSummarySheet.tsx
  18. 82
      src/components/modals/PaymentMethodsSheet.tsx
  19. 31
      src/components/modals/ShipmentTrackingSheet.tsx
  20. 38
      src/components/orders/OrderFilterTabs.tsx
  21. 86
      src/context/ShopAppContext.tsx
  22. 32
      src/hooks/use-animated-presence.ts
  23. 13
      src/hooks/useSmartBack.ts
  24. 298
      src/index.css
  25. 44
      src/lib/cookies.ts
  26. 42
      src/lib/http.ts
  27. 403
      src/lib/phone.ts
  28. 54
      src/lib/shopApi.ts
  29. 21
      src/pages/account/LanguageSettingPage.tsx
  30. 128
      src/pages/account/ProviderRequestPage.tsx
  31. 7
      src/pages/account/ShopAccountPage.tsx
  32. 15
      src/pages/catalog/ShopSinglePage.tsx
  33. 3
      src/pages/chat/ShopChatPage.tsx
  34. 15
      src/pages/checkout/ShopBuy01Page.tsx
  35. 19
      src/pages/checkout/ShopCartPage.tsx
  36. 2
      src/pages/checkout/ShopPayResultPage.tsx
  37. 1
      src/pages/checkout/ShopPaymentMethodsPage.tsx
  38. 67
      src/pages/checkout/ShopPaymentPage.tsx
  39. 1
      src/pages/orders/ShopOrderDetailPage.tsx
  40. 7
      src/pages/orders/ShopOrdersPage.tsx
  41. 2
      vite.config.ts

2
.env

@ -1,3 +1,5 @@
# Set to true to fall back to mock data when backend responses are empty or offline
VITE_USE_MOCK_DATA=false
VITE_BACKEND_ORIGIN=http://127.0.0.1:8000

139
index.html

@ -8,6 +8,83 @@
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>
<style id="habib-boot-shimmer-styles">
html,
body {
margin: 0;
padding: 0;
background-color: #f3f1ef;
-webkit-tap-highlight-color: transparent;
}
@media (min-width: 1024px) {
html,
body {
background-color: #1e2229;
}
}
@keyframes habib-boot-sweep {
0% {
background-position: 180% 0;
}
100% {
background-position: -40% 0;
}
}
.habib-boot-shell {
width: 100%;
min-height: 100vh;
min-height: 100dvh;
display: flex;
flex-direction: column;
align-items: center;
background-color: #f3f1ef;
}
@media (min-width: 1024px) {
.habib-boot-shell {
padding: 0 16px;
background-color: #1e2229;
}
}
.habib-boot-viewport {
width: 100%;
max-width: 100%;
min-height: 100vh;
min-height: 100dvh;
background-color: #f3f1ef;
display: flex;
flex-direction: column;
justify-content: space-between;
box-sizing: border-box;
overflow: hidden;
}
@media (min-width: 1024px) {
.habib-boot-viewport {
width: 375px;
box-shadow: 0 20px 50px rgba(0, 0, 0, 0.45);
}
}
.habib-boot-bone {
background: linear-gradient(90deg, #e5e1dc 0%, #f6f4f1 48%, #e5e1dc 96%);
background-size: 220% 100%;
animation: habib-boot-sweep 1.5s cubic-bezier(0.4, 0, 0.2, 1) infinite;
flex-shrink: 0;
}
html.is-bare-boot .habib-boot-shell {
display: none !important;
}
</style>
<script>
try {
if (
window.location.search.indexOf('bare=1') !== -1 ||
window.location.search.indexOf('embed=1') !== -1 ||
window.location.pathname.indexOf('/node/') === 0 ||
window.location.pathname === '/test'
) {
document.documentElement.classList.add('is-bare-boot');
}
} catch (_eBoot) {}
</script>
<script id="habib-core-bootstrap">
(function () {
var listeners = new Set();
@ -300,7 +377,67 @@
</script>
</head>
<body>
<div id="root"></div>
<div id="root">
<div class="habib-boot-shell" aria-hidden="true">
<div class="habib-boot-viewport">
<div style="padding: 37px 16px 22px; display: flex; flex-direction: column; gap: 20px;">
<div style="display: flex; align-items: center; justify-content: space-between; min-height: 40px; margin-bottom: 11px;">
<div class="habib-boot-bone" style="width: 40px; height: 40px; border-radius: 15px;"></div>
<div class="habib-boot-bone" style="width: 68px; height: 22px; border-radius: 8px;"></div>
<div class="habib-boot-bone" style="width: 40px; height: 40px; border-radius: 15px;"></div>
</div>
<div style="display: flex; gap: 10px; align-items: center;">
<div class="habib-boot-bone" style="flex: 1; height: 44px; border-radius: 14px;"></div>
<div class="habib-boot-bone" style="width: 44px; height: 44px; border-radius: 14px;"></div>
</div>
<div class="habib-boot-bone" style="width: 100%; height: 164px; border-radius: 15px;"></div>
<div style="display: grid; grid-template-columns: repeat(5, minmax(0, 1fr)); gap: 2px;">
<div style="display: flex; flex-direction: column; align-items: center; gap: 6px;">
<div class="habib-boot-bone" style="width: 43px; height: 43px; border-radius: 50%;"></div>
<div class="habib-boot-bone" style="width: 36px; height: 9px; border-radius: 4px;"></div>
</div>
<div style="display: flex; flex-direction: column; align-items: center; gap: 6px;">
<div class="habib-boot-bone" style="width: 43px; height: 43px; border-radius: 50%;"></div>
<div class="habib-boot-bone" style="width: 36px; height: 9px; border-radius: 4px;"></div>
</div>
<div style="display: flex; flex-direction: column; align-items: center; gap: 6px;">
<div class="habib-boot-bone" style="width: 43px; height: 43px; border-radius: 50%;"></div>
<div class="habib-boot-bone" style="width: 36px; height: 9px; border-radius: 4px;"></div>
</div>
<div style="display: flex; flex-direction: column; align-items: center; gap: 6px;">
<div class="habib-boot-bone" style="width: 43px; height: 43px; border-radius: 50%;"></div>
<div class="habib-boot-bone" style="width: 36px; height: 9px; border-radius: 4px;"></div>
</div>
<div style="display: flex; flex-direction: column; align-items: center; gap: 6px;">
<div class="habib-boot-bone" style="width: 43px; height: 43px; border-radius: 50%;"></div>
<div class="habib-boot-bone" style="width: 36px; height: 9px; border-radius: 4px;"></div>
</div>
</div>
<div style="display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 12px;">
<div style="padding: 12px; border-radius: 15px; background: #ffffff; display: flex; flex-direction: column; gap: 8px;">
<div class="habib-boot-bone" style="width: 100%; height: 112px; border-radius: 10px;"></div>
<div class="habib-boot-bone" style="width: 62%; height: 10px; border-radius: 5px;"></div>
<div class="habib-boot-bone" style="width: 90%; height: 13px; border-radius: 6px;"></div>
<div class="habib-boot-bone" style="width: 54px; height: 15px; border-radius: 6px;"></div>
</div>
<div style="padding: 12px; border-radius: 15px; background: #ffffff; display: flex; flex-direction: column; gap: 8px;">
<div class="habib-boot-bone" style="width: 100%; height: 112px; border-radius: 10px;"></div>
<div class="habib-boot-bone" style="width: 62%; height: 10px; border-radius: 5px;"></div>
<div class="habib-boot-bone" style="width: 90%; height: 13px; border-radius: 6px;"></div>
<div class="habib-boot-bone" style="width: 54px; height: 15px; border-radius: 6px;"></div>
</div>
</div>
</div>
<div style="height: 78px; border-radius: 17px 17px 0 0; background: #ffffff; display: flex; align-items: center; justify-content: space-around; padding: 0 16px;">
<div class="habib-boot-bone" style="width: 36px; height: 36px; border-radius: 10px;"></div>
<div class="habib-boot-bone" style="width: 36px; height: 36px; border-radius: 10px;"></div>
<div class="habib-boot-bone" style="width: 54px; height: 48px; border-radius: 24px;"></div>
<div class="habib-boot-bone" style="width: 36px; height: 36px; border-radius: 10px;"></div>
<div class="habib-boot-bone" style="width: 36px; height: 36px; border-radius: 10px;"></div>
</div>
</div>
</div>
</div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>

18
package-lock.json

@ -9,6 +9,7 @@
"version": "0.0.0",
"dependencies": {
"@tanstack/react-query": "^5.105.1",
"google-libphonenumber": "^3.2.48",
"react": "^19.3.1",
"react-dom": "^19.3.1",
"react-router-dom": "^7.18.5"
@ -17,6 +18,7 @@
"@babel/core": "^7.29.7",
"@rolldown/plugin-babel": "^0.2.4",
"@types/babel__core": "^7.20.5",
"@types/google-libphonenumber": "^7.4.31",
"@types/node": "^24.19.2",
"@types/react": "^19.3.0",
"@types/react-dom": "^19.3.0",
@ -1062,6 +1064,13 @@
"@babel/types": "^7.28.2"
}
},
"node_modules/@types/google-libphonenumber": {
"version": "7.4.31",
"resolved": "https://registry.npmjs.org/@types/google-libphonenumber/-/google-libphonenumber-7.4.31.tgz",
"integrity": "sha512-NqtRPbLfRbCsqYTVb2UHM67AhMUfTYarxy32u14QilQq7i2C37jtvxbEmb0U0oCMMZtFfpoAtbuhrXwF7/EyVg==",
"dev": true,
"license": "MIT"
},
"node_modules/@types/node": {
"version": "24.19.2",
"resolved": "https://registry.npmjs.org/@types/node/-/node-24.19.2.tgz",
@ -1655,6 +1664,15 @@
"node": ">=6.9.0"
}
},
"node_modules/google-libphonenumber": {
"version": "3.2.48",
"resolved": "https://registry.npmjs.org/google-libphonenumber/-/google-libphonenumber-3.2.48.tgz",
"integrity": "sha512-x8Z8baHTiMchHIcQUsCU5HNwbCVA8UOoVkOMfGxOpCtkoUG6pAAp6jtjKILHgmhNzEb6t3t8i4UxAMIkNZr3DA==",
"license": "(MIT AND Apache-2.0)",
"engines": {
"node": ">=0.10"
}
},
"node_modules/js-tokens": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",

4
package.json

@ -4,13 +4,14 @@
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"dev": "vite --host",
"build": "tsc -b && vite build",
"lint": "oxlint",
"preview": "vite preview"
},
"dependencies": {
"@tanstack/react-query": "^5.105.1",
"google-libphonenumber": "^3.2.48",
"react": "^19.3.1",
"react-dom": "^19.3.1",
"react-router-dom": "^7.18.5"
@ -19,6 +20,7 @@
"@babel/core": "^7.29.7",
"@rolldown/plugin-babel": "^0.2.4",
"@types/babel__core": "^7.20.5",
"@types/google-libphonenumber": "^7.4.31",
"@types/node": "^24.19.2",
"@types/react": "^19.3.0",
"@types/react-dom": "^19.3.0",

11
src/components/account/HabibCoinsBanner.tsx

@ -19,10 +19,15 @@ export const HabibCoinsBanner: React.FC<HabibCoinsBannerProps> = ({
}) => {
const location = useLocation();
const isBare = isBareMode(location.search);
const { habibCoinsBalance, setHabibCoinsBalance, showToast } = useShopApp();
const { showToast } = useShopApp();
const [hostCoins, setHostCoins] = React.useState<number>(() =>
typeof window !== 'undefined' && typeof window.HABIB_COINS === 'number'
? window.HABIB_COINS
: 21
);
const resolvedCoins =
coinsCount !== undefined ? coinsCount : isBare ? 21 : habibCoinsBalance;
coinsCount !== undefined ? coinsCount : isBare ? 21 : hostCoins;
const handleBuyCoins = async () => {
if (onBuyCoins) {
@ -32,7 +37,7 @@ export const HabibCoinsBanner: React.FC<HabibCoinsBannerProps> = ({
if (isInFlutterWebView()) {
const updated = await buyHabibCoinPackages();
if (typeof updated === 'number') {
setHabibCoinsBalance(updated);
setHostCoins(updated);
showToast(`Balance updated: ${updated} Habib Coins`);
}
return;

1
src/components/bridge/HabibBridgeProviders.tsx

@ -65,6 +65,7 @@ export const HabibBridgeProviders: React.FC<{ children: React.ReactNode }> = ({
<div
role="status"
aria-live="polite"
className="habib-toast"
style={{
position: 'fixed',
bottom: 'calc(92px + var(--safe-bottom, 0px))',

2
src/components/checkout/AddressCard.tsx

@ -52,10 +52,12 @@ export const AddressCard: React.FC<AddressCardProps> = ({
alignItems: 'center',
justifyContent: 'center',
flexShrink: 0,
transition: 'background-color 180ms ease, border-color 180ms ease',
}}
>
{item.selected && (
<div
className="habib-radio-dot"
style={{
width: '8px',
height: '8px',

3
src/components/checkout/CartItemCard.tsx

@ -117,6 +117,7 @@ export const MainCartItemCard: React.FC<MainCartItemCardProps> = ({
{/* Close / Remove Button */}
<div
className={onRemove ? 'habib-icon-btn' : undefined}
onClick={() => onRemove?.(item.id)}
role={onRemove ? 'button' : undefined}
aria-label="Remove item"
@ -210,6 +211,8 @@ export const MainCartItemCard: React.FC<MainCartItemCardProps> = ({
{/* Quantity Number */}
<span
key={item.quantity}
className="habib-badge-pop"
style={{
position: 'absolute',
left: '30px',

2
src/components/checkout/PaymentMethodCard.tsx

@ -42,10 +42,12 @@ export const PaymentMethodCard: React.FC<PaymentMethodCardProps> = ({
alignItems: 'center',
justifyContent: 'center',
flexShrink: 0,
transition: 'background-color 180ms ease, border-color 180ms ease',
}}
>
{isSelected && (
<div
className="habib-radio-dot"
style={{
width: '8px',
height: '8px',

669
src/components/common/PhoneNumberInput.tsx

@ -0,0 +1,669 @@
import React, { useEffect, useMemo, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
import { useAnimatedPresence } from '../../hooks/use-animated-presence';
import { useHardwareBackHandler } from '../../hooks/use-hardware-back-handler';
import {
getDialCodeForCountryName,
getPlaceholderForDialCode,
getSupportedCountryOptions,
parsePhoneParts,
resolveRegionFromDialCode,
validatePhoneNumber,
} from '../../lib/phone';
import { EmptyStateBox } from './ShimmerSkeletons';
export interface PhoneNumberInputProps {
id?: string;
value: string;
onChange: (nextValue: string, isValid: boolean, e164: string | null) => void;
countryHint?: string;
defaultDialCode?: string;
required?: boolean;
bare?: boolean;
height?: number;
borderRadius?: number;
backgroundColor?: string;
borderColor?: string;
fontSize?: number;
showError?: boolean;
errorMessage?: string | null;
}
export const PhoneNumberInput: React.FC<PhoneNumberInputProps> = ({
id,
value,
onChange,
countryHint,
defaultDialCode = '+1',
required = true,
bare = false,
height = 44,
borderRadius = 12,
backgroundColor = '#ffffff',
borderColor = '#d7dbe2',
fontSize = 13,
showError = false,
errorMessage,
}) => {
const resolvedDefaultDial = useMemo(
() =>
countryHint
? getDialCodeForCountryName(countryHint, defaultDialCode)
: defaultDialCode,
[countryHint, defaultDialCode]
);
const initialParts = useMemo(
() => parsePhoneParts(value, resolvedDefaultDial, countryHint),
// eslint-disable-next-line react-hooks/exhaustive-deps
[]
);
const [dialCode, setDialCode] = useState<string>(initialParts.dialCode);
const [selectedRegion, setSelectedRegion] = useState<string>(
initialParts.regionCode
);
const [nationalInput, setNationalInput] = useState<string>(
initialParts.nationalInput
);
const [touched, setTouched] = useState(false);
const [pickerOpen, setPickerOpen] = useState(false);
const [searchQuery, setSearchQuery] = useState('');
const listRef = useRef<HTMLDivElement | null>(null);
const lastEmittedValueRef = useRef<string>(value);
const userSelectedCountryRef = useRef<boolean>(false);
const prevCountryHintRef = useRef<string | undefined>(countryHint);
const { shouldRender: shouldRenderSheet, isClosing: isSheetClosing } =
useAnimatedPresence(pickerOpen, 200);
const closeSheet = () => {
setPickerOpen(false);
setSearchQuery('');
};
useHardwareBackHandler(() => {
closeSheet();
return true;
}, pickerOpen);
// Sync only when external value changes from outside (e.g. profile loaded or address modal opened)
useEffect(() => {
if (value === lastEmittedValueRef.current) return;
lastEmittedValueRef.current = value;
if (!value) {
setNationalInput('');
if (!userSelectedCountryRef.current) {
setDialCode(resolvedDefaultDial);
setSelectedRegion(resolveRegionFromDialCode(resolvedDefaultDial));
}
return;
}
const parsed = parsePhoneParts(
value,
dialCode || resolvedDefaultDial,
countryHint
);
setDialCode(parsed.dialCode);
setSelectedRegion(parsed.regionCode);
setNationalInput(parsed.nationalInput);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [value]);
// Update dial code only if countryHint prop itself changes and user hasn't picked a code or typed a number
useEffect(() => {
if (countryHint === prevCountryHintRef.current) return;
prevCountryHintRef.current = countryHint;
if (!countryHint || userSelectedCountryRef.current || nationalInput.trim()) {
return;
}
const nextDial = getDialCodeForCountryName(countryHint, defaultDialCode);
setDialCode(nextDial);
setSelectedRegion(resolveRegionFromDialCode(nextDial));
}, [countryHint, defaultDialCode, nationalInput]);
// Ensure list starts scrolled at the top when opened or when search query changes
useEffect(() => {
if (pickerOpen && listRef.current) {
listRef.current.scrollTop = 0;
}
}, [pickerOpen, searchQuery]);
const countries = useMemo(() => getSupportedCountryOptions('en'), []);
const activeCountry = useMemo(() => {
const bySelectedRegion = countries.find(
(c) => c.region === selectedRegion && c.dialCode === dialCode
);
if (bySelectedRegion) return bySelectedRegion;
const fallbackRegion = resolveRegionFromDialCode(dialCode);
return (
countries.find((c) => c.region === fallbackRegion) ||
countries.find((c) => c.dialCode === dialCode) ||
null
);
}, [countries, dialCode, selectedRegion]);
const filteredCountries = useMemo(() => {
const q = searchQuery.trim().toLowerCase();
if (!q) return countries;
const digits = q.replace(/\D/g, '');
return countries
.filter(
(c) =>
c.name.toLowerCase().includes(q) ||
c.region.toLowerCase().includes(q) ||
c.dialCode.includes(q) ||
(digits.length > 0 && c.callingCode.includes(digits))
)
.sort((a, b) => {
if (digits) {
const aExact = a.callingCode === digits;
const bExact = b.callingCode === digits;
if (aExact && !bExact) return -1;
if (!aExact && bExact) return 1;
const aStarts = a.callingCode.startsWith(digits);
const bStarts = b.callingCode.startsWith(digits);
if (aStarts && !bStarts) return -1;
if (!aStarts && bStarts) return 1;
}
const aStartsName = a.name.toLowerCase().startsWith(q);
const bStartsName = b.name.toLowerCase().startsWith(q);
if (aStartsName && !bStartsName) return -1;
if (!aStartsName && bStartsName) return 1;
return a.name.localeCompare(b.name, 'en');
});
}, [countries, searchQuery]);
const validation = useMemo(
() => validatePhoneNumber(dialCode, nationalInput, selectedRegion),
[dialCode, nationalInput, selectedRegion]
);
const hasError =
!bare &&
(showError || (touched && nationalInput.trim().length > 0)) &&
!validation.isValid;
const placeholderText = bare
? 'Phone number'
: `${getPlaceholderForDialCode(dialCode)}${required ? ' *' : ''}`;
const emitChange = (
nextDial: string,
nextNational: string,
nextRegion: string
) => {
const res = validatePhoneNumber(nextDial, nextNational, nextRegion);
const combined = nextNational ? `${nextDial} ${nextNational}` : '';
lastEmittedValueRef.current = combined;
onChange(combined, res.isValid, res.e164);
};
const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const raw = e.target.value;
if (bare) {
setNationalInput(raw);
lastEmittedValueRef.current = raw;
onChange(raw, true, raw);
return;
}
const nextNational = raw.replace(/[^\d]/g, '');
setNationalInput(nextNational);
emitChange(dialCode, nextNational, selectedRegion);
};
const handleSelectCountry = (nextDialCode: string, nextRegion: string) => {
userSelectedCountryRef.current = true;
setDialCode(nextDialCode);
setSelectedRegion(nextRegion);
closeSheet();
emitChange(nextDialCode, nationalInput, nextRegion);
};
return (
<div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
<div
dir="ltr"
style={{
width: '100%',
height,
padding: '0 15px',
borderRadius,
backgroundColor,
border: `1px solid ${hasError ? '#d44747' : borderColor}`,
boxSizing: 'border-box',
display: 'flex',
alignItems: 'center',
gap: 8,
}}
>
{bare ? (
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 400,
fontSize,
lineHeight: '20px',
color: '#292a2e',
flexShrink: 0,
}}
>
+23
</span>
) : (
<button
type="button"
onClick={() => setPickerOpen(true)}
aria-label="Select country code"
style={{
display: 'inline-flex',
alignItems: 'center',
gap: 5,
background: 'transparent',
border: 'none',
padding: 0,
cursor: 'pointer',
fontFamily: 'var(--font-sans)',
fontWeight: 600,
fontSize,
lineHeight: '20px',
color: '#292a2e',
flexShrink: 0,
}}
>
{activeCountry?.flag && (
<span aria-hidden="true" style={{ fontSize: fontSize + 1 }}>
{activeCountry.flag}
</span>
)}
<span>{dialCode}</span>
<svg
aria-hidden="true"
width="10"
height="6"
viewBox="0 0 10 6"
fill="none"
style={{
flexShrink: 0,
color: '#73889d',
transform: pickerOpen ? 'rotate(180deg)' : 'none',
transition: 'transform 180ms ease',
}}
>
<path
d="M1 1L5 5L9 1"
stroke="currentColor"
strokeWidth="1.5"
strokeLinecap="round"
strokeLinejoin="round"
/>
</svg>
</button>
)}
<div
style={{
width: 1,
height: 17,
backgroundColor: '#292a2e',
flexShrink: 0,
}}
/>
<input
id={id}
type="tel"
inputMode="tel"
required={required}
className="habib-search-input"
value={bare ? value : nationalInput}
maxLength={bare ? undefined : 15}
onChange={handleInputChange}
onBlur={() => setTouched(true)}
placeholder={placeholderText}
style={{
flex: 1,
minWidth: 0,
height: '100%',
border: 'none',
outline: 'none',
padding: 0,
fontFamily: 'var(--font-sans)',
fontWeight: 400,
fontSize,
lineHeight: '20px',
color: '#111111',
backgroundColor: 'transparent',
}}
/>
</div>
{hasError && (
<span
role="alert"
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 600,
fontSize: 11,
lineHeight: '15px',
color: '#d44747',
paddingLeft: 2,
}}
>
{errorMessage || validation.error || 'Enter a valid phone number'}
</span>
)}
{shouldRenderSheet &&
!bare &&
typeof document !== 'undefined' &&
createPortal(
<div
className={`habib-sheet-backdrop${isSheetClosing ? ' is-closing' : ''}`}
onClick={closeSheet}
style={{
position: 'fixed',
inset: 0,
backgroundColor: 'rgba(17, 17, 17, 0.9)',
zIndex: 140,
display: 'flex',
flexDirection: 'column',
justifyContent: 'flex-end',
}}
>
<div
className={`habib-bottom-sheet${isSheetClosing ? ' is-closing' : ''}`}
onClick={(e) => e.stopPropagation()}
style={{
height: '78dvh',
maxHeight: 620,
backgroundColor: '#f3f1ef',
padding:
'22px var(--page-px, 16px) calc(20px + var(--safe-bottom, 0px))',
display: 'flex',
flexDirection: 'column',
gap: 14,
overflow: 'hidden',
boxSizing: 'border-box',
}}
>
{/* Sheet Header */}
<div
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
gap: 12,
flexShrink: 0,
}}
>
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 15,
lineHeight: '20px',
color: '#111111',
}}
>
Select Country Code
</span>
<button
type="button"
className="habib-icon-btn"
onClick={closeSheet}
aria-label="Close country selector"
style={{
width: 24,
height: 24,
background: 'transparent',
border: 'none',
padding: 0,
cursor: 'pointer',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
flexShrink: 0,
}}
>
<img
src="/assets/images/icon-modal-close-cross.svg"
alt=""
style={{ width: 11.67, height: 11.67, display: 'block' }}
/>
</button>
</div>
{/* Search Input matching Habib Shop SearchBar design */}
<div
style={{
position: 'relative',
width: '100%',
height: 50,
borderRadius: 15,
backgroundColor: '#ffffff',
border: '1px solid #e5e2dd',
boxSizing: 'border-box',
flexShrink: 0,
}}
>
<img
src="/assets/images/icon-search-magnifier.svg"
alt="Search"
style={{
position: 'absolute',
left: 9,
top: 13,
width: 23.83,
height: 24,
pointerEvents: 'none',
}}
/>
<input
type="search"
enterKeyHint="search"
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
className="habib-search-input"
placeholder="Search country name or code (+1, +98...)"
aria-label="Search country name or code"
style={{
width: '100%',
height: '100%',
borderRadius: 15,
padding: searchQuery
? '15px 36px 17px 39px'
: '15px 12px 17px 39px',
fontFamily: 'var(--font-sans)',
fontWeight: 400,
fontSize: 12,
lineHeight: '18px',
color: '#111111',
backgroundColor: 'transparent',
boxSizing: 'border-box',
}}
/>
{searchQuery && (
<button
type="button"
className="habib-icon-btn"
onClick={() => setSearchQuery('')}
aria-label="Clear search"
style={{
position: 'absolute',
right: 10,
top: '50%',
transform: 'translateY(-50%)',
width: 22,
height: 22,
borderRadius: '50%',
backgroundColor: 'rgba(115, 136, 157, 0.14)',
border: 'none',
padding: 0,
cursor: 'pointer',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
}}
>
<img
src="/assets/images/icon-modal-close-cross.svg"
alt=""
style={{ width: 8.5, height: 8.5, display: 'block' }}
/>
</button>
)}
</div>
{/* Scrollable Country List */}
<div
ref={listRef}
style={{
display: 'flex',
flexDirection: 'column',
gap: 8,
overflowY: 'auto',
overscrollBehavior: 'contain',
flex: 1,
minHeight: 0,
paddingTop: 2,
paddingBottom: 6,
}}
>
{filteredCountries.length > 0 ? (
filteredCountries.map((country) => {
const selected =
country.dialCode === dialCode &&
country.region === activeCountry?.region;
return (
<button
key={`${country.region}-${country.dialCode}`}
type="button"
onClick={() =>
handleSelectCountry(country.dialCode, country.region)
}
style={{
width: '100%',
minHeight: 52,
padding: '11px 12px',
borderRadius: 15,
background: selected
? 'linear-gradient(180deg, #fff7e9 0%, #fdf9f4 100%)'
: '#ffffff',
border: selected
? '1px solid #d78e06'
: '1px solid transparent',
boxSizing: 'border-box',
cursor: 'pointer',
display: 'flex',
alignItems: 'center',
gap: 12,
flexShrink: 0,
textAlign: 'left',
transition:
'background-color 180ms ease, border-color 180ms ease',
}}
>
{/* Radio Indicator 20x20 matching AddressCard / PaymentMethodCard */}
<div
style={{
width: 20,
height: 20,
borderRadius: 10,
backgroundColor: selected ? '#d78e06' : 'transparent',
border: selected ? undefined : '1px solid #dbdbdb',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
flexShrink: 0,
transition:
'background-color 180ms ease, border-color 180ms ease',
}}
>
{selected && (
<div
className="habib-radio-dot"
style={{
width: 8,
height: 8,
borderRadius: '50%',
backgroundColor: '#ffffff',
}}
/>
)}
</div>
{/* Flag Badge */}
<div
style={{
width: 30,
height: 30,
borderRadius: 9,
backgroundColor: selected
? 'rgba(215, 142, 6, 0.14)'
: 'rgba(208, 208, 208, 0.25)',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
fontSize: 16,
flexShrink: 0,
}}
>
{country.flag}
</div>
{/* Country Name */}
<span
style={{
flex: 1,
minWidth: 0,
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 13,
lineHeight: '18px',
color: '#292a2e',
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
}}
>
{country.name}
</span>
{/* Dial Code Pill */}
<span
dir="ltr"
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 12,
lineHeight: '17px',
color: selected ? '#d78e06' : '#73889d',
backgroundColor: selected
? 'rgba(215, 142, 6, 0.12)'
: '#f3f1ef',
padding: '3px 8px',
borderRadius: 8,
flexShrink: 0,
}}
>
{country.dialCode}
</span>
</button>
);
})
) : (
<EmptyStateBox message="No countries found." compact />
)}
</div>
</div>
</div>,
document.body
)}
</div>
);
};

407
src/components/common/ShimmerSkeletons.tsx

@ -1,5 +1,9 @@
import React from 'react';
const ShimmerGate: React.FC<{ children: React.ReactNode }> = ({ children }) => (
<>{children}</>
);
interface ShimmerBoxProps {
width?: number | string;
height?: number | string;
@ -15,6 +19,7 @@ export const ShimmerBox: React.FC<ShimmerBoxProps> = ({
dark = false,
style,
}) => (
<ShimmerGate>
<div
aria-hidden="true"
className={dark ? 'habib-shimmer-dark' : 'habib-shimmer'}
@ -26,6 +31,7 @@ export const ShimmerBox: React.FC<ShimmerBoxProps> = ({
...style,
}}
/>
</ShimmerGate>
);
export const InlineSpinner: React.FC<{
@ -118,6 +124,7 @@ export const EmptyStateBox: React.FC<{
export const CompactCarouselShimmer: React.FC<{ count?: number }> = ({
count = 3,
}) => (
<ShimmerGate>
<div
className="habib-carousel-scroller habib-scroll-container"
data-testid="shimmer-compact-carousel"
@ -154,9 +161,11 @@ export const CompactCarouselShimmer: React.FC<{ count?: number }> = ({
))}
</div>
</div>
</ShimmerGate>
);
export const HomeFeedShimmer: React.FC = () => (
<ShimmerGate>
<div
data-testid="shimmer-home-feed"
style={{ display: 'flex', flexDirection: 'column', gap: 20 }}
@ -233,11 +242,13 @@ export const HomeFeedShimmer: React.FC = () => (
<CompactCarouselShimmer count={3} />
</div>
</div>
</ShimmerGate>
);
export const CategoryGridShimmer: React.FC<{ count?: number }> = ({
count = 6,
}) => (
<ShimmerGate>
<div className="habib-category-grid" data-testid="shimmer-category-grid">
{Array.from({ length: count }).map((_, idx) => (
<div
@ -262,11 +273,13 @@ export const CategoryGridShimmer: React.FC<{ count?: number }> = ({
</div>
))}
</div>
</ShimmerGate>
);
export const ProductGridShimmer: React.FC<{ count?: number }> = ({
count = 6,
}) => (
<ShimmerGate>
<div className="habib-product-grid" data-testid="shimmer-product-grid">
{Array.from({ length: count }).map((_, idx) => (
<div
@ -298,9 +311,11 @@ export const ProductGridShimmer: React.FC<{ count?: number }> = ({
</div>
))}
</div>
</ShimmerGate>
);
export const ProductDetailBodyShimmer: React.FC = () => (
<ShimmerGate>
<div data-testid="shimmer-product-detail" style={{ display: 'contents' }}>
<div
style={{
@ -427,9 +442,11 @@ export const ProductDetailBodyShimmer: React.FC = () => (
<ShimmerBox width={176} height={52} borderRadius={11} />
</div>
</div>
</ShimmerGate>
);
export const StoreBoothBodyShimmer: React.FC = () => (
<ShimmerGate>
<div
data-testid="shimmer-store-booth"
style={{
@ -511,11 +528,13 @@ export const StoreBoothBodyShimmer: React.FC = () => (
<ProductGridShimmer count={4} />
</div>
</div>
</ShimmerGate>
);
export const OrdersListShimmer: React.FC<{ count?: number }> = ({
count = 2,
}) => (
<ShimmerGate>
<div className="habib-orders-grid" data-testid="shimmer-orders-list">
{Array.from({ length: count }).map((_, idx) => (
<div
@ -550,9 +569,11 @@ export const OrdersListShimmer: React.FC<{ count?: number }> = ({
</div>
))}
</div>
</ShimmerGate>
);
export const OrderDetailShimmer: React.FC = () => (
<ShimmerGate>
<div
data-testid="shimmer-order-detail"
style={{ display: 'flex', flexDirection: 'column', gap: 20 }}
@ -625,9 +646,11 @@ export const OrderDetailShimmer: React.FC = () => (
))}
</div>
</div>
</ShimmerGate>
);
export const ChatThreadShimmer: React.FC = () => (
<ShimmerGate>
<div
data-testid="shimmer-chat-thread"
style={{
@ -661,11 +684,13 @@ export const ChatThreadShimmer: React.FC = () => (
/>
</div>
</div>
</ShimmerGate>
);
export const CartItemsShimmer: React.FC<{ count?: number }> = ({
count = 2,
}) => (
<ShimmerGate>
<div
data-testid="shimmer-cart-items"
style={{ display: 'flex', flexDirection: 'column', gap: 10 }}
@ -710,5 +735,387 @@ export const CartItemsShimmer: React.FC<{ count?: number }> = ({
</div>
))}
</div>
</ShimmerGate>
);
const BottomNavShimmer: React.FC = () => (
<div
style={{
marginTop: 'auto',
width: '100%',
minHeight: 78,
paddingBottom: '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-around',
paddingLeft: 16,
paddingRight: 16,
flexShrink: 0,
}}
>
<ShimmerBox width={36} height={36} borderRadius={10} />
<ShimmerBox width={36} height={36} borderRadius={10} />
<ShimmerBox width={54} height={48} borderRadius={24} />
<ShimmerBox width={36} height={36} borderRadius={10} />
<ShimmerBox width={36} height={36} borderRadius={10} />
</div>
);
const TopHeaderShimmer: React.FC<{ showRightAction?: boolean }> = ({
showRightAction = false,
}) => (
<div
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
minHeight: 40,
padding: 'calc(21px + var(--safe-top, 0px)) var(--page-px) 0',
flexShrink: 0,
}}
>
<ShimmerBox width={40} height={40} borderRadius={15} />
<ShimmerBox width={118} height={20} borderRadius={8} />
{showRightAction ? (
<ShimmerBox width={40} height={40} borderRadius={15} />
) : (
<div style={{ width: 40, height: 40 }} />
)}
</div>
);
export const FullPageRouteShimmer: React.FC<{ pathname: string }> = ({
pathname,
}) => {
const isHome = pathname === '/' || pathname === '/shop-home';
const isCategoryRoot =
pathname === '/categories' || pathname === '/shop-category';
const isProductGrid =
pathname.startsWith('/categories/') ||
pathname === '/search' ||
pathname === '/account/bookmarks' ||
pathname === '/shop-catitems';
const isProductSingle =
pathname.startsWith('/products/') || pathname === '/shop-single-page';
const isStoreBooth =
pathname === '/stores' ||
pathname.startsWith('/stores/') ||
pathname === '/shop-booth';
const isCart =
pathname === '/cart' ||
pathname === '/shop-cart' ||
pathname === '/shop-order-summery' ||
pathname === '/shop-payment-methods';
const isOrdersList = pathname === '/orders' || pathname === '/shop-orders';
const isOrderDetail =
(pathname.startsWith('/orders/') && !pathname.endsWith('/support')) ||
pathname === '/shop-order-detail';
const isChat =
pathname === '/chat' ||
pathname.startsWith('/chat/') ||
pathname === '/shop-chat';
const isAccount =
pathname === '/account' ||
pathname === '/shop-account' ||
pathname === '/shop-category-4214-345';
if (isProductSingle) {
return (
<div
className="habib-page-shimmer-overlay"
data-testid="shimmer-full-page"
aria-hidden="true"
>
<div className="habib-single-hero-wrap" style={{ flexShrink: 0 }}>
<ShimmerBox width="100%" height="100%" borderRadius={0} />
</div>
<ProductDetailBodyShimmer />
</div>
);
}
if (isStoreBooth) {
return (
<div
className="habib-page-shimmer-overlay"
data-testid="shimmer-full-page"
aria-hidden="true"
>
<div
style={{
position: 'relative',
width: '100%',
height: 152,
overflow: 'hidden',
flexShrink: 0,
}}
>
<ShimmerBox width="100%" height="100%" borderRadius={0} />
</div>
<StoreBoothBodyShimmer />
</div>
);
}
if (isHome) {
return (
<div
className="habib-page-shimmer-overlay"
data-testid="shimmer-full-page"
aria-hidden="true"
>
<div
style={{
flex: 1,
display: 'flex',
flexDirection: 'column',
padding: 'calc(37px + var(--safe-top, 0px)) var(--page-px) 22px',
gap: 20,
}}
>
<div
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
minHeight: 40,
marginBottom: 11,
}}
>
<ShimmerBox width={40} height={40} borderRadius={15} />
<ShimmerBox width={68} height={22} borderRadius={8} />
<ShimmerBox width={40} height={40} borderRadius={15} />
</div>
<div style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
<ShimmerBox height={44} borderRadius={14} style={{ flex: 1 }} />
<ShimmerBox width={44} height={44} borderRadius={14} />
</div>
<HomeFeedShimmer />
</div>
<BottomNavShimmer />
</div>
);
}
if (isCategoryRoot) {
return (
<div
className="habib-page-shimmer-overlay"
data-testid="shimmer-full-page"
aria-hidden="true"
>
<div
style={{
flex: 1,
display: 'flex',
flexDirection: 'column',
padding: 'calc(38px + var(--safe-top, 0px)) var(--page-px) 24px',
gap: 20,
}}
>
<ShimmerBox height={44} borderRadius={14} />
<CategoryGridShimmer count={6} />
</div>
<BottomNavShimmer />
</div>
);
}
if (isProductGrid) {
return (
<div
className="habib-page-shimmer-overlay"
data-testid="shimmer-full-page"
aria-hidden="true"
>
<TopHeaderShimmer />
<div
style={{
flex: 1,
display: 'flex',
flexDirection: 'column',
padding: '11px var(--page-px) 28px',
gap: 23,
}}
>
<ShimmerBox height={44} borderRadius={14} />
<ProductGridShimmer count={6} />
</div>
</div>
);
}
if (isCart) {
return (
<div
className="habib-page-shimmer-overlay"
data-testid="shimmer-full-page"
aria-hidden="true"
>
<div
style={{
flex: 1,
display: 'flex',
flexDirection: 'column',
padding: 'calc(42px + var(--safe-top, 0px)) var(--page-px) 24px',
gap: 13,
}}
>
<div
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
}}
>
<ShimmerBox width={120} height={14} borderRadius={5} />
<ShimmerBox width={54} height={14} borderRadius={5} />
</div>
<CartItemsShimmer count={2} />
</div>
<BottomNavShimmer />
</div>
);
}
if (isOrdersList) {
return (
<div
className="habib-page-shimmer-overlay"
data-testid="shimmer-full-page"
aria-hidden="true"
>
<TopHeaderShimmer />
<div
style={{
flex: 1,
display: 'flex',
flexDirection: 'column',
padding: '26px var(--page-px) 28px',
gap: 22,
}}
>
<ShimmerBox height={46} borderRadius={14} />
<OrdersListShimmer count={2} />
</div>
</div>
);
}
if (isOrderDetail) {
return (
<div
className="habib-page-shimmer-overlay"
data-testid="shimmer-full-page"
aria-hidden="true"
>
<TopHeaderShimmer />
<div
style={{
flex: 1,
display: 'flex',
flexDirection: 'column',
padding: '26px var(--page-px) 20px',
gap: 20,
}}
>
<OrderDetailShimmer />
</div>
</div>
);
}
if (isChat) {
return (
<div
className="habib-page-shimmer-overlay"
data-testid="shimmer-full-page"
aria-hidden="true"
>
<TopHeaderShimmer showRightAction />
<div
style={{
flex: 1,
display: 'flex',
flexDirection: 'column',
justifyContent: 'flex-end',
padding: '24px var(--page-px) 16px',
}}
>
<ChatThreadShimmer />
</div>
<div style={{ padding: '10px var(--page-px) 20px' }}>
<ShimmerBox height={52} borderRadius={16} />
</div>
</div>
);
}
if (isAccount) {
return (
<div
className="habib-page-shimmer-overlay"
data-testid="shimmer-full-page"
aria-hidden="true"
>
<div
style={{
flex: 1,
display: 'flex',
flexDirection: 'column',
padding: '21px var(--page-px) 24px',
gap: 24,
}}
>
<div
style={{
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
gap: 8,
}}
>
<ShimmerBox width={84} height={84} borderRadius="50%" />
<ShimmerBox width={128} height={20} borderRadius={7} />
<ShimmerBox width={96} height={12} borderRadius={5} />
</div>
<div className="habib-counters-grid">
<ShimmerBox height={78} borderRadius={15} />
<ShimmerBox height={78} borderRadius={15} />
<ShimmerBox height={78} borderRadius={15} />
</div>
<ShimmerBox height={290} borderRadius={15} />
</div>
<BottomNavShimmer />
</div>
);
}
return (
<div
className="habib-page-shimmer-overlay"
data-testid="shimmer-full-page"
aria-hidden="true"
>
<TopHeaderShimmer />
<div
style={{
flex: 1,
display: 'flex',
flexDirection: 'column',
padding: '24px var(--page-px) 24px',
gap: 18,
}}
>
<ShimmerBox height={116} borderRadius={15} />
<ShimmerBox height={148} borderRadius={15} />
<ShimmerBox height={96} borderRadius={15} />
</div>
</div>
);
};

2
src/components/layout/BottomNavBar.tsx

@ -390,6 +390,8 @@ export const BottomNavBar: React.FC<BottomNavBarProps> = ({
/>
{showCartBadge && resolvedBadgeCount > 0 && (
<div
key={resolvedBadgeCount}
className="habib-badge-pop"
style={{
position: 'absolute',
right: '-6px',

68
src/components/layout/MobileShell.tsx

@ -1,5 +1,6 @@
import React from 'react';
import { useLocation } from 'react-router-dom';
import { useLocation, useNavigationType } from 'react-router-dom';
import { consumeBackNavigation } from '../../hooks/useSmartBack';
interface MobileShellProps {
width?: number;
@ -9,6 +10,55 @@ interface MobileShellProps {
children: React.ReactNode;
}
const ROOT_TAB_PATHS = new Set([
'/',
'/shop-home',
'/categories',
'/shop-category',
'/cart',
'/shop-cart',
'/account',
'/shop-account',
'/shop-category-4214-345',
]);
let lastPathname: string | null = null;
let lastTransitionClass = '';
function resolvePageTransitionClass(
pathname: string,
navType: 'POP' | 'PUSH' | 'REPLACE'
): string {
if (lastPathname === null) {
lastPathname = pathname;
consumeBackNavigation();
lastTransitionClass = '';
return lastTransitionClass;
}
if (lastPathname === pathname) {
return lastTransitionClass;
}
const prev = lastPathname;
lastPathname = pathname;
const wasExplicitBack = consumeBackNavigation();
if (ROOT_TAB_PATHS.has(prev) && ROOT_TAB_PATHS.has(pathname)) {
lastTransitionClass = 'is-tab-switch';
} else if (
wasExplicitBack ||
navType === 'POP' ||
(!ROOT_TAB_PATHS.has(prev) && ROOT_TAB_PATHS.has(pathname))
) {
lastTransitionClass = 'is-page-pop';
} else {
lastTransitionClass = 'is-page-push';
}
return lastTransitionClass;
}
export const MobileShell: React.FC<MobileShellProps> = ({
width = 375,
height,
@ -17,6 +67,7 @@ export const MobileShell: React.FC<MobileShellProps> = ({
children,
}) => {
const location = useLocation();
const navigationType = useNavigationType();
const searchParams = new URLSearchParams(location.search);
const isEmbed = searchParams.get('embed') === '1' || searchParams.get('bare') === '1';
@ -38,9 +89,22 @@ export const MobileShell: React.FC<MobileShellProps> = ({
);
}
const transitionClass = resolvePageTransitionClass(
location.pathname,
navigationType
);
return (
<div className="habib-shell-outer" style={cssVars}>
<div className="habib-mobile-viewport" style={cssVars}>
<div
key={location.pathname}
className={
transitionClass
? `habib-mobile-viewport ${transitionClass}`
: 'habib-mobile-viewport'
}
style={cssVars}
>
{children}
</div>
</div>

1
src/components/layout/TopHeader.tsx

@ -34,6 +34,7 @@ export const StandardPageHeader: React.FC<StandardPageHeaderProps> = ({
{showBack && (
<button
type="button"
className="habib-icon-btn"
onClick={() => {
if (onBackClick) {
onBackClick();

67
src/components/modals/AddressFormSheet.tsx

@ -1,8 +1,15 @@
import React, { useEffect, useState } from 'react';
import React, { useEffect, useMemo, useState } from 'react';
import { useAnimatedPresence } from '../../hooks/use-animated-presence';
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';
import { PhoneNumberInput } from '../common/PhoneNumberInput';
import {
getDialCodeForCountryName,
parsePhoneParts,
validatePhoneNumber,
} from '../../lib/phone';
interface AddressFormSheetProps {
isOpen: boolean;
@ -17,6 +24,7 @@ export const AddressFormSheet: React.FC<AddressFormSheetProps> = ({
initialAddress,
onSave,
}) => {
const { shouldRender, isClosing } = useAnimatedPresence(isOpen, 200);
const [recipientName, setRecipientName] = useState('');
const [phone, setPhone] = useState('');
const [country, setCountry] = useState('United States');
@ -27,9 +35,21 @@ export const AddressFormSheet: React.FC<AddressFormSheetProps> = ({
const [lon, setLon] = useState<number | null>(null);
const [isDefault, setIsDefault] = useState(true);
const [saving, setSaving] = useState(false);
const [submitAttempted, setSubmitAttempted] = useState(false);
const phoneValidation = useMemo(() => {
const defaultDial = getDialCodeForCountryName(country, '+1');
const parts = parsePhoneParts(phone, defaultDial, country);
return validatePhoneNumber(
parts.dialCode,
parts.nationalInput,
parts.regionCode
);
}, [country, phone]);
useEffect(() => {
if (!isOpen) return;
setSubmitAttempted(false);
if (initialAddress) {
setRecipientName(initialAddress.recipient_name || '');
setPhone(initialAddress.phone || '');
@ -58,7 +78,7 @@ export const AddressFormSheet: React.FC<AddressFormSheetProps> = ({
return true;
}, isOpen);
if (!isOpen) return null;
if (!shouldRender) return null;
const handlePickMap = async () => {
const picked = await pickManualLocation();
@ -71,15 +91,30 @@ export const AddressFormSheet: React.FC<AddressFormSheetProps> = ({
}
};
const canSubmit =
Boolean(recipientName.trim()) &&
Boolean(streetLine.trim()) &&
phoneValidation.isValid &&
!saving;
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!recipientName.trim() || !streetLine.trim() || saving) return;
setSubmitAttempted(true);
if (
!recipientName.trim() ||
!streetLine.trim() ||
!phoneValidation.isValid ||
!phoneValidation.e164 ||
saving
) {
return;
}
setSaving(true);
try {
const saved = await onSave({
id: initialAddress?.id,
recipient_name: recipientName.trim(),
phone: phone.trim(),
phone: phoneValidation.e164,
country: country.trim() || 'United States',
city: city.trim() || 'New York',
street_line: streetLine.trim(),
@ -110,6 +145,7 @@ export const AddressFormSheet: React.FC<AddressFormSheetProps> = ({
return (
<div
className={`habib-sheet-backdrop${isClosing ? ' is-closing' : ''}`}
onClick={() => {
if (!saving) onClose();
}}
@ -124,7 +160,7 @@ export const AddressFormSheet: React.FC<AddressFormSheetProps> = ({
}}
>
<form
className="habib-bottom-sheet"
className={`habib-bottom-sheet${isClosing ? ' is-closing' : ''}`}
onClick={(e) => e.stopPropagation()}
onSubmit={handleSubmit}
style={{
@ -155,6 +191,7 @@ export const AddressFormSheet: React.FC<AddressFormSheetProps> = ({
</span>
<button
type="button"
className="habib-icon-btn"
onClick={onClose}
aria-label="Close"
style={{
@ -213,12 +250,18 @@ export const AddressFormSheet: React.FC<AddressFormSheetProps> = ({
style={inputStyle}
/>
<input
type="tel"
placeholder="Phone number"
<PhoneNumberInput
value={phone}
onChange={(e) => setPhone(e.target.value)}
style={inputStyle}
onChange={(nextValue) => setPhone(nextValue)}
countryHint={country}
required
height={44}
borderRadius={12}
backgroundColor="#ffffff"
borderColor="#d7dbe2"
fontSize={13}
showError={submitAttempted && !phoneValidation.isValid}
errorMessage={phoneValidation.error}
/>
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '10px' }}>
@ -278,7 +321,7 @@ export const AddressFormSheet: React.FC<AddressFormSheetProps> = ({
<button
type="submit"
disabled={saving || !recipientName.trim() || !streetLine.trim()}
disabled={!canSubmit}
className="habib-cta-btn"
style={{
width: '100%',
@ -289,7 +332,7 @@ export const AddressFormSheet: React.FC<AddressFormSheetProps> = ({
fontWeight: 700,
fontSize: '15px',
cursor: saving ? 'not-allowed' : 'pointer',
opacity: saving || !recipientName.trim() || !streetLine.trim() ? 0.65 : 1,
opacity: !canSubmit ? 0.65 : 1,
}}
>
{saving ? 'Saving...' : 'Save Address'}

7
src/components/modals/LoginRequiredModal.tsx

@ -1,4 +1,5 @@
import React from 'react';
import { useAnimatedPresence } from '../../hooks/use-animated-presence';
import { useHardwareBackHandler } from '../../hooks/use-hardware-back-handler';
import { InlineSpinner } from '../common/ShimmerSkeletons';
@ -24,6 +25,8 @@ export const LoginRequiredModal: React.FC<LoginRequiredModalProps> = ({
onConfirmLogin,
onClose,
}) => {
const { shouldRender, isClosing } = useAnimatedPresence(isOpen, 180);
useHardwareBackHandler(() => {
if (!isLoggingIn) {
onClose();
@ -31,13 +34,14 @@ export const LoginRequiredModal: React.FC<LoginRequiredModalProps> = ({
return true;
}, isOpen);
if (!isOpen) return null;
if (!shouldRender) return null;
return (
<div
role="dialog"
aria-modal="true"
aria-labelledby="habib-login-modal-title"
className={`habib-sheet-backdrop${isClosing ? ' is-closing' : ''}`}
onClick={() => {
if (!isLoggingIn) onClose();
}}
@ -54,6 +58,7 @@ export const LoginRequiredModal: React.FC<LoginRequiredModalProps> = ({
}}
>
<div
className={`habib-dialog-card${isClosing ? ' is-closing' : ''}`}
onClick={(e) => e.stopPropagation()}
style={{
width: '100%',

81
src/components/modals/OrderSummarySheet.tsx

@ -1,6 +1,6 @@
import React, { useState } from 'react';
import React from 'react';
import { useAnimatedPresence } from '../../hooks/use-animated-presence';
import { useHardwareBackHandler } from '../../hooks/use-hardware-back-handler';
import { InlineSpinner } from '../common/ShimmerSkeletons';
import { OrderSummaryRows, type SummaryLineRow } from '../checkout/OrderSummaryRows';
interface OrderSummarySheetProps {
@ -8,8 +8,6 @@ interface OrderSummarySheetProps {
onClose: () => void;
rows: SummaryLineRow[];
totalText: string;
promoCode?: string;
onApplyPromo?: (code: string) => Promise<boolean>;
ctaText?: string;
onCtaClick?: () => void;
}
@ -19,34 +17,21 @@ export const OrderSummarySheet: React.FC<OrderSummarySheetProps> = ({
onClose,
rows,
totalText,
promoCode = '',
onApplyPromo,
ctaText = 'Got it',
onCtaClick,
}) => {
const [promoInput, setPromoInput] = useState(promoCode);
const [applying, setApplying] = useState(false);
const { shouldRender, isClosing } = useAnimatedPresence(isOpen, 200);
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);
}
};
if (!shouldRender) return null;
return (
<div
className={`habib-sheet-backdrop${isClosing ? ' is-closing' : ''}`}
onClick={onClose}
style={{
position: 'fixed',
@ -59,7 +44,7 @@ export const OrderSummarySheet: React.FC<OrderSummarySheetProps> = ({
}}
>
<div
className="habib-bottom-sheet"
className={`habib-bottom-sheet${isClosing ? ' is-closing' : ''}`}
onClick={(e) => e.stopPropagation()}
style={{
padding: '22px var(--page-px) calc(24px + var(--safe-bottom, 0px))',
@ -89,6 +74,7 @@ export const OrderSummarySheet: React.FC<OrderSummarySheetProps> = ({
</span>
<button
type="button"
className="habib-icon-btn"
onClick={onClose}
aria-label="Close"
style={{
@ -110,58 +96,6 @@ export const OrderSummarySheet: React.FC<OrderSummarySheetProps> = ({
<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"
@ -192,4 +126,3 @@ export const OrderSummarySheet: React.FC<OrderSummarySheetProps> = ({
</div>
);
};

82
src/components/modals/PaymentMethodsSheet.tsx

@ -1,9 +1,9 @@
import React from 'react';
import { useAnimatedPresence } from '../../hooks/use-animated-presence';
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;
@ -14,9 +14,6 @@ interface PaymentMethodsSheetProps {
totalPriceText: string;
onConfirmPurchase: () => void;
isSubmitting?: boolean;
habibCoinsBalance?: number;
requiredCoins?: number;
onCoinsUpdated?: (coins: number) => void;
}
export const PaymentMethodsSheet: React.FC<PaymentMethodsSheetProps> = ({
@ -28,10 +25,9 @@ export const PaymentMethodsSheet: React.FC<PaymentMethodsSheetProps> = ({
totalPriceText,
onConfirmPurchase,
isSubmitting = false,
habibCoinsBalance = 21,
requiredCoins = 0,
onCoinsUpdated,
}) => {
const { shouldRender, isClosing } = useAnimatedPresence(isOpen, 200);
useHardwareBackHandler(() => {
if (!isSubmitting) {
onClose();
@ -39,24 +35,11 @@ export const PaymentMethodsSheet: React.FC<PaymentMethodsSheetProps> = ({
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);
}
}
};
if (!shouldRender) return null;
return (
<div
className={`habib-sheet-backdrop${isClosing ? ' is-closing' : ''}`}
onClick={() => {
if (!isSubmitting) onClose();
}}
@ -71,7 +54,7 @@ export const PaymentMethodsSheet: React.FC<PaymentMethodsSheetProps> = ({
}}
>
<div
className="habib-bottom-sheet"
className={`habib-bottom-sheet${isClosing ? ' is-closing' : ''}`}
onClick={(e) => e.stopPropagation()}
style={{
padding: '22px var(--page-px) calc(24px + var(--safe-bottom, 0px))',
@ -103,6 +86,7 @@ export const PaymentMethodsSheet: React.FC<PaymentMethodsSheetProps> = ({
<button
type="button"
className="habib-icon-btn"
disabled={isSubmitting}
onClick={onClose}
aria-label="Close"
@ -152,55 +136,10 @@ export const PaymentMethodsSheet: React.FC<PaymentMethodsSheetProps> = ({
)}
</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}
disabled={isSubmitting || methods.length === 0}
onClick={onConfirmPurchase}
className="habib-cta-btn"
style={{
@ -211,11 +150,11 @@ export const PaymentMethodsSheet: React.FC<PaymentMethodsSheetProps> = ({
borderRadius: '11px',
border: 'none',
cursor:
isSubmitting || needsMoreCoins || methods.length === 0
isSubmitting || methods.length === 0
? 'not-allowed'
: 'pointer',
opacity:
isSubmitting || needsMoreCoins || methods.length === 0 ? 0.65 : 1,
isSubmitting || methods.length === 0 ? 0.65 : 1,
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
@ -287,4 +226,3 @@ export const PaymentMethodsSheet: React.FC<PaymentMethodsSheetProps> = ({
</div>
);
};

31
src/components/modals/ShipmentTrackingSheet.tsx

@ -1,4 +1,5 @@
import React from 'react';
import React, { useRef } from 'react';
import { useAnimatedPresence } from '../../hooks/use-animated-presence';
import { useHardwareBackHandler } from '../../hooks/use-hardware-back-handler';
import type { ApiShipment } from '../../lib/shopApi';
import { copyToClipboard } from '../../lib/webview-actions';
@ -15,22 +16,29 @@ export const ShipmentTrackingSheet: React.FC<ShipmentTrackingSheetProps> = ({
onCopied,
}) => {
const isOpen = Boolean(shipment);
const { shouldRender, isClosing } = useAnimatedPresence(isOpen, 200);
const lastShipmentRef = useRef<ApiShipment | null>(shipment);
if (shipment) {
lastShipmentRef.current = shipment;
}
const activeShipment = shipment || lastShipmentRef.current;
useHardwareBackHandler(() => {
onClose();
return true;
}, isOpen);
if (!shipment) return null;
if (!shouldRender || !activeShipment) return null;
const handleCopyTracking = async () => {
if (!shipment.tracking_code) return;
const ok = await copyToClipboard(shipment.tracking_code);
if (!activeShipment.tracking_code) return;
const ok = await copyToClipboard(activeShipment.tracking_code);
if (ok && onCopied) onCopied();
};
return (
<div
className={`habib-sheet-backdrop${isClosing ? ' is-closing' : ''}`}
onClick={onClose}
style={{
position: 'fixed',
@ -43,7 +51,7 @@ export const ShipmentTrackingSheet: React.FC<ShipmentTrackingSheetProps> = ({
}}
>
<div
className="habib-bottom-sheet"
className={`habib-bottom-sheet${isClosing ? ' is-closing' : ''}`}
onClick={(e) => e.stopPropagation()}
style={{
padding: '22px var(--page-px) calc(24px + var(--safe-bottom, 0px))',
@ -69,10 +77,11 @@ export const ShipmentTrackingSheet: React.FC<ShipmentTrackingSheetProps> = ({
color: '#111111',
}}
>
Shipment Tracking • {shipment.booth_name}
Shipment Tracking • {activeShipment.booth_name}
</span>
<button
type="button"
className="habib-icon-btn"
onClick={onClose}
aria-label="Close"
style={{
@ -105,10 +114,10 @@ export const ShipmentTrackingSheet: React.FC<ShipmentTrackingSheetProps> = ({
<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'}
{activeShipment.carrier_name || 'Habib Global Post'}
</span>
</div>
{shipment.tracking_code && (
{activeShipment.tracking_code && (
<div
style={{
display: 'flex',
@ -128,20 +137,20 @@ export const ShipmentTrackingSheet: React.FC<ShipmentTrackingSheetProps> = ({
cursor: 'pointer',
}}
>
{shipment.tracking_code} (Copy)
{activeShipment.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'}
{activeShipment.estimated_delivery_label || '2–3 Business Days'}
</span>
</div>
</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: '12px' }}>
{(shipment.events || []).map((ev, idx) => (
{(activeShipment.events || []).map((ev, idx) => (
<div
key={ev.id || idx}
style={{

38
src/components/orders/OrderFilterTabs.tsx

@ -17,9 +17,15 @@ export const OrderFilterTabs: React.FC<OrderFilterTabsProps> = ({
activeTabId,
onSelectTab,
}) => {
const activeIndex = Math.max(
0,
tabs.findIndex((t) => t.id === activeTabId)
);
return (
<div
style={{
position: 'relative',
width: '100%',
minHeight: 45,
padding: 4,
@ -30,6 +36,26 @@ export const OrderFilterTabs: React.FC<OrderFilterTabsProps> = ({
gap: 4,
}}
>
{/* Sliding active pill indicator (matches native AppTabBar) */}
<div
aria-hidden="true"
style={{
position: 'absolute',
left: 4,
top: 4,
bottom: 4,
width: 'calc((100% - 16px) / 3)',
borderRadius: 12,
backgroundColor: '#d78e06',
border: '1px solid rgba(255, 255, 255, 0.3)',
boxShadow: '0px 4px 11px rgba(215, 142, 6, 0.3)',
transform: `translateX(calc(${activeIndex} * (100% + 4px)))`,
transition: 'transform 260ms cubic-bezier(0.22, 1, 0.36, 1)',
pointerEvents: 'none',
zIndex: 1,
}}
/>
{tabs.map((tab) => {
const isActive = tab.id === activeTabId;
@ -39,19 +65,18 @@ export const OrderFilterTabs: React.FC<OrderFilterTabsProps> = ({
type="button"
onClick={() => onSelectTab(tab.id)}
style={{
position: 'relative',
zIndex: 2,
width: '100%',
minHeight: 37,
padding: '0 4px',
borderRadius: 12,
background: isActive
? '#d78e06'
? 'transparent'
: tab.hasGradientFill
? 'linear-gradient(180deg, #ffffff 0%, #f4f7f5 100%)'
: 'transparent',
border: isActive ? '1px solid rgba(255, 255, 255, 0.3)' : 'none',
boxShadow: isActive
? '0px 4px 11px rgba(215, 142, 6, 0.3)'
: 'none',
border: 'none',
cursor: 'pointer',
display: 'flex',
alignItems: 'center',
@ -68,6 +93,7 @@ export const OrderFilterTabs: React.FC<OrderFilterTabsProps> = ({
lineHeight: '16px',
color: isActive ? '#ffffff' : '#787878',
whiteSpace: 'nowrap',
transition: 'color 220ms cubic-bezier(0.22, 1, 0.36, 1)',
}}
>
{tab.label}
@ -84,6 +110,7 @@ export const OrderFilterTabs: React.FC<OrderFilterTabsProps> = ({
alignItems: 'center',
justifyContent: 'center',
flexShrink: 0,
transition: 'background-color 220ms cubic-bezier(0.22, 1, 0.36, 1)',
}}
>
<span
@ -93,6 +120,7 @@ export const OrderFilterTabs: React.FC<OrderFilterTabsProps> = ({
fontSize: 10,
lineHeight: '13.9px',
color: isActive ? '#d78e06' : '#ffffff',
transition: 'color 220ms cubic-bezier(0.22, 1, 0.36, 1)',
}}
>
{tab.count}

86
src/context/ShopAppContext.tsx

@ -11,8 +11,7 @@ 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 { getUserLanguage, setUserLanguage } from '../lib/cookies';
import {
type ApiAddress,
type ApiCart,
@ -29,7 +28,7 @@ export interface SaveAddressInput {
id?: number;
label?: string;
recipient_name: string;
phone?: string;
phone: string;
country?: string;
city?: string;
street_line: string;
@ -72,8 +71,6 @@ interface ShopAppContextValue {
) => Promise<boolean>;
profile: ApiUserProfile | null;
orderCounters: ApiOrderCounters | null;
habibCoinsBalance: number;
setHabibCoinsBalance: (coins: number) => void;
language: string;
changeLanguage: (lang: string) => void;
addToCart: (
@ -84,7 +81,6 @@ interface ShopAppContextValue {
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>;
@ -109,13 +105,6 @@ export const ShopAppProvider: React.FC<{ children: React.ReactNode }> = ({
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<{
@ -135,49 +124,47 @@ export const ShopAppProvider: React.FC<{ children: React.ReactNode }> = ({
useHabibWebReady(true);
useEffect(() => {
ensureGuestToken();
}, []);
const hasAuthToken = Boolean(authToken);
const cartQuery = useQuery({
queryKey: shopKeys.cart(),
queryFn: () => shopApi.fetchCart(false),
enabled: !isBare,
enabled: !isBare && hasAuthToken,
});
const profileQuery = useQuery({
queryKey: shopKeys.profile(),
queryFn: () => shopApi.fetchProfile(),
enabled: !isBare,
enabled: !isBare && hasAuthToken,
});
const addressesQuery = useQuery({
queryKey: shopKeys.addresses(),
queryFn: () => shopApi.fetchAddresses(),
enabled: !isBare,
enabled: !isBare && hasAuthToken,
});
const shippingMethodsQuery = useQuery({
queryKey: shopKeys.shippingMethods(),
queryFn: () => shopApi.fetchShippingMethods(),
enabled: !isBare,
enabled: !isBare && hasAuthToken,
staleTime: 5 * 60_000,
});
const bookmarksQuery = useQuery({
queryKey: shopKeys.bookmarks(),
queryFn: () => shopApi.fetchBookmarks(),
enabled: !isBare,
enabled: !isBare && hasAuthToken,
});
const orderCountersQuery = useQuery({
queryKey: shopKeys.orderCounters(),
queryFn: () => shopApi.fetchOrderCounters(),
enabled: !isBare,
enabled: !isBare && hasAuthToken,
});
const hydrated =
isBare || (!cartQuery.isPending && !bookmarksQuery.isPending);
isBare || !hasAuthToken || (!cartQuery.isPending && !bookmarksQuery.isPending);
const cart = cartQuery.data ?? null;
const profile = profileQuery.data ?? null;
const orderCounters = orderCountersQuery.data ?? null;
@ -218,12 +205,6 @@ export const ShopAppProvider: React.FC<{ children: React.ReactNode }> = ({
[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') {
@ -260,28 +241,12 @@ export const ShopAppProvider: React.FC<{ children: React.ReactNode }> = ({
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]);
@ -375,6 +340,12 @@ export const ShopAppProvider: React.FC<{ children: React.ReactNode }> = ({
quantity = 1,
variantId?: number | null
): Promise<ApiCart | null> => {
if (!isBare && !isUserAuthenticated) {
const authed = await requireAuth({
featureName: 'shopping cart',
});
if (!authed) return null;
}
setIsCartBusy(true);
try {
const updated = await shopApi.addCartItem({
@ -393,7 +364,7 @@ export const ShopAppProvider: React.FC<{ children: React.ReactNode }> = ({
setIsCartBusy(false);
}
},
[queryClient, showToast]
[isBare, isUserAuthenticated, queryClient, requireAuth, showToast]
);
const updateCartItemQuantity = useCallback(
@ -441,24 +412,6 @@ export const ShopAppProvider: React.FC<{ children: React.ReactNode }> = ({
}
}, [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;
@ -636,15 +589,12 @@ export const ShopAppProvider: React.FC<{ children: React.ReactNode }> = ({
toggleBookmark,
profile,
orderCounters,
habibCoinsBalance,
setHabibCoinsBalance,
language,
changeLanguage,
addToCart,
updateCartItemQuantity,
removeCartItem,
clearCart,
applyPromoCode,
selectAddress,
saveAddress,
deleteAddress,
@ -675,14 +625,12 @@ export const ShopAppProvider: React.FC<{ children: React.ReactNode }> = ({
toggleBookmark,
profile,
orderCounters,
habibCoinsBalance,
language,
changeLanguage,
addToCart,
updateCartItemQuantity,
removeCartItem,
clearCart,
applyPromoCode,
selectAddress,
saveAddress,
deleteAddress,

32
src/hooks/use-animated-presence.ts

@ -0,0 +1,32 @@
import { useEffect, useState } from 'react';
/**
* Keeps a modal or sheet mounted briefly after `isOpen` turns false so CSS
* exit animations (slide-down / fade-out) can finish before unmounting.
*/
export function useAnimatedPresence(
isOpen: boolean,
exitDurationMs = 200
): {
shouldRender: boolean;
isClosing: boolean;
} {
const [rendered, setRendered] = useState(isOpen);
useEffect(() => {
if (isOpen) {
setRendered(true);
return;
}
if (!rendered) return;
const timer = window.setTimeout(() => {
setRendered(false);
}, exitDurationMs);
return () => window.clearTimeout(timer);
}, [isOpen, rendered, exitDurationMs]);
return {
shouldRender: isOpen || rendered,
isClosing: !isOpen && rendered,
};
}

13
src/hooks/useSmartBack.ts

@ -4,6 +4,7 @@ import { ROUTES } from '../lib/routes';
import { closeService, isInFlutterWebView } from '../lib/webview-actions';
let inAppNavigationCount = 0;
let pendingBackNavigation = false;
export function recordInAppNavigation(): void {
inAppNavigationCount += 1;
@ -13,6 +14,16 @@ export function getInAppNavigationCount(): number {
return inAppNavigationCount;
}
export function markBackNavigation(): void {
pendingBackNavigation = true;
}
export function consumeBackNavigation(): boolean {
const wasBack = pendingBackNavigation;
pendingBackNavigation = false;
return wasBack;
}
export function useSmartBack(defaultFallback: string = ROUTES.home) {
const navigate = useNavigate();
const location = useLocation();
@ -28,6 +39,7 @@ export function useSmartBack(defaultFallback: string = ROUTES.home) {
closeService();
return;
}
markBackNavigation();
navigate(ROUTES.test);
return;
}
@ -38,6 +50,7 @@ export function useSmartBack(defaultFallback: string = ROUTES.home) {
? window.history.state.idx
: inAppNavigationCount;
markBackNavigation();
if (historyIdx > 0) {
navigate(-1);
} else {

298
src/index.css

@ -107,6 +107,7 @@ a {
justify-content: flex-start;
padding: 0;
background-color: var(--shell-bg, var(--bg-page));
overflow-x: clip;
}
/* Mobile & Tablet Viewport (<1024px) */
@ -124,6 +125,18 @@ a {
user-select: none;
}
.habib-mobile-viewport:not(.is-embed).is-page-push {
animation: habib-page-push 300ms cubic-bezier(0.22, 1, 0.36, 1);
}
.habib-mobile-viewport:not(.is-embed).is-page-pop {
animation: habib-page-pop 220ms cubic-bezier(0.22, 1, 0.36, 1);
}
.habib-mobile-viewport:not(.is-embed).is-tab-switch > :first-child {
animation: habib-tab-page-in 220ms cubic-bezier(0.22, 1, 0.36, 1);
}
/* Desktop (>=1024px): show current 375px mobile size centered on dark backdrop */
@media (min-width: 1024px) {
.habib-shell-outer {
@ -139,6 +152,7 @@ a {
box-shadow: 0 20px 50px rgba(0, 0, 0, 0.45);
}
.habib-bottom-sheet,
.habib-mobile-viewport:not(.is-embed) .habib-bottom-sheet {
max-width: var(--desktop-frame-w, 375px);
margin: 0 auto;
@ -152,20 +166,39 @@ a {
min-height: var(--desktop-frame-h, 814px);
border-radius: 0;
box-shadow: none;
animation: none !important;
}
.habib-mobile-viewport.is-embed *,
.habib-mobile-viewport.is-embed *::before,
.habib-mobile-viewport.is-embed *::after {
animation: none !important;
transition: none !important;
}
.habib-node-btn {
cursor: pointer;
transition: opacity 0.12s ease;
transition: opacity 0.12s ease, transform 0.12s cubic-bezier(0.22, 1, 0.36, 1);
}
.habib-node-btn:active {
opacity: 0.85;
transform: scale(0.97);
}
.habib-icon-btn {
transition: transform 120ms cubic-bezier(0.22, 1, 0.36, 1),
background-color 150ms ease, opacity 120ms ease;
}
.habib-icon-btn:active:not(:disabled) {
transform: scale(0.92);
}
.habib-cta-btn {
background-color: #d78e06;
transition: background-color 0.15s ease, box-shadow 0.15s ease, opacity 0.15s ease;
transition: background-color 0.15s ease, box-shadow 0.15s ease,
opacity 0.15s ease, transform 120ms cubic-bezier(0.22, 1, 0.36, 1);
}
.habib-cta-btn:hover:not(:disabled) {
@ -173,15 +206,25 @@ a {
box-shadow: 0 4px 12px rgba(215, 142, 6, 0.3);
}
.habib-cta-btn:active:not(:disabled) {
transform: scale(0.97);
}
.habib-qty-btn {
background-color: rgba(215, 142, 6, 0.15);
transition: background-color 0.15s ease;
transition: background-color 0.15s ease,
transform 120ms cubic-bezier(0.22, 1, 0.36, 1);
}
.habib-qty-btn[role='button']:hover {
background-color: rgba(215, 142, 6, 0.28);
}
.habib-qty-btn[role='button']:active {
background-color: rgba(215, 142, 6, 0.34);
transform: scale(0.88);
}
.habib-scroll-container {
scrollbar-width: none;
-ms-overflow-style: none;
@ -208,7 +251,8 @@ a {
.habib-grid-card,
.habib-category-card {
transition: box-shadow 0.18s ease;
transition: box-shadow 0.18s ease,
transform 150ms cubic-bezier(0.22, 1, 0.36, 1);
}
.habib-category-card.is-right-col {
@ -220,6 +264,11 @@ a {
box-shadow: 0 4px 14px rgba(0, 0, 0, 0.09);
}
.habib-grid-card:active,
.habib-category-card:active {
transform: scale(0.98);
}
.habib-carousel-scroller {
margin: -10px calc(-1 * var(--page-px, 16px)) -18px;
padding: 10px var(--page-px, 16px) 18px;
@ -236,13 +285,18 @@ a {
.habib-compact-card {
width: 152px;
flex: 0 0 152px;
transition: box-shadow 0.18s ease;
transition: box-shadow 0.18s ease,
transform 150ms cubic-bezier(0.22, 1, 0.36, 1);
}
.habib-compact-card:hover {
box-shadow: 0 4px 14px rgba(0, 0, 0, 0.09);
}
.habib-compact-card:active {
transform: scale(0.98);
}
.habib-compact-card-img {
width: 100%;
height: 112px;
@ -328,10 +382,200 @@ a {
display: block;
}
.habib-sheet-backdrop {
animation: habib-backdrop-in 220ms cubic-bezier(0.22, 1, 0.36, 1) both;
}
.habib-sheet-backdrop.is-closing {
animation: habib-backdrop-out 200ms cubic-bezier(0.4, 0, 1, 1) forwards;
pointer-events: none;
}
.habib-bottom-sheet {
width: 100%;
border-radius: 22px 22px 0 0;
background-color: #fafafa;
animation: habib-sheet-up 280ms cubic-bezier(0.22, 1, 0.36, 1) both;
}
.habib-bottom-sheet.is-closing {
animation: habib-sheet-down 200ms cubic-bezier(0.4, 0, 1, 1) forwards;
}
.habib-dialog-card {
animation: habib-dialog-in 240ms cubic-bezier(0.22, 1, 0.36, 1) both;
}
.habib-dialog-card.is-closing {
animation: habib-dialog-out 180ms cubic-bezier(0.4, 0, 1, 1) forwards;
}
.habib-tab-panel {
animation: habib-fade-up 200ms cubic-bezier(0.22, 1, 0.36, 1);
}
.habib-badge-pop {
animation: habib-badge-pop 220ms cubic-bezier(0.22, 1, 0.36, 1);
}
.habib-radio-dot {
animation: habib-radio-pop 180ms cubic-bezier(0.22, 1, 0.36, 1);
}
.habib-dropdown-menu {
transform-origin: top right;
animation: habib-dropdown-in 180ms cubic-bezier(0.22, 1, 0.36, 1) both;
}
.habib-toast {
animation: habib-toast-in 240ms cubic-bezier(0.22, 1, 0.36, 1) both;
}
@keyframes habib-page-push {
0% {
opacity: 0;
transform: translateX(32px);
}
100% {
opacity: 1;
transform: translateX(0);
}
}
@keyframes habib-page-pop {
0% {
opacity: 0;
transform: translateX(-28px);
}
100% {
opacity: 1;
transform: translateX(0);
}
}
@keyframes habib-tab-page-in {
0% {
opacity: 0;
transform: translateY(6px);
}
100% {
opacity: 1;
transform: translateY(0);
}
}
@keyframes habib-fade-up {
0% {
opacity: 0;
transform: translateY(4px);
}
100% {
opacity: 1;
transform: translateY(0);
}
}
@keyframes habib-backdrop-in {
0% {
opacity: 0;
}
100% {
opacity: 1;
}
}
@keyframes habib-backdrop-out {
0% {
opacity: 1;
}
100% {
opacity: 0;
}
}
@keyframes habib-sheet-up {
0% {
transform: translateY(100%);
}
100% {
transform: translateY(0);
}
}
@keyframes habib-sheet-down {
0% {
transform: translateY(0);
}
100% {
transform: translateY(100%);
}
}
@keyframes habib-dialog-in {
0% {
opacity: 0;
transform: scale(0.94) translateY(6px);
}
100% {
opacity: 1;
transform: scale(1) translateY(0);
}
}
@keyframes habib-dialog-out {
0% {
opacity: 1;
transform: scale(1) translateY(0);
}
100% {
opacity: 0;
transform: scale(0.95) translateY(4px);
}
}
@keyframes habib-badge-pop {
0% {
transform: scale(0.76);
}
60% {
transform: scale(1.14);
}
100% {
transform: scale(1);
}
}
@keyframes habib-radio-pop {
0% {
transform: scale(0.4);
opacity: 0;
}
100% {
transform: scale(1);
opacity: 1;
}
}
@keyframes habib-dropdown-in {
0% {
opacity: 0;
transform: scale(0.92) translateY(-4px);
}
100% {
opacity: 1;
transform: scale(1) translateY(0);
}
}
@keyframes habib-toast-in {
0% {
opacity: 0;
transform: translate(-50%, 10px) scale(0.96);
}
100% {
opacity: 1;
transform: translate(-50%, 0) scale(1);
}
}
.habib-bottom-nav-inner {
@ -505,13 +749,23 @@ a {
}
@media (prefers-reduced-motion: reduce) {
.habib-mobile-viewport:not(.is-embed),
.habib-mobile-viewport:not(.is-embed).is-tab-switch > :first-child,
.habib-sheet-backdrop,
.habib-bottom-sheet,
.habib-dialog-card,
.habib-tab-panel,
.habib-badge-pop,
.habib-radio-dot,
.habib-dropdown-menu,
.habib-toast,
.habib-nav-wave.is-flatten,
.habib-nav-wave.is-rise,
.habib-nav-icon-wrap.is-entering .habib-nav-icon,
.habib-nav-icon-wrap.is-leaving .habib-nav-icon,
.habib-nav-label.is-entering,
.habib-nav-label.is-leaving {
animation: none;
animation: none !important;
}
.habib-nav-icon,
@ -559,7 +813,7 @@ a {
#e5e1dc 96%
);
background-size: 220% 100%;
animation: habib-shimmer-sweep 1.3s ease-in-out infinite;
animation: habib-shimmer-sweep 1.5s cubic-bezier(0.4, 0, 0.2, 1) infinite;
}
.habib-shimmer-dark {
@ -570,7 +824,7 @@ a {
rgba(255, 255, 255, 0.09) 96%
);
background-size: 220% 100%;
animation: habib-shimmer-sweep 1.3s ease-in-out infinite;
animation: habib-shimmer-sweep 1.5s cubic-bezier(0.4, 0, 0.2, 1) infinite;
}
.habib-inline-spinner {
@ -589,6 +843,33 @@ a {
border-top-color: #d78e06;
}
.habib-mobile-viewport.is-habib-loading {
height: 100vh;
height: 100dvh;
max-height: 100dvh;
overflow: hidden !important;
}
.habib-mobile-viewport.is-habib-loading > :not(.habib-page-shimmer-overlay) {
opacity: 0 !important;
pointer-events: none !important;
user-select: none !important;
}
.habib-page-shimmer-overlay {
position: absolute;
inset: 0;
z-index: 9999;
display: flex;
flex-direction: column;
width: 100%;
height: 100%;
min-height: 100vh;
min-height: 100dvh;
background-color: var(--shell-bg, var(--bg-page));
overflow: hidden;
}
/* Small Phone Refinements (<360px, e.g., 320px iPhone SE) */
@media (max-width: 359.98px) {
.habib-mobile-viewport:not(.is-embed) .habib-product-grid,
@ -782,6 +1063,7 @@ a {
object-fit: contain;
}
.habib-bottom-sheet,
.habib-mobile-viewport:not(.is-embed) .habib-bottom-sheet {
max-width: 560px;
margin: 0 auto;

44
src/lib/cookies.ts

@ -1,5 +1,3 @@
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';
@ -22,47 +20,6 @@ export function deleteCookie(name: string): void {
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 = (
@ -92,4 +49,3 @@ export function setUserLanguage(lang: string): void {
}
}
}

42
src/lib/http.ts

@ -1,36 +1,7 @@
import { getToken } from './auth-bridge';
import { ensureGuestToken, getUserLanguage } from './cookies';
import { 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;
@ -102,22 +73,12 @@ export async function shopRequest<T>(
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) {
@ -163,4 +124,3 @@ export async function shopRequest<T>(
return parsed as T;
}

403
src/lib/phone.ts

@ -0,0 +1,403 @@
import libphonenumber from 'google-libphonenumber';
const {
PhoneNumberUtil,
PhoneNumberFormat,
PhoneNumberType,
} = libphonenumber;
const phoneUtil = PhoneNumberUtil.getInstance();
export interface CountryPhoneOption {
region: string;
name: string;
callingCode: string;
dialCode: string;
flag: string;
}
export interface PhoneValidationResult {
isValid: boolean;
e164: string | null;
international: string | null;
national: string | null;
regionCode: string | null;
error: string | null;
}
const PRIMARY_REGION_BY_CALLING_CODE: Record<string, string> = {
'1': 'US',
'7': 'RU',
'39': 'IT',
'44': 'GB',
'61': 'AU',
'90': 'TR',
'92': 'PK',
'93': 'AF',
'98': 'IR',
'961': 'LB',
'964': 'IQ',
'965': 'KW',
'966': 'SA',
'968': 'OM',
'971': 'AE',
'973': 'BH',
'974': 'QA',
};
const COUNTRY_NAME_ALIASES: Record<string, string> = {
'united states': 'US',
'united states of america': 'US',
usa: 'US',
us: 'US',
america: 'US',
'united kingdom': 'GB',
uk: 'GB',
britain: 'GB',
england: 'GB',
iran: 'IR',
'islamic republic of iran': 'IR',
iraq: 'IQ',
lebanon: 'LB',
syria: 'SY',
'saudi arabia': 'SA',
'united arab emirates': 'AE',
uae: 'AE',
kuwait: 'KW',
bahrain: 'BH',
qatar: 'QA',
oman: 'OM',
pakistan: 'PK',
afghanistan: 'AF',
india: 'IN',
turkey: 'TR',
turkiye: 'TR',
germany: 'DE',
france: 'FR',
canada: 'CA',
australia: 'AU',
};
let cachedCountryOptions: CountryPhoneOption[] | null = null;
function regionToFlag(region: string): string {
const codePoints = region
.toUpperCase()
.split('')
.map((char) => 127397 + char.charCodeAt(0));
return String.fromCodePoint(...codePoints);
}
export function getSupportedCountryOptions(locale = 'en'): CountryPhoneOption[] {
if (cachedCountryOptions && locale === 'en') {
return cachedCountryOptions;
}
const regions = phoneUtil.getSupportedRegions();
const displayNames =
typeof Intl !== 'undefined' && typeof Intl.DisplayNames === 'function'
? new Intl.DisplayNames([locale, 'en'], { type: 'region' })
: null;
const list: CountryPhoneOption[] = [];
for (const region of regions) {
try {
const callingCodeNum = phoneUtil.getCountryCodeForRegion(region);
if (!callingCodeNum) continue;
const callingCode = String(callingCodeNum);
const name = displayNames?.of(region) || region;
list.push({
region,
name,
callingCode,
dialCode: `+${callingCode}`,
flag: regionToFlag(region),
});
} catch {
// ignore unsupported region
}
}
list.sort((a, b) => a.name.localeCompare(b.name, locale));
if (locale === 'en') {
cachedCountryOptions = list;
}
return list;
}
export function resolveRegionFromDialCode(dialCode: string): string {
const cleanCode = dialCode.replace(/[^\d]/g, '');
if (!cleanCode) return 'US';
if (PRIMARY_REGION_BY_CALLING_CODE[cleanCode]) {
return PRIMARY_REGION_BY_CALLING_CODE[cleanCode];
}
try {
const region = phoneUtil.getRegionCodeForCountryCode(Number(cleanCode));
return region && region !== 'ZZ' ? region : 'US';
} catch {
return 'US';
}
}
export function resolveRegionFromCountryName(
countryName?: string | null
): string | null {
if (!countryName) return null;
const trimmed = countryName.trim();
if (!trimmed) return null;
const upper = trimmed.toUpperCase();
const supported = phoneUtil.getSupportedRegions();
if (upper.length === 2 && supported.includes(upper as never)) {
return upper;
}
const lower = trimmed.toLowerCase();
if (COUNTRY_NAME_ALIASES[lower]) {
return COUNTRY_NAME_ALIASES[lower];
}
const options = getSupportedCountryOptions('en');
const exact = options.find((opt) => opt.name.toLowerCase() === lower);
if (exact) return exact.region;
const partial = options.find(
(opt) =>
opt.name.toLowerCase().includes(lower) ||
lower.includes(opt.name.toLowerCase())
);
return partial ? partial.region : null;
}
export function getDialCodeForCountryName(
countryName?: string | null,
fallback = '+1'
): string {
const region = resolveRegionFromCountryName(countryName);
if (!region) return fallback;
try {
const code = phoneUtil.getCountryCodeForRegion(region);
return code ? `+${code}` : fallback;
} catch {
return fallback;
}
}
export function sanitizeDialCode(value: string, fallback = '+1'): string {
const digits = value.replace(/[^\d]/g, '');
return digits ? `+${digits}` : fallback;
}
export function getPlaceholderForDialCode(dialCode: string): string {
try {
const cleanCode = dialCode.replace(/[^\d]/g, '');
if (!cleanCode) return 'Phone number';
if (cleanCode === '98') return '9123456789';
const region = resolveRegionFromDialCode(cleanCode);
const example =
phoneUtil.getExampleNumberForType(region, PhoneNumberType.MOBILE) ||
phoneUtil.getExampleNumber(region);
if (!example) return 'Phone number';
return String(example.getNationalNumberOrDefault());
} catch {
return 'Phone number';
}
}
export function parsePhoneParts(
rawPhone?: string | null,
fallbackDialCode = '+1',
countryHint?: string | null
): { dialCode: string; nationalInput: string; regionCode: string } {
const defaultDial = fallbackDialCode
? sanitizeDialCode(fallbackDialCode)
: countryHint
? getDialCodeForCountryName(countryHint, '+1')
: '+1';
const defaultRegion = resolveRegionFromDialCode(defaultDial);
if (!rawPhone || !rawPhone.trim()) {
return {
dialCode: defaultDial,
nationalInput: '',
regionCode: defaultRegion,
};
}
const trimmed = rawPhone.trim();
// 1. If stored as "<+dialCode>" or "<+dialCode> <nationalBody>", split directly without altering the body
const splitMatch = trimmed.match(/^\+(\d{1,4})(?:\s+(.*))?$/);
if (splitMatch) {
const dialCode = `+${splitMatch[1]}`;
const nationalInput = (splitMatch[2] || '').replace(/[^\d]/g, '');
return {
dialCode,
nationalInput,
regionCode: resolveRegionFromDialCode(dialCode),
};
}
// 2. If compact international E.164 (e.g. "+989102036523" from backend API), extract code + national digits
if (trimmed.startsWith('+')) {
try {
const parsed = phoneUtil.parse(trimmed);
const cc = parsed.getCountryCode();
const nat = parsed.getNationalNumber();
if (cc && nat !== undefined) {
const dialCode = `+${cc}`;
const regionCode =
phoneUtil.getRegionCodeForNumber(parsed) ||
resolveRegionFromDialCode(dialCode);
return {
dialCode,
nationalInput: String(nat),
regionCode,
};
}
} catch {
const compactDigits = trimmed.slice(1).replace(/[^\d]/g, '');
for (let len = 1; len <= 3 && len <= compactDigits.length; len += 1) {
const candidateCode = compactDigits.slice(0, len);
const region = phoneUtil.getRegionCodeForCountryCode(
Number(candidateCode)
);
if (region && region !== 'ZZ') {
const dialCode = `+${candidateCode}`;
return {
dialCode,
nationalInput: compactDigits.slice(len),
regionCode: resolveRegionFromDialCode(dialCode),
};
}
}
}
}
// 3. Plain national number (e.g. "09102036523") — keep body digits intact
const digitsOnly = trimmed.replace(/[^\d]/g, '');
if (digitsOnly.length === 11 && digitsOnly.startsWith('09')) {
return {
dialCode: '+98',
nationalInput: digitsOnly,
regionCode: 'IR',
};
}
return {
dialCode: defaultDial,
nationalInput: digitsOnly,
regionCode: defaultRegion,
};
}
export function validatePhoneNumber(
dialCode: string,
nationalInput: string,
regionOverride?: string | null
): PhoneValidationResult {
const cleanCode = sanitizeDialCode(dialCode, '+1');
const digits = nationalInput.replace(/[^\d]/g, '');
if (!digits) {
return {
isValid: false,
e164: null,
international: null,
national: null,
regionCode: null,
error: 'Phone number is required',
};
}
const cleanCodeDigits = cleanCode.replace(/[^\d]/g, '');
const region =
(regionOverride && regionOverride.length === 2
? regionOverride.toUpperCase()
: null) || resolveRegionFromDialCode(cleanCode);
// Strip leading trunk 0 only for libphonenumber parsing (except Italy +39)
const nationalForParse =
cleanCodeDigits !== '39' && digits.startsWith('0')
? digits.replace(/^0+/, '')
: digits;
if (!nationalForParse) {
return {
isValid: false,
e164: null,
international: null,
national: null,
regionCode: null,
error: 'Enter a valid phone number for the selected country code',
};
}
try {
const parsed = phoneUtil.parse(`${cleanCode}${nationalForParse}`, region);
if (
String(parsed.getCountryCode()) !== cleanCodeDigits ||
!phoneUtil.isPossibleNumber(parsed) ||
!phoneUtil.isValidNumber(parsed)
) {
return {
isValid: false,
e164: null,
international: null,
national: null,
regionCode: null,
error: 'Enter a valid phone number for the selected country code',
};
}
return {
isValid: true,
e164: phoneUtil.format(parsed, PhoneNumberFormat.E164),
international: phoneUtil.format(parsed, PhoneNumberFormat.INTERNATIONAL),
national: phoneUtil.format(parsed, PhoneNumberFormat.NATIONAL),
regionCode: phoneUtil.getRegionCodeForNumber(parsed) || region,
error: null,
};
} catch {
return {
isValid: false,
e164: null,
international: null,
national: null,
regionCode: null,
error: 'Enter a valid phone number with country code',
};
}
}
export function isValidPhoneString(
rawPhone?: string | null,
countryHint?: string | null
): boolean {
if (!rawPhone || !rawPhone.trim()) return false;
const defaultDial = countryHint
? getDialCodeForCountryName(countryHint, '+1')
: '+1';
const parts = parsePhoneParts(rawPhone, defaultDial, countryHint);
return validatePhoneNumber(parts.dialCode, parts.nationalInput, parts.regionCode)
.isValid;
}
export function formatPhoneForDisplay(
rawPhone?: string | null,
countryHint?: string | null
): string {
if (!rawPhone || !rawPhone.trim()) return '';
const defaultDial = countryHint
? getDialCodeForCountryName(countryHint, '+1')
: '+1';
const parts = parsePhoneParts(rawPhone, defaultDial, countryHint);
const validated = validatePhoneNumber(
parts.dialCode,
parts.nationalInput,
parts.regionCode
);
return validated.international || rawPhone.trim();
}

54
src/lib/shopApi.ts

@ -4,7 +4,6 @@ export interface ApiBanner {
id: number;
slug: string;
title: string;
title_i18n?: Record<string, string>;
subtitle: string;
cta_label: string;
image_url: string;
@ -18,7 +17,6 @@ export interface ApiCategory {
slug: string;
title: string;
localized_title: string;
title_i18n?: Record<string, string>;
icon_url: string;
small_icon_url: string;
accent_color: string;
@ -42,8 +40,8 @@ export interface ApiStoreSummary {
sales_label: string;
since_label: string;
avg_response_time: string;
on_time_delivery_rate: number;
satisfaction_rate: number;
on_time_delivery_rate: number | string;
satisfaction_rate: number | string;
rating_avg: string | number;
reviews_count: number;
products_count: number;
@ -62,7 +60,6 @@ export interface ApiProductCard {
compare_at_price: string | null;
formatted_old_price: string | null;
discount_badge: string;
coin_price: number;
currency: string;
stock_qty: number;
origin_label: string;
@ -92,7 +89,6 @@ export interface ApiProductVariant {
title: string;
attributes_json: Record<string, string>;
price_override: string | null;
coin_price_override: number | null;
stock_qty: number;
is_active: boolean;
}
@ -146,7 +142,6 @@ export interface ApiCartItem {
formatted_unit_price: string;
line_total: string;
formatted_line_total: string;
coin_unit_price: number;
}
export interface ApiCartPricing {
@ -158,21 +153,14 @@ export interface ApiCartPricing {
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;
@ -198,11 +186,9 @@ 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;
@ -214,7 +200,6 @@ export interface ApiPaymentMethod {
label: string;
icon_url: string;
is_default: boolean;
balance?: number;
}
export interface ApiShipmentEvent {
@ -235,6 +220,7 @@ export interface ApiShipment {
status: 'ordered' | 'packed' | 'shipping' | 'delivered' | 'canceled';
carrier_name: string;
tracking_code: string;
estimated_delivery_date?: string | null;
estimated_delivery_label: string;
completed_steps: number;
thumbnails: string[];
@ -253,7 +239,6 @@ export interface ApiOrderItem {
origin_snapshot: string;
unit_price: string;
formatted_unit_price: string;
coin_unit_price: number;
quantity: number;
line_total: string;
formatted_line_total: string;
@ -266,10 +251,10 @@ export interface ApiOrderSummary {
payment_method: string;
payment_method_label: string;
payment_status: string;
payment_id?: number | null;
currency: string;
total_amount: string;
formatted_total: string;
coins_charged: number;
formatted_date: string;
formatted_datetime: string;
thumbnails: string[];
@ -285,9 +270,6 @@ export interface ApiOrderDetail extends ApiOrderSummary {
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;
@ -313,12 +295,10 @@ export interface ApiOrderCounters {
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;
@ -333,7 +313,6 @@ export interface ApiSupportSubject {
id: number;
slug: string;
label: string;
title_i18n?: Record<string, string>;
icon_url: string;
display_order: number;
}
@ -367,7 +346,7 @@ export interface ApiConversation {
export interface ApiChatMessage {
id: number;
conversation: number;
sender_type: 'customer' | 'store' | 'system';
sender_type: 'user' | 'customer' | 'store' | 'system';
text: string;
attachment_url: string;
product_ref: number | null;
@ -386,7 +365,6 @@ export interface HomeFeedResponse {
new_store_products: ApiProductCard[];
featured_stores: ApiStoreSummary[];
cart_items_count: number;
habib_coins_balance: number;
}
export const shopApi = {
@ -462,18 +440,6 @@ export const shopApi = {
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/'),
@ -482,15 +448,12 @@ export const shopApi = {
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/'
),
shopRequest<{ results: ApiPaymentMethod[] }>('/payment/methods/'),
// Orders & Shipments
fetchOrders: (status?: 'current' | 'delivered' | 'canceled') =>
@ -505,7 +468,6 @@ export const shopApi = {
shipping_address?: Record<string, unknown>;
shipping_method?: string | number;
payment_method: string;
promo_code?: string;
notes?: string;
}) => shopRequest<ApiOrderDetail>('/orders/', { method: 'POST', body: payload }),
@ -520,7 +482,6 @@ export const shopApi = {
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/`),
@ -549,7 +510,7 @@ export const shopApi = {
createAddress: (payload: {
label?: string;
recipient_name: string;
phone?: string;
phone: string;
country?: string;
city?: string;
street_line: string;
@ -657,4 +618,3 @@ export const shopApi = {
{ method: 'POST', body: payload }
),
};

21
src/pages/account/LanguageSettingPage.tsx

@ -5,6 +5,7 @@ import { AccountMenuRow } from '../../components/account/AccountMenuRow';
import { EmptyStateBox } from '../../components/common/ShimmerSkeletons';
import type { AccountMenuRowItem } from '../../data/accountData';
import { useShopApp } from '../../context/ShopAppContext';
import { useAnimatedPresence } from '../../hooks/use-animated-presence';
import { useHardwareBackHandler } from '../../hooks/use-hardware-back-handler';
import { useSmartBack } from '../../hooks/useSmartBack';
import { resolveMediaUrl } from '../../lib/http';
@ -118,14 +119,19 @@ export const LanguageSettingPage: React.FC = () => {
profile,
selectedAddress,
orderCounters,
habibCoinsBalance,
setHabibCoinsBalance,
language,
changeLanguage,
showToast,
} = useShopApp();
const [habibCoinsBalance, setHabibCoinsBalance] = useState<number>(() =>
typeof window !== 'undefined' && typeof window.HABIB_COINS === 'number'
? window.HABIB_COINS
: 21
);
const [langSheetOpen, setLangSheetOpen] = useState(false);
const { shouldRender: shouldRenderLangSheet, isClosing: isLangSheetClosing } =
useAnimatedPresence(langSheetOpen, 200);
useHardwareBackHandler(() => {
setLangSheetOpen(false);
@ -270,6 +276,7 @@ export const LanguageSettingPage: React.FC = () => {
{/* Top Left Back Button */}
<button
type="button"
className="habib-icon-btn"
onClick={() => (bare ? navigate('/shop-account') : smartBack(ROUTES.account))}
aria-label="Back"
style={{
@ -313,6 +320,7 @@ export const LanguageSettingPage: React.FC = () => {
{/* Top Right Profile Edit Button */}
<button
type="button"
className="habib-icon-btn"
onClick={() => navigate(bare ? '/shop-account' : ROUTES.profile)}
aria-label="Edit Profile"
style={{
@ -821,8 +829,9 @@ export const LanguageSettingPage: React.FC = () => {
</div>
{/* Language Picker Bottom Sheet */}
{langSheetOpen && (
{shouldRenderLangSheet && (
<div
className={`habib-sheet-backdrop${isLangSheetClosing ? ' is-closing' : ''}`}
onClick={() => setLangSheetOpen(false)}
style={{
position: 'fixed',
@ -835,7 +844,7 @@ export const LanguageSettingPage: React.FC = () => {
}}
>
<div
className="habib-bottom-sheet"
className={`habib-bottom-sheet${isLangSheetClosing ? ' is-closing' : ''}`}
onClick={(e) => e.stopPropagation()}
style={{
padding: '22px var(--page-px) calc(24px + var(--safe-bottom, 0px))',
@ -864,6 +873,7 @@ export const LanguageSettingPage: React.FC = () => {
</span>
<button
type="button"
className="habib-icon-btn"
onClick={() => setLangSheetOpen(false)}
aria-label="Close"
style={{
@ -904,6 +914,7 @@ export const LanguageSettingPage: React.FC = () => {
justifyContent: 'space-between',
cursor: 'pointer',
textAlign: 'left',
transition: 'background-color 180ms ease, border-color 180ms ease',
}}
>
<div style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
@ -937,10 +948,12 @@ export const LanguageSettingPage: React.FC = () => {
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
transition: 'background-color 180ms ease, border-color 180ms ease',
}}
>
{active && (
<div
className="habib-radio-dot"
style={{
width: 8,
height: 8,

128
src/pages/account/ProviderRequestPage.tsx

@ -5,6 +5,12 @@ 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 { PhoneNumberInput } from '../../components/common/PhoneNumberInput';
import {
getDialCodeForCountryName,
parsePhoneParts,
validatePhoneNumber,
} from '../../lib/phone';
import {
type AccountMenuRowItem,
PROVIDER_BADGE_CARDS,
@ -49,13 +55,32 @@ export const ProviderRequestPage: React.FC = () => {
const [fullName, setFullName] = useState('');
const [email, setEmail] = useState('');
const [phoneNumber, setPhoneNumber] = useState('');
const [profileSubmitAttempted, setProfileSubmitAttempted] = useState(false);
const savingProfile = updateProfileMutation.isPending;
const [applyOpen, setApplyOpen] = useState(false);
const [storeName, setStoreName] = useState('');
const [storeDesc, setStoreDesc] = useState('');
const [providerSubmitAttempted, setProviderSubmitAttempted] = useState(false);
const submittingProvider = applyProviderMutation.isPending;
const phoneValidation = useMemo(() => {
const defaultDial = getDialCodeForCountryName(
selectedAddress?.country || null,
'+1'
);
const parts = parsePhoneParts(
phoneNumber,
defaultDial,
selectedAddress?.country || null
);
return validatePhoneNumber(
parts.dialCode,
parts.nationalInput,
parts.regionCode
);
}, [phoneNumber, selectedAddress?.country]);
useEffect(() => {
if (bare || !profile) return;
setFullName((prev) => prev || profile.full_name || '');
@ -167,6 +192,11 @@ export const ProviderRequestPage: React.FC = () => {
const handleSaveProfile = async () => {
if (savingProfile) return;
setProfileSubmitAttempted(true);
if (!phoneValidation.isValid || !phoneValidation.e164) {
showToast(phoneValidation.error || 'Please enter a valid phone number');
return;
}
if (!bare && !isUserAuthenticated) {
const authed = await requireAuth({
featureName: 'profile settings',
@ -177,7 +207,7 @@ export const ProviderRequestPage: React.FC = () => {
await updateProfileMutation.mutateAsync({
full_name: fullName.trim(),
email: email.trim(),
phone_number: phoneNumber.trim(),
phone_number: phoneValidation.e164,
});
showToast('Profile saved');
} catch (err) {
@ -187,7 +217,12 @@ export const ProviderRequestPage: React.FC = () => {
const handleApplyProvider = async (e: React.FormEvent) => {
e.preventDefault();
setProviderSubmitAttempted(true);
if (!storeName.trim() || submittingProvider) return;
if (!phoneValidation.isValid || !phoneValidation.e164) {
showToast(phoneValidation.error || 'Please enter a valid phone number');
return;
}
if (!bare && !isUserAuthenticated) {
const authed = await requireAuth({
featureName: 'provider application',
@ -195,6 +230,13 @@ export const ProviderRequestPage: React.FC = () => {
if (!authed) return;
}
try {
if (phoneValidation.e164 !== profile?.phone_number) {
await updateProfileMutation.mutateAsync({
full_name: fullName.trim() || profile?.full_name || '',
email: email.trim() || profile?.email || '',
phone_number: phoneValidation.e164,
});
}
const res = await applyProviderMutation.mutateAsync({
store_name: storeName.trim(),
description: storeDesc.trim(),
@ -408,61 +450,22 @@ export const ProviderRequestPage: React.FC = () => {
>
Phone Number
</label>
<div
style={{
width: '100%',
height: 55,
padding: '0 15px',
borderRadius: 11,
backgroundColor: '#fbfbfc',
border: '1px solid #8b8b8b',
boxSizing: 'border-box',
display: 'flex',
alignItems: 'center',
gap: 8,
}}
>
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 400,
fontSize: 14,
lineHeight: '20px',
color: '#292a2e',
flexShrink: 0,
}}
>
+23
</span>
<div
style={{
width: 1,
height: 17,
backgroundColor: '#292a2e',
flexShrink: 0,
}}
/>
<input
<PhoneNumberInput
id="provider-phone"
type="tel"
className="habib-search-input"
value={phoneNumber}
onChange={(e) => setPhoneNumber(e.target.value)}
placeholder="Phone number"
style={{
flex: 1,
minWidth: 0,
height: '100%',
fontFamily: 'var(--font-sans)',
fontWeight: 400,
fontSize: 14,
lineHeight: '20px',
color: '#111111',
backgroundColor: 'transparent',
}}
onChange={(nextValue) => setPhoneNumber(nextValue)}
countryHint={selectedAddress?.country}
required
bare={bare}
height={55}
borderRadius={11}
backgroundColor="#fbfbfc"
borderColor="#8b8b8b"
fontSize={14}
showError={profileSubmitAttempted && !phoneValidation.isValid}
errorMessage={phoneValidation.error}
/>
</div>
</div>
{!bare && (
<button
@ -943,6 +946,20 @@ export const ProviderRequestPage: React.FC = () => {
}}
/>
<PhoneNumberInput
value={phoneNumber}
onChange={(nextValue) => setPhoneNumber(nextValue)}
countryHint={selectedAddress?.country}
required
height={46}
borderRadius={12}
backgroundColor="#ffffff"
borderColor="#d7dbe2"
fontSize={13}
showError={providerSubmitAttempted && !phoneValidation.isValid}
errorMessage={phoneValidation.error}
/>
<textarea
rows={3}
placeholder="Tell us about your products, craftsmanship, or bookstore"
@ -963,7 +980,7 @@ export const ProviderRequestPage: React.FC = () => {
<button
type="submit"
disabled={submittingProvider || !storeName.trim()}
disabled={submittingProvider || !storeName.trim() || !phoneValidation.isValid}
className="habib-cta-btn"
style={{
width: '100%',
@ -974,7 +991,10 @@ export const ProviderRequestPage: React.FC = () => {
fontWeight: 700,
fontSize: 15,
cursor: submittingProvider ? 'not-allowed' : 'pointer',
opacity: submittingProvider || !storeName.trim() ? 0.65 : 1,
opacity:
submittingProvider || !storeName.trim() || !phoneValidation.isValid
? 0.65
: 1,
}}
>
{submittingProvider ? 'Submitting...' : 'Submit Provider Request'}

7
src/pages/account/ShopAccountPage.tsx

@ -11,6 +11,7 @@ import {
} from '../../data/accountData';
import { useShopApp } from '../../context/ShopAppContext';
import { resolveMediaUrl } from '../../lib/http';
import { formatPhoneForDisplay } from '../../lib/phone';
import { isBareMode, ROUTES, USE_MOCK_DATA } from '../../lib/routes';
/**
@ -149,7 +150,11 @@ export const ShopAccountPage: React.FC = () => {
const displaySub = bare
? '09102036523'
: isUserAuthenticated
? profile?.phone_number || profile?.email || 'Verified Habib Account'
? (profile?.phone_number
? formatPhoneForDisplay(profile.phone_number, selectedAddress?.country)
: '') ||
profile?.email ||
'Verified Habib Account'
: useMockFallback
? '09102036523'
: 'Sign in with your Habib account';

15
src/pages/catalog/ShopSinglePage.tsx

@ -207,6 +207,7 @@ export const ShopSinglePage: React.FC = () => {
>
<button
type="button"
className="habib-icon-btn"
onClick={() => smartBack(ROUTES.home)}
aria-label="Back"
style={{
@ -829,6 +830,7 @@ export const ShopSinglePage: React.FC = () => {
color: activeTab === 'info' ? '#111111' : '#8b8b8b',
textAlign: 'center',
cursor: 'pointer',
transition: 'color 200ms cubic-bezier(0.22, 1, 0.36, 1)',
}}
>
Information
@ -847,6 +849,7 @@ export const ShopSinglePage: React.FC = () => {
color: activeTab === 'review' ? '#111111' : '#8b8b8b',
textAlign: 'center',
cursor: 'pointer',
transition: 'color 200ms cubic-bezier(0.22, 1, 0.36, 1)',
}}
>
Review({displayReviews.length})
@ -863,7 +866,7 @@ export const ShopSinglePage: React.FC = () => {
borderTopLeftRadius: 2,
borderTopRightRadius: 2,
backgroundColor: '#111111',
transition: 'left 0.2s ease',
transition: 'left 250ms cubic-bezier(0.22, 1, 0.36, 1)',
}}
/>
</div>
@ -881,7 +884,11 @@ export const ShopSinglePage: React.FC = () => {
}}
>
{activeTab === 'info' ? (
<>
<div
key="info"
className="habib-tab-panel"
style={{ display: 'flex', flexDirection: 'column', gap: 18 }}
>
{/* Category block */}
<div style={{ display: 'flex', flexDirection: 'column', gap: 3 }}>
<div
@ -937,11 +944,13 @@ export const ShopSinglePage: React.FC = () => {
: 'No description available.')}
</div>
</div>
</>
</div>
) : (
<div
key="review"
role="tabpanel"
aria-label="Customer reviews"
className="habib-tab-panel"
style={{ display: 'flex', flexDirection: 'column', gap: 12 }}
>
<div

3
src/pages/chat/ShopChatPage.tsx

@ -263,6 +263,7 @@ export const ShopChatPage: React.FC = () => {
{/* Back Button */}
<button
type="button"
className="habib-icon-btn"
onClick={() => smartBack(ROUTES.store(storeSlug))}
aria-label="Back"
style={{
@ -336,6 +337,7 @@ export const ShopChatPage: React.FC = () => {
{/* Right 3-Dots Menu Button */}
<button
type="button"
className="habib-icon-btn"
onClick={() => setMenuOpen((prev) => !prev)}
aria-label="More options"
style={{
@ -365,6 +367,7 @@ export const ShopChatPage: React.FC = () => {
{/* Dropdown Menu Overlay */}
{menuOpen && (
<div
className="habib-dropdown-menu"
style={{
position: 'absolute',
right: 'var(--page-px)',

15
src/pages/checkout/ShopBuy01Page.tsx

@ -9,6 +9,7 @@ import { AddressFormSheet } from '../../components/modals/AddressFormSheet';
import { useShopApp } from '../../context/ShopAppContext';
import { BUY01_ADDRESSES } from '../../data/checkoutData';
import { mapAddressToOption } from '../../lib/mappers';
import { isValidPhoneString } from '../../lib/phone';
import { isBareMode, ROUTES, USE_MOCK_DATA } from '../../lib/routes';
import type { ApiAddress } from '../../lib/shopApi';
@ -25,6 +26,7 @@ export const ShopBuy01Page: React.FC = () => {
isUserAuthenticated,
requireAuth,
addresses,
selectedAddress,
selectedAddressId,
selectAddress,
saveAddress,
@ -59,9 +61,8 @@ export const ShopBuy01Page: React.FC = () => {
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);
const total = Math.max(0, subtotalNum + shipNum);
return `$${total.toFixed(2)}`;
}, [cart?.pricing, isBare, selectedShippingMethod?.price, useMockFallback]);
@ -79,6 +80,16 @@ export const ShopBuy01Page: React.FC = () => {
setAddressModalOpen(true);
return;
}
if (
!isBare &&
selectedAddress &&
!isValidPhoneString(selectedAddress.phone, selectedAddress.country)
) {
showToast('Please enter a valid phone number for your delivery address');
setEditingAddress(selectedAddress);
setAddressModalOpen(true);
return;
}
navigate(ROUTES.checkoutReview);
};

19
src/pages/checkout/ShopCartPage.tsx

@ -49,7 +49,6 @@ export const ShopCartPage: React.FC = () => {
updateCartItemQuantity,
removeCartItem,
clearCart,
applyPromoCode,
addToCart,
} = useShopApp();
@ -105,8 +104,6 @@ export const ShopCartPage: React.FC = () => {
? bareTotalQty > 0
? `$${bareTotalOldPrice.toFixed(2)}`
: undefined
: livePricing && Number(livePricing.discount_amount) > 0
? livePricing.formatted_subtotal
: undefined;
const footerTotalItemsLabel = useFigmaSnapshot
@ -131,7 +128,7 @@ export const ShopCartPage: React.FC = () => {
];
}
const rows: SummaryLineRow[] = [
return [
{
id: 'row-items',
label: `Items (${resolvedLiveQty})`,
@ -143,17 +140,7 @@ export const ShopCartPage: React.FC = () => {
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]);
}, [bareItems, bareTotalPrice, bareTotalQty, isBare, liveItems, livePricing, resolvedLiveQty]);
const summaryTotalText = isBare
? `$${bareTotalPrice.toFixed(2)}`
@ -445,8 +432,6 @@ export const ShopCartPage: React.FC = () => {
onClose={() => setIsSummaryOpen(false)}
rows={summaryRows}
totalText={summaryTotalText}
promoCode={cart?.promo_code || ''}
onApplyPromo={isBare ? undefined : applyPromoCode}
/>
</MobileShell>
);

2
src/pages/checkout/ShopPayResultPage.tsx

@ -356,6 +356,7 @@ export const ShopPayResultPage: React.FC = () => {
{/* "track Order" Secondary Button */}
<button
type="button"
className="habib-node-btn"
onClick={() => navigate(ROUTES.orderDetail(activeOrderCode))}
style={{
marginTop: 2,
@ -401,6 +402,7 @@ export const ShopPayResultPage: React.FC = () => {
{/* "Continue Shoping" Primary CTA Button */}
<button
type="button"
className="habib-cta-btn"
onClick={() => navigate(ROUTES.home)}
style={{
width: '100%',

1
src/pages/checkout/ShopPaymentMethodsPage.tsx

@ -177,6 +177,7 @@ export const ShopPaymentMethodsPage: React.FC = () => {
{/* "Purchase" CTA Button */}
<button
type="button"
className="habib-cta-btn"
onClick={() => navigate('/shop-payresult')}
style={{
position: 'relative',

67
src/pages/checkout/ShopPaymentPage.tsx

@ -1,4 +1,4 @@
import React, { useEffect, useMemo, useState } from 'react';
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';
@ -18,6 +18,7 @@ import {
} from '../../data/checkoutData';
import { resolveMediaUrl } from '../../lib/http';
import { mapCartItemToReview } from '../../lib/mappers';
import { formatPhoneForDisplay, isValidPhoneString } from '../../lib/phone';
import { isBareMode, ROUTES, USE_MOCK_DATA } from '../../lib/routes';
import {
usePaymentMethodsQuery,
@ -41,8 +42,6 @@ export const ShopPaymentPage: React.FC = () => {
selectedShippingMethod,
selectedPaymentMethod,
setSelectedPaymentMethod,
habibCoinsBalance,
setHabibCoinsBalance,
showToast,
} = useShopApp();
@ -52,22 +51,12 @@ export const ShopPaymentPage: React.FC = () => {
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,
label: pm.label,
iconSrc:
resolveMediaUrl(pm.icon_url) ||
'/assets/images/icon-payment-google.svg',
@ -76,7 +65,6 @@ export const ShopPaymentPage: React.FC = () => {
}
return useMockFallback ? PAYMENT_METHODS_LIST : [];
}, [
habibCoinsBalance,
isBare,
paymentMethodsData,
selectedPaymentMethod,
@ -85,27 +73,21 @@ export const ShopPaymentPage: React.FC = () => {
const livePricing = cart?.pricing;
const { rows, totalText, requiredCoins } = useMemo(() => {
const { rows, totalText } = 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 totalNum = Math.max(0, subtotalNum + shipNum);
const computedRows: SummaryLineRow[] = [
{
@ -124,18 +106,9 @@ export const ShopPaymentPage: React.FC = () => {
},
];
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]);
@ -156,6 +129,14 @@ export const ShopPaymentPage: React.FC = () => {
showToast('Please select a delivery address');
return;
}
if (
selectedAddress &&
!isValidPhoneString(selectedAddress.phone, selectedAddress.country)
) {
showToast('Please enter a valid phone number for your delivery address');
navigate(ROUTES.checkoutShipping);
return;
}
if (submitting) return;
try {
const order = await placeOrderMutation.mutateAsync({
@ -164,6 +145,7 @@ export const ShopPaymentPage: React.FC = () => {
? undefined
: {
recipient_name: 'Ali Ghaderi',
phone: '+12125550199',
street_line: '250 Park Avenue South',
city: 'New York',
postal_code: '10003',
@ -171,7 +153,6 @@ export const ShopPaymentPage: React.FC = () => {
},
shipping_method: selectedShippingMethod?.code || 'standard',
payment_method: selectedPaymentMethod || 'google_pay',
promo_code: cart?.promo_code || undefined,
});
setPaymentSheetOpen(false);
@ -321,6 +302,23 @@ export const ShopPaymentPage: React.FC = () => {
? selectedAddress.recipient_name
: 'Ali Ghaderi'}
</div>
{!isBare && selectedAddress?.phone && (
<div
dir="ltr"
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 600,
fontSize: 11,
lineHeight: '15px',
color: '#73889d',
}}
>
{formatPhoneForDisplay(
selectedAddress.phone,
selectedAddress.country
)}
</div>
)}
<div
style={{
fontFamily: 'var(--font-sans)',
@ -422,9 +420,6 @@ export const ShopPaymentPage: React.FC = () => {
void handleConfirmPurchase();
}}
isSubmitting={submitting}
habibCoinsBalance={habibCoinsBalance}
requiredCoins={requiredCoins}
onCoinsUpdated={setHabibCoinsBalance}
/>
</MobileShell>
);

1
src/pages/orders/ShopOrderDetailPage.tsx

@ -401,6 +401,7 @@ export const ShopOrderDetailPage: React.FC = () => {
{/* Bottom CTA Button "Order support" */}
<button
type="button"
className="habib-cta-btn"
onClick={() =>
navigate(
liveOrder?.order_number

7
src/pages/orders/ShopOrdersPage.tsx

@ -108,7 +108,7 @@ export const ShopOrdersPage: React.FC = () => {
<OrdersListShimmer count={2} />
) : !isBare && orders ? (
orders.length > 0 ? (
<div className="habib-orders-grid">
<div key={activeTabId} className="habib-orders-grid habib-tab-panel">
{orders.map((order, idx) => (
<OrderListCard
key={order.id}
@ -121,6 +121,8 @@ export const ShopOrdersPage: React.FC = () => {
</div>
) : (
<div
key={activeTabId}
className="habib-tab-panel"
style={{
padding: '42px 20px',
borderRadius: 20,
@ -145,6 +147,7 @@ export const ShopOrdersPage: React.FC = () => {
</span>
<button
type="button"
className="habib-cta-btn"
onClick={() => navigate(ROUTES.home)}
style={{
marginTop: 4,
@ -171,7 +174,7 @@ export const ShopOrdersPage: React.FC = () => {
/>
)}
{useMockFallback ? (
<div className="habib-orders-grid">
<div key={activeTabId} className="habib-orders-grid habib-tab-panel">
{ORDERS_LIST_CARDS.map((order) => (
<OrderListCard key={order.id} order={order} />
))}

2
vite.config.ts

@ -114,7 +114,7 @@ function clickToComponentServerPlugin(): Plugin {
}
}
const backendOrigin = process.env.VITE_BACKEND_ORIGIN || 'http://127.0.0.1:9000'
const backendOrigin = process.env.VITE_BACKEND_ORIGIN || 'http://127.0.0.1:8000'
const apiProxy = {
'/api/shop': {

Loading…
Cancel
Save