	@section('header')
		<meta name="csrf-token" content="{{ csrf_token() }}">
		<meta name="task-id" content="{{ $task->id }}">
		<meta name="user-extension" content="{{ App\Modules\ThreeCX\Services\ThreeCXExtensionResolver::getExtensionForUser() }}">
		
		{{-- 3CX Call Modal CSS --}}
		<link href="{{ asset('css/threecx-call-modal.css') }}" rel="stylesheet">
		
		@include('common.header')
	@stop

	@section('js')
		@parent

		<script src="{{ asset('js/typeahead.min.js') }}"></script>
		
		<!-- 3CX Call Integration - Auto-loaded via app.js → threecx/autoload.js -->
		<script src="{{ asset('js/directives/call-history.js') }}"></script>
		
		<!-- Initialize 3CX Core for task context -->
		<script>
		document.addEventListener('DOMContentLoaded', function() {
			if (window.ThreeCXCore) {
				// Set context to 'task' so it uses ThreeCXController endpoints
				window.ThreeCXCore.setContext('task');
				console.log('3CX Core initialized for task context');
			}
		});
		</script>

		<!-- Global SMTP CC/BCC Settings for mailto URLs -->
		<script>
		@php
			$smtpSettings = \App\Modules\Admin\EmailSettings::whereNotNull('smtp_host')
				->whereNotNull('smtp_username')
				->whereNotNull('smtp_password')
				->first();
			$smtpCc = $smtpSettings ? ($smtpSettings->smtp_cc ?: '') : '';
			$smtpBcc = $smtpSettings ? ($smtpSettings->smtp_bcc ?: '') : '';
		@endphp
		window.globalSmtpSettings = {
			cc: @json($smtpCc),
			bcc: @json($smtpBcc)
		};
		</script>

		<script type="text/ng-template" id="widgets/comments.html">
			@include('bookings::templates.comments')
		</script>
		<script type="text/ng-template" id="clients/templates/widget.html">
			@include('clients::widget')
		</script>
		<script type="text/ng-template" id="widgets/parts.html">
			@include('bookings::templates.parts')
		</script>
		<script type="text/ng-template" id="widgets/builds.html">
			@include('bookings::templates.builds')
		</script>
		<script type="text/ng-template" id="widgets/customer-notifications.html">
			@include('bookings::templates.customer-notifications')
		</script>
		<script type="text/ng-template" id="widgets/attachments.html">
			@include('bookings::templates.attachments')
		</script>
		<script type="text/ng-template" id="widgets/project-tasks.html">
			@include('bookings::templates.project-tasks')
		</script>
		<script type="text/ng-template" id="widgets/templates.html">
			@include('bookings::templates.templates')
		</script>
		<script type="text/ng-template" id="modals/change-dates.html">
			@include('bookings::templates.modals.change-dates')
		</script>
		<script type="text/ng-template" id="modals/change-alarm.html">
			@include('bookings::templates.modals.change-alarm')
		</script>
		<script type="text/ng-template" id="bookings/repairs/devices.html">
			@include('bookings::templates.devices')
		</script>
		<script type="text/ng-template" id="modals/subscribers.html">
			@include('bookings::templates.modals.subscribers')
		</script>
		<script type="text/ng-template" id="bookings/modals/device.html">
			@include('bookings::templates.modals.device')
		</script>
		<script type="text/ng-template" id="widgets/task-passwords.html">
			@include('bookings::templates.task-passwords')
		</script>
		<script type="text/ng-template" id="clients/modals/keychain.html">
			@include('clients::templates.modals.keychain')
		</script>
		<script type="text/ng-template" id="bookings/modals/promote.html">
			@include('bookings::templates.modals.promote')
		</script>

		<script type="text/ng-template" id="bookings/time-tracking.html">
			@include('bookings::templates.time-tracking')
		</script>
		<script type="text/ng-template" id="bookings/followup-task.html">
			@include('bookings::templates.followup-task')
		</script>
		<script type="text/ng-template" id="bookings/qa-task.html">
			@include('bookings::templates.qa-task')
		</script>
		<script type="text/ng-template" id="bookings/pickup-task.html">
			@include('bookings::templates.pickup-task')
		</script>
		<script type="text/ng-template" id="bookings/delivery-task.html">
			@include('bookings::templates.delivery-task')
		</script>


		@include('bookings::templates.modals.related-tasks-modal')
		@include('templates.modals.no-price-confirmation')
		@include('bookings::templates.modals.followup-declined-modal')
		@include('bookings::templates.modals.qa-declined-modal')
		@include('bookings::templates.modals.cancelled-reason-modal')
		@include('bookings::templates.modals.followup-aproved-modal')
		@include('bookings::templates.modals.qa-aproved-modal')
		@include('bookings::templates.modals.new-customer-notification')
		@include('bookings::templates.modals.dedicated-time-modal')
		@include('bookings::templates.modals.history')

		<script>
		// Debug script to check if functions exist
		$(document).ready(function() {
			// Page ready
		});
		</script>

	@stop

	@section('content')
		<div ng-controller="TasksCtrl" ng-init="taskId = '{!! $task->id !!}'" ng-cloak>
			<span ng-init="severities = {{ json_encode($severities) }}"></span>
			<span ng-init="statuses = {{ $statuses }}"></span>
			<span ng-init="users = {{ $users }}"></span>
			<span ng-init="subtypes = {{ App\Modules\Bookings\TaskSubtype::support()->get() }}"></span>
			<span ng-init="standard_prices = {{ App\Models\StandardPrice::all() }}"></span>
			<span ng-init="shelf_types = {{ json_encode(App\Modules\Bookings\Task::getShelfTypes()) }}"></span>

			<div class="navbar navbar-default task-navbar" data-spy="affix" data-offset-top="50">
				<div class="container-fluid">
					<!-- Brand and toggle get grouped for better mobile display -->
					<div class="navbar-header">
						<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#task-navbar-collapse-1" aria-expanded="false">
							<span class="sr-only">Toggle navigation</span>
							<span class="icon-bar"></span>
							<span class="icon-bar"></span>
							<span class="icon-bar"></span>
						</button>
						<span class="navbar-brand">
							{!! $task->id !!} - <span editable-text="data.title" onaftersave="save()">{[{ data.title }]}</span> <span class="label label-danger">{[{ data.client.contract.name }]}</span>
							{{-- Progress indicator near title --}}
							<span id="title-progress" style="display: none; margin-left: 10px;">
								<i class="fa fa-spinner fa-spin text-warning"></i> 
								<small id="title-progress-text" class="text-warning"><strong>Saving...</strong></small>
							</span>
						</span>
					</div>

					<!-- Collect the nav links, forms, and other content for toggling -->
					<div class="collapse navbar-collapse" id="task-navbar-collapse-1">
						<ul class="nav navbar-nav navbar-form navbar-right">
							<li>
								<span class="lead animated flash" ng-show="modified">modified</span>
							</li>
							@if ( ! $task->project_id)
								<li><span data-promote-project-btn="{!! $task->id !!}" data-redirect-url="{!! URL::to('projects') !!}"></span></li>
							@else
								<li>@include('bookings::templates.tasks_projects_header')</li>
							@endif
							<li><button class="btn btn-warning" ng-click="save()">Save changes</button>&nbsp;</li>
							<li>
								<div class="btn-group">
									<a class="btn btn-default dropdown-toggle" data-toggle="dropdown" href="#" eat-click="">
										<i class="fa fa-print"></i> Print
										<span class="caret"></span>
									</a>
									<ul class="dropdown-menu pull-right text-left">
										<!-- dropdown menu links -->
										<li><a href="{!! URL::to('tasks/'.$task->id.'/print-view') !!}" tabindex="-1">Print View</a></li>
										<li><a href="{!! URL::to('tasks/'.$task->id.'/print-report') !!}" tabindex="-1">Print Report</a></li>
									</ul>
								</div>
							</li>
							<li>
								<span class="btn btn-default go-top" ng-click="scrollTop()"><i class="fa fa-arrow-up"></i></span>
							</li>
						</ul>
					</div>
				</div>
			</div>

			{{--Directives that includes the page title, and the header (title and save and preview options) depending on the type of task (QA/Followup/Others)--}}

			@if (isset($followup))
				<div followup-task data-followup-id="{!! $followup->id !!}" data-task="data" data-users="users" ></div>
			@endif

			@if (isset($qa))
				<div qa-task data-qa-id="{!! $qa->id !!}" data-task="data" data-users="users" data-load-data="loadData()" ></div>
			@endif

			@if ($task->needs_pickup && $task->pickup_by && !$task->picked_up_at && ($task->pickup_by == Auth::id() || Auth::user()->hasPermission('admin')))
				<div pickup-task data-task="data" data-users="users"></div>
			@endif

			@if ($task->needs_delivery && $task->delivered_by && $task->delivered != 1 && ($task->delivered_by == Auth::id() || Auth::user()->hasPermission('admin')))
				<div delivery-task data-task="data" data-users="users"></div>
			@endif

			<div class="widget widget-classic task-beta">
				<div class="widget-content">

					{{-- Initial loading indicator DISABLED --}}
					{{-- 
					<div id="initial-loading" class="alert alert-info" style="margin: 20px; border-left: 4px solid #1f4e79; background-color: #d6ebf5; border-color: #5bc0de;">
						<div style="color: #1f4e79;">
							<i class="fa fa-spinner fa-spin" style="margin-right: 8px;"></i> 
							<strong>Please wait, all task details are loading...</strong>
							<button id="close-loading" class="btn btn-xs btn-link pull-right" title="Hide this message" style="color: #1f4e79;">
								<i class="fa fa-times"></i>
							</button>
							<br>
							<small style="color: #5a6c7d; margin-top: 5px; display: block;">Initializing page components...</small>
						</div>
					</div>
					--}}

					{{-- The layout will be split into 2 columns --}}
					<div class="row">
						<div class="col-sm-7">
							<!-- Progress indicator overlay - positioned prominently -->
							<div ng-show="isUpdating" class="alert alert-info" style="position: relative; z-index: 1000; margin-bottom: 15px; border-left: 4px solid #5bc0de; background-color: #d9edf7; color: #31708f;">
								<i class="fa fa-spinner fa-spin" style="margin-right: 8px;"></i> <strong>Saving changes...</strong>
							</div>
							
							<div class="headline">
								<h4><i class="fa fa-tag"></i> Details</h4>
							</div>

							<div class="alert alert-danger" ng-show="data.no_price_reason">
								<i class="fa fa-exclamation-triangle"></i> Reason for not having a price:
								<span editable-text="data.no_price_reason" onaftersave="save()"> {[{ data.no_price_reason }]}</span>
								<span ng-show="history.no_price_reasons.length > 1" ng-click="showHistory('Reason for not having price history', history.no_price_reasons)" class="pull-right"><i class="fa fa-history"></i></span>

							</div>
							<div class="alert alert-danger" ng-show="data.status_id == '8'">
								<i class="fa fa-exclamation-triangle"></i> Cancellation reason:
								<span editable-text="data.cancelled_reason" onaftersave="save()" > {[{ data.cancelled_reason }]}</span>
								<span ng-show="history.cancelled_reasons.length > 1" ng-click="showHistory('Cancellation reasons history', history.cancelled_reasons)" class="pull-right"><i class="fa fa-history"></i></span>

							</div>

							<div class="row">
								<div class="col-sm-9">
									<div class="row task-list">
										<div class="col-sm-4 task-details-block">
											<label class="task-label">Status:</label>
											<div class="text-info dropdown">
												<a href="#" data-toggle="dropdown" data-eat-click><span class="editable editable-click">{[{ data.status.name }]}</span></a>
												<ul class="dropdown-menu dropdown-menu-arrow">
													<li ng-if=" status.private == '0' || data.completed == '1' " ng-repeat="status in statuses" ng-class="{active: data.status_id == status.id}"><a tabindex="-1" href="#" ng-click="updateStatus(status.id)" ng-bind="status.name" data-eat-click></a></li>
												</ul>
											</div>
										</div>
										<div class="col-sm-4 task-details-block">
											<label class="task-label">Assigned to:</label>
											<div class="text-info dropdown">
												<a href="#" data-toggle="dropdown" data-eat-click><span class="editable editable-click">{[{ data.user.name || 'No one' }]}</span></a>
												<ul class="dropdown-menu dropdown-menu-arrow">
													<li class="disabled"><a href="#"><b>Assign to:</b></a></li>
													<li>
														<ul class="dropdown-menu scroll-menu">
															<li ng-class="{active: !data.assigned_to}"><a tabindex="-1" href="#" ng-confirm-click="Are you sure you want to unassign thes job and place it back in the queue?" confirmed-click="unassign()" class="text-warning">No one - Queue</a></li>
															<li ng-repeat="user in users" ng-class="{active: data.assigned_to == user.id}"><a tabindex="-1" href="#" ng-click="updateValue({assigned_to: user.id})" ng-bind="user.name" data-eat-click></a></li>
														</ul>
													</li>
												</ul>
											</div>
										</div>
										<div class="col-sm-4 task-details-block">
											<label class="task-label">Severity:</label>
											<div class="text-info dropdown">
												<a href="#" data-toggle="dropdown" data-eat-click><span class="editable editable-click">{[{ getSeverityDisplay(data.severity_id) }]}</span></a>
												<ul class="dropdown-menu dropdown-menu-arrow">
													<li ng-repeat="(id, name) in severities" ng-class="{active: data.severity_id == id}"><a tabindex="-1" href="#" ng-click="updateValue({severity_id: id})" ng-bind="name" data-eat-click></a></li>
												</ul>
											</div>
										</div>
										@if ($task->type == 'repair')
											<div class="col-sm-4 task-details-block">
												<label class="task-label">Prebook:</label>
												<div>
													<span class="text-info dropdown">
														<a href="#" data-toggle="dropdown" data-eat-click><span class="editable editable-click">{[{ getBooleanDisplay(data.prebook) }]}</span></a>
														<ul class="dropdown-menu dropdown-menu-arrow">
															<li ng-repeat="option in boolean_options" ng-class="{active: data.prebook == option.value}"><a tabindex="-1" href="#" ng-click="setPrebook(option.value)" ng-bind="option.name" data-eat-click></a></li>
														</ul>
													</span>
													<span ng-show="data.prebook == '1'" ng-model="prebook_date" bs-datepicker data-date-format="DD-MM-YYYY"><i class="fa fa-calendar"></i> {[{ (data.prebook_date | date:"dd/MM/yyyy") || 'empty' }]}</span>
												</div>
											</div>
										@endif
										@if ($task->type == 'repair')
											<div class="col-sm-4 task-details-block">
												<label class="task-label">Needs pickup:</label><br/>
												<div class="text-info dropdown" style="display: inline-block;">
													<a href="#" data-toggle="dropdown" data-eat-click><span class="editable editable-click">{[{ getBooleanDisplay(data.needs_pickup) }]}</span></a>
													<ul class="dropdown-menu dropdown-menu-arrow">
														<li ng-repeat="option in boolean_options" ng-class="{active: data.needs_pickup == option.value}"><a tabindex="-1" href="#" ng-click="updateValue({needs_pickup: option.value})" ng-bind="option.name" data-eat-click></a></li>
													</ul>
												</div>
												<div class="text-info dropdown" ng-if="data.needs_pickup == '1'" style="display: inline-block; margin-left: 5px;">
													<a href="#" data-toggle="dropdown" data-eat-click><span class="editable editable-click"><span class="text-warning">By:</span> {[{ getUserName(data.pickup_by) }]}</span></a>
													<ul class="dropdown-menu dropdown-menu-arrow">
														<li class="disabled"><a href="#"><b>Pickup by:</b></a></li>
														<li>
															<ul class="dropdown-menu scroll-menu">
																<li ng-repeat="user in users" ng-class="{active: data.pickup_by == user.id}"><a tabindex="-1" href="#" ng-click="updateValue({pickup_by: user.id})" ng-bind="user.name" data-eat-click></a></li>
															</ul>
														</li>
													</ul>
												</div>
											</div>
											<div class="col-sm-4 task-details-block">
												<label class="task-label">Needs delivery:</label><br/>
												<div class="text-info dropdown" style="display: inline-block;">
													<a href="#" data-toggle="dropdown" data-eat-click><span class="editable editable-click">{[{ getBooleanDisplay(data.needs_delivery) }]}</span></a>
													<ul class="dropdown-menu dropdown-menu-arrow">
														<li ng-repeat="option in boolean_options" ng-class="{active: data.needs_delivery == option.value}"><a tabindex="-1" href="#" ng-click="updateValue({needs_delivery: option.value})" ng-bind="option.name" data-eat-click></a></li>
													</ul>
												</div>
												<div class="text-info dropdown" ng-if="data.needs_delivery == '1'" style="display: inline-block; margin-left: 5px;">
													<a href="#" data-toggle="dropdown" data-eat-click><span class="editable editable-click"><span class="text-warning">By:</span> {[{ getUserName(data.delivered_by) }]}</span></a>
													<ul class="dropdown-menu dropdown-menu-arrow">
														<li class="disabled"><a href="#"><b>Deliver by:</b></a></li>
														<li>
															<ul class="dropdown-menu scroll-menu">
																<li ng-repeat="user in users" ng-class="{active: data.delivered_by == user.id}"><a tabindex="-1" href="#" ng-click="updateValue({delivered_by: user.id})" ng-bind="user.name" data-eat-click></a></li>
															</ul>
														</li>
													</ul>
												</div>
											</div>
										@endif
										@if ($task->type == 'repair')
											<div class="col-sm-4 task-details-block">
												<label class="task-label">Repair type:</label>
												<div class="text-info dropdown">
													<a href="#" data-toggle="dropdown" data-eat-click><span class="editable editable-click">{[{ getStandardPriceDisplay(data.standard_price_id) }]}</span></a>
													<ul class="dropdown-menu dropdown-menu-arrow">
														<li ng-repeat="price in standard_prices" ng-class="{active: data.standard_price_id == price.id}"><a tabindex="-1" href="#" ng-click="updateValue({standard_price_id: price.id})" ng-bind="price.name" data-eat-click></a></li>
													</ul>
												</div>
											</div>
										@endif
										@if ($task->type == 'onsite')
											<div class="col-sm-4 task-details-block">
												<label class="task-label">Calendar visit:</label>
												<div><a href="#" ng-click="changeDates()" data-eat-click>{[{ data.onsite_start | date:"dd/MM/yyyy HH:mm" }]}</a> to <a href="#" ng-click="changeDates()" data-eat-click>{[{ data.onsite_end | date:"dd/MM/yyyy HH:mm" }]}</a></div>
											</div>
										@endif
										@if ($task->type == 'repair')
											<div class="col-sm-4 task-details-block">
												<label class="task-label">Return / Old job id:</label>
												<div class="text-info" editable-text="data.return_id" onaftersave="save()"><span>{[{ data.return_id || 'Not a return' }]}</span></div>
											</div>
										@endif
										@if ($task->type == 'repair')
											<div class="col-sm-4 task-details-block">
												<label class="task-label">Shelf/Slot:</label>
												<div>
													<span class="text-info dropdown">
														<a href="#" data-toggle="dropdown" data-eat-click><span class="editable editable-click">{[{ getShelfTypeDisplay(data.shelf_type) }]}</span></a>
														<ul class="dropdown-menu dropdown-menu-arrow">
															<li ng-repeat="(id, shelf) in shelf_types" ng-class="{active: data.shelf_type == id}"><a tabindex="-1" href="#" ng-click="updateValue({shelf_type: id})" ng-bind="shelf" data-eat-click></a></li>
														</ul>
													</span>
													<span class="text-info" editable-text="data.shelf" onaftersave="save()" e-max-length="2"><span>&nbsp;&nbsp;{[{ data.shelf || 'Not set' }]}</span></span>
												</div>
											</div>
										@endif
										@if ($task->type == 'support')
											<div class="col-sm-4 task-details-block">
												<label class="task-label">Time spent:</label>
												<div class="text-info" editable-text="data.formatedTimeSpent" onaftersave="save()" e-placeholder="e.g., 10m, 2h, 30" e-class="input-tiny"><span>{[{ data.formatedTimeSpent || '0m' }]}</span></div>
											</div>
											<div class="col-sm-4 task-details-block">
												<label class="task-label">Subtype:</label>
												<div class="text-info dropdown">
													<a href="#" data-toggle="dropdown" data-eat-click><span class="editable editable-click">{[{ getSubtypeDisplay(data.subtype_id) }]}</span></a>
													<ul class="dropdown-menu dropdown-menu-arrow">
														<li ng-repeat="type in subtypes" ng-class="{active: data.subtype_id == type.id}"><a tabindex="-1" href="#" ng-click="updateValue({subtype_id: type.id})" ng-bind="type.name" data-eat-click></a></li>
													</ul>
												</div>
											</div>
										@endif
										<div class="col-sm-4 task-details-block">
											<label class="task-label">Direct dial:</label>
											<div class="text-info" editable-text="data.direct_dial" onaftersave="save()" e-class="input-tiny"><span>{[{ data.direct_dial }]}</span></div>
										</div>
										@if ($task->type == 'repair')
											<div class="col-sm-4 task-details-block">
												<label class="task-label">Attended Time:</label>
												<div class="text-info" editable-text="data.formatedAttendedTime" onaftersave="save()"><span>{[{ data.formatedAttendedTime || '0 min' }]}</span></div>
											</div>
										@endif
										@if ($task->type == 'repair')
											<div class="col-sm-4 task-details-block">
												<label class="task-label">Unattended Time:</label>
												<div class="text-info" editable-text="data.formatedUnattendedTime" onaftersave="save()"><span>{[{ data.formatedUnattendedTime || '0 min' }]}</span></div>
											</div>
										@endif
										<div class="col-sm-4 task-details-block">
											<label class="task-label">Alarm:</label>
											<div><a href="#" ng-click="changeAlarm()" data-eat-click>{[{ data.alarm_date ? (data.alarm_date | moment:"DD/MM/YYYY HH:mm") : 'No alarm' }]}</a></div>
											<div ng-show="data.alarm_date" ng-confirm-click="Are you sure you want to remove the alarm?" confirmed-click="deleteAlarm()"><i class="fa fa-times text-danger"></i></div>
										</div>
										<div class="col-sm-4 task-details-block">
											<label class="task-label">Due Date:</label>
											<div>
												<a href="#" ng-click="changeDueDate()" data-eat-click>{[{ data.due_date ? (data.due_date | moment:"DD/MM/YYYY HH:mm") : 'Not set' }]}</a>
												<span ng-show="data.due_date" ng-confirm-click="Are you sure you want to remove the due date?" confirmed-click="deleteDueDate()"><i class="fa fa-times text-danger"></i></span>
											</div>
										</div>
										@if ($task->type == 'repair')
											<div class="col-sm-4 task-details-block">
												<label class="task-label">Antivirus / ESET:</label>
												<div class="text-info dropdown">
													<a href="#" data-toggle="dropdown" data-eat-click><span class="editable editable-click">{[{ antivirus_states[data.antivirus_state] || 'Not set' }]}</span></a>
													<ul class="dropdown-menu dropdown-menu-arrow" ng-init="antivirus_states = {{ json_encode(App\Modules\Bookings\Task::getAntivirusStates()) }}">
														<li ng-repeat="(value, name) in antivirus_states" ng-class="{active: data.antivirus_state == value}">
															<a tabindex="-1" href="#" ng-click="updateValue({antivirus_state: value}); value == 2 ? openLicensesModal() : ''" ng-bind="name" data-eat-click></a>
														</li>
													</ul>
												</div>
											</div>
										@endif
										@if ($task->type == 'onsite')
										<div class="col-sm-4 task-details-block">
											<label class="task-label">Recurring</label>
												<div class="text-info dropdown">
												<a href="#" data-toggle="dropdown" data-eat-click>
													<span class="editable editable-click">
														<span ng-if="data.recurring == 1">Yes</span>
														<span ng-if="data.recurring == 0">No</span>
												</span></a>
												<ul class="dropdown-menu dropdown-menu-arrow">
													<li><a ng-click="data.recurring = 1">Yes</a></li>
													<li><a ng-click="data.recurring = 0">No</a></li>
												</ul>
											</div>
										</div>
										@endif
									</div>
								</div>
								<div class="col-sm-3">
									<div class="headline">
										<h4><i class="fa fa-lightbulb-o"></i> Pricing</h4>
									</div>
									<table class="table table-condensed table-striped-odd table-no-header">
										<tbody>
											<tr style="font-size: 13px;">
												<td>Labour</td>
												<td><span editable-number="data.labour" onaftersave="save()">{[{ data.labour | currency:"£" }]}</span></td>
											</tr>
											<tr style="font-size: 13px;">
												<td>Points</td>
												<td><span ng-bind="data.points"></span></td>
											</tr>
											<tr style="font-size: 13px;">
												<td>Parts</td>
												<td>{[{ PartsService.total | currency:"£" }]}</td>
											</tr>
											<tr style="font-size: 13px;">
												<td><strong>Total</strong></td>
												<td><strong>{[{ total | currency:"£" }]}</strong></td>
											</tr>
										</tbody>
									</table>

									<!-- notification badges -->
									<div class="text-center" style="margin-top: 10px; font-size: 14px;">

										<!-- below items are only visible on repairs -->
										<div class="clearfix">
											@if ($task->type == 'repair')
												<div class="pull-left" style="margin-right: 7px; width: 45px;">
													<span class="fa fa-stack">
														<i class="fa fa-square fa fa-stack-base" ng-class="{'text-success': data.booking_fee.paid == '1', 'text-danger': !data.booking_fee_id || data.booking_fee.paid == '0'}"></i>
														<i class=" fa fa-light" ng-class="{'fa fa-check-circle': data.booking_fee.paid == '1', 'fa fa-times-circle': !data.booking_fee_id || data.booking_fee.paid == '0'}"></i>
													</span>
													<p><small>B.I.F.</small></p>
												</div>
												<div class="pull-left" style="margin-right: 7px; width: 45px;">
													<span class="fa fa-stack">
														<i class="fa fa-square fa fa-stack-base" ng-class="{'text-success': data.paid == '1', 'text-danger': data.paid == '0'}"></i>
														<i class="fa fa-light" ng-class="{'fa fa-check-circle': data.paid == '1', 'fa fa-times-circle': data.paid == '0'}"></i>
													</span>
													<p><small>Paid</small></p>
												</div>
												<div class="pull-left" style="margin-right: 7px; width: 45px;">
													<span class="fa fa-stack">
														<i class="fa fa-square fa fa-stack-base" ng-class="{'text-success': data.collected_at, 'text-danger': !data.collected_at}"></i>
														<i class="fa fa-light" ng-class="{'fa fa-check-circle': data.collected_at, 'fa fa-times-circle': !data.collected_at}"></i>
													</span>
													<p><small>Collected</small></p>
												</div>
												<div class="pull-left" style="margin-right: 7px; width: 45px;" ng-if="data.needs_delivery == '1'">
													<span class="fa fa-stack">
														<i class="fa fa-square fa fa-stack-base" ng-class="{'text-success': data.delivered == '1', 'text-danger': data.delivered == '0'}"></i>
														<i class="fa fa-light" ng-class="{'fa fa-check-circle': data.delivered == '1', 'fa fa-times-circle': data.delivered == '0'}"></i>
													</span>
													<p><small>Delivered</small></p>
												</div>
											@endif
										</div>

										@if ($task->type == 'repair')
											<div style="margin-top: 5px;">
												<a href="{!! URL::to('bookings/confirmation-sheet/' . $task->id) !!}" class="btn btn-default btn-sm"><i class="fa fa-paperclip"></i> Booking Sheet</a>
											</div>
										@endif
									</div>
								</div>
							</div>

						
							<!-- Task subscribers -->
							<hr>
							<div style="margin-left: 12px; margin-top: 10px;">
								<i class="fa fa-rss-square fa-lg"></i> &nbsp; <a href="#" ng-click="showSubscribers()" data-eat-click><span ng-show="data.user_subscribed">You and </span>{[{ (data.subscribers | exclude:'id':auth.data.id).length }]} people</a> subscribed to this task.
								<a href="#" ng-if="!data.user_subscribed" ng-click="subscribe()">Subscribe</a>
								<a href="#" ng-if="data.user_subscribed" ng-click="unsubscribe()">Unsubscribe</a>
								<div class="pull-right">
									<a href="mailto:helpdesk@wiseserve.net?Subject=[{!! $task->id !!}] - {!! $task->title !!}" target="_top">
										<button type="button" class="btn btn-primary btn-sm" style="margin-right:5px">
										<span class="glyphicon glyphicon-envelope" aria-hidden="true"></span> Escalate to Remote Support
										</button>
									</a> <i class="fa fa-plus-square"></i> Booked by <span class="text-info" ng-bind="data.creator.name"></span> <span class="muted" uib-tooltip="{[{ ::data.created_at }]}">{[{ data.created_at | fromNow }]}</span></div>
							</div>
							<hr>
							<textarea rows="5" ng-model="data.problem" summernote summernote-height="200"></textarea>


							{{-- Comments section --}}
							<div widget-comments="data" comment-type="task"></div>

						</div>

						<div class="col-sm-5" style="padding-left: 10px;">
							<div class="task-group">
								<div class="headline">
									<h4><i class="fa fa-user fa-fw"></i> Customer</h4>
								</div>
								<div clients-widget data-site="data.site" data-site-user="data.site_user" data-task="data" data-show-new-booking="true"></div>
							
							<!-- Call Records Section -->
							<div class="task-group" ng-if="(data.client_type == 'customer' && (data.client.phone || data.client.phone2 || data.client.mobile)) || (data.client_type == 'client' && (data.site.primary_phone || data.site_user.phone || data.site_user.mobile))">
								<div class="headline">
									<h5><i class="fa fa-phone fa-fw"></i> Call Records</h5>
								</div>
								<div class="task-group-inner">									
									<!-- Call History -->
									<call-history 
										task-id="data.id"
										max-records="5"
										show-pagination="true">
									</call-history>
								</div>
							</div>
							</div>

							<div class="task-group" ng-if="data.feedback">
								<div class="headline">
									<h4><i class="fa fa-star fa-fw"></i> Customer Feedback</h4>
								</div>
								<div class="task-group-inner">
									<p ng-if="data.feedback.code && data.feedback.emailed == '0'">An email is scheduled to go out on <em>{[{ data.feedback.send_date | moment:"DD/MM/YYYY" }]}</em>. <a href="#" ng-confirm-click="Are you sure you want to cancel this feedback request?" data-confirmed-click="cancelFeedback()" data-eat-click>Cancel the feedback request</a></p>
									<p ng-if="data.feedback.emailed == '1' && !data.feedback.rating">An email was sent on the <em>{[{ data.feedback.emailed_at | moment:"DD/MM/YYYY" }]}</em>, but the customer hasn't left any feedback yet.</p>
									<p ng-if="data.feedback.rating">
										Feedback received <span data-rating value="data.feedback.rating" max="5" readonly="true"></span> <br>
										{[{ data.feedback.feedback }]}
									</p>
								</div>
							</div>
							<script type="module">
								import wiki from '/v2/js/vue/embedded/wiki.js?v={{ time() }}'
								</script>
							<script type="module">
								@if($task->client && $task->client->id)
									window.taskid="{!!$task->client->id!!}"
									import hours from '/v2/js/vue/embedded/hours.js?v={{ time() }}'
									hours()
								@else
									console.log('Hours component: No client ID available, skipping hours component')
								@endif
							</script>						
						<div class="task-group">
							<div class="headline">
								<h4><i class="fa fa-bar-chart-o fa-fw"></i> Statistics</h4>
							</div>
							<ul class="fa-ul">
								<li><i class="fa-li fa fa-angle-right"></i>Booked in by <strong><em>{[{ ::data.creator.name }]}</em></strong> <span class="pull-right" uib-tooltip="{[{ ::data.created_at }]}"><i class="fa fa-clock-o"></i> {[{ data.created_at | fromNow }]}</span></li>
								<li><i class="fa-li fa fa-angle-right"></i>There were <strong uib-tooltip="{[{ getWorkerNames() }]}"><em>{[{ data.workers.length }]} people</em></strong> working on this task.</li>
								<li ng-show="data.completed_at"><i class="fa-li fa fa-angle-right"></i>The task was completed in <strong><em>{[{ getTotalDays() }]} days</em></strong></li>
								<li><i class="fa-li fa fa-angle-right"></i>Last updated by <strong><em>{[{ data.modifier.name }]}</em></strong> <span class="pull-right" uib-tooltip="{[{ ::data.updated_at }]}"><i class="fa fa-clock-o"></i> {[{ data.updated_at | fromNow }]}</span></li>
							</ul>
						</div>
						<div id="wiki"></div>
						@if($task->client && $task->client->id)
							<div id="hours"></div>
						@endif	
						<div class="task-group">
							<div class="headline">
								<h4><i class="fa fa-thumbs-up fa-fw"></i> Accounts</h4>
							</div>
							@if ( $task->project && $task->project->single_invoice)
								<p>The invoice and payments for this task are done through project <a href="{!! URL::to('projects') !!}/{[{ data.project_id }]}" uib-tooltip="Click to open project">#{[{ data.project_id }]}</a>.</p>
								<p>
									{!! $task->project->invoiced ? '<span class="label label-success">Invoiced</span>' : '<span class="label label-danger">Not Invoiced</span>' !!}
									{!! $task->project->paid ? '<span class="label label-success">Paid</span>' : '<span class="label label-danger">Not Paid</span>' !!}
								</p>
							@else
								<ul class="fa-ul">
									@if ( $task->type == 'repair' )
										<li>
											<i class="fa-li fa fa-angle-right"></i>
											Booking fee: <span class="text-warning" editable-number="data.booking_fee_id">{[{ data.booking_fee_id || 'not paid' }]}</span>
											<a href="#" class="pull-right" ng-hide="data.booking_fee_id" ng-click="SalesService.generateBookingFee(data)"><i class="fa fa-tint"></i> Generate</a>
											<a href="#" class="pull-right" ng-show="data.booking_fee_id" ng-click="SalesService.showBookingFee(data)"><i class="fa fa-tint"></i> View Receipt</a>
										</li>
									@endif
									<li>
										<i class="fa-li fa fa-angle-right"></i>
										Invoice number: <span class="text-warning" editable-number="data.invoice_number">{[{ data.invoice_number ? data.invoice_number : 'not invoiced' }]}</span>
										<a href="#" class="pull-right" ng-hide="data.invoice_number" ng-click="generateInvoice(data)"><i class="fa fa-tint"></i> Generate</a>
										<a href="#" class="pull-right" ng-show="data.invoice_number" ng-click="InvoiceService.show(data)"><i class="fa fa-tint"></i> View Invoice</a>
									</li>
									<li>
											<i class="fa-li fa fa-angle-right"></i>
											Payment status: <span editable-select="data.paid" e-ng-options="o.value as o.name for o in payment_options" onaftersave="save()"><span ng-class="{'text-danger': data.paid == '0', 'text-success': data.paid == '1'}">{[{ getPaymentDisplay(data.paid) }]}</span></span>
											<span class="pull-right" ng-show="data.paid == '1'" editable-bsdate="data.paid_at" e-datepicker-popup="dd-MM-yyyy" onaftersave="save()"><i class="fa fa-calendar"></i> {[{ data.paid_at | date:"dd/MM/yyyy" }]}</span>
									</li>
								</ul>
							@endif
						</div>

						@if ($task->type == 'repair')
							<div class="task-group">
								<div class="headline">
									<h4><i class="fa fa-laptop fa-fw"></i> Devices</h4>
								</div>
								<div customer-devices="data.devices" view="selected"></div>
							</div>
						@endif
						<div class="task-group">
							<div class="headline">
								<h4><i class="fa fa-key fa-fw"></i> Passwords</h4>
							</div>
							<div widget-passwords data-task="data"></div>
						</div>

						<div class="task-group">
							<div class="headline">
								<h4><i class="fa fa-clock-o fa-fw"></i> Time tracking</h4>
							</div>
							<div data-time-tracking="" data-task-id="{[{ data.id }]}"></div>
						</div>

						<div class="task-group">
							<div class="headline">
								<h4><i class="fa fa-wrench fa-puzzle-piece"></i> Parts</h4>
							</div>
							<div widget-parts="data" related-type="task" ></div>
						</div>

						<div class="task-group">
							<div class="headline">
								<h4><i class="fa fa-wrench fa-fw"></i> Builds</h4>
							</div>
							<div widget-builds="data" related-type="task" ></div>
						</div>

						<div class="task-group">
							<div class="headline">
								<h4><i class="fa fa-paperclip fa-fw"></i> Attachments</h4>
							</div>
							<div attachments task="data" type="task"></div>
						</div>

						<div class="task-group">
							<div class="headline">
								<h4><i class="fa fa-paper-plane-o"></i>  Customer Notifications</h4>
							</div>
							<div widget-customer-notifications task="data" ></div>
						</div>

						<div class="task-group" ng-if="data.project_id">
							<div class="headline">
								<h4><i class="fa fa-folder-open fa-fw"></i> Project</h4>
							</div>
							<div data-project-tasks="data.project_id"></div>
						</div>

						<div class="task-group">
							<div class="headline">
								<h4><i class="fa fa-random fa-fw"></i> Related tasks</h4>
							</div>
							<div class="task-group-inner">
								<small ng-show="data.related_tasks.length == 0 && data.related_tasks.length == 0">No tasks. <a href="" ng-click="showLinkTaskModal()">Link a task now</a></small>
								<table class="table table-striped-odd table-condensed table-no-header">
									<tbody>
										<tr ng-repeat="task in data.related_tasks">
											<td><a href="{{ URL::to('tasks/{[{ task.id }]}') }}" target="_blank">{[{ task.id }]}</a></td>
											<td>{[{ task.title }]}</td>
											<td>{[{ task.status.name }]}</td>
											<td><a href="#" ng-confirm-click="Remove task {[{ task.id }]}?" confirmed-click="removeRelatedTask(task)" data-eat-click><span class="text-danger">Remove</span></a></td>
										</tr>
										<tr ng-repeat="task in data.qa_tasks">
											<td><a href="{{ URL::to('tasks/qa/{[{ task.id }]}') }}" target="_blank">{[{ task.id }]}</a></td>
											<td>{[{ task.title }]}</td>
											<td>{[{ task.status.name }]}</td>
											<td>&nbsp;</td>
										</tr>
									</tbody>
								</table>
								<div class="buttons text-right" ng-show="data.related_tasks.length > 0" style="margin-top: 5px;">
									<span class="btn btn-default" ng-click="showLinkTaskModal()">Link new task</span>
								</div>
							</div>
						</div>

						<div class="task-group relative">
							<div class="headline">
								<h4><i class="fa fa-check-square-o fa-fw"></i> Templates</h4>
							</div>
							<div data-task-templates="data"></div>
						</div>
					</div>
				</div>

			</div>
		</div>
	</div>

