# TASK: connect this storefront to the NShop API and complete every missing storefront UI component

You are a senior full-stack engineer. This repository is (or will become) an online store front end for a shop that runs on NShop. All shop
data (store settings, categories, products, prices, offers, stock, shipping cities, banners, orders) comes from the NShop REST API.
Your job has two parts:

1. **Integrate** the API: one server-side client, environment variables, caching, error handling.
2. **Audit and complete the UI**: compare the existing front end with the component checklist below, report what exists, what is partial and
   what is missing, then build every missing or partial component in the project's own style.

Work in the phases below, in order. Do not skip the audit report: produce it BEFORE writing UI code, and wait for no one: continue after
printing it unless something blocks you.

## 0. Ground rules (non-negotiable)

1. **The API key is a server secret.** Read it only on the server (`process.env.NSHOP_API_KEY`). Never prefix it with `NEXT_PUBLIC_`/`VITE_`/`PUBLIC_`,
   never ship it to the browser, never log it, never commit it. If the project has no server tier (pure SPA), create a tiny proxy/BFF (serverless
   function or small server) that holds the key and exposes only the endpoints the UI needs.
2. **Never trust or send client prices.** Orders carry only `product_id` and `quantity`. The server prices every line, adds shipping from the
   city, applies offers; there is no tax and no manual discount. Cart totals in the UI are estimates: label them as such and show the order
   response as the source of truth.
3. **Do not invent API fields, endpoints, query parameters or sort options.** Use only what is in this prompt or in the OpenAPI document
   (`https://nshop.naqsh-tech.com/api/v1/openapi.json`). The products endpoint has NO server-side sort and NO price filter: if the UI needs sorting, sort only the
   loaded page client-side and say so in the code comment.
4. **Match the project.** Detect and reuse the existing framework, router, language (TypeScript or JavaScript), styling system, component library,
   state management, i18n and formatting helpers. Do not add a UI library or a state library if one exists. Follow existing file naming and folder layout.
5. **Minimal, reversible changes.** Keep existing behaviour that already works. Remove dead data-access code only after everything is switched. Do
   not reformat unrelated files.
6. **Accessibility and RTL.** Semantic HTML, labels for every input, focus states, alt text (empty alt for decorative images), keyboard operable
   controls. If the store language is Arabic (`ecommerce_language`) or the project is RTL, use logical CSS properties (`start/end`, not `left/right`)
   and `dir` correctly.
7. **No real orders while testing.** Test checkout only with requests that must FAIL validation (see phase 5). Place a real order only if the
   owner explicitly asks, then ask them to cancel it in NShop.
8. **Money.** Values are numbers with up to 2 decimals in the shop currency (`store.company.ecommerce_currency`, falling back to `currency`:
   `ILS`, `USD` or `JOD`). Never do floating-point money math you then submit; round only for display with `Intl.NumberFormat`.

## 1. Recon (print a short summary)

Detect and state: framework and version (Next.js app/pages router, Nuxt, SvelteKit, Remix, Astro, Vite SPA...), language, package manager,
styling (Tailwind, CSS modules, styled-components...), component library, data fetching/caching approach, i18n library, existing routes/pages,
where product data is read today (database client, mock JSON, another API), existing cart implementation, existing checkout, deployment target.

## 2. API client and configuration

Create ONE server-side module (for example `src/lib/nshop-client.ts`) that every page, route handler and server action uses. Requirements:

- Reads `NSHOP_API_BASE_URL` and `NSHOP_API_KEY`; fails fast with a clear error at first use when either is missing.
- Sends `Authorization: Bearer <key>`; sets a ~10 s timeout.
- Unwraps the response envelope: success is `{ "data": ..., "meta"?: ... }`, errors are `{ "error": { "code", "message", "details"? } }`.
  Throw a typed `NShopApiError` carrying `status`, `code`, `message`, `details`, and the `X-Request-Id` header.
- Retries ONLY `429`, `500`, `502` and network errors (exponential backoff plus jitter, honour `Retry-After`, max 3 attempts); never retries other 4xx.
  `POST /orders` always sends an `Idempotency-Key` and reuses the same key on retries.
