# RentalDriveGo Carplace and Production Authentication Fix Plan

**Version:** 2.2  
**Date:** July 2, 2026  
**Status:** Planning approved for review  
**Implementation status:** No application code changed

---

## 1. Purpose

This plan replaces the legacy RentalDriveGo storefront with Carplace, a new renter-first marketplace experience and retains the production dashboard authentication repair as a separate priority workstream.

### 1.1 Product naming

**Carplace** is the public product name for the renter marketplace. The word “storefront” is retained only when referring to the legacy implementation or existing technical paths during migration.

The canonical public route will become `/carplace`. Existing `/storefront` URLs must remain functional through permanent path-preserving redirects so bookmarks, indexed pages, and external company links do not break. The deployable application may remain at `apps/storefront` during the first implementation phase to avoid an unnecessary repository-wide rename while product behavior is still changing.

**Carplace is trilingual from its first release. English (`en`), French (`fr`), and Arabic (`ar`) are equal, required product languages. No page, workflow, validation message, metadata field, or release phase may be shipped in only one or two languages.**


The new Carplace marketplace must:

1. Feel like part of the current RentalDriveGo website.
2. Serve renters rather than reuse business-to-business homepage messaging.
3. Make vehicle discovery, comparison, availability checking, and reservation requests clear and fast.
4. Preserve existing public URLs during migration.
5. Use real platform data and avoid unsupported claims such as instant confirmation, final-price guarantees, or renter accounts that the backend does not currently provide.
6. Allow controlled company branding without letting every company turn the page into an unrelated website.
7. Be deployable beside the legacy storefront and switched over safely.
8. Preserve full feature and content parity across English, French, and Arabic, including proper Arabic RTL behavior.

---

## 2. Findings From the Current Code

### 2.1 The legacy storefront is a collection of pages, not a coherent product

The current application has working foundations:

- Main marketplace page
- Company public pages
- Vehicle detail pages
- Search form
- Vehicle cards
- Reservation request form
- Offers
- Reviews
- Renter-area pages
- English, French, and Arabic copy
- Theme and locale preferences

However, the user experience is assembled from independent cards and utility classes. It lacks a consistent marketplace information hierarchy, search-results experience, trust model, quote model, conversion flow, and shared public design system.

### 2.2 Carplace and the homepage need one visual foundation

The legacy storefront currently renders:

- `StorefrontHeader`
- `StorefrontFooter`

The homepage renders:

- `HeaderRouter`
- `SiteHeader`
- `SiteFooter`
- Homepage design tokens and component styles

The new Carplace marketplace must use the same visual foundation as the homepage, but it must not blindly copy homepage navigation or business-focused calls to action.

### 2.3 Existing API capabilities are useful but underused

The existing public marketplace API already exposes:

- Cities
- Public vehicle search
- Listed rental companies
- Public offers
- Company profiles
- Company reviews
- Company vehicles
- Vehicle details
- Date-scoped availability
- Reservation requests
- Offer-code validation
- Funnel-event tracking

This is enough to build a credible renter marketplace without inventing an entirely new backend.

### 2.4 Reservations are requests, not instant bookings

The current reservation service creates a reservation with status `PENDING` and returns a message stating that the rental company will review the request.

The new Carplace marketplace must use language such as:

- “Request this vehicle”
- “Send reservation request”
- “The company will confirm availability and contact you”

It must not use language such as:

- “Booking confirmed”
- “Guaranteed vehicle”
- “Instant booking”

unless the backend and company settings later support those guarantees.

### 2.5 Renter account authentication is disabled

The API currently rejects renter sign-up and sign-in. The legacy storefront contains renter sign-in, registration, dashboard, saved-company, notification, and profile pages, but the authentication service intentionally disables login and registration.

Carplace must therefore launch as a guest-first experience. Renter-account links must remain hidden until the backend capability is deliberately enabled and tested.

### 2.6 The legacy editable homepage content model is mismatched

The current admin-managed storefront homepage schema contains operator-oriented content such as:

- Start trial
- Create workspace
- Multi-tenant messaging
- Company and renter audience cards
- Platform launch steps

That content belongs to the SaaS marketing homepage, not the renter marketplace.

Carplace needs a separate marketplace content schema. Reusing the current schema would preserve the current confusion in a better-looking wrapper.

### 2.7 Current pricing is only a simple estimate

The marketplace reservation service calculates:

`daily rate × rental days`

It does not currently expose a complete public quote containing all applicable taxes, fees, deposits, mileage rules, insurance choices, delivery charges, or pricing-rule adjustments.

Carplace must label the current value as an estimated rental subtotal unless a proper quote endpoint is added.

### 2.8 Production dashboard authentication remains a P0 issue

The dashboard middleware requires the `employee_session` cookie. In local development, the dashboard and API share the `localhost` hostname, so a host-only cookie works across ports. In production, direct API requests to `api.rentaldrivego.ma` can create a host-only cookie that is unavailable to `rentaldrivego.ma/dashboard`.

The preferred repair remains a same-origin dashboard API proxy.

---

