# Project instructions

## Visual baseline

Backend work must also follow [the backend instructions](BACKEND_INSTRUCTIONS.md), including MySQL configuration, query performance, safe data saving, code structure, and verification requirements.

Use [the design reference](DESIGN_REFERENCE.md) as the starting specification. Preserve the Arabic product name, RTL reading order, semantic status colors, typography, and component hierarchy. Do not replace the visual identity with framework defaults.

The source HTML is reference material. Keep it intact while developing the application separately. Stage 1 uses React with TypeScript and Vite in `frontend/`, and Laravel API routes in `backend/`. Follow the composition and feature boundaries in [the Stage 1 foundation record](STAGE_1_FOUNDATION.md).

## Administration UI and UX

- Language uses an immediately applied Arabic/English segmented toggle. Appearance uses a three-option toggle with labeled sun (Light), moon (Dark), and monitor (Auto) icons, a clear selected state, keyboard focus, and accessible pressed states. Persist the appearance preference; Auto follows device appearance changes. Avoid select menus and an extra Save step for these preferences.
- Use a standard dashboard shell: a persistent desktop sidebar, top navbar, and an avatar with the current administrator's name/account menu. Show the selected module in navigation. Use the person's initial when no avatar image exists; do not invent a profile photo.
- Mirror sidebar placement and navigation direction for Arabic RTL and English LTR. On smaller screens, open the sidebar as an accessible navigation drawer. Keep language/theme settings and account controls reachable without crowding the navbar.
- Management modules open to tables listing paginated records, with search, filters, counts, and labeled row actions. Keep fixed user types read-only, with links to their users; do not offer unsupported create/edit permission actions.
- A module's Create button opens a modal. Row and detail-page Edit actions open the same shared editor in a modal. Standalone form URLs may remain as fallback routes, but normal navigation uses modals.
- Reuse server validation, authorization, and save services. Show loading, validation, conflict, session-expiry, and request-failure feedback inside the modal. Keep invalid forms open with entered values and selections intact. Disable repeat saves and editing during an in-flight save.
- Keep modal header and footer actions visible while the form body scrolls. Support keyboard focus containment, Escape, backdrop closing, background scroll locking, and focus restoration. Ask before discarding changed form values, with a Keep editing option. Language switching must preserve the open editor and its unsaved values without writing passwords to browser storage.
- After saving, refresh the current module/detail view and show confirmation. Preserve filters, pagination, and the current URL; do not force the user onto a separate record page after every save.
- Display related record names as real, keyboard-accessible hyperlinks: user → school, school → directorate, user → supervisor, and counselor → user details. Record detail pages show their information and relevant related records, with pagination where collections grow. All linked routes must enforce server-side permissions.
- School manager name, phone, and email are school contact information, not a user account. Do not link a manager name to a fabricated user profile or create credentials for the manager.
- Reserve a clearly labeled Students section on school details until student management is implemented. Do not present invented students or an unverified zero student count. Students will remain separate from users and will not log in.
- Consume shared visual settings from the root theme configuration and verify both languages, themes, keyboard behavior, and mobile layouts before accepting admin UI changes.

## Public frontend

Use subtle, one-time entrance/scroll reveals and small hover/press feedback. Animate opacity and transforms, not layout dimensions; avoid continuous decorative loops, parallax, and animation dependencies. Shared durations, easing, and distances belong in the root theme configuration. Reduced-motion mode must remove nonessential animation and smooth scrolling. Content must remain usable without IntersectionObserver, during keyboard navigation, and when printing; reveals must disconnect after entering and on unmount.

The public frontend root is a landing page explaining Masar, with role relationships, news, articles, and a separate staff login. Use a public navbar/footer, real content-detail links, and loading/error/retry/empty/pagination states. Label sample publications and future features clearly. Do not invent school statistics or expose private staff/student data. Support Arabic/English and icon toggles for Light/Dark/Auto. Directorate heads have a scoped management workspace for schools and staff; supervisors and counselors have separate scoped workspaces. The backend login remains super-admin-only, and signup remains disabled.

