You are Cline, acting as a Senior Frontend Engineer + Django Template/UI Engineer + UX-focused Product Engineer.
The backend for PX360 is already implemented (Django + DRF + Celery). Your mission is to build a comprehensive modern web frontend that:
	•	Covers full CRUD for all core modules (not minimal)
	•	Provides dashboards and control panels as first-class features
	•	Uses best-practice UI patterns (filter panels, table toolbars, bulk actions, saved views, responsive design)
	•	Integrates tightly with backend permissions (RBAC), audit logs, and workflow actions
	•	Is production-ready and maintainable

Primary UI goal: PX360 should feel like a modern enterprise operations console (Command Center + control panels), not a basic CRUD app.

⸻

0) Non-Negotiable Frontend Rules
	1.	UI must be consistent: one design system, one layout, reusable components.
	2.	Must support Arabic/English UI toggles, including RTL layout support.
	3.	Must support RBAC-aware navigation (only show allowed modules/links).
	4.	All list pages must provide:
	•	server-side pagination
	•	advanced filters
	•	CSV/Excel export
	•	bulk actions where relevant
	5.	Must provide dashboards with charts and drill-down.
	6.	Use Select2 on large selects (patient, physician, department, assignee).
	7.	Use HTMX (recommended) for inline actions, modals, partial updates (no full SPA required).
	8.	Prefer Django templates + HTMX + small JS utilities. Avoid heavy JS frameworks unless necessary.
	9.	Keep accessibility in mind: labels, keyboard nav, clear feedback messages.

⸻

1) Frontend Stack & Libraries

Implement using:
	•	Django templates (server-rendered)
	•	Bootstrap 5
	•	HTMX for partial updates
	•	Select2 for enhanced selects
	•	Chart library: ApexCharts or Chart.js (choose one and standardize)
	•	DataTables (or bootstrap table + custom sorting/search) — prefer server-side listing
	•	Icon set: Bootstrap Icons
	•	Optional: Toastr (notifications) or Bootstrap toast

Add frontend dependencies in a clean way (local vendor bundle under /static/vendor/ or via npm build if already set up). Keep it simple and stable.

⸻

2) Create a Dedicated Frontend App and Structure

Create an app named: ui (or dashboard) responsible for server-rendered views.

Folder structure

apps/ui/
  views/
    dashboard.py
    complaints.py
    action_center.py
    journeys.py
    surveys.py
    social.py
    callcenter.py
    analytics.py
    admin_config.py
  urls.py
  forms/
    complaints.py
    surveys.py
    journeys.py
    action_center.py
    common.py
  services/
    api_client.py
    permissions.py
    exports.py
  templatetags/
    ui_extras.py
  templates/
    layouts/
    partials/
    dashboard/
    complaints/
    actions/
    journeys/
    surveys/
    social/
    callcenter/
    analytics/
    config/
  static/
    px360/
      css/
      js/
      images/

Important: Use a service layer (api_client.py) to call internal APIs cleanly (or call ORM directly if backend includes classic views). Choose one approach and apply consistently:
	•	Option A: UI uses ORM (Django views + models) and DRF remains for external clients.
	•	Option B: UI calls DRF endpoints internally (recommended if backend is API-centric).

If the backend is API-centric, build:
	•	APIClient wrapper supporting:
	•	JWT injection
	•	error normalization
	•	pagination parsing
	•	retries for transient errors

⸻

3) Global Layout + Navigation (Modern Control Panel)

3.1 Base Layout Requirements

Create:
	•	templates/layouts/base.html
	•	partials/sidebar.html
	•	partials/topbar.html
	•	partials/breadcrumbs.html
	•	partials/messages.html
	•	partials/filters_panel.html
	•	partials/table_toolbar.html
	•	partials/pagination.html
	•	partials/stat_cards.html
	•	partials/chart_card.html
	•	partials/confirm_modal.html
	•	partials/form_modal.html

Base Layout must include:
	•	Top bar:
	•	global search (encounter_id, MRN, complaint ID)
	•	notifications dropdown (recent SLA breaches, escalations)
	•	language toggle (AR/EN)
	•	user menu (profile, logout)
	•	Sidebar:
	•	command center
	•	complaints
	•	action center
	•	journeys
	•	surveys
	•	social monitoring
	•	call center
	•	analytics & KPIs
	•	configuration (admin only)