## 3. Product Definition

### 3.1 Homepage and Carplace have different jobs

The public website homepage is a business-to-business SaaS marketing surface for rental companies.

Carplace is a business-to-consumer marketplace for renters.

They should share:

- Brand identity
- Typography
- Spacing system
- Color system
- Header and footer foundations
- Accessibility behavior
- Theme behavior
- Localization behavior

They should not share:

- Navigation labels
- Primary calls to action
- Page hierarchy
- Conversion language
- Content schema

### 3.2 Carplace primary user promise

> Find a suitable vehicle from a trusted local rental company, understand the important rental conditions, and submit a clear reservation request without unnecessary friction.

### 3.3 Primary users

1. Renters searching by location and date.
2. Renters comparing vehicles and companies.
3. Renters returning from a shared vehicle or company link.
4. Rental companies receiving qualified reservation requests.
5. Platform administrators controlling marketplace content and quality.

### 3.4 Primary conversion

The main conversion is a successfully submitted reservation request.

Secondary conversions are:

- Search completed
- Vehicle viewed
- Availability checked
- Company profile viewed
- Offer applied
- Contact action initiated

---

## 4. Scope Control

### 4.1 Included in Carplace launch

- New marketplace homepage
- New search-results experience
- New company page in Carplace
- New vehicle detail page
- Progressive reservation-request flow
- Request-success page
- Shared website visual foundation
- Complete English, French, and Arabic feature and content parity
- Server-rendered Arabic RTL behavior
- Language switching that preserves the current page, search filters, dates, and reservation progress
- Light and dark themes
- Responsive desktop, tablet, and mobile behavior
- Search-engine metadata
- Accessibility baseline
- Funnel analytics
- Safe cutover from the legacy storefront

### 4.2 Explicitly excluded from the first launch

- Instant booking claims
- Guaranteed final pricing without a quote contract
- Online renter sign-up or sign-in while the API disables it
- Saved vehicles or saved companies requiring authentication
- Public maps without reliable coordinates
- Live chat unless a staffed support process exists
- Fake scarcity messages
- Unverified review counts or ratings
- Arbitrary company HTML, CSS, or JavaScript
- A complete redesign of the SaaS homepage

These exclusions are deliberate. A strong marketplace is not one with the largest pile of features. It is one whose promises survive contact with the backend and real customers.

---

## 5. Recommended Technical Strategy

### 5.1 Rebuild inside the legacy storefront application

Keep `apps/storefront` as the deployable application.

Do not create another standalone Next.js application. A second Carplace app would duplicate:

- Proxy rules
- Asset-prefix configuration
- Security headers
- API configuration
- Deployment configuration
- Monitoring
- Localization

The new experience should be implemented as a clean feature area inside the existing app.

Recommended structure:

```text
apps/storefront/src/
  app/
    (public)/
      page.tsx
      search/page.tsx
      [slug]/page.tsx
      [slug]/vehicles/[id]/page.tsx
      request/[reference]/page.tsx
  features/
    marketplace/
      home/
      search/
      companies/
      vehicles/
      booking/
      analytics/
      content/
  components/
    public-shell/
    marketplace/
  lib/
    api/
    localization/
      config.ts
      server.ts
      messages/en.ts
      messages/fr.ts
      messages/ar.ts
    metadata/
    preferences/
```

### 5.2 Build V2 in parallel before switching routes

Create Carplace components and data adapters without deleting the current implementation.

Use a server-side release setting such as:

```env
CARPLACE_EXPERIENCE_VERSION=v2
```

During migration, the legacy `/storefront/*` routes should continue serving V1 until their matching Carplace routes are ready. Once a Carplace route passes its release gates, redirect the corresponding legacy path to `/carplace/*`.

Do not leave two independently indexed public URL systems. `/carplace/*` becomes canonical, while `/storefront/*` exists only as a compatibility redirect. Redirects must preserve the resolved language, path, query parameters, selected dates, locations, offer codes, and campaign attribution.

### 5.3 Introduce Carplace routes without breaking legacy URLs

Keep these routes working:

```text
/carplace
/carplace/search
/carplace/[company-slug]
/carplace/[company-slug]/vehicles/[vehicle-id]
```

Existing company and vehicle links must not break during cutover. Add permanent, path-preserving redirects from `/storefront/*` to `/carplace/*`, including query parameters used for dates, locations, offers, and campaign attribution. The redirect must also migrate the legacy `storefront-language` preference into the shared `rentaldrivego-language` cookie when needed.

### 5.4 Separate API response types from page components

Create explicit Carplace contracts for:

- Marketplace home
- Search filters
- Search results
- Search facets
- Company summary
- Company detail
- Vehicle summary
- Vehicle detail
- Availability result
- Quote result
- Reservation request
- Reservation success
- Public review summary

Do not define slightly different `Vehicle` interfaces independently inside several page files.

---

## 6. Shared Website Design Foundation

### 6.1 Create a reusable public-site UI package

Create or extend a workspace package such as:

```text
packages/public-site-ui
```

It should contain presentation-only components and tokens:

- Brand link
- Public header frame
- Public footer frame
- Desktop navigation
- Mobile navigation
- Locale selector
- Theme selector
- Buttons
- Cards
- Badges
- Section containers
- Form controls
- Empty states
- Skeletons
- Error states
- Breadcrumbs
- Dialogs and drawers
- Shared design tokens

The package must not import homepage routes or Carplace routes.

### 6.2 Use adapters instead of cross-app imports

The homepage and Carplace should each provide their own navigation data and link behavior.

The Carplace header should use renter-focused navigation such as:

- Find a car
- Rental companies
- Deals
- How it works
- Help

The account or business actions should be visually secondary:

- Company login
- List your fleet or create a company account

Do not make “Create account” the primary renter action while renter account creation is disabled.

### 6.3 Visual alignment rules

Carplace should reuse the homepage:

- Blue and orange semantic action colors
- Surface and border colors
- Typography stack
- Container widths
- Spacing scale
- Radius scale
- Focus treatment
- Theme behavior
- Reduced-motion behavior

Carplace-specific imagery and cards may be more visual, but they must remain recognizably part of RentalDriveGo.

### 6.4 Company branding boundaries

Allow each rental company to contribute:

- Logo
- Display name
- Primary accent color
- Cover image
- Localized public description in English, French, and Arabic
- Contact details
- Localized rental-policy summaries in English, French, and Arabic

Do not allow companies to replace:

- Global typography
- Layout grid
- Core action colors
- Header structure
- Footer structure
- Accessibility behavior

Company accent colors must pass contrast checks. If a configured color fails, use the platform fallback color.

---

## 7. Carplace Page Architecture

## 7.1 Marketplace homepage: `/carplace`

### Purpose

Move renters immediately toward a useful search while establishing trust.

### Recommended sections

1. **Compact marketplace hero**
   - Clear renter-focused title
   - Pickup location
   - Return location mode
   - Pickup date and time
   - Return date and time
   - Driver age
   - Search action

2. **Trust strip**
   - Local rental companies
   - Verified marketplace listings
   - Direct company confirmation
   - Transparent request status

3. **Popular locations**
   - Generated from real city data
   - No hard-coded “popular” claim unless analytics support it
   - Initially label as “Browse by city”

4. **Vehicle categories**
   - Economy
   - Compact
   - Sedan or midsize
   - SUV
   - Luxury
   - Van

5. **Featured offers**
   - Only active public offers
   - Clear validity date
   - Clear company ownership
   - No unsupported “best deal” ranking

6. **Recommended vehicles**
   - Available or recently available inventory
   - Explain the ranking rule
   - Prefer a simple deterministic order at launch

7. **Trusted rental companies**
   - Company name
   - City
   - Verified review rating when available
   - Published vehicle count
   - Link to company page

8. **How reservation requests work**
   - Search
   - Select
   - Submit request
   - Receive company confirmation

9. **Rental guidance**
   - Documents commonly required
   - Deposit expectations
   - Age-policy warning
   - Final terms are controlled by the rental company

10. **Help and FAQ**
   - What happens after a request
   - When payment is collected
   - Availability and price changes
   - Cancellation and company policies

### Homepage content model

Create a dedicated `CarplaceHomepageConfig`, separate from the existing operator-focused `StorefrontHomepageConfig`.

Suggested fields:

```ts
type CarplaceLocale = 'en' | 'fr' | 'ar'
type LocalizedText = Record<CarplaceLocale, string>

interface CarplaceHomepageContent {
  hero: {
    eyebrow: LocalizedText
    title: LocalizedText
    body: LocalizedText
  }
  trustItems: Array<{ title: LocalizedText; body: LocalizedText }>
  sectionLabels: {
    locations: LocalizedText
    categories: LocalizedText
    offers: LocalizedText
    vehicles: LocalizedText
    companies: LocalizedText
    howItWorks: LocalizedText
    guidance: LocalizedText
    faq: LocalizedText
  }
  howItWorks: Array<{ title: LocalizedText; body: LocalizedText }>
  guidance: Array<{ title: LocalizedText; body: LocalizedText }>
  faq: Array<{ question: LocalizedText; answer: LocalizedText }>
  seo: {
    title: LocalizedText
    description: LocalizedText
  }
}
```

Dynamic vehicles, offers, cities, and companies must remain API-driven rather than editable as arbitrary admin text. Every administrator-managed Carplace content record must contain approved `en`, `fr`, and `ar` values before it can be published.

---

## 7.2 Search results: `/carplace/search`

The current homepage mixes search input and results. Carplace should use a dedicated results route.

### Required layout

- Persistent search summary at the top
- Edit-search action
- Desktop filter sidebar
- Mobile filter drawer
- Sort control
- Result count
- Vehicle grid
- Pagination or controlled “load more”
- Empty state with actionable alternatives
- Error state that does not pretend there are zero vehicles

### Initial filters

Use filters supported by real data:

- Pickup location
- Return location
- Dates and times
- Category
- Maximum daily rate
- Transmission
- Make
- Model