- Caching by data type (use the framework's fetch cache tags/ISR): store config, shipping cities and banner statements 300-3600 s; categories and
  products 60-600 s; order lookups and order creation never cached. Expose a revalidate hook/route (protected by the project's own secret, compared
  in constant time, accepted only from an `Authorization` header) so the owner can refresh on demand.
- Typed functions, one per endpoint (see the contract below), with response types matching the documented fields.
- Never exposes the key through any value passed to client components.

Update `.env.example` (placeholders only, no real values) and the README setup section. Remove variables that belonged to the old data layer
only after the switch works (for example database URLs, service keys, a hard-coded company id).

## 3. API contract (authoritative summary)

Base URL `https://nshop.naqsh-tech.com`. All paths below are under `/api/v1`. Every response has `X-Request-Id` and `X-RateLimit-*` headers.
Rate limit: 120 requests per minute per key and endpoint (order creation 20 per minute). `429` includes `Retry-After` seconds.

| Method | Path | Scope | Purpose |
|---|---|---|---|
| GET | `/health` | public | Liveness. `configured:false` means the NShop server lacks its database key |
| GET | `/store` | `store:read` | `{ company, settings, theme }`: name, logo, banners, WhatsApp, social links, contact info, policies, currency, language, theme |
| GET | `/shipping-cities` | `store:read` | Active delivery cities `{ id, city_name, shipping_cost, sort_order }` |
| GET | `/banner-statements` | `store:read` | Announcement-bar texts `{ id, body, sort_order }` |
| GET | `/categories?tree=true` | `catalog:read` | Categories `{ id, name, description, parent_id, level, sort_order, icon_url, children }`; flat by default, nested with `tree=true` |
| GET | `/products` | `catalog:read` | Paged product list. Query: `limit` 1-100 (default 24), `page` or `offset`, `category_id`, `q` (matches name, SKU and barcode, case-insensitive substring), `ids` (comma list, max 100), `updated_since` (full ISO-8601 datetime). Response: `data` = items, `meta` = `{ total, limit, page, has_more }` |
| GET | `/products/{id}` | `catalog:read` | One product (id of the product) |
| GET | `/best-sellers?limit&days` | `catalog:read` | Best selling products of the last `days` (1-365), ranked, full product objects |
| POST | `/orders` | `orders:write` | Place a cash-on-delivery order. Header `Idempotency-Key` (8-128 chars) |
| GET | `/orders/{orderNumber}?phone_last4=` | `orders:read` | Track an order; `phone_last4` (4 digits) is required |
| GET | `/openapi.json` | public | OpenAPI 3.1 document (use it to generate types) |

### Product object

```json
{
  "id": "uuid", "name": "...", "sku": "...", "barcode": "...", "description": "...",
  "category_id": "uuid", "category_name": "...", "images": ["https://..."],
  "price": 90, "compare_at_price": 100,
  "offer": { "id": "uuid", "kind": "percent", "value": 10, "ends_at": "2026-12-01T00:00:00Z" },
  "in_stock": true, "stock_quantity": 14, "updated_at": "2026-09-21T06:45:26.062544+00:00"
}
```

- `price` is the effective price AFTER the best active offer: show and use this. `compare_at_price` is the original price, only when an offer applies
  (show it crossed out); otherwise `null`. `offer.kind` is `percent` or `fixed`; `ends_at` may be `null`.
- `stock_quantity` and `in_stock` are INFORMATIONAL (the API does not reject orders that exceed stock yet): show an "out of stock" badge when
  `in_stock` is false, but do not hard-block checkout on them beyond a friendly warning. `images` are public URLs, main image first, possibly empty
  (use a placeholder image).

### Place an order

```http
POST /api/v1/orders
Authorization: Bearer <key>
Idempotency-Key: <one uuid per checkout attempt>
Content-Type: application/json

{
  "customer_name": "Ahmad Saleh",
  "customer_phone": "0599123456",
  "customer_phone2": "0568123456",
  "customer_email": "ahmad@example.com",
  "customer_city": "Ramallah",
  "customer_address": "Al-Masyoun, Street 5, building 12",
  "order_note": "Call before delivery",
  "items": [{ "product_id": "uuid", "quantity": 2 }]
}
```

Rules: `customer_name` 2-200 chars; `customer_phone` must be a Palestinian mobile (`05XXXXXXXX`; `+9705...`, `+9725...`, `00970...` and Arabic digits
are accepted and normalized); `customer_phone2` and `customer_email` optional (valid email, max 320); `customer_city` must equal a `city_name`
from `/shipping-cities` when the store has cities; `customer_address` 5-2000 chars; `order_note` max 2000; `items` 1-50 lines, `quantity` 1-9999.
Unknown fields (`unit_price`, `total_price`, `discount_amount`, `tax_amount`, `shipping_amount`, `payment_method`, product names...) are rejected with `400`.
Success `201`: `{ "data": { "id", "order_number", "status", "subtotal", "shipping_amount", "discount_amount", "total_amount" } }`.

### Track an order

`GET /orders/{order_number}?phone_last4=1234` returns `{ order_number, status, payment_status, customer_name, customer_phone_masked, customer_address,
subtotal, shipping_amount, tax_amount, discount_amount, total_amount, payment_method, shipping_method, tracking_number, notes, created_at,
updated_at, items: [{ product_id, product_name, product_sku, quantity, unit_price, total_price, product_image_url }] }`.
A wrong order number or wrong last four digits both return `404 not_found` (identical on purpose). `status` is one of `pending`, `confirmed`,
`processing`, `shipped`, `delivered`, `cancelled`, `refunded`; `payment_status` one of `pending`, `paid`, `failed`, `refunded`. The shop owner
changes them in NShop; the storefront only displays them.

### Errors

| HTTP | `error.code` | What to do in the UI |
|---|---|---|
| 400 | `validation_error` | Map `details.issues` (field paths) to the matching form fields |
| 401 | `invalid_api_key` | Server misconfiguration: log with request id, show a generic error page, alert the owner |
| 403 | `insufficient_scope` / `ecommerce_disabled` | Same as 401: configuration problem, not a user error |
| 404 | `not_found` | Unknown product: 404 page. Tracking: "order not found or phone digits do not match" |
| 409 | `conflict` / `idempotency_conflict` / `insufficient_stock` | Retry once with a NEW attempt / do not reuse the key with a different body / (stock is not enforced yet) ask the customer to adjust the cart |
| 422 | `product_not_available` | Remove that line from the cart and tell the customer |
| 429 | `rate_limited` | Wait `Retry-After` seconds then retry; show a calm "try again in a moment" |
| 500/502 | `internal_error` | Retry with the same `Idempotency-Key`; if it still fails show an apology and keep the cart intact |

## 4. UI component checklist (audit, then build what is missing)

For EACH row decide `PRESENT`, `PARTIAL` or `MISSING` by reading the actual code (do not guess from file names). `PARTIAL` means it exists but fails
an acceptance criterion. Every component must have loading, empty and error states where data is fetched, and must work on mobile.

| # | Component | Data source | Acceptance criteria |
|---|---|---|---|
| 1 | **Site header and branding** | `/store` (`company.ecommerce_store_name` or `name`, `ecommerce_logo_url`), `/categories?tree=true` | Logo/name linking home, primary category navigation (drawer on mobile), search box, cart icon with live item count, language/RTL aware |
| 2 | **Announcement bar** | `/banner-statements` | Shows the texts in `sort_order`, rotates or stacks if several, hidden when empty, dismissible optional |
| 3 | **Hero and promotional banners** | `company.ecommerce_banner_url`, `ecommerce_small_banner_2_url`, `ecommerce_small_banner_3_url` | Responsive images with correct aspect ratio, optimised loading (priority for the hero), graceful absence when a banner is null |
| 4 | **Category navigation and category page** | `/categories?tree=true`, `/products?category_id=` | Nested menu from the tree, category icon (`icon_url`) when present, category page lists its products with pagination; for a parent category, also include products of its children (request each child id and merge, or filter client-side) |
| 5 | **Product card** | product object | Image (placeholder when `images` is empty), name, `price`, crossed-out `compare_at_price` and an offer badge ("-10%" for percent, amount for fixed) when `offer` exists, "out of stock" badge when `in_stock` is false, link to the product page, quick add-to-cart |
| 6 | **Product listing with search and paging** | `/products` (`q`, `page`, `limit`, `meta`) | Grid with `meta.total` results count, debounced search box using `q`, pagination or "load more" using `meta.has_more`, no-results state, skeleton while loading, URL reflects page/query/category so it is shareable |
| 7 | **Product detail page** | `/products/{id}` | Image gallery from `images` (thumbnails, zoom or swipe), name, SKU, description, price block with offer details and end date when `offer.ends_at` exists, stock indicator, quantity selector (1-9999), add-to-cart, 404 page for unknown id |
| 8 | **Best sellers / featured rail** | `/best-sellers` | Horizontal rail or grid on the home page, same product card, hidden when empty |
| 9 | **Cart** | client state persisted (localStorage or cookie), lines = `{ product_id, quantity }` plus display snapshot | Add, change quantity, remove, empty state, line totals and subtotal clearly labelled as an estimate, count in header, survives reload; before checkout refresh the lines with `/products?ids=` and flag price changes or products that disappeared |
| 10 | **Checkout form** | `/shipping-cities`, `POST /orders` | Fields: full name, mobile, optional second mobile, optional email, city `<select>` from `shipping-cities`, address, order note. Client validation mirroring the rules in section 3 (and normalising Arabic digits), shipping cost shown from the selected city, "cash on delivery" payment notice, order summary, one `Idempotency-Key` per attempt generated when checkout opens, submit button disabled while sending, server `details.issues` mapped to fields, all error codes handled per section 3 |
| 11 | **Order confirmation page** | `POST /orders` response | Shows `order_number`, `total_amount`, the delivery city, what happens next, a clear "track your order" link, clears the cart only after success; reloading does not create a second order |
| 12 | **Order tracking page** | `GET /orders/{n}?phone_last4=` | Form for order number and last 4 digits of the phone; result with a status stepper over `pending, confirmed, processing, shipped, delivered` (and distinct cancelled/refunded states), items, totals, `tracking_number` when present; identical "not found" message for any mismatch; never cached |
| 13 | **Footer and policies** | `company.ecommerce_contact_info`, `ecommerce_social_links`, `ecommerce_policies`, `ecommerce_whatsapp` | Contact details, social icons for the links that exist, links/pages for each non-empty policy, copyright |
| 14 | **WhatsApp contact button** | `company.ecommerce_whatsapp` | Floating or header button opening `https://wa.me/<digits>` (digits only, international format), hidden when the value is empty; on a product page prefill a message with the product name |
| 15 | **Global states** | all | Skeleton loaders, empty states, a friendly error boundary with retry, a 404 page, a calm message for `429`, an offline/network message, no raw error text or stack traces shown to customers |
| 16 | **SEO and metadata** | `settings.seo_settings`, products | Page titles/descriptions, Open Graph image, canonical URLs, `Product` JSON-LD (name, image, sku, offers with `price` and currency, availability from `in_stock`), `sitemap.xml` built by paging through ALL products and categories, `robots.txt` |
| 17 | **Localisation, currency and RTL** | `company.ecommerce_language`, `ecommerce_currency` | Language and `dir` follow the store setting, one shared money formatter using the store currency, numbers and dates localised, all user-facing strings in the project's i18n system |
| 18 | **Theme** | `settings.theme_config`, `theme.config` | Brand colours/fonts applied through CSS variables or the project's theme mechanism when provided; sensible defaults when not (do not block the build on a missing theme) |

Order of work: 1 (client, env) then 5, 6, 7, 9, 10, 11 (the shopping path), then 12, 4, 8, 2, 3, 13, 14, 15, then 16, 17, 18.

## 5. Verification (do all of it, report the evidence)

1. Type-check, lint and build the project; fix what you broke.
2. Prove the connection with the key from the environment (do not print the key): `GET /health` shows `configured: true`; `GET /store`,
   `/shipping-cities`, `/categories?tree=true` and `/products?limit=3` return data; an invalid key returns `401`.
3. Exercise the failure paths of `POST /orders` WITHOUT creating an order: invalid phone, missing city, empty `items`, a body containing `unit_price`,
   an `Idempotency-Key` shorter than 8 characters. Each must produce the documented `400` and the UI must show a field-level message.
4. Walk the shopping path in the dev server: browse, search, open a product, add to cart, change quantity, reload (cart persists), reach checkout,
   see validation errors, see shipping cost change with the city. Test at a mobile width and, if the store language is Arabic, in RTL.
5. Search the repository for the API key and for `NEXT_PUBLIC_NSHOP`: neither may appear in client bundles or in git history of your changes.

## 6. Final report (exact format)

1. **Gap table**: the 18 components with `PRESENT` / `PARTIAL` (what failed) / `MISSING`, and for each the files you created or changed.
2. **Integration summary**: files added, environment variables required (names only), caching choices.
3. **Verification evidence**: commands run and results, including the checkout failure-path tests.
4. **Open questions and risks**: anything you assumed, anything the owner must do in NShop (for example creating the key with all four scopes,
   setting banners, shipping cities, WhatsApp number and policies in the store settings).

Stop after the report. Do not push, deploy or place real orders unless the owner asks.