3.2 RTL / Language Support
	•	Implement language toggle that sets a user preference (DB or session).
	•	Base layout must switch:
	•	dir="rtl" + appropriate Bootstrap RTL file (or custom RTL stylesheet)
	•	Use i18n tags where feasible.

⸻

4) Pages and Features (Must Build Fully)

4.1 PX Command Center Dashboard (Primary)

Route: /dashboard/command-center/

Must include:

KPI cards (clickable drill-down):
	•	Active complaints
	•	Overdue complaints
	•	Open actions
	•	Overdue actions
	•	Negative surveys (last 24h / 7d)
	•	Negative social mentions
	•	Low call center ratings
	•	Complaint resolution dissatisfaction rate

Charts:
	•	Complaints trend over time
	•	SLA compliance trend (complaints + actions)
	•	Survey score by stage (OPD MD / LAB / Radiology / Pharmacy / EMS MD)
	•	Sentiment distribution
	•	Department leaderboard (best/worst)
	•	Physician leaderboard (best/worst)

Live feeds:
	•	Latest high severity complaints
	•	Latest escalated actions
	•	Latest negative mentions with “Create Action”
	•	Latest inbound integration events processed

Filters (persist):
	•	date range, hospital, department, journey type, source

Exports:
	•	export snapshot PDF/Excel

Implementation details:
	•	Dashboard page uses backend analytics endpoints
	•	Each card and chart supports drill-down to a filtered list view

⸻

4.2 Complaints Console (Full CRUD + Workflow + SLA)

Routes:
	•	/complaints/ list
	•	/complaints/new/
	•	/complaints/<id>/
	•	/complaints/<id>/edit/

Features:
	•	Advanced filter panel (status/severity/priority/SLA/source/hospital/department/physician/date range)
	•	Bulk actions:
	•	assign
	•	change status
	•	export
	•	Row quick actions (HTMX):
	•	assign
	•	add note
	•	escalate
	•	close
	•	Detail page:
	•	header with SLA countdown + status badge
	•	tabs: Details / Timeline / Attachments / Related Surveys & Journey / Linked Actions
	•	timeline shows audit events and notes
	•	attachments upload
	•	“Trigger resolution satisfaction survey” button (RBAC protected)
	•	Export:
	•	CSV/Excel list export
	•	PDF detail summary

⸻

4.3 PX Action Center (Operational Hub)

Routes:
	•	/actions/ list
	•	/actions/board/ (optional kanban view)
	•	/actions/<id>/ detail

Features:
	•	Views: My actions / Overdue / Escalated / From Surveys / From Complaints / From Social
	•	Advanced filters: status, SLA, priority, type, dept, assignee
	•	Bulk actions: assign, escalate, status update
	•	Detail:
	•	SLA progress bar
	•	tabs: Details / Evidence / Logs / SLA History / Approval
	•	Evidence upload required for closure if configured
	•	Approval workflow: Department closes → PX approves
	•	Inline updates via HTMX:
	•	status changes
	•	add log message
	•	request approval

⸻

4.4 Journey Console (Templates + Instances + Monitoring)

Routes:
	•	/journeys/templates/
	•	/journeys/templates/new/
	•	/journeys/templates/<id>/edit/
	•	/journeys/instances/
	•	/journeys/instances/<id>/

Template Builder:
	•	Create/edit journey templates (EMS/OPD/Inpatient)
	•	Stage builder with:
	•	reorder stages (drag-drop if feasible; otherwise ordering controls)
	•	set trigger_event_code
	•	set auto_send_survey
	•	bind survey_template
	•	physician_required
	•	Provide a “Test Trigger” section:
	•	enter encounter_id + event_code -> simulate inbound event (calls backend test endpoint or posts inbound event)

Instance Detail:
	•	Stage progress stepper
	•	Each stage card shows:
	•	status, timestamp, dept, physician
	•	survey instance status + link
	•	resend survey invite (RBAC)
	•	Event history timeline (inbound events)
	•	Stage analytics summary