Add only after API support and data quality are confirmed:

- Minimum price
- Seats
- Fuel type
- Mileage policy
- Deposit range
- Delivery option
- Instant confirmation

### Search state

All search state must be represented in the URL query string so that users can:

- Refresh without losing filters
- Share search links
- Use browser back and forward
- Open results in another tab

### Search result contract

Replace the bare array response with a versioned result contract:

```ts
interface VehicleSearchResponse {
  items: VehicleSummary[]
  pagination: {
    page: number
    pageSize: number
    totalItems: number
    totalPages: number
  }
  facets: {
    categories: Array<{ value: string; count: number }>
    transmissions: Array<{ value: string; count: number }>
    makes: Array<{ value: string; count: number }>
    price: { min: number | null; max: number | null }
  }
}
```

The API currently loads and filters a broader vehicle set before slicing it in memory. Replace this with database-level filtering and a count query where possible. Availability may remain a second-stage check, but the result must expose accurate pagination semantics.

---

## 7.3 Vehicle cards

Every vehicle card should provide enough information to decide whether the detail page is worth opening.

Required content:

- Optimized vehicle image
- Make, model, and year
- Category
- Transmission when available
- Seats when available
- Company name
- Company rating only when based on real reviews
- Pickup city or supported location
- Date-scoped availability status
- Daily price
- Clear price qualifier
- Primary detail action

### Price wording

Until a quote endpoint exists:

- “From MAD X/day”
- “Estimated rental subtotal shown on detail page”
- “Taxes, deposit, insurance, and company charges may apply”

Do not display the simple daily-rate multiplication as a guaranteed final total.

### Images

Replace raw `<img>` use with `next/image` where practical.

Implement:

- Stable aspect ratio
- Responsive sizes
- Blur or neutral placeholder
- Safe fallback image
- Descriptive alt text
- Image host allowlist

---

## 7.4 Company page: `/carplace/[slug]`

### Purpose

Give renters confidence in the rental company and let them browse that company’s fleet without leaving the RentalDriveGo marketplace experience.

### Recommended sections

1. Branded company header
2. Company summary and verified contact information
3. Location and service area
4. Rating and review summary
5. Active offers
6. Search-within-company controls
7. Fleet grid
8. Rental policies
9. Pickup and return information
10. Company contact actions

### Trust rules

- Show “Verified listing” only when an actual platform verification flag exists.
- Show ratings only when review data exists.
- Show review count with the rating.
- Do not infer opening hours, delivery coverage, or airport service from free-text location fields.
- Phone and WhatsApp links must be clearly identified as direct contact with the rental company.

### Company page content

Extend the public company brand contract to include structured fields as needed:

- Public summary
- Cover image
- Supported languages
- Operating hours
- Service areas
- Pickup instructions
- Deposit policy summary
- Mileage policy summary
- Cancellation policy summary
- Required documents summary

These fields should be controlled from the company dashboard and subject to subscription entitlements where required.

---

## 7.5 Vehicle detail: `/carplace/[slug]/vehicles/[id]`

### Required content hierarchy

1. Breadcrumbs
2. Vehicle gallery
3. Vehicle identity and category
4. Date-scoped availability
5. Daily rate and estimated quote area
6. Key specifications
7. Included features
8. Pickup and return locations
9. Company information
10. Rental-policy summary
11. Review summary
12. Similar vehicles
13. Sticky reservation-request action

### Availability behavior

- Availability must be checked for selected dates.
- An undated “available” badge must not imply future availability.
- When unavailable, show the next available date only when supplied by the API.
- Preserve the user’s search dates and locations when moving from results to detail.

### Quote behavior

Add a public quote endpoint before presenting a complete total:

```text
POST /api/v1/carplace/quotes
```

Suggested input:

```ts
{
  vehicleId: string
  startDate: string
  endDate: string
  pickupLocation?: string
  returnLocation?: string
  promoCode?: string
  selectedOptions?: string[]
}
```

Suggested output:

```ts
{
  available: boolean
  currency: 'MAD'
  rentalDays: number
  dailyRate: number
  baseSubtotal: number
  discounts: Array<{ label: string; amount: number }>
  fees: Array<{ label: string; amount: number }>
  taxes: Array<{ label: string; amount: number }>
  estimatedTotal: number
  securityDeposit?: number | null
  quoteExpiresAt?: string | null
  finalPriceRequiresCompanyConfirmation: boolean
}
```

The endpoint should use the existing pricing-rule and availability services rather than duplicating pricing logic in the frontend.

---

## 7.6 Progressive reservation-request flow

Replace the current oversized booking form with a focused three-step flow.

### Step 1: Trip

- Pickup location
- Return location
- Pickup date and time
- Return date and time
- Promo code
- Availability recheck
- Quote or estimated subtotal

### Step 2: Contact

Required:

- First name
- Last name
- Email
- Phone

Optional and collapsed:

- Notes for the company

Do not require identity and license details at the initial request unless a company has a legitimate configured requirement and the privacy implications have been reviewed.

### Step 3: Review and submit