<script>
// Robust loading indicator that works without jQuery dependency
(function() {
	'use strict';
	
	var initialLoading = null;
	var titleProgress = null;
	var titleProgressText = null;
	var closeButton = null;
	var isHidden = false;
	
	// Initialize elements when DOM is ready
	function initElements() {
		initialLoading = document.getElementById('initial-loading');
		titleProgress = document.getElementById('title-progress');
		titleProgressText = document.getElementById('title-progress-text');
		closeButton = document.getElementById('close-loading');
		
		// Setup close button
		if (closeButton && !isHidden) {
			closeButton.addEventListener('click', hideInitialLoading);
		}
	}
	
	// Hide initial loading indicator
	function hideInitialLoading() {
		if (initialLoading && !isHidden) {
			initialLoading.style.display = 'none';
			isHidden = true;
			console.log('Loading indicator hidden');
		}
	}
	
	// Context tracking for editable fields
	var currentEditableField = null;
	var currentEditableFieldType = null;
	
	// Simple progress for field updates (jQuery independent)
	var progressTimeout = null;
	function showTitleProgress(message) {
		message = message || 'Saving changes...';
		if (titleProgressText) {
			titleProgressText.innerHTML = '<strong>' + message + '</strong>';
		}
		if (titleProgress) {
			titleProgress.style.display = 'inline-block';
		}
		
		// Clear any existing timeout
		if (progressTimeout) {
			clearTimeout(progressTimeout);
		}
		
		// Fallback timeout in case Angular watcher doesn't work
		progressTimeout = setTimeout(function() {
			console.log('Progress indicator fallback timeout - hiding after 5 seconds');
			hideTitleProgress();
		}, 4000);
	}
	
	// Get message for save() function based on which editable field is active
	function getSaveMessage() {
		if (currentEditableField && currentEditableFieldType) {
			switch(currentEditableField) {
				case 'data.formatedTimeSpent': return 'Updating time spent...';
				case 'data.direct_dial': return 'Updating direct dial number...';
				case 'data.labour': return 'Updating pricing...';
				case 'data.title': return 'Updating task title...';
				case 'data.return_id': return 'Updating return ID...';
				case 'data.shelf': return 'Setting shelf location...';
				case 'data.formatedAttendedTime': return 'Updating attended time...';
				case 'data.formatedUnattendedTime': return 'Updating unattended time...';
				case 'data.no_price_reason': return 'Setting no price reason...';
				case 'data.cancelled_reason': return 'Setting cancellation reason...';
				case 'data.booking_fee_id': return 'Updating booking fee...';
				case 'data.invoice_number': return 'Updating invoice number...';
				case 'data.paid': return 'Updating payment status...';
				case 'data.paid_at': return 'Setting payment date...';
				default: 
					// Try to infer from field name
					if (currentEditableField.indexOf('Time') !== -1) return 'Updating time...';
					if (currentEditableField.indexOf('dial') !== -1) return 'Updating phone number...';
					if (currentEditableField.indexOf('labour') !== -1) return 'Updating pricing...';
					if (currentEditableField.indexOf('paid') !== -1) return 'Updating payment...';
					return 'Saving changes...';
			}
		}
		return 'Saving changes...';
	}
	
	function hideTitleProgress() {
		if (titleProgress) {
			titleProgress.style.display = 'none';
		}
		
		// Clear the fallback timeout since progress is now hidden
		if (progressTimeout) {
			clearTimeout(progressTimeout);
			progressTimeout = null;
		}
	}
	
	// Use existing Messenger service for notifications
	function showNotification(message, type) {
		// Only show notifications after page has fully loaded to avoid false notifications
		if (document.readyState === 'complete' && typeof window.Messenger === 'function') {
			try {
				window.Messenger().post({
					message: message,
					hideAfter: 3,
					type: type || 'success'
				});
			} catch (e) {
				console.log('Could not show notification:', e);
			}
		}
	}
	
	// Wait for actual Angular data to load via API (simplified and more reliable)
	function waitForContent() {
		var attempts = 0;
		var maxAttempts = 40; // 8 seconds max
		var dataLoaded = false;
		
		var checkContent = setInterval(function() {
			attempts++;
			
			// Method 1: Check if Angular controller has loaded and has data
			try {
				if (typeof window.angular !== 'undefined') {
					var angularElement = document.querySelector('[ng-controller="TasksCtrl"]');
					if (angularElement) {
						var scope = window.angular.element(angularElement).scope();
						
						// Check if scope exists and has real task data
						if (scope && scope.data && scope.data.id && scope.data.title) {
							// Also check if the data is not just empty templates
							if (scope.data.title.indexOf('{{') === -1 && scope.data.title.trim().length > 0) {
								console.log('✅ Task data loaded successfully! ID:', scope.data.id, 'Title:', scope.data.title);
								dataLoaded = true;
								hideInitialLoading();
								clearInterval(checkContent);
								return;
							}
						}
						
						// If scope exists but no data yet, check if we have some basic elements populated
						if (scope && scope.taskId && attempts > 5) {
							var statusElement = document.querySelector('.editable-click');
							var titleElement = document.querySelector('.navbar-brand span[editable-text]');
							
							// Check if the UI elements are populated with real data
							if (statusElement && statusElement.textContent && 
								statusElement.textContent.trim().length > 0 && 
								statusElement.textContent.indexOf('{{') === -1 &&
								statusElement.textContent.indexOf('{[{') === -1) {
								
								console.log('✅ UI elements populated with real data');
								dataLoaded = true;
								hideInitialLoading();
								clearInterval(checkContent);
								return;
							}
						}
					}
				}
			} catch (e) {
				// Angular not ready yet, continue checking
			}
			
			// Fallback Method: Check DOM elements directly (more aggressive)
			if (attempts > 8) {
				var statusElement = document.querySelector('.editable-click');
				var titleElement = document.querySelector('.navbar-brand span[editable-text]');
				var taskIdInUrl = window.location.pathname.match(/\/tasks\/\w+\/(\d+)/);
				var taskIdFromMeta = document.querySelector('meta[name="task-id"]');
				
				// Check if basic task elements are populated
				var hasValidStatus = statusElement && statusElement.textContent && 
									 statusElement.textContent.trim().length > 0 && 
									 statusElement.textContent.indexOf('{{') === -1 && 
									 statusElement.textContent.indexOf('{[{') === -1;
									 
				var hasValidTitle = titleElement && titleElement.textContent && 
								   titleElement.textContent.trim().length > 0 && 
								   titleElement.textContent.indexOf('{{') === -1 && 
								   titleElement.textContent.indexOf('{[{') === -1;
				
				// Also check if we have task ID available (indicating server data is loaded)
				var hasTaskId = (taskIdInUrl && taskIdInUrl[1]) || (taskIdFromMeta && taskIdFromMeta.getAttribute('content'));
				
				if ((hasValidStatus || hasValidTitle) && hasTaskId) {
					console.log('Fallback: DOM elements show real content loaded, task ID available');
					dataLoaded = true;
					hideInitialLoading();
					clearInterval(checkContent);
					return;
				}
			}
			
			// Final fallback - hide after max attempts regardless
			if (attempts >= maxAttempts) {
				console.log('Timeout reached after', maxAttempts * 200, 'ms - hiding loading indicator');
				hideInitialLoading();
				clearInterval(checkContent);
			}
		}, 200);
	}
	
	// Setup progress indicators for both jQuery and Angular
	function setupProgressIndicators() {
		// First, let's debug what HTTP system is actually being used
		console.log('=== DEBUGGING HTTP SYSTEM ===');
		console.log('jQuery available:', typeof window.$ !== 'undefined');
		console.log('Angular available:', typeof window.angular !== 'undefined');
		
		// Monitor XMLHttpRequest (direct AJAX calls)
		var originalXHROpen = XMLHttpRequest.prototype.open;
		var originalXHRSend = XMLHttpRequest.prototype.send;
		
		XMLHttpRequest.prototype.open = function(method, url, async, user, password) {
			this._method = method;
			this._url = url;
			return originalXHROpen.apply(this, arguments);
		};
		
		XMLHttpRequest.prototype.send = function(data) {
			var url = this._url;
			var method = this._method;
			
			// Parts operations detection
			if (url && (url.indexOf('/api/v1/parts') !== -1 || url.match(/\/api\/v1\/parts\/\d+/))) {
				if (method === 'POST') {
					showTitleProgress('Adding part to stock...');
				} else if (method === 'PUT' || method === 'PATCH') {
					showTitleProgress('Updating part...');
				} else if (method === 'DELETE') {
					showTitleProgress('Removing part...');
				}
				
				// Handle success and error responses
				this.addEventListener('loadend', function() {
					setTimeout(hideTitleProgress, 300);
					
					// Only show notifications if this is a user-initiated action (not page load)
					if (document.readyState === 'complete') {
						if (this.status >= 200 && this.status < 300) {
							// Success notification using existing system
							if (method === 'POST') {
								showNotification('Part added successfully!', 'success');
							} else if (method === 'PUT' || method === 'PATCH') {
								showNotification('Part updated successfully!', 'success');
							} else if (method === 'DELETE') {
								showNotification('Part removed successfully!', 'success');
							}
						} else if (this.status >= 400) {
							// Error notification using existing system
							try {
								var response = JSON.parse(this.responseText);
								var errorMessage = response.message || response.error || 'Operation failed';
								showNotification(errorMessage, 'error');
							} catch (e) {
								showNotification('Operation failed - Server error', 'error');
							}
						}
					}
				});
			}
			
			// File operations with CSRF token fix
			if (url && url.indexOf('/api/v1/files') !== -1) {
				if (method === 'POST') {
					showTitleProgress('Uploading file...');
					
					// Add CSRF token to upload requests
					var token = document.querySelector('meta[name="csrf-token"]');
					if (token && token.getAttribute('content')) {
						this.setRequestHeader('X-CSRF-TOKEN', token.getAttribute('content'));
					}
				} else if (method === 'DELETE') {
					showTitleProgress('Deleting file...');
				}
				
				this.addEventListener('loadend', function() {
					setTimeout(hideTitleProgress, 300);
					
					// Only show notifications if this is a user-initiated action (not page load)
					if (document.readyState === 'complete') {
						if (this.status >= 200 && this.status < 300) {
							// Success notification based on method
							if (method === 'POST') {
								showNotification('File uploaded successfully!', 'success');
							} else if (method === 'DELETE') {
								showNotification('File deleted successfully!', 'success');
							}
						} else if (this.status >= 400) {
							try {
								var response = JSON.parse(this.responseText);
								var errorMessage = response.message || response.error || 'Operation failed';
								if (method === 'POST') {
									showNotification('Upload Error: ' + errorMessage, 'error');
								} else if (method === 'DELETE') {
									showNotification('Delete Error: ' + errorMessage, 'error');
								} else {
									showNotification('File Error: ' + errorMessage, 'error');
								}
							} catch (e) {
								if (method === 'POST') {
									showNotification('Upload failed - Server error', 'error');
								} else if (method === 'DELETE') {
									showNotification('Delete failed - Server error', 'error');
								} else {
									showNotification('File operation failed - Server error', 'error');
								}
							}
						}
					}
				});
			}
			
			return originalXHRSend.apply(this, arguments);
		};
		
		// Monitor Fetch API  
		if (window.fetch) {
			var originalFetch = window.fetch;
			window.fetch = function(url, options) {
				if (url && (url.indexOf('/api/v1/parts') !== -1 || url.match(/\/api\/v1\/parts\/\d+/))) {
					var method = options ? options.method : 'GET';
					if (method === 'POST') {
						showTitleProgress('Adding part to stock...');
					} else if (method === 'PUT' || method === 'PATCH') {
						showTitleProgress('Updating part...');
					} else if (method === 'DELETE') {
						showTitleProgress('Removing part...');
					}
				}
				
				return originalFetch.apply(this, arguments);
			};
		}
		
		// Setup jQuery AJAX monitoring with proper URL detection
		if (typeof window.$ !== 'undefined' && window.$) {
			console.log('Setting up jQuery AJAX monitoring...');
			
			window.$(document).ajaxSend(function(event, xhr, settings) {
				var url = '';
				
				// Try to get URL from multiple sources
				if (settings && settings.url) {
					url = settings.url;
				} else if (xhr && xhr.responseURL) {
					url = xhr.responseURL;
				} else if (xhr && xhr._requestURL) {
					url = xhr._requestURL;
				}
				
				// Skip progress for stock search (GET requests with query)
				if (url && url.indexOf('/api/v1/stock') !== -1 && url.indexOf('query=') !== -1) {
					// Don't show progress for search
				}
				// Generic message for other API operations (exclude parts - handled by XHR)
				else if (url && url.indexOf('/api/v1/') !== -1 && url.indexOf('/api/v1/parts') === -1) {
					showTitleProgress('Saving changes...');
				}
			});
						
		}
		
		// Setup Angular monitoring by overriding scope functions  
		setTimeout(function() {
			try {
				if (typeof window.angular !== 'undefined') {
					console.log('Setting up Angular scope function monitoring...');
					
					// Note: jQuery AJAX monitoring above should handle parts operations
					console.log('jQuery should handle parts operations automatically');
					
					var angularElement = document.querySelector('[ng-controller="TasksCtrl"]');
					if (angularElement) {
						var scope = window.angular.element(angularElement).scope();
						if (scope) {
							// Setup watcher for isUpdating flag to hide progress when API calls complete
							var setupProgressWatcher = function() {
								if (scope.$watch) {
									scope.$watch('isUpdating', function(newValue, oldValue) {
										if (oldValue === true && newValue === false) {
											// API call just completed, hide progress
											console.log('API call completed - hiding progress indicator');
											setTimeout(function() {
												hideTitleProgress();
											}, 100);
										} else if (newValue === true && oldValue === false) {
											// API call just started
											console.log('API call started - isUpdating is now true');
										}
									});
									console.log('Progress watcher setup - will hide indicators when API calls complete');
								} else {
									console.log('Warning: Angular $watch not available for progress tracking');
								}
							};
							
							// Override updateValue function (for dropdowns, assignments, etc.)
							if (scope.updateValue && typeof scope.updateValue === 'function') {
								var originalUpdateValue = scope.updateValue;
								scope.updateValue = function(params) {
									try {
										showTitleProgress(getUpdateMessage(params));
										
										// Call original function
										var result = originalUpdateValue.call(this, params);
										
										// Don't hide progress here - let the isUpdating watcher handle it
										return result;
									} catch (error) {
										console.log('Error in updateValue override:', error);
										hideTitleProgress();
										return originalUpdateValue.call(this, params);
									}
								};
							}
							
							// Override save function (for editable fields like price, time spent, direct dial)
							if (scope.save && typeof scope.save === 'function') {
								var originalSave = scope.save;
								scope.save = function() {
									try {
										// Use context-aware message for editable fields
										var message = getSaveMessage();
										showTitleProgress(message);
										
										// Call original save function
										var result = originalSave.call(this);
										
										// Clear the context after save
										setTimeout(function() {
											currentEditableField = null;
											currentEditableFieldType = null;
										}, 100);
										
										// Don't hide progress here - let the isUpdating watcher handle it
										return result;
									} catch (error) {
										console.log('Error in save override:', error);
										hideTitleProgress();
										// Safely call original function
										try {
											return originalSave.call(this);
										} catch (e) {
											console.log('Error calling original save function:', e);
											return null;
										}
									}
								};
							}
							
							// Setup the progress watcher
							setupProgressWatcher();
							
							console.log('Angular progress indicators enabled with API response tracking');
						}
					}
				}
			} catch (e) {
				console.log('Could not setup Angular progress indicators:', e);
			}
		}, 2000); // Wait for Angular to be fully initialized
	}
	
	// Get smart message for different update types
	function getUpdateMessage(params) {
		if (!params) return 'Saving changes...';
		
		// Specific field updates
		if (params.title) return 'Updating task title...';
		if (params.status_id) return 'Changing task status...';
		if (params.assigned_to !== undefined) {
			return params.assigned_to ? 'Assigning task...' : 'Unassigning task...';
		}
		if (params.formatedTimeSpent) return 'Updating time spent...';
		if (params.direct_dial) return 'Updating direct dial number...';
		if (params.labour || params.labour === 0) return 'Updating pricing...';
		if (params.severity_id) return 'Changing priority level...';
		if (params.problem) return 'Saving problem description...';
		if (params.paid !== undefined) return 'Updating payment status...';
		if (params.paid_at) return 'Setting payment date...';
		if (params.invoice_number) return 'Updating invoice number...';
		if (params.booking_fee_id) return 'Updating booking fee...';
		if (params.return_id) return 'Updating return ID...';
		if (params.shelf) return 'Setting shelf location...';
		if (params.formatedAttendedTime) return 'Updating attended time...';
		if (params.formatedUnattendedTime) return 'Updating unattended time...';
		if (params.no_price_reason) return 'Setting no price reason...';
		if (params.cancelled_reason) return 'Setting cancellation reason...';
		if (params.due_date) return 'Updating due date...';
		if (params.alarm_date) return 'Setting alarm date...';
		if (params.prebook_date || params.prebook !== undefined) return 'Updating prebook status...';
		
		// Check for multiple fields being updated
		var fieldCount = Object.keys(params).filter(key => 
			key !== 'id' && key !== 'updated_at' && key !== '_token'
		).length;
		
		if (fieldCount > 1) {
			return 'Saving multiple changes...';
		}
		
		return 'Saving changes...';
	}
	
	// Setup editable field tracking to capture which field is being edited
	function setupEditableTracking() {
		try {
			// Listen for clicks on editable elements to track which field is being edited
			document.addEventListener('click', function(event) {
				var target = event.target;
				
				// Check if clicked element or its parents have editable attributes
				var editableElement = target.closest('[editable-text], [editable-number], [editable-select], [editable-bsdate]');
				
				if (editableElement) {
					// Get the field name and type
					currentEditableField = editableElement.getAttribute('editable-text') ||
										   editableElement.getAttribute('editable-number') ||
										   editableElement.getAttribute('editable-select') ||
										   editableElement.getAttribute('editable-bsdate');
					
					if (editableElement.hasAttribute('editable-text')) {
						currentEditableFieldType = 'text';
					} else if (editableElement.hasAttribute('editable-number')) {
						currentEditableFieldType = 'number';
					} else if (editableElement.hasAttribute('editable-select')) {
						currentEditableFieldType = 'select';
					} else if (editableElement.hasAttribute('editable-bsdate')) {
						currentEditableFieldType = 'date';
					}
					
					console.log('Editing field:', currentEditableField, 'type:', currentEditableFieldType);
				}
			});
			
			// Also listen for focus events on input elements within editable fields
			document.addEventListener('focus', function(event) {
				var target = event.target;
				
				if (target.tagName === 'INPUT' || target.tagName === 'SELECT' || target.tagName === 'TEXTAREA') {
					var editableParent = target.closest('[editable-text], [editable-number], [editable-select], [editable-bsdate]');
					
					if (editableParent) {
						currentEditableField = editableParent.getAttribute('editable-text') ||
											   editableParent.getAttribute('editable-number') ||
											   editableParent.getAttribute('editable-select') ||
											   editableParent.getAttribute('editable-bsdate');
						
						console.log('Focused on editable field:', currentEditableField);
					}
				}
			}, true);
			
			console.log('Editable field tracking enabled - will show specific field names in progress indicators');
		} catch (e) {
			console.log('Could not setup editable field tracking:', e);
		}
	}
	
	// Initialize when DOM is ready
	function initialize() {
		initElements();
		
		// Start content checking immediately
		setTimeout(waitForContent, 100);
		
		// Setup progress indicators for both jQuery and Angular
		setTimeout(setupProgressIndicators, 1000);
		
		// Setup editable field tracking for better progress messages
		setTimeout(setupEditableTracking, 1500);
		
		// Absolute fallback - always hide after 5 seconds max
		setTimeout(function() {
			if (!isHidden) {
				console.log('Final fallback: hiding loading indicator after 5 seconds');
				hideInitialLoading();
			}
		}, 5000);
	}
	
	// Wait for DOM to be ready (works without jQuery)
	if (document.readyState === 'loading') {
		document.addEventListener('DOMContentLoaded', initialize);
	} else {
		initialize();
	}
	
	// Expose global functions for manual control
	window.taskProgress = {
		hide: hideInitialLoading,
		showField: showTitleProgress,
		hideField: hideTitleProgress,
		isHidden: function() { return isHidden; }
	};
	
	console.log('Robust loading indicator initialized (jQuery-independent)');
	
	// Global error handler to catch unhandled errors
	window.addEventListener('error', function(event) {
		if (event.message && event.message.indexOf('cb is not a function') !== -1) {
			console.log('Caught "cb is not a function" error - this is likely an Angular HTTP interceptor issue and can be safely ignored');
			event.preventDefault();
			return false;
		}
		if (event.message && event.message.indexOf('Cannot read properties of undefined') !== -1) {
			console.log('Caught undefined property error - likely from Vue component with missing data');
			event.preventDefault();
			return false;
		}
	});
	
	// Prevent unhandled promise rejections from cluttering console
	window.addEventListener('unhandledrejection', function(event) {
		if (event.reason && event.reason.message && event.reason.message.indexOf('404') !== -1) {
			console.log('Caught 404 error - likely from hours component trying to load client data');
			event.preventDefault();
		}
	});
})();
</script>


@stop