Directorate-head screens use the agreed administration shell and modal/table interactions. Limit management to the head's directorate and to supervisor/counselor accounts. Keep the directorate fixed on forms. Preserve filters after saves, unsaved values through language changes, keyboard focus on close, and visible modal save controls. School/user/supervisor names link to real scoped detail routes. Directorate-head student sections remain reserved. Counselor student management is implemented separately. Heads also have read-only access to all eight counselor form types in their directorate, including supervisor notes/status; they cannot edit answers or review forms. Reports remain deferred.

## One source for visual configuration

The application MUST use a single root-level file named `style-theme.config.json` as the editable source for all shared visual settings. Changing a shared setting there must update every component that uses it after the normal development reload or build.

The configuration must contain:

| Section                       | Controlled settings                                                                                                       |
| ----------------------------- | ------------------------------------------------------------------------------------------------------------------------- |
| `themes.light`, `themes.dark` | Text, backgrounds, surfaces, borders, brand, sidebar, status colors, on-color text, overlays, and theme-dependent shadows |
| `typography`                  | Body and heading families, fallback stacks, loaded weights, font sizes, line heights                                      |
| `spacing`                     | Shared spacing scale and component padding/gaps                                                                           |
| `radii`                       | Controls, cards, dialogs, badges, and pills                                                                               |
| `borders`                     | Standard widths, focus outline width and offset                                                                           |
| `layout`                      | Sidebar width, content maximum width, login width, grid sizes, dialog widths, gutters                                     |
| `breakpoints`                 | Phone/tablet/desktop transitions defined in the responsive requirements                                                   |
| `sizes`                       | Icons, controls, touch targets, progress bars, and other reusable dimensions                                              |
| `motion`                      | Hover, drawer, and toast transition durations                                                                             |
| `layers`                      | Sidebar, backdrop, zoom-independent overlays, dialog, and toast stacking levels                                           |
| `print`                       | Print colors, borders, and typography overrides                                                                           |

Use semantic names such as `brand`, `surface`, `textPrimary`, and `statusDanger`. Preserve the relationship to the original CSS variables in the design reference. Include sidebar-specific and on-color text tokens instead of scattered white or green literals.

## Configuration integration contract

1. Validate the JSON and required token keys during the application build.
2. Generate theme CSS variables and responsive media rules from this file, or use an equivalent framework integration reading this same file.
3. Treat generated styles as outputs; never edit a second palette or generated file manually.
4. Components consume semantic variables or shared theme helpers. Shared colors, fonts, spacing, radii, shadows, and breakpoint numbers must not be duplicated in components or inline styles.
5. Component selectors, grid behavior, and interaction logic can live in their own files. Their shared visual values come from the configuration.
6. Keep derived settings derived: for example, generate RGB/alpha variants from a configured base color where appropriate.
7. Store responsive thresholds in configuration and generate literal media-query values at build time. Ordinary CSS custom properties cannot be used directly as media-query width conditions.
8. Include print and accessibility states in central configuration. Reduced-motion preference must disable nonessential transitions independently of configured durations.

All shared visual settings must have one editable source. A central config without component integration does not satisfy this requirement.

## Themes

Support light, dark, and system-following appearance. Use the prototype palettes as initial values. Resolve the active theme once at the application root; components must not maintain independent theme flags.

Use explicit light/dark root selectors for consistent hover behavior. The prototype has an explicit-dark-only button-hover text override; system-following dark appearance must receive the same appropriate on-color treatment in the application. Verify text contrast for each normal, hover, focus, selected, and disabled state rather than assuming the extracted palette already passes accessibility checks.

## Arabic and English support

The application MUST support Arabic and English across the React frontend and Laravel backend interface. Arabic remains the default language. This is an implementation requirement for current and future features; the existing interface has not yet been fully translated.