- Vehicle
- Company
- Dates and locations
- Price estimate
- Important policy notes
- Contact information
- Consent and privacy links
- Clear “Send reservation request” action

### Submission behavior

Before submission:

1. Recheck availability.
2. Refresh the quote or estimated subtotal.
3. Validate dates and locations.
4. Prevent duplicate submissions.
5. Use an idempotency key.

After submission:

- Show request reference
- Show `PENDING` status
- Explain the next step
- Show company contact information when allowed
- Send confirmation email
- Provide a printable or downloadable summary later, if needed

### Reservation success route

Add:

```text
/carplace/request/[reference]
```

The page must not expose reservation data from only a guessable reference. Use a public access token or signed link for any detailed status page.

---

## 8. Renter Account Strategy

### Launch decision

Do not expose renter sign-in, sign-up, saved-company, notifications, or profile navigation in Carplace launch while the backend rejects renter authentication.

### Future account phase

When renter accounts are approved:

1. Enable sign-up and sign-in in the API.
2. Define cookie-domain behavior for production.
3. Add email verification and password reset.
4. Link guest requests to an account after verified ownership.
5. Add saved vehicles and companies.
6. Add reservation history and status.
7. Add notification preferences.
8. Add account deletion and privacy controls.

The existing renter pages should either be removed from public navigation or protected by a disabled-feature route until that phase begins.

---

## 9. API and Data Work

### 9.1 Keep existing endpoints operational during migration

Do not break the V1 frontend while V2 is being built.

### 9.2 Add versioned or additive contracts

Recommended additions:

```text
GET  /api/v1/carplace/home
GET  /api/v1/carplace/search
POST /api/v1/carplace/quotes
POST /api/v1/carplace/reservations
GET  /api/v1/carplace/requests/:token
```

During migration, existing `/api/v1/storefront/*` endpoints should remain as compatibility aliases or internal adapters until all deployed clients use Carplace contract.

### 9.3 Marketplace-home aggregation

A `GET /carplace/home` endpoint may return:

- Cities
- Categories with inventory counts
- Featured offers
- Featured vehicles
- Listed companies
- Public marketplace content

This reduces server-side request fan-out while preserving cacheability.

### 9.4 Reservation idempotency

Add idempotency support to reservation creation. A repeated browser submission must not create multiple reservation records.

### 9.5 Error contract

Use stable public error codes for:

- Invalid dates
- Invalid pickup location
- Invalid return location
- Same-location return required
- Vehicle unavailable
- Quote expired
- Offer invalid
- Offer expired
- Duplicate request
- Service unavailable

The frontend must map these codes to localized messages rather than showing raw server text.

### 9.6 Data-quality controls

Before a vehicle appears publicly, validate:

- Published state
- Active or trialing company
- Marketplace listing enabled
- Valid daily rate
- At least one usable photo or fallback
- Pickup location
- Required vehicle identity fields
- Supported booking behavior

Before a company appears publicly, validate:

- Public display name
- Marketplace listing enabled
- Public city or service area
- Contact method
- Active or trialing status

---

## 10. Admin and Company Management

### 10.1 Separate marketplace content from SaaS marketing content

Create a new admin endpoint and schema:

```text
GET   /api/v1/admin/site-config/marketplace-homepage
PATCH /api/v1/admin/site-config/marketplace-homepage
```

Do not rename the existing content silently. Migrate deliberately and preserve backward compatibility until the SaaS homepage confirms whether it still consumes the old structure.

### 10.2 Admin controls

Administrators should be able to manage:

- Marketplace homepage copy in English, French, and Arabic
- Translation completeness and publication status for every locale
- Section visibility
- Featured companies
- Featured offers
- Featured locations
- Marketplace guidance and FAQ
- Content moderation state
- Company marketplace eligibility

### 10.3 Company controls

Companies should be able to manage:

- Public profile with English, French, and Arabic fields
- Logo and cover image
- Safe accent color
- Public contact details
- Locations and service areas
- Rental-policy summaries
- Vehicle publication
- Public offers
- Booking expectations

### 10.4 Subscription entitlements

Advanced public branding and content features should respect subscription entitlements.

Suggested model:

- Basic plan: marketplace listing, logo, public contact, standard vehicle cards
- Advanced plan: cover image, expanded company profile, additional policy sections, featured positioning eligibility
- Premium plan: custom domain, advanced analytics, enhanced branded content

Core renter safety information must never be hidden behind a paid plan.

---

## 11. Localization and Directionality

### 11.1 Supported languages are mandatory

Carplace must ship and remain complete in exactly these three supported languages:

- English (`en`)
- French (`fr`)
- Arabic (`ar`)

These are equal product languages. English is not the source-language UI with partial translations layered on top. A feature is incomplete until its interface, validation, error states, metadata, emails, and reservation status copy work in all three languages.

### 11.2 Shared language resolution

Use the website-wide `rentaldrivego-language` cookie as the single language preference for the homepage, Carplace, and dashboard-facing links.

Resolve language on the server in this order:

1. Explicit valid language selected by the user.
2. Existing `rentaldrivego-language` cookie.
3. Migrated legacy `storefront-language` cookie.
4. Supported browser `Accept-Language` value.
5. English fallback.

The language selector must:

- Offer `EN`, `FR`, and `AR` on every public Carplace page.
- Update the shared cookie.
- Preserve the current pathname and query string.
- Preserve search dates, locations, filters, sorting, offer codes, and attribution parameters.
- Preserve completed reservation-form fields when switching language during the request flow.
- Never redirect a Carplace user back to the legacy `/storefront` route.

### 11.3 Translation architecture

Keep platform interface messages in typed locale files:

```text
lib/localization/messages/en.ts
lib/localization/messages/fr.ts
lib/localization/messages/ar.ts
```

Requirements:

- All three locale files must implement the same typed message contract.
- Missing translation keys must fail CI or type-checking.
- Raw API messages must never be displayed directly.
- Stable API error codes must map to localized client messages.
- Dynamic administrator-managed content must store separate approved values for `en`, `fr`, and `ar`.
- Do not use unreviewed automatic translation in production.
- Company-authored content may use an explicit company default-language fallback only when a translation is missing; the platform UI itself may not fall back silently.

### 11.4 Arabic RTL requirements

Arabic must be resolved before the initial render and set:

```html
<html lang="ar" dir="rtl">
```

English and French must render with `dir="ltr"`.

Arabic requirements include:

- Logical CSS properties such as `margin-inline`, `padding-inline`, `inset-inline`, and `border-inline`.
- Mirrored directional arrows, breadcrumbs, carousels, drawers, steppers, and pagination controls where meaning depends on direction.
- Correct input alignment without reversing phone numbers, email addresses, vehicle identifiers, promo codes, prices, or dates.
- Correct mixed-direction rendering for Arabic text containing Latin vehicle names.
- RTL-safe galleries, sticky booking actions, filter drawers, and mobile navigation.
- No layout implementation based on scattered one-off `rtl:` overrides when a logical-property solution exists.

### 11.5 Formatting rules

Use locale-aware formatters rather than concatenated strings:

- English: `en-MA`
- French: `fr-MA`
- Arabic: `ar-MA`

Localize:

- Dates and times
- Rental-day pluralization
- Currency and number formatting
- Reservation status labels
- Validation messages
- Availability messages
- Price qualifiers
- Email and printable request summaries

The currency remains MAD unless the pricing contract says otherwise. Numeric values sent to the API must remain locale-neutral even when displayed with localized digits or separators.

### 11.6 Content and translation governance

The admin editor must provide:

- Separate EN, FR, and AR editing tabs.
- Translation completeness indicators by section.
- Preview in LTR and RTL.
- Prevention of publication when a required locale is incomplete.
- Per-locale SEO title and description validation.
- Audit history showing which locale changed.

Reusable vehicle specifications, transmission labels, category names, policy labels, and reservation statuses should come from controlled translation dictionaries, not repeated free text.

### 11.7 URL and migration behavior

The initial canonical route remains `/carplace`, using server-resolved language from the shared cookie so the migration does not simultaneously change product name, path structure, and localization architecture.

All `/storefront/*` redirects must preserve language preference and query state. Locale-prefixed Carplace URLs may be introduced later only as a deliberate SEO migration with complete redirects, canonical tags, `hreflang`, sitemap updates, and analytics normalization. Do not create three competing URL systems during the first cutover.

---

## 12. Accessibility Requirements

Minimum requirements:

- Keyboard-operable navigation and filters
- Visible focus states
- Semantic headings and landmarks
- Proper labels and error associations
- Accessible mobile dialogs and drawers
- Status messages announced through live regions
- Sufficient color contrast
- Touch targets of at least 44 pixels
- Reduced-motion support
- Alternative text for meaningful images
- No information communicated by color alone
- Logical RTL keyboard and visual behavior

Target WCAG 2.2 AA for the public booking journey.

---

## 13. SEO and Sharing

### Marketplace homepage

- Localized English, French, and Arabic title and description
- Canonical URL
- Organization and WebSite structured data where accurate

### Company page

- Company-specific metadata in English, French, and Arabic where content exists
- Open Graph image
- Canonical URL
- LocalBusiness structured data only when required fields are reliable

### Vehicle page

- Vehicle-specific metadata in English, French, and Arabic
- Open Graph image
- Canonical URL
- Product or Vehicle structured data only when pricing and availability semantics are accurate

### Multilingual metadata and indexing

- Metadata generation must use the same server-resolved locale as the rendered page.
- Open Graph locale values must use `en_MA`, `fr_MA`, and `ar_MA` where supported.
- Structured-data text must match the visible language.
- Do not emit `hreflang` alternatives until each locale has a stable, independently addressable URL.

### Indexing controls

- Search result combinations should generally be canonicalized to avoid uncontrolled duplicate indexing.
- Private request-status pages must be `noindex`.
- Disabled or unpublished companies and vehicles must return proper not-found behavior.

---

## 14. Performance Requirements

Targets for production mobile testing:

