---
title: "Angular Timeline Truck Dispatch Planning Example | Mobiscroll"
component: "Timeline"
framework: "Angular"
library_version: "6.2.0"
url: "https://demo.mobiscroll.com/angular/timeline/truck-transport-planning-and-dispatch"
---

# Truck Dispatch Planning - Angular Timeline demo

Assign transports on the Angular timeline — hide trucks with capacity or time-window conflicts during drag and snap failed drops to the nearest valid slot.

- [Live demo](https://demo.mobiscroll.com/angular/timeline/truck-transport-planning-and-dispatch)
- [View code on GitHub](https://github.com/acidb/mobiscroll-demos-angular/tree/main/src/demos/eventcalendar/timeline/truck-transport-planning-and-dispatch)
- This demo in other frameworks: [JavaScript](https://demo.mobiscroll.com/javascript/timeline/truck-transport-planning-and-dispatch.md), [jQuery](https://demo.mobiscroll.com/jquery/timeline/truck-transport-planning-and-dispatch.md), [React](https://demo.mobiscroll.com/react/timeline/truck-transport-planning-and-dispatch.md), [Vue](https://demo.mobiscroll.com/vue/timeline/truck-transport-planning-and-dispatch.md)

## Description

Managing a fleet of delivery trucks means constantly matching incoming jobs against available vehicles - checking cargo capacity, time windows, and maintenance schedules, all at once. This demo brings that workflow onto an interactive timeline where dispatchers can drag unscheduled jobs from a sidebar directly onto a truck row without leaving the screen.

To enable external drops from the sidebar, set [`externalDrop`](https://mobiscroll.com/docs/angular/eventcalendar/api#opt-externalDrop) to `true` on the timeline, and initialize each job card in the sidebar using the `draggable` component with `dragData` pointing to the full job object.

When the dispatcher starts dragging a job, the [`onEventDragStart`](https://mobiscroll.com/docs/angular/eventcalendar/api#event-onEventDragStart) event fires and drives a real-time resource validation pass: trucks with insufficient cargo capacity or a conflicting scheduled trip are filtered out of the resource list, and the grid is locked outside the job's pickup-to-drop-off window using the [`invalid`](https://mobiscroll.com/docs/angular/eventcalendar/api#opt-invalid) option. This gives the dispatcher an immediate visual map of valid drop targets.

A successful drop is confirmed via [`onEventCreated`](https://mobiscroll.com/docs/angular/eventcalendar/api#event-onEventCreated) , which removes the job from the sidebar and marks it as scheduled. If the drop lands in an invalid position, [`onEventCreateFailed`](https://mobiscroll.com/docs/angular/eventcalendar/api#event-onEventCreateFailed) snaps the job to the first free slot within the time window instead of rejecting the drop outright. The same snap logic runs for existing event moves via [`onEventUpdateFailed`](https://mobiscroll.com/docs/angular/eventcalendar/api#event-onEventUpdateFailed). The trucks are grouped into capacity-tier categories and rendered using [`resourceTemplate`](https://mobiscroll.com/docs/angular/eventcalendar/api#template-resourceTemplate), which shows each truck's name, license plate, and a colour-coded maintenance-status dot. Each truck has a parallel "actual" sub-row that tracks live trip progress and is refreshed automatically every 60 seconds.

**Looking for a simpler external drag & drop example?** [Check out the external drag & drop example →](https://demo.mobiscroll.com/angular/timeline/external-drag-drop-sortable-dragula)

## What this demo shows

- The demo shows a full-page truck dispatch and planning console that combines an unscheduled job queue with a resource timeline.
- **Job queue** The left sidebar lists unscheduled transport jobs in a scrollable queue, grouped by date under sticky day headers such as "Thu, 22 May".
- **Job cards** Each job card shows the pickup and delivery addresses, the pickup-to-drop time window, and the cargo weight in tonnes.
- **Scheduling flow** Jobs disappear from the sidebar after they are successfully assigned to a truck on the timeline.
- **Timeline layout** The main panel uses a timeline Eventcalendar view with trucks shown as resources.
- **Resource details** Each truck row displays the truck name, license plate, and a colour-coded status dot for operational, maintenance planned, or in maintenance states.
- **Resource grouping** Trucks are grouped under collapsible capacity tiers such as 3.5 t, 7 t, 12 t, 20 t, and 24 t.
- **Actual rows** Each truck includes a second, indented actual sub-row rendered in a lighter style for live trip progress.
- **Toolbar** A custom toolbar above the timeline includes a date-range label button, a segmented status filter, zoom controls with minus and plus buttons, and a Now button.
- **Date range selection** The date-range button opens a range picker popup for changing the visible planning window.
- **Status filtering** The segmented control filters the visible events by Scheduled, In Progress, and Completed states.
- **Zooming** The zoom slider changes the timeline across multiple detail levels, from broader 4-hour cells down to finer 15-minute cells.
- **Event styling** Timeline events are colour-coded by status, such as blue for scheduled, orange for in progress, and grey for completed.
- **Event content** Planned events show the route between the pickup and delivery locations together with a Planned badge.
- **Live progress display** In-progress trips on the actual sub-row show a pulsing In progress label.
- **Drag validation** When a job is dragged from the sidebar, trucks that cannot take the job because of capacity limits or time conflicts are hidden from the resource list.
- **Invalid ranges** During drag, invalid time ranges are greyed out so only valid drop targets remain visible on the timeline.
- **Successful drop** Dropping a job onto a valid slot adds it to the timeline and confirms the action with a toast message.
- **Auto-snap behavior** Dropping onto an invalid slot snaps the job to the nearest available valid slot within the allowed window when possible.
- **Failure handling** If no valid slot can be found, the demo shows an error toast instead of placing the job.
- **Actual event details** Clicking an actual-progress event opens a toast with delay and elapsed or arrival information for the transport.

## Best for

- **Truck dispatching** Planning and assigning incoming transport jobs across a fleet of trucks from a single scheduling screen.
- **Logistics operations** Managing deliveries where dispatchers need to balance cargo capacity, time windows, and vehicle availability at the same time.
- **Constraint-based scheduling** Evaluating valid assignments quickly when jobs can only be placed on resources that meet size and timing requirements.
- **Live operations visibility** Showing both the scheduled plan and the actual trip progress in the same timeline view.
- **Large resource sets** Working with bigger fleets where drag-time filtering helps narrow the visible list down to valid trucks only.

## API used in this demo

- [`theme`](https://mobiscroll.com/docs/angular/eventcalendar/api#opt-theme) - option
- [`themeVariant`](https://mobiscroll.com/docs/angular/eventcalendar/api#opt-themeVariant) - option
- [`cssClass`](https://mobiscroll.com/docs/angular/eventcalendar/api#opt-cssClass) - option
- [`zoomLevel`](https://mobiscroll.com/docs/angular/eventcalendar/api#opt-zoomLevel) - option
- [`refDate`](https://mobiscroll.com/docs/angular/eventcalendar/api#opt-refDate) - option
- [`display`](https://mobiscroll.com/docs/angular/popup/api#opt-display) - option
- [`touchUi`](https://mobiscroll.com/docs/angular/popup/api#opt-touchUi) - option
- [`buttons`](https://mobiscroll.com/docs/angular/popup/api#opt-buttons) - option
- [`cssClass`](https://mobiscroll.com/docs/angular/popup/api#opt-cssClass) - option
- [`scrollLock`](https://mobiscroll.com/docs/angular/popup/api#opt-scrollLock) - option
- [`maxWidth`](https://mobiscroll.com/docs/angular/popup/api#opt-maxWidth) - option
- [`getEvents`](https://mobiscroll.com/docs/angular/eventcalendar/api#method-getEvents) - method
- [`navigateToEvent`](https://mobiscroll.com/docs/angular/eventcalendar/api#method-navigateToEvent) - method
- [`clickToCreate`](https://mobiscroll.com/docs/angular/eventcalendar/api#opt-clickToCreate) - option
- [`dragToCreate`](https://mobiscroll.com/docs/angular/eventcalendar/api#opt-dragToCreate) - option
- [`dragToResize`](https://mobiscroll.com/docs/angular/eventcalendar/api#opt-dragToResize) - option
- [`dragToMove`](https://mobiscroll.com/docs/angular/eventcalendar/api#opt-dragToMove) - option
- [`externalDrop`](https://mobiscroll.com/docs/angular/eventcalendar/api#opt-externalDrop) - option
- [`eventOverlap`](https://mobiscroll.com/docs/angular/eventcalendar/api#opt-eventOverlap) - option
- [`view`](https://mobiscroll.com/docs/angular/eventcalendar/api#opt-view) - option
- [`data`](https://mobiscroll.com/docs/angular/eventcalendar/api#opt-data) - option
- [`resources`](https://mobiscroll.com/docs/angular/eventcalendar/api#opt-resources) - option
- [`invalid`](https://mobiscroll.com/docs/angular/eventcalendar/api#opt-invalid) - option
- [`resourceTemplate`](https://mobiscroll.com/docs/angular/eventcalendar/api#template-resourceTemplate) - template
- [`resourceHeaderTemplate`](https://mobiscroll.com/docs/angular/eventcalendar/api#template-resourceHeaderTemplate) - template
- [`timelineEventContentTemplate`](https://mobiscroll.com/docs/angular/eventcalendar/api#template-timelineEventContentTemplate) - template
- [`onEventCreated`](https://mobiscroll.com/docs/angular/eventcalendar/api#event-onEventCreated) - event
- [`onEventCreateFailed`](https://mobiscroll.com/docs/angular/eventcalendar/api#event-onEventCreateFailed) - event
- [`onEventUpdateFailed`](https://mobiscroll.com/docs/angular/eventcalendar/api#event-onEventUpdateFailed) - event
- [`onEventDragStart`](https://mobiscroll.com/docs/angular/eventcalendar/api#event-onEventDragStart) - event
- [`onEventDragEnd`](https://mobiscroll.com/docs/angular/eventcalendar/api#event-onEventDragEnd) - event
- [`onEventClick`](https://mobiscroll.com/docs/angular/eventcalendar/api#event-onEventClick) - event
- [`onPageLoaded`](https://mobiscroll.com/docs/angular/eventcalendar/api#event-onPageLoaded) - event
- [`focusOnClose`](https://mobiscroll.com/docs/angular/popup/api#opt-focusOnClose) - option
- [`showOverlay`](https://mobiscroll.com/docs/angular/popup/api#opt-showOverlay) - option
- [`width`](https://mobiscroll.com/docs/angular/popup/api#opt-width) - option
- [`anchor`](https://mobiscroll.com/docs/angular/popup/api#opt-anchor) - option
- [`responsive`](https://mobiscroll.com/docs/angular/popup/api#opt-responsive) - option
- [`label`](https://mobiscroll.com/docs/angular/select/api#opt-label) - option
- [`labelStyle`](https://mobiscroll.com/docs/angular/select/api#opt-labelStyle) - option
- [`inputStyle`](https://mobiscroll.com/docs/angular/select/api#opt-inputStyle) - option
- [`data`](https://mobiscroll.com/docs/angular/select/api#opt-data) - option
- [`onChange`](https://mobiscroll.com/docs/angular/select/api#event-onChange) - event
- [`display`](https://mobiscroll.com/docs/angular/datepicker/api#opt-display) - option
- [`controls`](https://mobiscroll.com/docs/angular/datepicker/api#opt-controls) - option
- [`select`](https://mobiscroll.com/docs/angular/datepicker/api#opt-select) - option
- [`showRangeLabels`](https://mobiscroll.com/docs/angular/datepicker/api#opt-showRangeLabels) - option
- [`pages`](https://mobiscroll.com/docs/angular/datepicker/api#opt-pages) - option
- [`showOnClick`](https://mobiscroll.com/docs/angular/datepicker/api#opt-showOnClick) - option
- [`showOnFocus`](https://mobiscroll.com/docs/angular/datepicker/api#opt-showOnFocus) - option
- [`startInput`](https://mobiscroll.com/docs/angular/datepicker/api#opt-startInput) - option
- [`endInput`](https://mobiscroll.com/docs/angular/datepicker/api#opt-endInput) - option
- [`onChange`](https://mobiscroll.com/docs/angular/datepicker/api#event-onChange) - event

## Code

### Component

```ts
import { CommonModule } from '@angular/common';
import { Component, OnDestroy, OnInit, ViewChild } from '@angular/core';
import { FormsModule } from '@angular/forms';
import {
  formatDate,
  MbscCalendarEvent,
  MbscEventcalendar,
  MbscEventcalendarView,
  MbscModule,
  MbscPopup,
  MbscPopupButton,
  MbscPopupOptions,
  MbscResource,
  Notifications,
  setOptions,
} from '@mobiscroll/angular';

setOptions({
  theme: 'ios',
  themeVariant: 'light'
});

@Component({
  selector: 'app-root', 
  templateUrl: './app.component.html',
  providers: [Notifications],
  standalone: true,
  imports: [CommonModule, FormsModule, MbscModule],
})
export class AppComponent implements OnInit, OnDestroy {
  @ViewChild('calendar') calendarRef!: MbscEventcalendar;
  @ViewChild('filterPopup') filterPopupRef!: MbscPopup;
  @ViewChild('rangePopup') rangePopupRef!: MbscPopup;

  constructor(private notify: Notifications) {}

  myResources: MbscResource[] = [
    {
      id: 'cap1',
      name: '3.5 tons capacity',
      eventCreation: false,
      children: [
        { id: 1, name: 'Isuzu N-Series N35', capacity: 3.5, status: 'operational', plate: 'AB14 KTP' },
        {
          id: '1-actual',
          name: '',
          capacity: 3.5,
          status: 'operational',
          plate: 'AB14 KTP',
          eventCreation: false,
          cssClass: 'mds-dispatch-actual-resource',
        },
        { id: 2, name: 'Mercedes-Benz Sprinter 3500', capacity: 3.5, status: 'operational', plate: 'FR19 XDL' },
        {
          id: '2-actual',
          name: '',
          capacity: 3.5,
          status: 'operational',
          plate: 'FR19 XDL',
          eventCreation: false,
          cssClass: 'mds-dispatch-actual-resource',
        },
        {
          id: 3,
          name: 'Ford Transit 350',
          capacity: 3.5,
          status: 'operational',
          plate: 'QN62 RPV',
          maintenanceFrom: '2026-11-01T00:00',
          maintenanceTo: '2026-11-05T00:00',
        },
        {
          id: '3-actual',
          name: '',
          capacity: 3.5,
          status: 'operational',
          plate: 'QN62 RPV',
          eventCreation: false,
          cssClass: 'mds-dispatch-actual-resource',
          maintenanceFrom: '2026-11-01T00:00',
          maintenanceTo: '2026-11-05T00:00',
        },
      ],
    },
    {
      id: 'cap2',
      name: '7 tons capacity',
      eventCreation: false,
      children: [
        { id: 4, name: 'Ford F-650 Super Duty', capacity: 7, status: 'operational', plate: 'GR12 PEV' },
        {
          id: '4-actual',
          name: '',
          capacity: 7,
          status: 'operational',
          plate: 'GR12 PEV',
          eventCreation: false,
          cssClass: 'mds-dispatch-actual-resource',
        },
        { id: 5, name: 'Isuzu F-Series FTR', capacity: 7, status: 'operational', plate: 'MB27 FTK' },
        {
          id: '5-actual',
          name: '',
          capacity: 7,
          status: 'operational',
          plate: 'MB27 FTK',
          eventCreation: false,
          cssClass: 'mds-dispatch-actual-resource',
        },
        {
          id: 6,
          name: 'Hino 300 Series 716',
          capacity: 7,
          status: 'operational',
          plate: 'KT73 ZLD',
          maintenanceFrom: '2026-11-05T00:00',
          maintenanceTo: '2026-11-08T00:00',
        },
        {
          id: '6-actual',
          name: '',
          capacity: 7,
          status: 'operational',
          plate: 'KT73 ZLD',
          eventCreation: false,
          cssClass: 'mds-dispatch-actual-resource',
          maintenanceFrom: '2026-11-05T00:00',
          maintenanceTo: '2026-11-08T00:00',
        },
      ],
    },
    {
      id: 'cap3',
      name: '12 tons capacity',
      eventCreation: false,
      children: [
        { id: 7, name: 'Hino 500 Series FD', capacity: 12, status: 'operational', plate: 'EP17 GMF' },
        {
          id: '7-actual',
          name: '',
          capacity: 12,
          status: 'operational',
          plate: 'EP17 GMF',
          eventCreation: false,
          cssClass: 'mds-dispatch-actual-resource',
        },
        { id: 8, name: 'Isuzu F-Series FVR', capacity: 12, status: 'operational', plate: 'DS41 CXP' },
        {
          id: '8-actual',
          name: '',
          capacity: 12,
          status: 'operational',
          plate: 'DS41 CXP',
          eventCreation: false,
          cssClass: 'mds-dispatch-actual-resource',
        },
        {
          id: 9,
          name: 'Mercedes-Benz Atego 1218',
          capacity: 12,
          status: 'operational',
          plate: 'NH65 QWD',
          maintenanceFrom: '2026-11-02T00:00',
          maintenanceTo: '2026-11-04T00:00',
        },
        {
          id: '9-actual',
          name: '',
          capacity: 12,
          status: 'operational',
          plate: 'NH65 QWD',
          eventCreation: false,
          cssClass: 'mds-dispatch-actual-resource',
          maintenanceFrom: '2026-11-02T00:00',
          maintenanceTo: '2026-11-04T00:00',
        },
      ],
    },
    {
      id: 'cap4',
      name: '20 tons capacity',
      eventCreation: false,
      children: [
        { id: 10, name: 'Mercedes Actros 2545', capacity: 20, status: 'operational', plate: 'KT19 LNV' },
        {
          id: '10-actual',
          name: '',
          capacity: 20,
          status: 'operational',
          plate: 'KT19 LNV',
          eventCreation: false,
          cssClass: 'mds-dispatch-actual-resource',
        },
        { id: 11, name: 'DAF XF 530', capacity: 20, status: 'operational', plate: 'WP64 GBX' },
        {
          id: '11-actual',
          name: '',
          capacity: 20,
          status: 'operational',
          plate: 'WP64 GBX',
          eventCreation: false,
          cssClass: 'mds-dispatch-actual-resource',
        },
        {
          id: 12,
          name: 'Renault T High 520',
          capacity: 20,
          status: 'operational',
          plate: 'CD70 UJE',
          maintenanceFrom: '2026-11-07T00:00',
          maintenanceTo: '2026-11-10T00:00',
        },
        {
          id: '12-actual',
          name: '',
          capacity: 20,
          status: 'operational',
          plate: 'CD70 UJE',
          eventCreation: false,
          cssClass: 'mds-dispatch-actual-resource',
          maintenanceFrom: '2026-11-07T00:00',
          maintenanceTo: '2026-11-10T00:00',
        },
      ],
    },
    {
      id: 'cap5',
      name: '24 tons capacity',
      eventCreation: false,
      children: [
        { id: 13, name: 'Volvo FH16', capacity: 24, status: 'operational', plate: 'BD67 HTA' },
        {
          id: '13-actual',
          name: '',
          capacity: 24,
          status: 'operational',
          plate: 'BD67 HTA',
          eventCreation: false,
          cssClass: 'mds-dispatch-actual-resource',
        },
        { id: 14, name: 'Freightliner Cascadia', capacity: 24, status: 'operational', plate: 'VA18 RQW' },
        {
          id: '14-actual',
          name: '',
          capacity: 24,
          status: 'operational',
          plate: 'VA18 RQW',
          eventCreation: false,
          cssClass: 'mds-dispatch-actual-resource',
        },
        { id: 15, name: 'Kenworth T680', capacity: 24, status: 'operational', plate: 'HY22 BPL' },
        {
          id: '15-actual',
          name: '',
          capacity: 24,
          status: 'operational',
          plate: 'HY22 BPL',
          eventCreation: false,
          cssClass: 'mds-dispatch-actual-resource',
        },
      ],
    },
  ];

  private myEvents: MbscCalendarEvent[] = [
    {
      resource: 1,
      from: '100 Main St, Dallas, TX',
      to: '50 Congress Ave, Tulsa, OK',
      size: 3,
      pickup: ['2026-11-02T08:00', '2026-11-02T10:00'],
      drop: ['2026-11-02T12:00', '2026-11-02T14:00'],
      status: 'completed',
    },
    {
      resource: 2,
      from: '200 Elm St, Fargo, ND',
      to: '75 N 3rd St, Bismarck, ND',
      size: 2.5,
      pickup: ['2026-11-03T09:00', '2026-11-03T11:00'],
      drop: ['2026-11-03T13:00', '2026-11-03T15:00'],
      status: 'in progress',
    },
    {
      resource: 3,
      from: '150 Broadway, Manchester, NH',
      to: '50 Kennedy Memorial Dr, Waterville, ME',
      size: 3.5,
      pickup: ['2026-11-06T07:00', '2026-11-06T09:00'],
      drop: ['2026-11-06T12:00', '2026-11-06T14:00'],
      status: 'scheduled',
    },
    {
      resource: 1,
      from: '50 N Main St, Phoenix, AZ',
      to: '200 Broadway Ave, Albuquerque, NM',
      size: 3,
      pickup: ['2026-11-06T10:00', '2026-11-06T12:00'],
      drop: ['2026-11-06T15:00', '2026-11-06T17:00'],
      status: 'scheduled',
    },
    {
      resource: 4,
      from: '85 Arch St, Boston, MA',
      to: '40 Middle St, Portland, ME',
      size: 6.5,
      pickup: ['2026-11-02T08:00', '2026-11-02T10:00'],
      drop: ['2026-11-02T12:00', '2026-11-02T14:00'],
      status: 'completed',
    },
    {
      resource: 5,
      from: '300 E Main St, Richmond, VA',
      to: '100 S Tryon St, Charlotte, NC',
      size: 7,
      pickup: ['2026-11-03T05:00', '2026-11-03T07:00'],
      drop: ['2026-11-03T10:00', '2026-11-03T12:00'],
      status: 'completed',
    },
    {
      resource: 6,
      from: '900 W Belmont Ave, Chicago, IL',
      to: '300 Market St, St Louis, MO',
      size: 6,
      pickup: ['2026-11-09T09:00', '2026-11-09T11:00'],
      drop: ['2026-11-09T14:00', '2026-11-09T16:00'],
      status: 'scheduled',
    },
    {
      resource: 4,
      from: '250 King St, Greensboro, NC',
      to: '200 Hay St, Fayetteville, NC',
      size: 6.5,
      pickup: ['2026-11-03T13:00', '2026-11-03T15:00'],
      drop: ['2026-11-03T18:00', '2026-11-03T20:00'],
      status: 'scheduled',
    },
    {
      resource: 7,
      from: '233 S Wacker Dr, Chicago, IL',
      to: '10 Public Square, Cleveland, OH',
      size: 11,
      pickup: ['2026-11-03T08:00', '2026-11-03T11:00'],
      drop: ['2026-11-03T16:00', '2026-11-03T19:00'],
      status: 'scheduled',
    },
    {
      resource: 8,
      from: '180 S High St, Columbus, OH',
      to: '75 E Main St, Lexington, KY',
      size: 12,
      pickup: ['2026-11-05T07:00', '2026-11-05T10:00'],
      drop: ['2026-11-05T15:00', '2026-11-05T18:00'],
      status: 'scheduled',
    },
    {
      resource: 9,
      from: '100 E Capitol St, Jackson, MS',
      to: '250 Riverfront Pkwy, Chattanooga, TN',
      size: 10,
      pickup: ['2026-11-08T07:00', '2026-11-08T10:00'],
      drop: ['2026-11-08T16:00', '2026-11-08T19:00'],
      status: 'scheduled',
    },
    {
      resource: 7,
      from: '50 Arch St, Boston, MA',
      to: '200 Middle St, Portland, ME',
      size: 9,
      pickup: ['2026-11-09T08:00', '2026-11-09T10:00'],
      drop: ['2026-11-09T12:00', '2026-11-09T14:00'],
      status: 'scheduled',
    },
    {
      resource: 10,
      from: '50 N 1st Ave, Phoenix, AZ',
      to: '200 Broadway Ave, Albuquerque, NM',
      size: 20,
      pickup: ['2026-11-03T10:00', '2026-11-03T13:00'],
      drop: ['2026-11-03T18:00', '2026-11-03T21:00'],
      status: 'in progress',
    },
    {
      resource: 11,
      from: '120 Broadway, New York, NY',
      to: '55 Canal St, New Orleans, LA',
      size: 18,
      pickup: ['2026-11-06T06:00', '2026-11-06T09:00'],
      drop: ['2026-11-06T10:00', '2026-11-06T14:00'],
      status: 'scheduled',
    },
    {
      resource: 12,
      from: '600 Poydras St, New Orleans, LA',
      to: '200 Commerce St, Montgomery, AL',
      size: 20,
      pickup: ['2026-11-10T06:00', '2026-11-10T09:00'],
      drop: ['2026-11-10T14:00', '2026-11-10T17:00'],
      status: 'scheduled',
    },
    {
      resource: 10,
      from: '120 Main St, Boston, MA',
      to: '50 Canal St, New Orleans, LA',
      size: 19,
      pickup: ['2026-11-04T07:00', '2026-11-04T10:00'],
      drop: ['2026-11-04T14:00', '2026-11-04T17:00'],
      status: 'scheduled',
    },
    {
      resource: 13,
      from: '100 Main St, Dallas, TX',
      to: '15 Broadway St, Denver, CO',
      size: 22,
      pickup: ['2026-11-03T07:00', '2026-11-03T10:00'],
      drop: ['2026-11-04T04:00', '2026-11-04T08:00'],
      status: 'scheduled',
    },
    {
      resource: 14,
      from: '300 Main St, Houston, TX',
      to: '120 W Capitol Ave, Little Rock, AR',
      size: 24,
      pickup: ['2026-11-05T10:00', '2026-11-05T13:00'],
      drop: ['2026-11-05T18:00', '2026-11-05T22:00'],
      status: 'scheduled',
    },
    {
      resource: 15,
      from: '900 S Flower St, Los Angeles, CA',
      to: '300 2nd Ave, Seattle, WA',
      size: 23,
      pickup: ['2026-11-08T05:00', '2026-11-08T08:00'],
      drop: ['2026-11-08T12:00', '2026-11-08T16:00'],
      status: 'scheduled',
    },
    {
      resource: 13,
      from: '350 S Spring St, Los Angeles, CA',
      to: '500 E Rim Rd, El Paso, TX',
      size: 24,
      pickup: ['2026-11-11T06:00', '2026-11-11T09:00'],
      drop: ['2026-11-11T18:00', '2026-11-11T21:00'],
      status: 'scheduled',
    },
    {
      resource: 14,
      from: '200 Market St, Philadelphia, PA',
      to: '400 Washington Ave, Minneapolis, MN',
      size: 23,
      pickup: ['2026-11-06T13:00', '2026-11-06T16:00'],
      drop: ['2026-11-06T20:00', '2026-11-06T23:00'],
      status: 'scheduled',
    },
    {
      resource: 15,
      from: '500 S Wacker Dr, Chicago, IL',
      to: '100 State St, Portland, ME',
      size: 24,
      pickup: ['2026-11-09T08:00', '2026-11-09T11:00'],
      drop: ['2026-11-09T16:00', '2026-11-09T19:00'],
      status: 'scheduled',
    },
    {
      resource: 1,
      from: '300 W Madison St, Chicago, IL',
      to: '500 Euclid Ave, Cleveland, OH',
      size: 3,
      pickup: ['2026-11-04T08:00', '2026-11-04T10:00'],
      drop: ['2026-11-04T13:00', '2026-11-04T16:00'],
      status: 'scheduled',
    },
    {
      resource: 4,
      from: '800 N 3rd St, Philadelphia, PA',
      to: '200 W Baltimore St, Baltimore, MD',
      size: 6.5,
      pickup: ['2026-11-05T07:00', '2026-11-05T09:00'],
      drop: ['2026-11-05T12:00', '2026-11-05T15:00'],
      status: 'scheduled',
    },
    {
      resource: 5,
      from: '900 Biscayne Blvd, Miami, FL',
      to: '400 N Orange Ave, Orlando, FL',
      size: 7,
      pickup: ['2026-11-04T09:00', '2026-11-04T11:00'],
      drop: ['2026-11-04T14:00', '2026-11-04T18:00'],
      status: 'scheduled',
    },
    {
      resource: 7,
      from: '100 S 5th St, Minneapolis, MN',
      to: '300 W Kellogg Blvd, St Paul, MN',
      size: 9,
      pickup: ['2026-11-06T08:00', '2026-11-06T10:00'],
      drop: ['2026-11-06T14:00', '2026-11-06T17:00'],
      status: 'scheduled',
    },
    {
      resource: 8,
      from: '500 W 2nd St, Austin, TX',
      to: '2200 Post Oak Blvd, Houston, TX',
      size: 12,
      pickup: ['2026-11-07T07:00', '2026-11-07T10:00'],
      drop: ['2026-11-07T15:00', '2026-11-07T18:00'],
      status: 'scheduled',
    },
    {
      resource: 11,
      from: '600 Grant St, Pittsburgh, PA',
      to: '200 W Washington St, Indianapolis, IN',
      size: 18,
      pickup: ['2026-11-04T06:00', '2026-11-04T09:00'],
      drop: ['2026-11-04T16:00', '2026-11-04T20:00'],
      status: 'scheduled',
    },
    {
      resource: 14,
      from: '400 N Michigan Ave, Chicago, IL',
      to: '250 E Wisconsin Ave, Milwaukee, WI',
      size: 23,
      pickup: ['2026-11-08T08:00', '2026-11-08T11:00'],
      drop: ['2026-11-08T15:00', '2026-11-08T18:00'],
      status: 'scheduled',
    },
    {
      resource: 13,
      from: '700 Figueroa St, Los Angeles, CA',
      to: '50 W San Fernando St, San Jose, CA',
      size: 22,
      pickup: ['2026-11-07T06:00', '2026-11-07T09:00'],
      drop: ['2026-11-07T17:00', '2026-11-07T21:00'],
      status: 'scheduled',
    },
  ];

  private externalEvents: any[] = [
    {
      id: 1,
      from: '2000 Q St, Sacramento, CA',
      to: '500 Poydras St, New Orleans, LA',
      size: 9,
      pickup: ['2026-11-03T09:00', '2026-11-03T11:00'],
      drop: ['2026-11-03T12:00', '2026-11-03T17:00'],
    },
    {
      id: 2,
      from: '100 State St, Madison, WI',
      to: '300 S Wacker Dr, Chicago, IL',
      size: 22,
      pickup: ['2026-11-03T13:00', '2026-11-03T15:00'],
      drop: ['2026-11-03T16:00', '2026-11-03T21:00'],
    },
    {
      id: 3,
      from: '1500 Market St, Philadelphia, PA',
      to: '600 Liberty St, Pittsburgh, PA',
      size: 13,
      pickup: ['2026-11-03T13:00', '2026-11-03T17:00'],
      drop: ['2026-11-03T18:00', '2026-11-03T22:00'],
    },
    {
      id: 25,
      from: '350 Fifth Ave, New York, NY',
      to: '100 Broad St, Newark, NJ',
      size: 3.5,
      pickup: ['2026-11-03T14:00', '2026-11-03T16:00'],
      drop: ['2026-11-03T18:00', '2026-11-03T21:00'],
    },
    {
      id: 26,
      from: '800 Market St, San Francisco, CA',
      to: '400 Capitol Mall, Sacramento, CA',
      size: 6,
      pickup: ['2026-11-03T15:00', '2026-11-03T17:00'],
      drop: ['2026-11-03T19:00', '2026-11-03T22:00'],
    },
    {
      id: 4,
      from: '1100 Congress Ave, Austin, TX',
      to: '500 E Main St, Dallas, TX',
      size: 20,
      pickup: ['2026-11-04T07:00', '2026-11-04T09:00'],
      drop: ['2026-11-04T10:00', '2026-11-04T15:00'],
    },
    {
      id: 5,
      from: '200 Peachtree St NW, Atlanta, GA',
      to: '50 Music Sq E, Nashville, TN',
      size: 8,
      pickup: ['2026-11-04T08:00', '2026-11-04T10:00'],
      drop: ['2026-11-04T12:00', '2026-11-04T16:00'],
    },
    {
      id: 6,
      from: '500 Boylston St, Boston, MA',
      to: '200 State St, Portland, ME',
      size: 3.5,
      pickup: ['2026-11-04T08:30', '2026-11-04T10:30'],
      drop: ['2026-11-04T12:30', '2026-11-04T18:30'],
    },
    {
      id: 27,
      from: '200 S Lamar Blvd, Austin, TX',
      to: '500 Commerce St, Dallas, TX',
      size: 19,
      pickup: ['2026-11-04T13:00', '2026-11-04T15:00'],
      drop: ['2026-11-04T18:00', '2026-11-04T22:00'],
    },
    {
      id: 28,
      from: '300 W Colfax Ave, Denver, CO',
      to: '100 N Main St, Pueblo, CO',
      size: 10,
      pickup: ['2026-11-05T10:00', '2026-11-05T12:00'],
      drop: ['2026-11-05T14:00', '2026-11-05T18:00'],
    },
    {
      id: 7,
      from: '400 S 4th St, Louisville, KY',
      to: '1400 Main St, Cincinnati, OH',
      size: 7,
      pickup: ['2026-11-05T06:00', '2026-11-05T08:00'],
      drop: ['2026-11-05T09:00', '2026-11-05T12:00'],
    },
    {
      id: 8,
      from: '410 S Houston Ave, Tulsa, OK',
      to: '250 W Capitol Ave, Little Rock, AR',
      size: 11.5,
      pickup: ['2026-11-05T06:30', '2026-11-05T08:30'],
      drop: ['2026-11-05T10:30', '2026-11-05T15:30'],
    },
    {
      id: 29,
      from: '450 Sutter St, San Francisco, CA',
      to: '200 Pine Ave, Long Beach, CA',
      size: 22,
      pickup: ['2026-11-06T07:00', '2026-11-06T09:00'],
      drop: ['2026-11-06T13:00', '2026-11-06T17:00'],
    },
    {
      id: 9,
      from: '999 3rd Ave, Seattle, WA',
      to: '500 W 8th St, Vancouver, WA',
      size: 3,
      pickup: ['2026-11-06T09:00', '2026-11-06T11:00'],
      drop: ['2026-11-06T12:00', '2026-11-06T17:00'],
    },
    {
      id: 10,
      from: '50 S Main St, Salt Lake City, UT',
      to: '300 N Broadway, Denver, CO',
      size: 5,
      pickup: ['2026-11-06T10:00', '2026-11-06T12:00'],
      drop: ['2026-11-06T13:00', '2026-11-06T18:00'],
    },
    {
      id: 11,
      from: '300 S Grand Ave, Los Angeles, CA',
      to: '400 E Van Buren St, Phoenix, AZ',
      size: 5,
      pickup: ['2026-11-10T08:00', '2026-11-10T10:00'],
      drop: ['2026-11-10T13:00', '2026-11-10T18:00'],
    },
    {
      id: 12,
      from: '200 W Washington St, Indianapolis, IN',
      to: '100 N Main St, Louisville, KY',
      size: 18,
      pickup: ['2026-11-11T07:00', '2026-11-11T09:00'],
      drop: ['2026-11-11T12:00', '2026-11-11T17:00'],
    },
    {
      id: 13,
      from: '500 N Michigan Ave, Chicago, IL',
      to: '250 Marquette Ave, Minneapolis, MN',
      size: 3,
      pickup: ['2026-11-12T09:00', '2026-11-12T11:00'],
      drop: ['2026-11-12T14:00', '2026-11-12T19:00'],
    },
    {
      id: 14,
      from: '600 Congress Ave, Austin, TX',
      to: '700 Texas Ave, Houston, TX',
      size: 12,
      pickup: ['2026-11-13T06:00', '2026-11-13T08:00'],
      drop: ['2026-11-13T11:00', '2026-11-13T16:00'],
    },
    {
      id: 15,
      from: '100 Broad St, Newark, NJ',
      to: '200 S Orange Ave, Orlando, FL',
      size: 7,
      pickup: ['2026-11-15T10:00', '2026-11-15T12:00'],
      drop: ['2026-11-15T15:00', '2026-11-15T20:00'],
    },
    {
      id: 16,
      from: '400 Pike St, Seattle, WA',
      to: '800 SW Broadway, Portland, OR',
      size: 9,
      pickup: ['2026-11-17T07:00', '2026-11-17T09:00'],
      drop: ['2026-11-17T12:00', '2026-11-17T16:00'],
    },
    {
      id: 17,
      from: '300 Main St, Buffalo, NY',
      to: '500 Euclid Ave, Cleveland, OH',
      size: 22,
      pickup: ['2026-11-18T08:00', '2026-11-18T11:00'],
      drop: ['2026-11-18T14:00', '2026-11-18T19:00'],
    },
    {
      id: 18,
      from: '150 S Miami Ave, Miami, FL',
      to: '300 Peachtree St, Atlanta, GA',
      size: 6,
      pickup: ['2026-11-19T09:00', '2026-11-19T11:00'],
      drop: ['2026-11-19T13:00', '2026-11-19T18:00'],
    },
    {
      id: 19,
      from: '700 W 3rd St, Kansas City, MO',
      to: '400 N Broadway, St Louis, MO',
      size: 15,
      pickup: ['2026-11-21T06:00', '2026-11-21T08:00'],
      drop: ['2026-11-21T10:00', '2026-11-21T15:00'],
    },
    {
      id: 20,
      from: '250 E Houston St, San Antonio, TX',
      to: '1200 Commerce St, Dallas, TX',
      size: 4,
      pickup: ['2026-11-22T11:00', '2026-11-22T13:00'],
      drop: ['2026-11-22T15:00', '2026-11-22T20:00'],
    },
    {
      id: 21,
      from: '800 N Michigan Ave, Chicago, IL',
      to: '500 Woodward Ave, Detroit, MI',
      size: 11,
      pickup: ['2026-11-24T07:00', '2026-11-24T09:00'],
      drop: ['2026-11-24T12:00', '2026-11-24T17:00'],
    },
    {
      id: 22,
      from: '900 Market St, San Francisco, CA',
      to: '600 Wilshire Blvd, Los Angeles, CA',
      size: 20,
      pickup: ['2026-11-25T08:00', '2026-11-25T10:00'],
      drop: ['2026-11-25T14:00', '2026-11-25T19:00'],
    },
    {
      id: 23,
      from: '350 5th Ave, New York, NY',
      to: '100 Federal St, Boston, MA',
      size: 3.5,
      pickup: ['2026-11-26T09:00', '2026-11-26T11:00'],
      drop: ['2026-11-26T13:00', '2026-11-26T17:00'],
    },
    {
      id: 24,
      from: '200 S Tryon St, Charlotte, NC',
      to: '100 N Main St, Greenville, SC',
      size: 8,
      pickup: ['2026-11-28T06:00', '2026-11-28T08:00'],
      drop: ['2026-11-28T10:00', '2026-11-28T14:00'],
    },
  ];

  private statusColors: Record<string, string> = {
    scheduled: '#2196f3',
    'in progress': '#f97316',
    completed: '#78909c',
  };

  private maintenanceColors: Record<string, string> = {
    'in-maintenance': '#f44336',
    'maintenance-planned': '#ff9800',
    operational: '#4caf50',
  };

  private maintenanceLabelsMap: Record<string, string> = {
    'in-maintenance': 'In Maintenance',
    'maintenance-planned': 'Maintenance Planned',
    operational: 'Operational',
  };

  private now = new Date();
  private today = new Date(this.now.getFullYear(), this.now.getMonth(), this.now.getDate());
  private myInvalids: any[] = [];
  private maintenanceInvalids: any[] = [];
  private scheduledJobIds: (string | number)[] = [];
  private currentViewStart = this.today;
  private currentViewEnd = new Date(this.today.getTime() + 7 * 24 * 60 * 60 * 1000);
  private currentRangeStart = this.today;
  private currentRangeDays = 7;
  private pendingRangeStart = this.today;
  private pendingRangeDays = 7;
  private refreshInterval: any;
  private searchTimeout: any;

  filters: Record<string, boolean> = {};
  statusFilters: string[] = ['scheduled', 'in progress', 'completed'];
  filteredResources: MbscResource[] = [];
  calendarData: MbscCalendarEvent[] = [];
  calendarInvalid: any[] = [];
  zoomLevel = 3;
  refDate: Date = this.today;
  calView: MbscEventcalendarView = this.buildViewConfig(7);
  rangeLabel = '';
  visibleJobs: any[] = [];
  jobListItems: any[] = [];
  searchQuery = '';
  filterAnchor: HTMLElement | undefined;
  tempFilters: Record<string, boolean> = {};
  rangeSelectValue = '7';
  rangeInputsDisabled = true;
  calendarRangeValue: Date[] = [];
  rangeSelectorData = [
    { value: 'custom', text: 'Custom' },
    { value: '7', text: 'Next 7 days' },
    { value: '14', text: 'Next 14 days' },
    { value: '30', text: 'Next 30 days' },
    { value: '60', text: 'Next 60 days' },
    { value: '90', text: 'Next 90 days' },
  ];

  rangePopupResponsive: Record<string, MbscPopupOptions & { breakpoint?: number }> = {
    xsmall: {
      display: 'bottom',
      touchUi: true,
      buttons: [
        {
          text: 'Apply',
          keyCode: 'enter' as const,
          handler: () => {
            this.applyPendingRange();
          },
          cssClass: 'mbsc-popup-button-primary',
        },
        'cancel',
      ],
    },
    custom: {
      breakpoint: 575,
      buttons: [],
      display: 'anchored',
      touchUi: false,
      scrollLock: false,
      maxWidth: 920,
    },
  };

  filterPopupButtons: (MbscPopupButton | 'ok' | 'close' | 'set' | 'cancel')[] = [
    'cancel',
    {
      text: 'Apply',
      keyCode: 'enter' as const,
      handler: () => {
        this.filters = { ...this.tempFilters };
        this.filterResources();
        this.refreshJobList();
        this.filterPopupRef.close();
        this.showToast('Filters applied');
      },
      cssClass: 'mbsc-popup-button-primary',
    },
  ];

  ngOnInit(): void {
    this.filters['operational'] = true;
    this.filters['maintenance'] = true;
    this.myResources.forEach((category) => {
      this.filters[category.id as string] = true;
    });

    this.setEventData(this.myEvents);
    this.addActualEvents(this.myEvents);
    this.setupMaintenanceDates();
    this.maintenanceInvalids = this.buildMaintenanceInvalids();
    this.filteredResources = this.computeFilteredResources();
    this.calendarData = this.getStatusFilteredEvents();
    this.calendarInvalid = [...this.maintenanceInvalids];

    this.setEventData(this.externalEvents);
    const end = new Date(this.today.getTime() + 6 * 24 * 60 * 60 * 1000);
    this.calendarRangeValue = [this.today, end];

    this.rangeLabel = this.formatRangeLabel(this.today, 7);
    this.refreshJobList();

    this.refreshInterval = setInterval(() => this.refresh(), 60000);
  }

  ngOnDestroy(): void {
    clearInterval(this.refreshInterval);
  }

  private showToast(message: string): void {
    this.notify.toast({ message });
  }

  private getResourceMaintenanceStatus(resource: any): string {
    if (!resource.maintenanceFrom || !resource.maintenanceTo) return 'operational';
    const from = new Date(resource.maintenanceFrom);
    const to = new Date(resource.maintenanceTo);
    if (this.now >= from && this.now <= to) return 'in-maintenance';
    if (from < this.currentViewEnd && to > this.currentViewStart) return 'maintenance-planned';
    return 'operational';
  }

  getMaintenanceColor(resource: any): string {
    return this.maintenanceColors[this.getResourceMaintenanceStatus(resource)] || '#4caf50';
  }

  getMaintenanceLabel(resource: any): string {
    return this.maintenanceLabelsMap[this.getResourceMaintenanceStatus(resource)] || 'Operational';
  }

  private buildMaintenanceInvalids(): any[] {
    const invalids: any[] = [];
    this.myResources.forEach((group: any) => {
      group.children?.forEach((resource: any) => {
        if (resource.maintenanceFrom && resource.maintenanceTo && !String(resource.id).includes('actual')) {
          invalids.push({
            start: resource.maintenanceFrom,
            end: resource.maintenanceTo,
            resource: resource.id,
            cssClass: 'mds-dispatch-maintenance-invalid',
          });
        }
      });
    });
    return invalids;
  }

  private setupMaintenanceDates(): void {
    this.myResources.forEach((group: any) => {
      group.children?.forEach((resource: any) => {
        if (resource.maintenanceFrom) resource.maintenanceFrom = new Date(resource.maintenanceFrom);
        if (resource.maintenanceTo) resource.maintenanceTo = new Date(resource.maintenanceTo);
      });
    });
  }

  private getActualDates(start: Date, end: Date): Date[] {
    const possibleOffsets = [-120, -90, -60, -30, -15, 0, 15, 30, 60, 90, 120];
    const departureOffset = possibleOffsets[Math.floor(Math.random() * possibleOffsets.length)] * 60000;
    const arrivalOffset = possibleOffsets[Math.floor(Math.random() * possibleOffsets.length)] * 60000;
    return [new Date(start.getTime() + departureOffset), new Date(end.getTime() + arrivalOffset)];
  }

  private addActualEvents(events: any[]): void {
    for (const event of events) {
      event.start = event.start ? new Date(event.start) : event.start;
      event.end = event.end ? new Date(event.end) : event.end;

      if (event.status === 'actual') continue;

      if (event.end <= this.now) {
        event.color = this.statusColors['completed'];
      } else if (event.start < this.now) {
        event.color = this.statusColors['in progress'];
      } else {
        event.color = this.statusColors[event.status] || this.statusColors['scheduled'];
      }

      event.editable = this.now < event.start;

      if (event.start < this.now && event.end > this.now) {
        if (!event.actual) {
          const actualDates = this.getActualDates(event.start, new Date(event.drop[0]));
          const actualStart = actualDates[0] >= event.start && actualDates[0] < this.now ? actualDates[0] : event.start;
          const newEvent = {
            resource: event.resource + '-actual',
            from: event.from,
            to: event.to,
            pickup: event.pickup,
            drop: event.drop,
            size: event.size,
            start: actualStart,
            end: this.now,
            title: 'In progress',
            status: 'actual',
            color: event.color,
            cssClass: 'mds-dispatch-actual-event mds-dispatch-pulse',
            editable: false,
          };
          event.actual = true;
          event.actualRef = newEvent;
          events.push(newEvent);
        } else if (event.actualRef) {
          event.actualRef.end = this.now;
        }
      } else if (event.end <= this.now) {
        if (!event.actual) {
          const completedActualDates = this.getActualDates(event.start, new Date(event.drop[0]));
          const completedActualStart =
            completedActualDates[0] >= event.start && completedActualDates[0] < event.end ? completedActualDates[0] : event.start;
          let completedActualEnd = completedActualDates[1];
          const minEnd = new Date(completedActualStart.getTime() + 30 * 60000);
          if (completedActualEnd < minEnd) completedActualEnd = minEnd;
          const completedNewEvent = {
            resource: event.resource + '-actual',
            from: event.from,
            to: event.to,
            pickup: event.pickup,
            drop: event.drop,
            size: event.size,
            start: completedActualStart,
            end: completedActualEnd,
            title: 'Completed',
            status: 'actual',
            color: event.color,
            cssClass: 'mds-dispatch-actual-event',
            editable: false,
          };
          event.actual = true;
          event.actualRef = completedNewEvent;
          events.push(completedNewEvent);
        } else if (event.actualRef && event.actualRef.title !== 'Completed') {
          const completedActualDates = this.getActualDates(event.actualRef.start, new Date(event.drop[0]));
          let completedActualEnd = completedActualDates[1];
          const minEnd = new Date(event.actualRef.start.getTime() + 30 * 60000);
          if (completedActualEnd < minEnd) completedActualEnd = minEnd;
          event.actualRef.end = completedActualEnd;
          event.actualRef.color = event.color;
          event.actualRef.cssClass = 'mds-dispatch-actual-event';
          event.actualRef.title = 'Completed';
        }
      }
    }
  }

  private setEventData(events: any[]): void {
    for (const event of events) {
      event.start = event.start ? event.start : event.pickup[0];
      event.end = event.end ? event.end : event.drop[0];
      event.title = event.from + ' → ' + event.to;
    }
  }

  private computeFilteredResources(): MbscResource[] {
    return this.myResources
      .map((category: any) => {
        const keptIds: Record<string, boolean> = {};
        category.children?.forEach((resource: any) => {
          if (String(resource.id).includes('actual')) return;
          const filterKey = this.getResourceMaintenanceStatus(resource) === 'operational' ? 'operational' : 'maintenance';
          if (
            this.filters[filterKey] &&
            (!this.searchQuery ||
              resource.name.toLowerCase().includes(this.searchQuery.toLowerCase()) ||
              resource.plate.toLowerCase().includes(this.searchQuery.toLowerCase()))
          ) {
            keptIds[resource.id] = true;
          }
        });
        return {
          id: category.id,
          name: category.name,
          eventCreation: category.eventCreation,
          children: category.children?.filter((resource: any) => {
            if (String(resource.id).includes('actual')) {
              const parentId = String(resource.id).replace('-actual', '');
              if (!keptIds[parentId]) return false;
              const parent = category.children?.find((r: any) => String(r.id) === parentId);
              return !parent || this.getResourceMaintenanceStatus(parent) === 'operational';
            }
            return keptIds[resource.id];
          }),
        };
      })
      .filter((res: any) => res.children?.length > 0 && this.filters[res.id]);
  }

  private filterResources(): void {
    this.filteredResources = this.computeFilteredResources();
  }

  private getEffectiveStatus(ev: any): string {
    if (ev.status === 'actual') return ev.title === 'Completed' ? 'completed' : 'in progress';
    if (ev.end && ev.end <= this.now) return 'completed';
    if (ev.start && ev.start < this.now) return 'in progress';
    return ev.status || 'scheduled';
  }

  private getStatusFilteredEvents(): MbscCalendarEvent[] {
    return this.myEvents.filter((ev) => this.statusFilters.includes(this.getEffectiveStatus(ev)));
  }

  private getMaxAvailableCapacity(): number {
    let max = 0;
    this.myResources.forEach((group: any) => {
      if (this.filters[group.id]) {
        group.children?.forEach((child: any) => {
          if (!String(child.id).includes('actual') && child.capacity > max) max = child.capacity;
        });
      }
    });
    return max;
  }

  private buildViewConfig(days: number): MbscEventcalendarView {
    return {
      timeline: {
        type: 'day',
        size: days,
        timeCellStep: 60,
        timeLabelStep: 60,
        eventHeight: 'variable',
        zoomLevels: {
          1: { type: 'day', size: days, columnWidth: 'xsmall', timeCellStep: 240, timeLabelStep: 240 },
          2: { type: 'day', size: days, columnWidth: 'small', timeCellStep: 120, timeLabelStep: 120 },
          3: { type: 'day', size: days, columnWidth: 'medium', timeCellStep: 60, timeLabelStep: 60 },
          4: { type: 'day', size: days, columnWidth: 'xlarge', timeCellStep: 30, timeLabelStep: 60 },
          5: { type: 'day', size: days, columnWidth: 'xlarge', timeCellStep: 15, timeLabelStep: 60 },
        },
      },
    };
  }

  private applyDaysRange(days: number, startDate?: Date): void {
    const target = startDate || this.today;
    this.currentViewStart = target;
    this.currentViewEnd = new Date(target.getTime() + days * 24 * 60 * 60 * 1000);
    this.filteredResources = this.computeFilteredResources();
    this.refDate = target;
    this.calView = this.buildViewConfig(days);
    const navigateTo = this.today >= target && this.today < this.currentViewEnd ? this.now : target;
    setTimeout(() => {
      this.calendarRef?.navigate(navigateTo);
    }, 100);
  }

  private formatDelay(minutes: number): string {
    if (Math.abs(minutes) < 5) return 'on time';
    if (minutes > 0) return minutes + ' min late';
    return Math.abs(minutes) + ' min early';
  }

  private formatDuration(ms: number): string {
    const totalMin = Math.round(ms / 60000);
    const h = Math.floor(totalMin / 60);
    const m = totalMin % 60;
    if (h === 0) return m + ' min';
    if (m === 0) return h + ' h';
    return h + ' h ' + m + ' min';
  }

  private formatRangeLabel(start: Date, days: number): string {
    const end = new Date(start.getTime() + (days - 1) * 24 * 60 * 60 * 1000);
    return formatDate('MMM D', start) + ' – ' + formatDate('MMM D, YYYY', end);
  }

  formatTime(date: Date | string): string {
    return formatDate('H:mm', new Date(date));
  }

  private findResourceById(id: any): any {
    const baseId = String(id).replace('-actual', '');
    for (const group of this.myResources as any[]) {
      for (const child of group.children || []) {
        if (String(child.id) === baseId) return child;
      }
    }
    return null;
  }

  private findFirstSlot(draggedEvent: any): { start: Date; end: Date } | null {
    this.now = new Date();
    const minStart = new Date(this.now.getTime() + 2 * 60 * 60 * 1000);
    const windowStart = new Date(draggedEvent.pickup[0]);
    const windowEnd = new Date(draggedEvent.drop[1]);
    let eventStart = new Date(draggedEvent.start);
    let eventEnd = new Date(draggedEvent.end);

    const effectiveWindowStart = windowStart < minStart ? minStart : windowStart;
    const eventDuration = eventEnd.getTime() - eventStart.getTime();
    const windowSize = windowEnd.getTime() - effectiveWindowStart.getTime();

    if (eventDuration > windowSize) return null;
    if (eventStart < effectiveWindowStart) {
      eventStart = new Date(effectiveWindowStart);
      eventEnd = new Date(effectiveWindowStart.getTime() + eventDuration);
    }
    if (eventEnd > windowEnd) {
      eventEnd = new Date(windowEnd);
      eventStart = new Date(windowEnd.getTime() - eventDuration);
    }

    if (draggedEvent.resource) {
      const resource = this.findResourceById(draggedEvent.resource);
      if (resource?.maintenanceFrom && resource?.maintenanceTo) {
        const mFrom = new Date(resource.maintenanceFrom);
        const mTo = new Date(resource.maintenanceTo);
        if (eventStart < mTo && eventEnd > mFrom) {
          eventStart = new Date(mTo);
          eventEnd = new Date(mTo.getTime() + eventDuration);
          if (eventEnd > windowEnd) return null;
        }
      }
    }

    return { start: eventStart, end: eventEnd };
  }

  private moveToFirstAvailableSlot(draggedEvent: any, isEdit: boolean): boolean {
    const slot = this.findFirstSlot(draggedEvent);
    if (slot) {
      draggedEvent.start = slot.start;
      draggedEvent.end = slot.end;
      if (isEdit) {
        this.calendarRef.updateEvent(draggedEvent);
      } else {
        this.calendarRef.addEvent(draggedEvent);
      }
      return true;
    }
    return false;
  }

  private invalidateResources(event: any): any {
    this.now = new Date();
    const minTime = new Date(this.now.getTime() + 2 * 60 * 60 * 1000);
    const sevenDaysFromNow = new Date(this.now.getTime() + 7 * 24 * 60 * 60 * 1000);
    const invalidIds: any[] = [];
    const validIds: any[] = [];
    const windowStart = new Date(event.pickup[0]);
    const windowEnd = new Date(event.drop[1]);

    for (const group of this.myResources as any[]) {
      for (const truck of group.children || []) {
        let isValid = true;
        if (truck.capacity < event.size) {
          truck.eventCreation = false;
          invalidIds.push(truck.id);
          isValid = false;
        }
        if (isValid) {
          const truckEvents = this.calendarRef.getEvents().filter((ev: any) => ev.resource === truck.id);
          const overlappingEvent = truckEvents.find((ev: any) => {
            const evEnd = ev.drop ? new Date(ev.drop[1]) : ev.end;
            return evEnd > windowStart && ev.start < windowEnd;
          });
          if (overlappingEvent && event.resource !== truck.id) {
            truck.eventCreation = false;
            invalidIds.push(truck.id);
            if (!String(truck.id).includes('actual')) invalidIds.push(truck.id + '-actual');
            isValid = false;
          }
        }
        if (isValid && !String(truck.id).includes('actual')) validIds.push(truck.id);
      }
    }

    this.myInvalids = [
      { start: this.today, end: windowStart < minTime ? minTime : windowStart, cssClass: 'mds-dispatch-disabled-row' },
      { start: windowStart < minTime ? minTime : windowStart, end: windowEnd, resource: invalidIds, cssClass: 'mds-dispatch-disabled-row' },
      { start: windowEnd, end: sevenDaysFromNow, cssClass: 'mds-dispatch-disabled-row' },
    ];

    setTimeout(() => {
      this.calendarInvalid = [...this.myInvalids, ...this.maintenanceInvalids];
    });

    return validIds.length > 0 ? validIds[0] : null;
  }

  private resetEventCreationFlags(): void {
    for (const group of this.myResources as any[]) {
      for (const truck of group.children || []) {
        if (!String(truck.id).includes('actual')) truck.eventCreation = true;
      }
    }
  }

  private refresh(): void {
    this.now = new Date();
    this.filteredResources = this.computeFilteredResources();
    this.addActualEvents(this.myEvents);
    setTimeout(() => {
      this.calendarData = this.getStatusFilteredEvents();
      this.calendarInvalid = [...this.myInvalids, ...this.maintenanceInvalids];
    });
  }

  refreshJobList(): void {
    this.now = new Date();
    const rangeEnd = new Date(this.currentRangeStart.getTime() + this.currentRangeDays * 24 * 60 * 60 * 1000);
    const minPickup = new Date(this.now.getTime() + 2 * 60 * 60 * 1000);
    const maxCapacity = this.getMaxAvailableCapacity();
    this.visibleJobs = this.externalEvents.filter((job) => {
      if (this.scheduledJobIds.indexOf(job.id) !== -1) return false;
      if (job.size > maxCapacity) return false;
      const pickupStart = new Date(job.pickup[0]);
      if (pickupStart < minPickup) return false;
      return pickupStart >= this.currentRangeStart && pickupStart < rangeEnd;
    });

    const items: any[] = [];
    let lastDayKey: string | null = null;
    for (const job of this.visibleJobs) {
      const pickupDate = new Date(job.pickup[0]);
      const dayKey = formatDate('YYYY-MM-DD', pickupDate);
      if (dayKey !== lastDayKey) {
        items.push({ type: 'header', label: formatDate('DDD, DD MMM', pickupDate) });
        lastDayKey = dayKey;
      }
      items.push({ type: 'job', job });
    }
    this.jobListItems = items;
  }

  handleZoom(zoom: number): void {
    this.zoomLevel = zoom;
    this.calView = this.buildViewConfig(this.currentRangeDays);
  }

  onStatusFilterChange(): void {
    this.calendarData = this.getStatusFilteredEvents();
  }

  onSearchChange(): void {
    clearTimeout(this.searchTimeout);
    this.searchTimeout = setTimeout(() => {
      this.filteredResources = this.computeFilteredResources();
    }, 300);
  }

  openFilterPopup(event: MouseEvent): void {
    this.tempFilters = { ...this.filters };
    this.filterAnchor = event.target as HTMLElement;
    this.filterPopupRef.open();
  }

  resetFilters(): void {
    this.searchQuery = '';
    this.myResources.forEach((cat: any) => {
      this.filters[cat.id] = true;
    });
    this.filters['operational'] = true;
    this.filters['maintenance'] = true;
    this.filterResources();
    this.refreshJobList();
    this.showToast('Filters cleared');
  }

  openRangePopup(): void {
    this.rangePopupRef.open();
  }

  applyPendingRange(): void {
    this.currentRangeStart = this.pendingRangeStart;
    this.currentRangeDays = this.pendingRangeDays;
    this.applyDaysRange(this.currentRangeDays, this.currentRangeStart);
    this.rangeLabel = this.formatRangeLabel(this.currentRangeStart, this.currentRangeDays);
    this.refreshJobList();
    this.rangePopupRef.close();
  }

  onRangeSelectChange(args: any): void {
    const val = args.value;
    if (val === 'custom') {
      this.rangeInputsDisabled = false;
    } else {
      this.rangeInputsDisabled = true;
      this.pendingRangeDays = +val;
      this.pendingRangeStart = this.today;
      const end = new Date(this.today.getTime() + (this.pendingRangeDays - 1) * 24 * 60 * 60 * 1000);
      this.calendarRangeValue = [this.today, end];
    }
  }

  onCalendarRangeChange(args: any): void {
    const dates = args.value;
    if (dates) {
      this.rangeInputsDisabled = false;
      this.rangeSelectValue = 'custom';
      if (dates[0] && dates[1]) {
        const start = new Date(dates[0]);
        const end = new Date(dates[1]);
        this.pendingRangeStart = start;
        this.pendingRangeDays = Math.round((end.getTime() - start.getTime()) / (24 * 60 * 60 * 1000)) + 1;
      }
    }
  }

  goLive(): void {
    this.now = new Date();
    this.today = new Date(this.now.getFullYear(), this.now.getMonth(), this.now.getDate());
    this.currentRangeStart = this.today;
    this.applyDaysRange(this.currentRangeDays, this.today);
    this.rangeLabel = this.formatRangeLabel(this.today, this.currentRangeDays);
    setTimeout(() => this.calendarRef?.navigate(this.now));
    this.refreshJobList();
  }

  onEventCreated(args: any): void {
    if (args.action === 'externalDrop') {
      this.scheduledJobIds.push(args.event.id);
      const scheduledEvent = { ...args.event, status: 'scheduled', color: this.statusColors['scheduled'] };
      this.calendarRef.updateEvent(scheduledEvent);
      this.myEvents.push(scheduledEvent);
      setTimeout(() => {
        this.visibleJobs = this.visibleJobs.filter((j) => j.id !== args.event.id);
        this.jobListItems = this.jobListItems.filter((item) => item.type !== 'job' || item.job.id !== args.event.id);
      });
    }
    this.showToast(args.event.from + ' → ' + args.event.to + ' added');
  }

  onEventCreateFailed(args: any): void {
    const draggedEvent = args.event;
    const moved = this.moveToFirstAvailableSlot(draggedEvent, false);
    if (moved) {
      if (args.action === 'externalDrop') {
        setTimeout(() => {
          this.visibleJobs = this.visibleJobs.filter((j) => j.id !== args.event.id);
          this.jobListItems = this.jobListItems.filter((item) => item.type !== 'job' || item.job.id !== args.event.id);
        });
      }
      setTimeout(() => this.calendarRef?.navigateToEvent({ start: draggedEvent.start, resource: draggedEvent.resource }));
      this.showToast(draggedEvent.from + ' → ' + draggedEvent.to + ' added to first available slot');
    } else {
      this.showToast('No available slot found for ' + args.event.from + ' → ' + args.event.to);
    }
  }

  onEventUpdateFailed(args: any): void {
    const draggedEvent = args.event;
    const moved = this.moveToFirstAvailableSlot(draggedEvent, true);
    if (moved) {
      setTimeout(() => this.calendarRef?.navigateToEvent({ start: draggedEvent.start, resource: draggedEvent.resource }));
      this.showToast(draggedEvent.from + ' → ' + draggedEvent.to + ' moved to first available slot');
    } else {
      const originalEvent = args.oldEvent;
      setTimeout(() => this.calendarRef?.navigateToEvent({ start: originalEvent.start, resource: originalEvent.resource }));
      this.showToast('No available slot found for ' + args.event.from + ' → ' + args.event.to);
    }
  }

  onEventDragStart(args: any): void {
    const resourceToNavigate = this.invalidateResources(args.event);
    if (!args.event.resource) {
      if (resourceToNavigate && this.findFirstSlot(args.event)) {
        this.calendarRef.navigateToEvent({ start: args.event.start, resource: resourceToNavigate });
      } else {
        this.showToast('No available slot for: ' + args.event.from + ' → ' + args.event.to);
      }
    }
  }

  onEventDragEnd(): void {
    this.resetEventCreationFlags();
    this.myInvalids = [];
    this.filteredResources = this.computeFilteredResources();
    this.calendarInvalid = [...this.maintenanceInvalids];
  }

  onEventClick(args: any): void {
    if (args.event.status === 'actual') {
      const ev = args.event;
      const actualStart = new Date(ev.start);
      const scheduledDeparture = new Date(ev.pickup[0]);
      const departureDelay = Math.round((actualStart.getTime() - scheduledDeparture.getTime()) / 60000);
      let msg: string;
      if (ev.title === 'In progress') {
        msg =
          'Actual transport: departed ' +
          this.formatDelay(departureDelay) +
          ' · running ' +
          this.formatDuration(new Date().getTime() - actualStart.getTime());
      } else {
        const actualEnd = new Date(ev.end);
        const scheduledArrival = new Date(ev.drop[0]);
        const arrivalDelay = Math.round((actualEnd.getTime() - scheduledArrival.getTime()) / 60000);
        msg = 'Actual transport: departed ' + this.formatDelay(departureDelay) + ' · arrived ' + this.formatDelay(arrivalDelay);
      }
      this.notify.toast({ message: msg });
    }
  }

  onPageLoaded(args: any): void {
    this.currentViewStart = args.firstDay;
    this.currentViewEnd = args.lastDay;
  }
}
```

### Template

```html
<mbsc-page class="mds-dispatch-page">
  <div class="mds-dispatch-outer mbsc-flex-col">
    <div class="mds-dispatch-custom-header mbsc-flex">
      <mbsc-button variant="flat" (click)="openRangePopup()">
        <span class="mds-dispatch-range-label">{{ rangeLabel }}</span>
      </mbsc-button>
      <div class="mds-dispatch-header-right mbsc-flex">
        <div class="mds-dispatch-status-filter">
          <mbsc-segmented-group [(ngModel)]="statusFilters" select="multiple" (ngModelChange)="onStatusFilterChange()">
            <mbsc-segmented value="scheduled"
              ><span class="mds-dispatch-seg-dot mds-dispatch-seg-dot-scheduled"></span>Scheduled</mbsc-segmented
            >
            <mbsc-segmented value="in progress"
              ><span class="mds-dispatch-seg-dot mds-dispatch-seg-dot-inprogress"></span>In progress</mbsc-segmented
            >
            <mbsc-segmented value="completed"
              ><span class="mds-dispatch-seg-dot mds-dispatch-seg-dot-completed"></span>Completed</mbsc-segmented
            >
          </mbsc-segmented-group>
        </div>
        <div class="mds-dispatch-zoom mbsc-flex">
          <mbsc-button icon="minus" variant="flat" (click)="handleZoom(zoomLevel - 1)" [disabled]="zoomLevel === 1"></mbsc-button>
          <input
            type="range"
            min="1"
            max="5"
            [value]="zoomLevel"
            class="mds-dispatch-zoom-slider"
            (input)="handleZoom(+$any($event.target).value)"
          />
          <mbsc-button icon="plus" variant="flat" (click)="handleZoom(zoomLevel + 1)" [disabled]="zoomLevel === 5"></mbsc-button>
        </div>
        <mbsc-button variant="outline" startIcon="clock" class="mds-dispatch-now-btn" (click)="goLive()">Now</mbsc-button>
      </div>
    </div>
    <div class="mbsc-grid mbsc-no-padding mds-dispatch-content">
      <div class="mbsc-row mds-dispatch-full-height">
        <div class="mbsc-col-sm-3 mds-dispatch-full-height mds-dispatch-wrapper">
          <div class="mbsc-flex-col mbsc-flex-1-0 mbsc-padding">
            <ng-container *ngIf="visibleJobs.length === 0">
              <p class="mbsc-font mbsc-margin mbsc-medium mbsc-italic mbsc-txt-muted mds-dispatch-jobs-empty">No jobs for this period.</p>
            </ng-container>
            <ng-container *ngFor="let item of jobListItems">
              <div *ngIf="item.type === 'header'" class="mds-dispatch-job-day-header">{{ item.label }}</div>
              <div *ngIf="item.type === 'job'" mbsc-draggable [dragData]="item.job" class="mds-dispatch-jobs mbsc-flex">
                <div class="mds-dispatch-job-route">
                  <div class="mds-dispatch-job-stop mbsc-flex">
                    <span class="mds-dispatch-job-dot mds-dispatch-job-dot-origin"></span>
                    <span class="mds-dispatch-job-addr">{{ item.job.from }}</span>
                  </div>
                  <div class="mds-dispatch-job-connector"></div>
                  <div class="mds-dispatch-job-stop mbsc-flex">
                    <span class="mds-dispatch-job-dot mds-dispatch-job-dot-dest"></span>
                    <span class="mds-dispatch-job-addr">{{ item.job.to }}</span>
                  </div>
                </div>
                <div class="mds-dispatch-job-meta mbsc-flex-col mbsc-flex-none">
                  <span class="mds-dispatch-job-time">{{ formatTime(item.job.pickup[0]) }} – {{ formatTime(item.job.drop[1]) }}</span>
                  <span class="mds-dispatch-job-size">{{ item.job.size }} t</span>
                </div>
              </div>
            </ng-container>
          </div>
        </div>
        <div class="mbsc-col-sm-9 mds-dispatch-column mds-dispatch-full-height">
          <mbsc-eventcalendar
            #calendar
            class="mds-dispatch-calendar"
            [clickToCreate]="false"
            [dragToCreate]="false"
            [dragToResize]="false"
            [dragToMove]="true"
            [externalDrop]="true"
            [eventOverlap]="false"
            [refDate]="refDate"
            [zoomLevel]="zoomLevel"
            [view]="calView"
            [data]="calendarData"
            [resources]="filteredResources"
            [invalid]="calendarInvalid"
            [resourceTemplate]="resourceTemplate"
            [resourceEmptyTemplate]="resourceEmptyTemplate"
            [resourceHeaderTemplate]="resourceHeaderTemplate"
            [timelineEventContentTemplate]="eventContentTemplate"
            (onEventCreated)="onEventCreated($event)"
            (onEventCreateFailed)="onEventCreateFailed($event)"
            (onEventUpdateFailed)="onEventUpdateFailed($event)"
            (onEventDragStart)="onEventDragStart($event)"
            (onEventDragEnd)="onEventDragEnd()"
            (onEventClick)="onEventClick($event)"
            (onPageLoaded)="onPageLoaded($event)"
          ></mbsc-eventcalendar>
        </div>
      </div>
    </div>
  </div>

  <ng-template #resourceHeaderTemplate>
    <div class="mbsc-flex mbsc-align-items-center mbsc-font mds-dispatch-search">
      <mbsc-input
        class="mbsc-flex-1-1"
        type="text"
        inputStyle="outline"
        startIcon="material-search"
        autocomplete="off"
        placeholder="Search..."
        [(ngModel)]="searchQuery"
        (ngModelChange)="onSearchChange()"
      ></mbsc-input>
      <mbsc-button startIcon="material-filter-list" variant="outline" class="mbsc-flex-none" (click)="openFilterPopup($event)"
        >Filter</mbsc-button
      >
    </div>
  </ng-template>

  <ng-template #resourceTemplate let-resource>
    <div>
      <div class="mds-dispatch-name">
        {{ resource.name }}
        <span *ngIf="resource.name && resource.plate" class="mds-dispatch-plate">{{ resource.plate }}</span>
      </div>
      <div *ngIf="!resource.isParent && resource.name" class="mds-dispatch-status">
        <span class="mds-dispatch-status-dot" [style.backgroundColor]="getMaintenanceColor(resource)"></span>
        {{ getMaintenanceLabel(resource) }}
      </div>
    </div>
  </ng-template>

  <ng-template #resourceEmptyTemplate>
    <div class="mds-dispatch-empty mbsc-flex mbsc-align-items-center">
      <div class="mbsc-flex-1-1">
        <img src="https://img.mobiscroll.com/demos/filter-no-result.png" alt="Empty list" style="width: 100px" />
        <p class="mbsc-font mbsc-margin mbsc-medium mbsc-italic mbsc-txt-muted">No resources match your search.</p>
        <p class="mbsc-margin mbsc-medium mbsc-italic mbsc-txt-muted">Adjust your filters or try a different keyword.</p>
        <mbsc-button variant="outline" (click)="resetFilters()">Reset Filters</mbsc-button>
      </div>
    </div>
  </ng-template>

  <ng-template #eventContentTemplate let-data>
    <ng-container *ngIf="data.original.status === 'actual'; else plannedEvent">
      <span *ngIf="data.original.title === 'In progress'" class="mds-dispatch-actual-label">In progress</span>
    </ng-container>
    <ng-template #plannedEvent>
      <div class="mds-dispatch-event-content-wrapper mbsc-flex">
        <span class="mds-dispatch-event-route mbsc-flex-1-1">{{ data.original.from }} → {{ data.original.to }}</span>
        <span class="mds-dispatch-event-planned-badge"><span class="mds-dispatch-event-planned-badge-text">Planned</span></span>
      </div>
    </ng-template>
  </ng-template>

  <mbsc-popup
    #filterPopup
    [buttons]="filterPopupButtons"
    [contentPadding]="false"
    display="anchored"
    [focusOnClose]="false"
    [focusOnOpen]="false"
    [showOverlay]="false"
    [width]="400"
    [anchor]="filterAnchor"
  >
    <div class="mbsc-form-group">
      <div class="mbsc-form-group-title">Capacity</div>
      <div *ngFor="let res of myResources">
        <mbsc-checkbox [label]="res.name" [(ngModel)]="tempFilters[res.id]"></mbsc-checkbox>
      </div>
    </div>
    <div class="mbsc-form-group">
      <div class="mbsc-form-group-title">Operational Status</div>
      <mbsc-checkbox label="In maintenance/Maintenance planned" [(ngModel)]="tempFilters['maintenance']"></mbsc-checkbox>
      <mbsc-checkbox label="Operational" [(ngModel)]="tempFilters['operational']"></mbsc-checkbox>
    </div>
  </mbsc-popup>

  <mbsc-popup #rangePopup [responsive]="rangePopupResponsive">
    <div class="mds-dispatch-range-popup">
      <div class="mbsc-grid mbsc-no-padding">
        <div class="mbsc-row">
          <div class="mbsc-col-sm-4 mbsc-push-sm-8 mbsc-flex mbsc-flex-col">
            <div class="mds-dispatch-range-inputs">
              <mbsc-select
                label="Date range"
                labelStyle="stacked"
                inputStyle="box"
                [data]="rangeSelectorData"
                [(ngModel)]="rangeSelectValue"
                (onChange)="onRangeSelectChange($event)"
              ></mbsc-select>
              <div>
                <mbsc-input
                  #rangeStartInput
                  label="Start"
                  labelStyle="stacked"
                  inputStyle="box"
                  class="mds-dispatch-range-input"
                  [disabled]="rangeInputsDisabled"
                ></mbsc-input>
                <mbsc-input
                  #rangeEndInput
                  label="End"
                  labelStyle="stacked"
                  inputStyle="box"
                  class="mds-dispatch-range-input"
                  [disabled]="rangeInputsDisabled"
                ></mbsc-input>
              </div>
            </div>
            <div class="mds-dispatch-range-desktop-btns mbsc-button-group-justified">
              <mbsc-button (click)="applyPendingRange()">Apply</mbsc-button>
              <mbsc-button (click)="rangePopup.close()">Cancel</mbsc-button>
            </div>
          </div>
          <div class="mbsc-col-sm-8 mbsc-pull-sm-4">
            <mbsc-datepicker
              display="inline"
              [controls]="['calendar']"
              select="range"
              [showRangeLabels]="false"
              pages="auto"
              [showOnClick]="false"
              [showOnFocus]="false"
              [(ngModel)]="calendarRangeValue"
              [startInput]="rangeStartInput"
              [endInput]="rangeEndInput"
              (onChange)="onCalendarRangeChange($event)"
            ></mbsc-datepicker>
          </div>
        </div>
      </div>
    </div>
  </mbsc-popup>
</mbsc-page>
```

### CSS

```css
.mds-dispatch-calendar .mbsc-calendar-header {
  display: none;
}
.mds-dispatch-calendar .mbsc-timeline-resource-header {
  height: 100%;
  padding: 8px;
  box-sizing: border-box;
}
.mds-dispatch-calendar .mbsc-timeline-resource-col {
  width: 300px;
}
.mds-dispatch-calendar .mbsc-timeline-resource-title {
  height: 100%;
  box-sizing: border-box;
}
.mds-dispatch-calendar .mbsc-timeline-row:not(.mds-dispatch-actual-resource):not(.mbsc-timeline-parent) {
  height: 58px;
}
.mds-dispatch-page {
  height: 100%;
}
.mds-dispatch-calendar .mds-dispatch-actual-resource {
  height: 8px !important;
  min-height: 0 !important;
}
.mbsc-timeline-row:has(+ .mds-dispatch-actual-resource) {
  border-bottom: none;
}
.mds-dispatch-actual-resource .mbsc-timeline-event {
  height: 10px;
  margin-top: -7px;
}
.mds-dispatch-actual-resource .mbsc-timeline-event-background {
  margin: 0;
}
.mds-dispatch-calendar .mbsc-timeline-parent {
  height: 34px;
}
.mds-dispatch-calendar .mbsc-timeline-parent .mbsc-timeline-invalid {
  display: none;
}
.mds-dispatch-calendar .mbsc-timeline-parent .mbsc-timeline-column {
  border: 0;
}
.mds-dispatch-calendar .mbsc-timeline-row-gutter {
  height: 6px;
}
.mds-dispatch-search .mbsc-textfield-wrapper {
  margin: 0;
}
.mds-dispatch-search .mbsc-textfield-wrapper.mbsc-ltr {
  margin-right: 8px;
}
.mds-dispatch-search .mbsc-textfield-wrapper.mbsc-rtl {
  margin-left: 8px;
}
.mds-dispatch-search .mbsc-textfield-wrapper.mbsc-material {
  margin-top: 2px;
}
.mds-dispatch-search .mbsc-textfield {
  height: 36px;
  padding: 0 8px 0 38px;
}
.mds-dispatch-search .mbsc-textfield-icon {
  top: 50%;
  left: 8px;
  font-size: 20px;
  height: 24px;
  line-height: 24px;
  margin-top: -12px;
}
.mds-dispatch-search .mbsc-button {
  margin: 0;
  height: 36px;
  font-size: 14px;
}
.mds-dispatch-actual-event .mbsc-schedule-event-range,
.mds-dispatch-actual-event .mbsc-schedule-event-bar,
.mds-dispatch-actual-event .mbsc-schedule-event-title,
.mds-dispatch-actual-event .mbsc-schedule-event-time,
.mds-dispatch-actual-event .mbsc-timeline-event-time {
  display: none;
}
.mds-dispatch-disabled-row.mbsc-schedule-invalid {
  background: rgba(128, 128, 128, 0.2);
}
.mds-dispatch-maintenance-invalid.mbsc-schedule-invalid {
  background: repeating-linear-gradient(
    -45deg,
    rgba(128, 128, 128, 0.12),
    rgba(128, 128, 128, 0.12) 11px,
    rgba(128, 128, 128, 0.28) 11px,
    rgba(128, 128, 128, 0.28) 22px
  );
}
.mds-dispatch-pulse:not(.mbsc-schedule-event-hover) .mbsc-timeline-event-background {
  box-shadow: 0 0 0 rgba(249, 115, 22, 0.4);
  animation: pulse 2s infinite;
}
.mds-dispatch-now-btn.mbsc-ios {
  padding-top: 0;
  padding-bottom: 0;
}
.mds-dispatch-seg-dot {
  content: '';
  display: inline-block;
  width: 8px;
  height: 8px;
  border-radius: 50%;
  margin-right: 5px;
  vertical-align: middle;
}
.mds-dispatch-seg-dot-scheduled {
  background: #2196f3;
}
.mds-dispatch-seg-dot-inprogress {
  background: #f97316;
}
.mds-dispatch-seg-dot-completed {
  background: #78909c;
}
.mbsc-ios-dark .mds-dispatch-custom-header,
.mbsc-material-dark .mds-dispatch-custom-header,
.mbsc-ios-dark .mds-dispatch-wrapper,
.mbsc-material-dark .mds-dispatch-wrapper {
  background-color: #000;
}
.mbsc-windows-dark .mds-dispatch-custom-header,
.mbsc-windows-dark .mds-dispatch-wrapper {
  background-color: #1f1f1f;
}
.mds-dispatch-range-popup .mbsc-datepicker-inline {
  border: none;
  border-radius: 20px;
  overflow: hidden;
}
.mds-dispatch-range-popup .mbsc-textfield-wrapper-box {
  margin-top: 0;
  margin-right: 0;
}
.mds-dispatch-range-desktop-btns.mbsc-button-group-justified,
.mds-dispatch-range-desktop-btns.mbsc-button-group-justified button {
  margin-bottom: 0;
}
.mds-dispatch-content > .mbsc-row {
  height: 100%;
}
.mds-dispatch-calendar.mbsc-eventcalendar .mbsc-calendar-wrapper {
  border: none;
}
@media (max-width: 575px) {
  .mds-dispatch-range-desktop-btns {
    display: none;
  }
  .mds-dispatch-range-popup .mbsc-textfield-wrapper-box {
    margin-left: 0;
  }
}
/* --- Demo styles --- */
.mds-dispatch-full-height {
  height: 100%;
}
.mds-dispatch-column {
  border-left: 1px solid #ccc;
}
.mds-dispatch-wrapper {
  overflow: auto;
  background-color: #fff;
}
.mds-dispatch-job-day-header {
  font-family:
    -apple-system,
    Segoe UI,
    Roboto,
    sans-serif;
  font-size: 11px;
  font-weight: 600;
  text-transform: uppercase;
  letter-spacing: 0.5px;
  color: #6b7280;
  padding: 10px 2px 4px;
}
.mds-dispatch-job-day-header:first-child {
  padding-top: 2px;
}
.mds-dispatch-jobs {
  align-items: center;
  gap: 8px;
  margin: 4px 0;
  padding: 6px 10px;
  touch-action: none;
  color: #fff;
  background-color: #488dc5;
  border-radius: 8px;
  font-family:
    -apple-system,
    Segoe UI,
    Roboto,
    sans-serif;
  font-size: 12px;
  cursor: grab;
}
.mds-dispatch-job-route {
  flex: 1 1 0;
  min-width: 0;
}
.mds-dispatch-job-stop {
  align-items: center;
  gap: 6px;
}
.mds-dispatch-job-dot {
  flex: 0 0 8px;
  width: 8px;
  height: 8px;
  border-radius: 50%;
  border: 2px solid #fff;
}
.mds-dispatch-job-dot-origin {
  background: transparent;
}
.mds-dispatch-job-dot-dest {
  background: #fff;
}
.mds-dispatch-job-addr {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  line-height: 1.5;
}
.mds-dispatch-job-connector {
  width: 2px;
  height: 5px;
  background: rgba(255, 255, 255, 0.4);
  margin-left: 3px;
}
.mds-dispatch-job-meta {
  align-items: flex-end;
  gap: 3px;
  font-size: 11px;
  opacity: 0.9;
}
.mds-dispatch-job-size {
  background: rgba(255, 255, 255, 0.2);
  border-radius: 10px;
  padding: 1px 7px;
  font-weight: 600;
}
.mds-dispatch-actual-event {
  height: 20px;
}
.mds-dispatch-actual-label {
  font-size: 9px;
  font-weight: 600;
  white-space: nowrap;
  opacity: 0.9;
  line-height: 1;
}
@keyframes pulse {
  0% {
    box-shadow: 0 0 0 0 rgba(249, 115, 22, 0.4);
  }
  70% {
    box-shadow: 0 0 0 8px rgba(249, 115, 22, 0);
  }
  100% {
    box-shadow: 0 0 0 0 rgba(249, 115, 22, 0);
  }
}
.mds-dispatch-event-content-wrapper {
  width: 100%;
  height: 100%;
  align-items: center;
  gap: 5px;
  overflow: hidden;
}
.mds-dispatch-event-route {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.mds-dispatch-event-planned-badge {
  flex-shrink: 100;
  min-width: 0;
  overflow: hidden;
}
.mds-dispatch-event-planned-badge-text {
  font-size: 10px;
  padding: 0 5px;
  border-radius: 4px;
  background: rgba(255, 255, 255, 0.3);
  white-space: nowrap;
  display: block;
}
.mds-dispatch-search {
  height: 100%;
}
.mds-dispatch-name {
  font-size: 14px;
  font-weight: bold;
  margin-bottom: 5px;
}
.mds-dispatch-plate {
  border: 1px solid #488dc5;
  border-radius: 4px;
  margin: 0 5px;
  padding: 0 5px;
}
.mds-dispatch-status-dot {
  display: inline-block;
  width: 10px;
  height: 10px;
  border-radius: 50%;
  margin-right: 5px;
}
.mds-dispatch-status {
  font-size: 13px;
  font-weight: normal;
}
.mds-dispatch-empty {
  height: 100%;
  text-align: center;
}
.mds-dispatch-header-right {
  align-items: center;
  gap: 16px;
  margin-left: auto;
}
.mds-dispatch-status-filter.mbsc-ios {
  width: 300px;
}
.mds-dispatch-zoom {
  align-items: center;
  gap: 6px;
}
.mds-dispatch-zoom-slider {
  width: 80px;
  cursor: pointer;
}
.mds-dispatch-outer {
  height: 100%;
}
.mds-dispatch-custom-header {
  align-items: center;
  flex-shrink: 0;
  height: 52px;
  padding: 0 12px;
  border-bottom: 1px solid #ccc;
  gap: 12px;
  background-color: #fff;
}
.mds-dispatch-range-label {
  font-size: 20px;
  font-weight: bold;
}
.mds-dispatch-range-inputs {
  flex: 1;
}
.mds-dispatch-content {
  flex: 1 1 0;
  min-height: 0;
}
```

## Implementation notes

- Use `type: 'day'` with a `size` equal to the active day count, `timeCellStep: 60`, `timeLabelStep: 60`, `eventHeight: 'variable'`, and a `zoomLevels` map (keys 1-5) where each level sets a `columnWidth` (`'xsmall'` through `'xlarge'`) and its own `timeCellStep`/`timeLabelStep` values. Pass the active `zoomLevel` state as a prop to the `Eventcalendar`.
- Define resources as a two-level tree of capacity tier groups (`eventCreation: false`) with truck leaf nodes beneath them. For each truck, add a parallel `{id}-actual` sibling row (`eventCreation: false`, custom `cssClass`) to display live trip progress separately from the plan. Give each truck custom `capacity`, `plate`, and optional `maintenanceFrom`/`maintenanceTo` properties.
- Store each transport job with `from`, `to`, `size`, `pickup: [earliest, latest]`, `drop: [earliest, latest]`, and `status`. Derive `start = pickup[0]`, `end = drop[0]`, and `title` from the route. Keep scheduled events in a `myEventsRef` and unscheduled sidebar jobs in a separate `externalEventsRef`.
- In `addActualEvents`, generate a companion event on the `{id}-actual` row for every in-progress trip (set `end` to `now`, add a pulse CSS class) and every completed trip. Call this function on mount and repeat every 60 seconds in a `setInterval`.
- Render each sidebar job card with a ref-callback to obtain the DOM element, then mount a `Draggable` with `dragData={job}` and `element={elem}`. Filter the sidebar list to jobs within the current date range, whose cargo fits the maximum visible truck capacity, that have not yet been scheduled, and whose pickup is at least 2 hours from now.
- Set `externalDrop={true}`, `dragToMove={true}`, and `eventOverlap={false}` on the `Eventcalendar`. Disable `clickToCreate`, `dragToCreate`, and `dragToResize`.
- In `onEventDragStart`, set `eventCreation: false` on every truck that is over-capacity or has an overlapping scheduled event within the dragged job's `pickup[0]`-`drop[1]` window. Build three `invalid` segments: the period before the pickup window (all resources), the pickup-to-drop window restricted to the invalid truck IDs, and the period after the drop window. Combine these with the static maintenance invalids when setting `calendarInvalid`.
- In `onEventDragEnd`, reset `eventCreation: true` on all trucks, clear the drag-time invalids, and restore `calendarInvalid` to maintenance invalids only.
- In `onEventCreated`, only act when `args.action === 'externalDrop'`: add the job ID to `scheduledJobIdsRef`, apply the scheduled color and status by replacing the event in place in the array bound to `data` (the `Eventcalendar` React ref only exposes `getEvents`/`getInvalids`/`getViewDate`/`navigateToEvent` - it has no `updateEvent`/`addEvent`; JS/jQuery: call `inst.updateEvent()` for the imperative-only equivalent), remove the job from the sidebar list, and show a `Toast`.
- In both `onEventCreateFailed` and `onEventUpdateFailed`, call a shared `findFirstSlot` function that searches within `pickup[0]`-`drop[1]`, advancing past any truck maintenance window. If a slot is found, splice/replace the job into the array bound to `data` (add for create, replace for update) - the React ref exposes no `addEvent`/`updateEvent`; JS/jQuery: call `inst.addEvent()`/`inst.updateEvent()` for the imperative-only equivalent - then call `navigateToEvent` (this method IS available on the React ref) and show a success `Toast`; if none is found, show an error `Toast` (and for `onEventUpdateFailed`, navigate back to the original event position).
- Use `renderTimelineEventContent` (Angular: `timelineEventContentTemplate`, Vue: `#timelineEventContent` slot) to render event bodies: show a route string and a "Planned" badge for scheduled events, a pulsing "In progress" label for actual in-progress events, and `null` for completed actual events. In `onEventClick`, show a `Toast` with departure delay and elapsed or arrival time when the clicked event has `status: 'actual'`.
- Use `renderResource` (Angular: `resourceTemplate`, Vue: `#resource` slot) to display the truck name, license plate, and a color-coded maintenance status dot for leaf nodes (operational/maintenance-planned/in-maintenance). Use `renderResourceHeader` (Angular: `resourceHeaderTemplate`, Vue: `#resourceHeader` slot) for a search `Input` and a Filter `Button`. Use `renderResourceEmpty` (Angular: `resourceEmptyTemplate`, Vue: `#resourceEmpty` slot) for a no-results placeholder with a Reset Filters button.
- Build the toolbar outside the `Eventcalendar` as a custom header div. Include a flat `Button` showing the current date-range label that opens the range `Popup`, a `SegmentedGroup` with `select="multiple"` for filtering by Scheduled/In Progress/Completed status, a native `<input type="range" min="1" max="5">` flanked by minus and plus `Button` controls for zoom, and a "Now" `Button` that resets `refDate` to today and navigates to the current time.
- Use a `Popup` with a `responsive` config (bottom sheet on mobile, wide anchored popup on desktop) for range selection. Inside, place a `Select` for preset ranges (7/14/30/60/90 days or Custom), a `Datepicker` in range mode, and `Input` fields for custom start and end dates that are disabled unless "Custom" is selected. Apply the selection with an "Apply" button.
- Use a `Popup` anchored to the Filter button for the filter panel. Render two `Checkbox` groups - one for capacity tiers and one for operational status - using a temp filter state: copy active filters on open, commit on Apply, and discard on cancel.

## Run it in your project

1. If not signed up yet, or don't own a license, you can [start a free trial](https://mobiscroll.com/starttrial).

2. Clone the repository:

   ```
   git clone https://github.com/acidb/mobiscroll-demos-angular.git
   ```

3. If not installed yet, install the Mobiscroll CLI from NPM:

   ```
   npm install -g @mobiscroll/cli
   ```

4. Config Mobiscroll - open a terminal window in the root directory and run:

   ```
   mobiscroll config angular
   ```

5. Install dependencies - open a terminal window in the root directory and run:

   ```
   npm install
   ```

6. Run the project:

   ```
   ng serve
   ```

On a trial, add `--trial` to the config command: `mobiscroll config angular --trial`.

Running a demo locally requires a Mobiscroll trial or a license; setup is per framework at https://mobiscroll.com/docs/angular/getting-started/installation

## Related demos

- Previous: [Drag People onto Events](https://demo.mobiscroll.com/angular/timeline/drop-assignee-on-event-from-list.md) - Build a team assignment interface on the Angular Timeline — drag people from an external list onto meetings with conflict validation.