- Provide a clearly labeled language switcher on login pages and application layouts, including the super-admin dashboard. Users must be able to switch languages before signing in.
- Remember the selected language across navigation, reloads, login, and logout. Each surface must resolve its active language in one shared place; components must not maintain independent language flags. Document how the preference is shared when frontend and backend are hosted on different origins.
- Use `lang="ar"` and `dir="rtl"` for Arabic, and `lang="en"` and `dir="ltr"` for English. Update page titles and other user-facing metadata with the selected language.
- Keep interface translations in centralized, matching Arabic/English translation files, using stable keys. React components and Laravel views/controllers must not contain duplicate hardcoded language branches.
- Translate navigation, headings, form labels, placeholders, buttons, empty/loading states, validation, authentication errors, notifications, and user-facing error pages. Use Laravel localization for backend messages and a shared translation mechanism for React.
- Translate display labels without changing database values, role identifiers, API field names, URLs, or query parameters. User-entered names and counseling content must remain as entered; do not automatically translate them.
- Use logical layout properties so sidebars, drawers, spacing, alignment, and directional navigation icons follow the active reading direction. Preserve readable email addresses, numbers, and mixed-language content with appropriate direction isolation.
- Keep Arabic and English font choices and any shared language-specific visual settings in root `style-theme.config.json`, consumed by both interfaces. Do not introduce a separate theme configuration for English.
- Format displayed dates, numbers, and plural messages for the active locale where appropriate. Keep stored values and API representations stable.
- Add both translations when adding or changing interface text. Verify translation-key coverage, language persistence, and layout direction; report missing translations or unverified workflows explicitly.

## Accessibility

- Set the interface language and reading direction according to the active locale as required above.
- Prefer logical CSS properties such as `padding-inline`, `inset-inline-start`, and `text-align: start`.
- Preserve visible focus, form labels, required indicators, status text, and accessible icon-button names.
- Keep numbers, dates, phone numbers, and mixed-direction content readable; isolate direction where needed.
- Use keyboard-operable navigation and dialogs. Trap dialog focus, support Escape, and restore focus to the opener.
- Associate validation messages with fields and announce save/review feedback accessibly.

## Responsive delivery and verification

Implement [all responsive requirements](RESPONSIVE_REQUIREMENTS.md) as part of the initial application. Page-wide zoom is not the responsive strategy.

Before accepting styling work, verify both themes, Arabic text, keyboard interaction, narrow layouts, and printing. Verify that changing a shared token in `style-theme.config.json` propagates to representative buttons, cards, forms, and tables. Report the checks actually performed and any unverified behavior.


### Separate counselor and supervisor pages

In the directorate-head workspace, show separate Counselors (المرشدون التربويون) and Supervisors (المشرفون) sidebar entries and pages. Each page must have its own paginated table, search/status filters, details, and Create/Edit dialogs. Fix the user type to the page for list requests and saves; do not offer a user-type selector there. Reuse shared components and the scoped users API rather than duplicating storage or permissions. Overview cards and related-record links must open the matching role page. Preserve existing bookmarked users URLs.


### Multi-selects and long dialogs

- For large sets of related records, use a compact expandable picker with server-side search, checkbox rows, a selected count, removable chips, Clear selections, and Done. Keep selections when the search changes or the picker closes. Fetch bounded results only when the picker is open; do not load entire tables. Do not offer Select all for a partial search result.
- For small fixed sets such as school stages, use labeled checkbox chips with clear selected and keyboard-focus states. Preserve native checkbox semantics. Use radio buttons for single choices.
- Opening a picker focuses its search field. Done and Escape close the picker and restore focus to its trigger; Escape inside the picker must not dismiss the containing dialog. Do not use a second modal for selection.
- Bound dialogs to the dynamic viewport, keep their header and Save/Cancel footer visible, and scroll only the form body. Use a subtle themed scrollbar, stable scrollbar space, contained scrolling, and a hint when more fields remain below. Bound the results list independently so it cannot make the dialog taller than the viewport.
- Selection chips, long labels, and dialog controls must wrap without horizontal overflow at 320px. Support Arabic RTL, English LTR, light/dark/system appearance, keyboard interaction, and touch targets. Shared colors, spacing, and picker dimensions come from `style-theme.config.json`; reuse components rather than adding a UI dependency.


### Supervisor workspace