- Largest Contentful Paint: under 2.5 seconds at the 75th percentile
- Interaction to Next Paint: under 200 milliseconds at the 75th percentile
- Cumulative Layout Shift: under 0.1

Implementation requirements:

- Server-render initial marketplace and search content
- Cache safe public data
- Use image optimization
- Avoid loading the 721-line booking interaction on pages that do not need it
- Code-split filter drawers, galleries, and booking steps
- Avoid client-side fetching for content already available on the server
- Add skeletons only where they reduce perceived instability
- Do not animate every card merely because CSS permits it

---

## 15. Analytics and Observability

### Funnel events

Extend the existing event model to include:

- Marketplace viewed
- Search submitted
- Search result viewed
- Filter applied
- Sort changed
- Vehicle viewed
- Company viewed
- Availability checked
- Quote requested
- Reservation flow started
- Reservation step completed
- Reservation submitted
- Reservation succeeded
- Reservation failed
- Contact action clicked

### Privacy

Do not place names, emails, phone numbers, identity numbers, or license data in analytics metadata.

### Operational monitoring

Track:

- Search failure rate
- Availability-check failure rate
- Quote failure rate
- Reservation submission failure rate
- Duplicate reservation rate
- API latency
- Zero-result search rate
- Image failure rate
- Client-side runtime errors

---

## 16. Production Dashboard Authentication Repair

This remains a separate P0 workstream and should be completed before or alongside Carplace deployment.

### 16.1 Preferred topology

Route dashboard browser API traffic through the dashboard origin:

```env
NEXT_PUBLIC_API_URL=/dashboard/api/v1
API_INTERNAL_URL=http://api:4000/api/v1
API_URL=http://api:4000
```

This allows the employee session cookie to be issued from the same public hostname used by dashboard pages.

### 16.2 Alternative topology

If direct browser requests to `api.rentaldrivego.ma` must remain, configure:

```env
SESSION_COOKIE_DOMAIN=.rentaldrivego.ma
CORS_ORIGINS=https://rentaldrivego.ma,https://www.rentaldrivego.ma
NODE_ENV=production
```

Verify:

- `Domain=.rentaldrivego.ma`
- `Path=/`
- `Secure`
- `HttpOnly`
- Appropriate `SameSite`

### 16.3 Dashboard acceptance tests

After production login:

1. Navigate to every dashboard menu route.
2. Hard-refresh nested routes.
3. Open nested routes in a new tab.
4. Confirm `/auth/employee/me` succeeds.
5. Confirm only a real `401` causes a sign-in redirect.
6. Confirm logout clears the session consistently.

---

## 17. Implementation Phases

## Phase 0: Freeze contracts and record baselines

- Capture current route behavior
- Capture current production screenshots
- Record API response examples
- Record current analytics baseline
- Add V1 smoke tests
- Confirm production cookie behavior

**Exit condition:** Existing behavior can be compared before and after changes.

## Phase 1: Shared public design foundation

- Extract shared tokens
- Build public header and footer frames
- Build common controls and layout primitives
- Add theme and locale adapters
- Validate homepage visual parity

**Exit condition:** Homepage can consume the shared foundation without regression.

## Phase 2: Carplace application foundation

- Create `features/marketplace`
- Define typed contracts
- Add typed `en`, `fr`, and `ar` message contracts
- Add shared server-side language resolution and legacy-cookie migration
- Add data adapters
- Add server-side release switch
- Add common loading, empty, and error states

**Exit condition:** V2 shell renders safely behind the release setting in EN, FR, and AR, with Arabic rendered RTL on the server.

## Phase 3: Marketplace homepage

- Build new renter-focused hero and search
- Build trust, city, category, offer, vehicle, company, guidance, and FAQ sections
- Add marketplace content contract
- Add admin editor support

**Exit condition:** Homepage is complete using real API data and localized content.

## Phase 4: Search results

- Add dedicated search route
- Add URL-backed filters
- Add sorting
- Add pagination
- Add facets
- Add mobile filter drawer
- Optimize API search contract

**Exit condition:** Searches are shareable, repeatable, and correctly paginated.

## Phase 5: Company pages

- Build company identity and trust area
- Add offers, reviews, policies, and fleet search
- Add safe brand accent behavior
- Add structured metadata

**Exit condition:** Company pages provide enough evidence for a renter to proceed.

## Phase 6: Vehicle detail and quote

- Build gallery and specifications
- Preserve search context
- Add date-scoped availability
- Add quote endpoint
- Add policy and price disclosures
- Add similar vehicles

**Exit condition:** Vehicle detail provides truthful availability and pricing context.

## Phase 7: Reservation request flow

- Replace the monolithic form
- Add progressive steps
- Add availability and quote recheck
- Add idempotency
- Add localized errors, validation, status copy, and confirmation emails in EN, FR, and AR
- Add success route and secure token

**Exit condition:** A renter can submit one clear request and understand what happens next.

## Phase 8: Quality, performance, and accessibility