⸻

4.5 Surveys Console (Templates + Instances + Analytics)

Routes:
	•	/surveys/templates/
	•	/surveys/templates/new/
	•	/surveys/templates/<id>/edit/
	•	/surveys/instances/
	•	/surveys/instances/<id>/
	•	/surveys/analytics/

Template builder:
	•	Add/edit questions (bilingual)
	•	Reorder questions
	•	Branch logic editor (validated JSON)
	•	Preview survey

Instances:
	•	filter by journey type, stage, status
	•	instance detail:
	•	invitation status, responses, computed score
	•	sentiment results
	•	“Create Action” if negative

Analytics:
	•	score by hospital/department/physician/journey/stage
	•	time trends
	•	negative heatmap

⸻

4.6 Survey Public Form (Token Link)

Route: /s/<token>/

Must be:
	•	mobile-first
	•	bilingual toggle
	•	progress indicator
	•	validation
	•	final thank-you page
	•	secure token handling, expiry, single-submit rules if required

⸻

4.7 Social Monitoring Console

Routes:
	•	/social/mentions/
	•	/social/mentions/<id>/

Features:
	•	feed with filters (platform/sentiment/hospital/date)
	•	mention detail includes sentiment breakdown
	•	one-click “Create Action”
	•	sentiment trend chart

⸻

4.8 Call Center Console

Routes:
	•	/callcenter/interactions/
	•	/callcenter/interactions/<id>/
	•	/callcenter/dashboard/

Features:
	•	KPIs: avg wait time, satisfaction, low rating alerts
	•	drill-down
	•	create action on low rating

⸻

4.9 Analytics / KPI Console

Routes:
	•	/analytics/kpis/
	•	/analytics/dashboard/

Features:
	•	KPI definitions (admin)
	•	KPI values
	•	breach alerts + create actions
	•	ranking tables

⸻

4.10 Configuration Console (Admin-only)

Routes:
	•	/config/
Includes CRUD for:
	•	routing rules
	•	SLA configs
	•	survey thresholds
	•	delivery channel toggles
	•	integration keys (view/rotate with audit)

⸻

5) Reusable UX Patterns (Must Implement Everywhere)
	•	Filters panel:
	•	collapsible
	•	“Apply” and “Clear”
	•	“Save view” button (SavedViewFilter model)
	•	Table toolbar:
	•	export, bulk actions, column toggles
	•	Status badges:
	•	standardized mapping for status -> badge class
	•	Confirm modal:
	•	used for destructive actions and status transitions
	•	Toast notifications:
	•	success/failure feedback

⸻

6) Performance Requirements
	•	All list views use server-side pagination
	•	Use select_related/prefetch_related (or efficient API expansions)
	•	Debounce global search
	•	Avoid N+1 in templates

⸻

7) Frontend Testing & QA Checklist

Create basic tests for:
	•	key pages load with RBAC rules
	•	survey public form token validation
	•	filters apply correctly
	•	export endpoints respond

Also provide a manual QA checklist in /docs/ui-qa.md.

⸻

8) Deliverables (Must Produce)
	•	Full UI app with templates, partials, static assets
	•	URLs integrated into main urls.py
	•	RBAC navigation
	•	Saved filters functionality
	•	Export support (CSV/Excel, PDF where required)
	•	Dashboard charts integrated with backend analytics endpoints
	•	Survey public pages complete

⸻

9) Implementation Order (Do Not Deviate)
	1.	Layout + sidebar/topbar + RTL toggle
	2.	Command Center dashboard
	3.	Complaints console
	4.	Action Center console
	5.	Journey template builder + journey instance viewer
	6.	Survey templates + instances + analytics
	7.	Survey public form
	8.	Social + callcenter + analytics + config
	9.	Polish, performance pass, QA checklist

After each module, ensure:
	•	templates are consistent
	•	navigation updated
	•	permissions enforced
	•	errors handled gracefully

⸻

10) Start Now

Begin with layout scaffolding and Command Center dashboard first.
Do not create placeholder UI—use real backend endpoints and real data.