Supervisors enter `/portal/supervisor` through the existing staff login. Reuse the responsive sidebar/navbar/avatar shell and bilingual display controls. Provide Schools and Counselors navigation tabs, searchable/filterable paginated tables, and related details links. School details have keyboard-accessible Information, Counselors, and reserved Students tabs. Supervisors can only view information: omit create, edit, delete, and assignment-changing actions. Show only currently supervised counselors and schools covered by their current assignments; school relationships and counts must obey the same scope. A counselor at the same school remains hidden unless supervised by this actor. Keep students reserved for a later stage. Do not build evaluation or counseling business workflows yet.


### Counselor workspace

Provide a separate `/portal/counselor` workspace using the shared responsive sidebar/navbar/avatar shell and Arabic/English light/dark/system controls. The staff portal must route counselors here automatically. Its pages are My account and information and My supervisor. Show only the signed-in counselor's profile, directorate, and current assigned supervisor's name/email/mobile. Keep all information read-only for this scope. Show a clear translated empty state when no active same-directorate supervisor is currently assigned. Do not link to other users' profile or management routes. The separate Students module now allows viewing and adding students in assigned schools, including Excel template/preview/import. Evaluations and counseling workflows remain deferred. Scope query caches by counselor identity/directorate/locale and clear them at logout.


### Counselor student UI

The counselor Students page selects from current assigned schools, then shows a searchable/filterable paginated table and linked student details. Provide Add student, Download Excel template and Import Excel actions, disabled until a school is selected. Add/import use the existing modal design: fixed header/footer, scrollable body, visible errors, preserved drafts and filters, discard confirmation, focus containment/restoration, and Arabic/English responsiveness. A file change must clear its old preview. Show selected school, limits, duplicate/no-overwrite behavior, the first ten preview rows, and an explicit final Import button. Preserve student number/phone text. A row error prevents the whole import; do not silently skip or partially save students. Student records must never become login accounts. Other roles' Students sections remain reserved.


## Counselor form review interface

The supervisor workspace keeps school/counselor/student management read-only. Its Counselor forms page may display authorized form answers and offer the dedicated review action. Use a table with scoped filters, real counselor/school/form detail links, and a modal review editor with status and an optional note. Keep student links absent until supervisor student-detail access is implemented. Translate Pending review, Reviewed (تم الاطلاع), and Approved; do not automatically mark forms reviewed merely by opening them. Counselors see the latest decision/note/date, and a clear warning when it applies to an earlier content version. Preserve unsaved review notes/status through language switching and failed/conflicting saves, with fixed modal actions and scrolling on small screens.


## Deployment documentation maintenance

Update [DEPLOYMENT.md](DEPLOYMENT.md) in the same change whenever dependencies, environment variables, migrations, seeders, server routes, build artifacts, persistent storage, workers or operational checks change. Keep first installation separate from existing-installation updates, preserve the environment and APP_KEY, and record deployment-impacting changes in its dated change log. Distinguish local verification from server/production verification. Never include real credentials or demo passwords in deployment instructions.


## Attachment uploads and downloads

Use the shared `FormAttachments` component for supported form records and reuse its drop-zone interaction for future attachment fields. Provide drag-and-drop plus a labeled Choose files button that works with keyboard and touch; drag-and-drop must never be the only way to attach a file. Show accepted formats, per-file size and total-count limits before selection. List selected filenames with remove controls, disable repeat actions during uploads, upload sequentially, and retain failed selections for retry. Do not add an upload dependency for this interaction. Use root theme tokens, logical RTL/LTR styles, wrapping filenames and responsive actions.

Save a form before attaching files. The create/edit modal explains where attachments are added; saved details contain the drop zone. Currently studies, bulletins, vocational guidance and committee activities accept optional PDF, DOCX, XLSX, JPG/JPEG and PNG files, up to 10 MB each and five per record. The four student-linked forms do not gain attachments implicitly. Supervisors and heads see Download actions only within their existing record scope. Preview means downloading and opening the file; do not embed untrusted documents or render uploaded HTML. Upload/removal returns the parent to Pending review and refreshes its status/version while retaining previous supervisor notes as historical.