- Add unit tests
- Add integration tests
- Add Playwright flows
- Add visual regression tests
- Run accessibility scans and manual checks
- Measure Core Web Vitals
- Test RTL and mobile layouts

**Exit condition:** Release gates pass on all supported languages and breakpoints.

## Phase 9: Production dashboard authentication

- Apply same-origin proxy configuration
- Validate cookie behavior
- Test dashboard navigation and refresh
- Monitor production authentication errors

**Exit condition:** Authenticated dashboard users are no longer redirected to sign-in.

## Phase 10: Controlled Carplace cutover

- Deploy V2 disabled
- Run internal production smoke tests
- Enable for administrators or test traffic
- Compare V1 and V2 errors and conversion events
- Enable V2 for all traffic
- Retain rollback capability
- Remove V1 only after a stable observation period

**Exit condition:** Carplace serves all public marketplace traffic and rollback is no longer required.

---

## 18. Testing Matrix

### Browsers

- Current Chrome
- Current Safari
- Current Firefox
- Current Edge
- Mobile Safari
- Mobile Chrome

### Languages

- English (`en-MA`, LTR)
- French (`fr-MA`, LTR)
- Arabic (`ar-MA`, RTL)

Every core flow must be executed separately in all three languages. Passing the flow in English does not qualify the French and Arabic variants by association, however comforting that fiction might be.

### Themes

- Light
- Dark
- System preference

### Breakpoints

- Small mobile
- Large mobile
- Tablet
- Laptop
- Wide desktop

### Core flows

1. Browse without dates.
2. Search with same pickup and return location.
3. Search with different return location.
4. Search with no results.
5. Filter and sort results.
6. Open a company page.
7. Open a vehicle from search.
8. Change dates on vehicle detail.
9. Check unavailable dates.
10. Apply a valid offer.
11. Apply an invalid or expired offer.
12. Submit a reservation request.
13. Attempt duplicate submission.
14. View request success.
15. Switch EN → FR while preserving the current route and search state.
16. Switch FR → AR while preserving the current route and search state.
17. Switch AR → EN during the reservation flow without losing completed fields.
18. Switch theme.
19. Navigate the complete core journey in RTL.
20. Use keyboard-only navigation.
21. Use a screen reader through the booking flow.
22. Simulate API timeout and database unavailability.

---

## 19. Release Gates

Carplace must not replace V1 until all of these are true:

- Public URLs remain valid.
- Search returns correct, paginated results.
- Availability is date-scoped.
- Pricing language is honest.
- Reservation requests are idempotent.
- Request success is clearly marked `PENDING`.
- English, French, and Arabic each pass complete functional and editorial review.
- Language switching preserves route, query state, and in-progress reservation data.
- No required platform translation key is missing in any locale.
- Arabic RTL layout and mixed-direction content pass review on desktop and mobile.
- Mobile booking flow passes review.
- Critical accessibility violations are zero.
- No renter-account links lead to disabled authentication.
- Error monitoring is active.
- Rollback is tested.
- Dashboard production authentication is validated.

---

## 20. Final Acceptance Criteria

### Brand and architecture

- Homepage and Carplace use the same shared visual foundation.
- Carplace has renter-specific navigation and content.
- No homepage-only route logic is imported into Carplace.
- Carplace components are organized by marketplace domain rather than page-level duplication.

### Discovery

- Users can search by supported location and dates.
- Search state survives refresh and sharing.
- Filters and sorting behave consistently.
- Empty and error states are distinct.

### Trust

- Ratings, reviews, availability, and company verification are displayed only from real data.
- Direct-company contact is clearly identified.
- Rental terms and price limitations are visible before submission.

### Vehicle selection

- Vehicle cards and detail pages expose useful specifications.
- Images are optimized and resilient.
- Availability is checked for the requested period.
- Price is described as an estimate unless a full quote exists.

### Reservation request

- The flow is progressive and focused.
- Only necessary personal information is required.
- Availability and pricing are revalidated before submission.
- Duplicate submissions are prevented.
- Success clearly states that company confirmation is pending.

### Localization and accessibility

- English, French, and Arabic have complete feature, content, validation, email, and metadata parity.
- Language switching preserves the user’s current context and in-progress data.
- Arabic uses server-rendered RTL layout with correct mixed-direction behavior.
- The core flow is keyboard and screen-reader usable.
- Focus, contrast, labels, and errors meet the agreed accessibility standard.

### Production reliability

- V2 can be enabled or rolled back safely.
- Carplace failures are observable.
- Dashboard links no longer redirect authenticated production users to sign-in.

---

## 21. Recommended Execution Order

1. Repair and verify production dashboard authentication.
2. Extract the shared public design foundation.
3. Define Carplace contracts and content model.
4. Build the marketplace homepage.
5. Build dedicated search results.
6. Rebuild company and vehicle pages.
7. Add the quote contract.
8. Replace the booking form with the progressive request flow.
9. Complete testing and observability.
10. Perform a controlled V2 cutover.

This order prevents visual work from hiding authentication failures and prevents the booking UI from being finalized before pricing, availability, and reservation contracts are stable.
