<template>
	<div class="job-page">
		<!-- Modern Header -->
		<div class="page-header">
			<div class="header-left">
				<div class="breadcrumb">
					<span class="breadcrumb-item">Projects</span>
					<span class="breadcrumb-separator">/</span>
					<span class="breadcrumb-item active">{{ job?.name || 'Loading...' }}</span>
				</div>
				<h1 class="page-title">{{ job?.projectName || 'Loading Job Details...' }}</h1>
				<div class="header-badges">
					<span class="badge badge-status" :class="getStatusClass(job?.status)">
						{{ job?.status }}
					</span>
					<span class="badge badge-priority" :class="'priority-' + job?.priority?.toLowerCase()">
						{{ job?.priority }} Priority
					</span>
					<span class="badge badge-template">
						{{ job?.projectTemplate }}
					</span>
				</div>
			</div>
			<div class="header-actions">
				<button class="btn btn-secondary">
					<span class="btn-icon">📧</span>
					Email Customer
				</button>
				<button class="btn btn-primary" @click="createInvoiceForJob()">
					<span class="btn-icon">💰</span>
					Create Invoice
				</button>
			</div>
		</div>

		<!-- Main Content Layout -->
		<div class="main-layout">
			<!-- Large Row 1: Left modules + Right map -->
			<div class="top-section">
				<!-- Left Column: Two rows of modules -->
				<div class="left-modules">
					<!-- Row 1: Metrics (Progress, Status, Financial) -->
					<div class="metrics-bar">
						<!-- Progress Card -->
						<Card class="stat-card progress-card">
							<template #content>
								<div class="stat-content">
									<div class="stat-header">
										<span class="stat-icon">📊</span>
										<h3>Progress</h3>
									</div>
									<div class="progress-circle">
										<svg viewBox="0 0 100 100">
											<defs>
												<linearGradient id="progress-gradient" x1="0%" y1="0%" x2="100%" y2="100%">
													<stop offset="0%" style="stop-color:#3b82f6;stop-opacity:1" />
													<stop offset="100%" style="stop-color:#2563eb;stop-opacity:1" />
												</linearGradient>
											</defs>
											<circle cx="50" cy="50" r="45" class="progress-bg" />
											<circle 
												cx="50" 
												cy="50" 
												r="45" 
												class="progress-fill"
												:style="{ strokeDashoffset: getProgressOffset(job?.percentComplete) }"
											/>
										</svg>
										<div class="progress-text">
											<span class="progress-value">{{ job?.percentComplete || 0 }}%</span>
											<span class="progress-label">Complete</span>
										</div>
									</div>
									<div class="progress-details">
										<div class="progress-detail">
											<span class="detail-label">Tasks Completed</span>
											<span class="detail-value">{{ completedTasksCount }} / {{ totalTasksCount }}</span>
										</div>
									</div>
								</div>
							</template>
						</Card>

				<!-- Status Tracking -->
				<Card class="stat-card status-card">
					<template #content>
						<div class="stat-content">
							<div class="stat-header">
								<span class="stat-icon">✓</span>
								<h3>Status Checks</h3>
							</div>
							<div class="status-checks">
								<div class="status-check-item">
									<div class="check-icon" :class="{ 'checked': job?.readyToSchedule }">
										{{ job?.readyToSchedule ? '✓' : '○' }}
									</div>
									<span class="check-label">Ready to Schedule</span>
								</div>
								<div class="status-check-item">
									<div class="check-icon" :class="{ 'checked': job?.customPermitStatus === 'Permit Approved' }">
										{{ job?.customPermitStatus === 'Permit Approved' ? '✓' : '○' }}
									</div>
									<span class="check-label">{{ job?.customPermitStatus || 'Permit Status' }}</span>
								</div>
								<div class="status-check-item">
									<div class="check-icon" :class="{ 'checked': job?.customUtlityLocateStatus === 'Locate complete' }">
										{{ job?.customUtlityLocateStatus === 'Locate complete' ? '✓' : '○' }}
									</div>
									<span class="check-label">{{ job?.customUtlityLocateStatus || 'Utility Locate' }}</span>
								</div>
								<div class="status-check-item">
									<div class="check-icon" :class="{ 'checked': job?.isScheduled }">
										{{ job?.isScheduled ? '✓' : '○' }}
									</div>
									<span class="check-label">{{ job?.isScheduled ? 'Scheduled' : 'Not Scheduled' }}</span>
								</div>
							</div>
						</div>
					</template>
				</Card>

				<!-- Financial Summary -->
				<Card class="stat-card financial-card">
					<template #content>
						<div class="stat-content">
							<div class="stat-header">
								<span class="stat-icon">💵</span>
								<h3>Financial</h3>
							</div>
							<div class="financial-amount">
								<span class="currency">$</span>
								<span class="amount">{{ formatAmount(job?.salesOrder?.grandTotal) }}</span>
							</div>
							<div class="financial-details">
								<div class="financial-item">
									<span class="item-label">Invoice Status</span>
									<span class="item-value" :class="getInvoiceStatusClass(job?.invoiceStatus)">
										{{ job?.invoiceStatus || 'N/A' }}
									</span>
								</div>
								<div class="financial-item" v-if="job?.salesOrder?.requiresHalfPayment">
									<span class="item-label">Down Payment ({{ formatAmount(job.salesOrder.customHalfdownAmount) }})</span>
									<span class="item-value" :class="job.salesOrder.customHalfdownIsPaid ? 'paid' : 'pending'">
										{{ job.salesOrder.customHalfdownIsPaid ? '✓ Paid' : '⏳ Pending' }}
									</span>
								</div>
								<div class="financial-item" v-if="job?.salesOrder?.advancePaid">
									<span class="item-label">Total Paid</span>
									<span class="item-value paid">${{ formatAmount(job.salesOrder.advancePaid) }}</span>
								</div>
								<div class="financial-item" v-if="job?.salesOrder?.billingStatus">
									<span class="item-label">Billing Status</span>
									<span class="item-value" :class="getBillingStatusClass(job.salesOrder.billingStatus)">
										{{ job.salesOrder.billingStatus }}
									</span>
								</div>
							</div>
						</div>
					</template>
				</Card>
			</div>

			<!-- Row 2: Client Info, Billing Address, Schedule -->
			<div class="info-bar">
				<!-- Customer Information -->
				<Card class="info-card customer-card">
					<template #content>
						<div class="card-content-flex">
							<div class="customer-header">
								<div class="customer-avatar">
									{{ getInitials(job?.customer) }}
								</div>
								<div class="customer-info">
									<h3>{{ job?.customer || 'N/A' }}</h3>
									<span class="customer-type">{{ job?.client?.customerType || 'Customer' }}</span>
								</div>
							</div>
							<div class="customer-details">
								<div class="detail-row" v-if="job?.client?.mobileNo">
									<span class="detail-icon">📱</span>
									<span class="detail-text">{{ job.client.mobileNo }}</span>
								</div>
								<div class="detail-row" v-if="job?.client?.emailId">
									<span class="detail-icon">✉️</span>
									<span class="detail-text">{{ job.client.emailId }}</span>
								</div>
								<div class="detail-row" v-if="job?.client?.territory">
									<span class="detail-icon">🗺️</span>
									<span class="detail-text">Territory: {{ job.client.territory }}</span>
								</div>
							</div>
						</div>
					</template>
				</Card>

				<!-- Billing Address -->
				<Card class="info-card billing-card">
					<template #content>
						<div class="card-content-flex">
							<div class="stat-header">
								<span class="stat-icon">📍</span>
								<h3>Job Address</h3>
							</div>
							<div class="customer-details">
								<div class="detail-row" v-if="job?.jobAddress?.fullAddress">
									<span class="detail-icon">📍</span>
									<span class="detail-text">{{ job.jobAddress.fullAddress }}</span>
								</div>
								<div class="detail-row" v-if="job?.jobAddress?.city">
									<span class="detail-icon">🏙️</span>
									<span class="detail-text">{{ job.jobAddress.city }}, {{ job.jobAddress.state }} {{ job.jobAddress.pincode }}</span>
								</div>
							</div>
						</div>
					</template>
				</Card>

				<!-- Service Appointment -->
				<Card class="info-card appointment-card">
					<template #content>
						<div class="card-content-flex">
							<div class="stat-header">
								<span class="stat-icon">📅</span>
								<h3>Service Appointment</h3>
							</div>
							<div v-if="job?.serviceAppointment" class="customer-details">
								<div class="detail-row">
									<span class="detail-label">Status:</span>
									<span class="detail-text status-badge" :class="getStatusClass(job.serviceAppointment.status)">
										{{ job.serviceAppointment.status }}
									</span>
								</div>
								<div class="detail-row" v-if="job.serviceAppointment.expectedStartDate">
									<span class="detail-label">Start:</span>
									<span class="detail-text">{{ formatDate(job.serviceAppointment.expectedStartDate) }}</span>
								</div>
								<div class="detail-row" v-if="job.serviceAppointment.expectedEndDate">
									<span class="detail-label">End:</span>
									<span class="detail-text">{{ formatDate(job.serviceAppointment.expectedEndDate) }}</span>
								</div>
								<div class="detail-row" v-if="job.serviceAppointment.foreman">
									<span class="detail-label">Foreman:</span>
									<span class="detail-text">{{ job.serviceAppointment.foreman }}</span>
								</div>
								<!-- Action Buttons -->
								<div class="appointment-actions" v-if="job.serviceAppointment.expectedStartDate">
									<button 
										class="appointment-btn appointment-btn-view"
										@click="router.push(`/calendar?tab=projects&apt=${job.serviceAppointment.name}`)"
									>
										View Appointment
									</button>
								</div>
								<div class="appointment-actions" v-else>
									<button 
										class="appointment-btn appointment-btn-schedule"
										:disabled="!job.readyToSchedule"
										@click="navigateToCalendar"
									>
										Schedule
									</button>
								</div>
							</div>
							<div v-else class="appointment-placeholder">
								<span class="placeholder-icon">📅</span>
								<p>Service appointment has not been scheduled yet</p>
							</div>
						</div>
					</template>
				</Card>
			</div>
		</div>

		<!-- Right Column: Map (Full Height) -->
		<Card class="map-card">
			<template #content>
				<div class="map-container" ref="mapContainer">
					<div v-if="!hasValidCoordinates" class="map-placeholder">
						<span class="placeholder-icon">🗺️</span>
						<p>No coordinates available</p>
					</div>
				</div>
			</template>
		</Card>
	</div>

	<!-- Large Row 2: Tasks Section (Full Width) -->
	<Card class="tasks-card">
		<template #header>
			<div class="section-header">
				<div class="header-left">
					<span class="section-icon">✓</span>
					<h3>Tasks</h3>
					<span class="task-count">{{ job?.tasks?.length || 0 }} tasks</span>
				</div>
				<div class="task-filters">
								<button 
									class="filter-btn" 
									:class="{ active: taskFilter === 'all' }"
									@click="taskFilter = 'all'"
								>
									All
								</button>
								<button 
									class="filter-btn" 
									:class="{ active: taskFilter === 'open' }"
									@click="taskFilter = 'open'"
								>
									Open
								</button>
								<button 
									class="filter-btn" 
									:class="{ active: taskFilter === 'completed' }"
									@click="taskFilter = 'completed'"
								>
									Completed
								</button>
							</div>
						</div>
					</template>
					<template #content>
						<div class="tasks-list">
							<div 
								v-for="task in filteredTasks" 
								:key="task.name"
								class="task-item"
								:class="{ 'completed': task.status === 'Completed' }"
							>
								<div class="task-left">
									<label class="task-checkbox">
										<input 
											type="checkbox" 
											:checked="task.status === 'Completed'"
											@change="toggleTaskComplete(task)"
										/>
										<span class="checkmark"></span>
									</label>
									<div class="task-info">
										<div class="task-title-row">
											<h4 class="task-title">{{ task.subject }}</h4>
											<span class="task-id">{{ task.name }}</span>
										</div>
										<div class="task-meta">
											<span class="task-badge task-type" v-if="task.type?.name">
												{{ task.type.name }}
											</span>
											<span class="task-badge task-priority" :class="'priority-' + task.priority?.toLowerCase()">
												{{ task.priority }}
											</span>
											<span class="task-badge task-weight" v-if="task.type?.weight">
												Weight: {{ task.type.weight }}
											</span>
											<span class="task-badge task-work-type" v-if="task.type?.workType">
												{{ task.type.workType }}
											</span>
											<span class="task-due" v-if="task.type?.noDueDate === 0 && task.expEndDate">
												<span class="due-icon">📅</span>
												{{ formatDate(task.expEndDate) }}
											</span>
											<span class="task-due task-due-not-set" v-else-if="task.type?.noDueDate === 0 && !task.expEndDate">
												<span class="due-icon">📅</span>
												Due date not set yet
											</span>
											<span class="task-due task-no-due" v-else-if="task.type?.noDueDate === 1">
												<span class="due-icon">📅</span>
												No due date
											</span>
										</div>
									</div>
								</div>
								<div class="task-right">
									<select 
										v-model="task.status"
										@change="updateTaskStatus(task)"
										class="task-status-select"
										:class="getStatusClass(task.status)"
									>
										<option v-for="status in statusOptions" :key="status" :value="status">
											{{ status }}
										</option>
									</select>
								</div>
							</div>
							<div v-if="filteredTasks.length === 0" class="no-tasks">
								<span class="no-tasks-icon">📋</span>
								<p>No {{ taskFilter !== 'all' ? taskFilter : '' }} tasks found</p>
							</div>
						</div>
					</template>
				</Card>
		</div>
	</div>
</template>

<script setup>
import Card from "../common/Card.vue";
import { ref, onMounted, computed, nextTick } from "vue";
import { useRoute, useRouter } from "vue-router";
import Api from "../../api";
import { useNotificationStore } from "../../stores/notifications-primevue";

const notifications = useNotificationStore();
const route = useRoute();
const router = useRouter();
const jobIdQuery = computed(() => route.query.name || "");
const isNew = computed(() => route.query.new === "true");

const job = ref(null);
const mapContainer = ref(null);
const mapInstance = ref(null);
const taskFilter = ref('all');

const statusOptions = ref([
	"Open",
	"Working",
	"Pending Review",
	"Overdue",
	"Completed",
	"Cancelled",
]);

const hasValidCoordinates = computed(() => {
	const lat = parseFloat(job.value?.jobAddress?.customLatitude);
	const lng = parseFloat(job.value?.jobAddress?.customLongitude);
	return !isNaN(lat) && !isNaN(lng) && lat !== 0 && lng !== 0;
});

const completedTasksCount = computed(() => {
	return job.value?.tasks?.filter(task => task.status === 'Completed').length || 0;
});

const totalTasksCount = computed(() => {
	return job.value?.tasks?.length || 0;
});

const filteredTasks = computed(() => {
	if (!job.value?.tasks) return [];
	
	if (taskFilter.value === 'all') return job.value.tasks;
	if (taskFilter.value === 'completed') {
		return job.value.tasks.filter(task => task.status === 'Completed');
	}
	if (taskFilter.value === 'open') {
		return job.value.tasks.filter(task => task.status !== 'Completed');
	}
	return job.value.tasks;
});

const getProgressOffset = (percent) => {
	const circumference = 2 * Math.PI * 45;
	const offset = circumference - (percent / 100) * circumference;
	return offset;
};

const getInitials = (name) => {
	if (!name) return '?';
	const parts = name.split(' ');
	if (parts.length >= 2) {
		return (parts[0][0] + parts[1][0]).toUpperCase();
	}
	return name.substring(0, 2).toUpperCase();
};

const getInvoiceStatusClass = (status) => {
	if (!status) return '';
	const statusLower = status.toLowerCase();
	if (statusLower.includes('ready')) return 'ready';
	if (statusLower.includes('not ready')) return 'not-ready';
	if (statusLower.includes('completed')) return 'completed';
	return '';
};

const getBillingStatusClass = (status) => {
	if (!status) return '';
	const statusLower = status.toLowerCase();
	if (statusLower.includes('fully billed')) return 'completed';
	if (statusLower.includes('partly billed')) return 'pending';
	if (statusLower.includes('not billed')) return 'not-ready';
	return '';
};

const initializeMap = async () => {
	if (!hasValidCoordinates.value || !mapContainer.value) return;

	// Wait for next tick to ensure DOM is ready
	await nextTick();

	try {
		// Dynamically import Leaflet
		const L = (await import('leaflet')).default;
		await import('leaflet/dist/leaflet.css');

		const lat = parseFloat(job.value.jobAddress.customLatitude);
		const lng = parseFloat(job.value.jobAddress.customLongitude);

		// Initialize map
		mapInstance.value = L.map(mapContainer.value, {
			zoomControl: true,
			scrollWheelZoom: true,
		}).setView([lat, lng], 15);

		// Add OpenStreetMap tiles
		L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
			attribution: '© OpenStreetMap contributors',
			maxZoom: 19,
		}).addTo(mapInstance.value);

		// Add marker
		const customIcon = L.divIcon({
			className: 'custom-marker',
			html: '<div style="background: #3b82f6; width: 30px; height: 30px; border-radius: 50% 50% 50% 0; transform: rotate(-45deg); border: 3px solid white; box-shadow: 0 2px 8px rgba(0,0,0,0.3);"><div style="width: 10px; height: 10px; background: white; border-radius: 50%; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%);"></div></div>',
			iconSize: [30, 30],
			iconAnchor: [15, 30],
		});

		L.marker([lat, lng], { icon: customIcon })
			.addTo(mapInstance.value)
			.bindPopup(`
				<div style="font-size: 14px;">
					<strong>${job.value.jobAddress.addressLine1}</strong><br>
					${job.value.jobAddress.city}, ${job.value.jobAddress.state} ${job.value.jobAddress.pincode}
				</div>
			`);

		// Trigger resize to ensure proper rendering
		setTimeout(() => {
			if (mapInstance.value) {
				mapInstance.value.invalidateSize();
			}
		}, 100);
	} catch (error) {
		console.error("Error initializing map:", error);
	}
};

const createInvoiceForJob = async () => {
	if (!job.value) return;
	try {
		await Api.createInvoiceForJob(job.value.name);
		notifications.addSuccess("Invoice created successfully");
	} catch (error) {
		console.error("Error creating invoice:", error);
		notifications.addError("Failed to create invoice");
	}
};

const navigateToCalendar = () => {
	router.push('/calendar?tab=projects');
};

const toggleTaskComplete = async (task) => {
	const newStatus = task.status === "Completed" ? "Open" : "Completed";
	task.status = newStatus;
	await updateTaskStatus(task);
};

const updateTaskStatus = async (task) => {
	try {
		await Api.setTaskStatus(task.name, task.status);
		notifications.addSuccess(`Task status updated to ${task.status}`);
	} catch (error) {
		console.error("Error updating task status:", error);
		notifications.addError("Failed to update task status");
	}
};

const formatDate = (dateString) => {
	if (!dateString) return 'N/A';
	const date = new Date(dateString);
	return date.toLocaleDateString('en-US', { 
		year: 'numeric', 
		month: 'short', 
		day: 'numeric' 
	});
};

const formatAmount = (amount) => {
	if (!amount) return '0.00';
	return Number(amount).toLocaleString('en-US', {
		minimumFractionDigits: 2,
		maximumFractionDigits: 2
	});
};

const getStatusClass = (status) => {
	if (!status) return '';
	const statusLower = status.toLowerCase();
	if (statusLower.includes('complete')) return 'status-completed';
	if (statusLower.includes('open')) return 'status-open';
	if (statusLower.includes('working') || statusLower.includes('progress')) return 'status-working';
	if (statusLower.includes('cancelled')) return 'status-cancelled';
	if (statusLower.includes('overdue')) return 'status-overdue';
	return '';
};

onMounted(async () => {
	console.log("DEBUG: Query params:", route.query);

	try {
		const optionsResult = await Api.getTaskStatusOptions();
		if (optionsResult && optionsResult.length > 0) {
			statusOptions.value = optionsResult;
		}
	} catch (error) {
		console.error("Error loading task status options:", error);
	}

	if (jobIdQuery.value) {
		try {
			job.value = await Api.getJob(jobIdQuery.value);
			console.log("DEBUG: Loaded job:", job.value);
			
			// Initialize map after job data is loaded
			await nextTick();
			await initializeMap();
		} catch (error) {
			console.error("Error loading job from DB:", error);
			notifications.addError("Failed to load job details");
		}
	}
});
</script>

<style scoped>
/* Base Styles */
.job-page {
	padding: 0;
	background: #f8f9fa;
	min-height: 100vh;
}

/* Compact Header */
.page-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	background: white;
	padding: 16px 32px;
	box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);
	border-bottom: 1px solid #e9ecef;
	margin-bottom: 0;
}

.header-left {
	flex: 1;
	max-width: calc(100% - 380px);
}

.breadcrumb {
	display: flex;
	align-items: center;
	gap: 6px;
	margin-bottom: 8px;
	font-size: 12px;
	color: #6c757d;
}

.breadcrumb-item {
	color: #6c757d;
}

.breadcrumb-item.active {
	color: #212529;
	font-weight: 500;
}

.breadcrumb-separator {
	color: #dee2e6;
}

.page-title {
	margin: 0 0 8px 0;
	font-size: 20px;
	font-weight: 600;
	color: #212529;
	line-height: 1.3;
}

.header-badges {
	display: flex;
	gap: 8px;
	flex-wrap: wrap;
}

.badge {
	padding: 4px 10px;
	border-radius: 4px;
	font-size: 11px;
	font-weight: 600;
	text-transform: uppercase;
	letter-spacing: 0.3px;
}

.badge-status.status-open {
	background: #0d6efd;
	color: white;
}

.badge-status.status-completed {
	background: #198754;
	color: white;
}

.badge-status.status-working {
	background: #fd7e14;
	color: white;
}

.badge-priority {
	background: #e9ecef;
	color: #495057;
}

.badge-priority.priority-high {
	background: #dc3545;
	color: white;
}

.badge-priority.priority-medium {
	background: #ffc107;
	color: #000;
}

.badge-priority.priority-low {
	background: #198754;
	color: white;
}

.badge-template {
	background: #6c757d;
	color: white;
}

.header-actions {
	display: flex;
	gap: 10px;
	align-items: center;
}

.btn {
	display: flex;
	align-items: center;
	gap: 6px;
	padding: 8px 16px;
	border-radius: 4px;
	border: none;
	font-size: 13px;
	font-weight: 600;
	cursor: pointer;
	transition: all 0.2s;
	white-space: nowrap;
}

.btn:hover {
	transform: translateY(-1px);
	box-shadow: 0 2px 4px rgba(0, 0, 0, 0.15);
}

.btn-primary {
	background: #0d6efd;
	color: white;
}

.btn-primary:hover {
	background: #0b5ed7;
}

.btn-secondary {
	background: white;
	color: #495057;
	border: 1px solid #ced4da;
}

.btn-secondary:hover {
	background: #f8f9fa;
}

.btn-icon {
	font-size: 14px;
}

/* Main Layout - Dashboard Style */
.main-layout {
	display: flex;
	flex-direction: column;
	gap: 24px;
	padding: 24px 32px;
	max-width: 100%;
	margin: 0;
}

/* Top Section: 2 Columns (Left Modules + Map) */
.top-section {
	display: grid;
	grid-template-columns: 1fr 1fr;
	gap: 24px;
	align-items: start;
}

/* Left Column: 2 Rows of Modules */
.left-modules {
	display: flex;
	flex-direction: column;
	gap: 24px;
}

/* Row 1: Metrics Bar (3 modules) */
.metrics-bar {
	display: grid;
	grid-template-columns: repeat(3, 1fr);
	gap: 0;
	background: white;
	border: 1px solid #e9ecef;
	border-radius: 6px;
	overflow: hidden;
	box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);
}

/* Row 2: Info Bar (3 modules) */
.info-bar {
	display: grid;
	grid-template-columns: repeat(3, 1fr);
	gap: 0;
	background: white;
	border: 1px solid #e9ecef;
	border-radius: 6px;
	overflow: hidden;
	box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);
}

.stat-card {
	background: white;
	border-radius: 0;
	box-shadow: none;
	overflow: hidden;
	transition: background 0.2s;
	border-right: 1px solid #e9ecef;
}

.stat-card:last-child {
	border-right: none;
}

.stat-card:hover {
	background: #f8f9fa;
}

.info-card {
	background: white;
	border-radius: 0;
	box-shadow: none;
	overflow: hidden;
	transition: background 0.2s;
	border-right: 1px solid #e9ecef;
}

.info-card:last-child {
	border-right: none;
}

.info-card:hover {
	background: #f8f9fa;
}

.stat-content {
	padding: 20px 24px;
}

.stat-header {
	display: flex;
	align-items: center;
	gap: 8px;
	margin-bottom: 12px;
}

.stat-icon {
	font-size: 18px;
}

.stat-header h3 {
	margin: 0;
	font-size: 13px;
	font-weight: 600;
	color: #6c757d;
	text-transform: uppercase;
	letter-spacing: 0.5px;
}

/* Progress Card with Circle */
.progress-circle {
	position: relative;
	width: 100px;
	height: 100px;
	margin: 12px auto;
}

.progress-circle svg {
	width: 100%;
	height: 100%;
	transform: rotate(-90deg);
}

.progress-bg {
	fill: none;
	stroke: #e9ecef;
	stroke-width: 8;
}

.progress-fill {
	fill: none;
	stroke: url(#progress-gradient);
	stroke-width: 8;
	stroke-linecap: round;
	stroke-dasharray: 283;
	transition: stroke-dashoffset 1s ease;
}

.progress-text {
	position: absolute;
	top: 50%;
	left: 50%;
	transform: translate(-50%, -50%);
	text-align: center;
}

.progress-value {
	display: block;
	font-size: 24px;
	font-weight: 700;
	color: #0d6efd;
	line-height: 1;
	margin-bottom: 2px;
}

.progress-label {
	display: block;
	font-size: 10px;
	color: #6c757d;
	font-weight: 600;
	text-transform: uppercase;
	letter-spacing: 0.5px;
}

.progress-details {
	margin-top: 12px;
	padding-top: 12px;
	border-top: 1px solid #e9ecef;
}

.progress-detail {
	display: flex;
	justify-content: space-between;
	align-items: center;
	gap: 8px;
}

.detail-label {
	font-size: 11px;
	color: #6c757d;
	font-weight: 500;
}

.detail-value {
	font-size: 14px;
	color: #212529;
	font-weight: 700;
}

/* Financial Card - Compact */
.financial-amount {
	display: flex;
	align-items: baseline;
	justify-content: flex-start;
	margin: 0 0 12px 0;
}

.currency {
	font-size: 18px;
	color: #198754;
	font-weight: 700;
	margin-right: 2px;
}

.amount {
	font-size: 28px;
	font-weight: 700;
	color: #198754;
	line-height: 1;
}

.financial-details {
	display: flex;
	flex-direction: column;
	gap: 6px;
	margin-top: 12px;
	padding-top: 0;
	border-top: none;
}

.financial-item {
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.item-label {
	font-size: 12px;
	color: #6c757d;
	font-weight: 500;
}

.item-value {
	font-size: 11px;
	font-weight: 600;
	padding: 2px 8px;
	border-radius: 3px;
}

.item-value.paid {
	background: #d1e7dd;
	color: #0f5132;
}

.item-value.pending {
	background: #fff3cd;
	color: #664d03;
}

.item-value.not-ready {
	background: #f8d7da;
	color: #842029;
}

.item-value.ready {
	background: #cfe2ff;
	color: #084298;
}

.item-value.completed {
	background: #d1e7dd;
	color: #0f5132;
}

/* Status Card - Compact */
.status-checks {
	display: flex;
	flex-direction: column;
	gap: 8px;
	margin-top: 0;
}

.status-check-item {
	display: flex;
	align-items: center;
	gap: 10px;
	padding: 6px 0;
	border-radius: 0;
	transition: none;
}

.status-check-item:hover {
	background: transparent;
}

.check-icon {
	width: 20px;
	height: 20px;
	border-radius: 3px;
	border: 2px solid #ced4da;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 11px;
	color: #adb5bd;
	font-weight: 700;
	transition: all 0.2s;
	flex-shrink: 0;
}

.check-icon.checked {
	background: #198754;
	border-color: #198754;
	color: white;
}

.check-label {
	font-size: 12px;
	color: #495057;
	font-weight: 500;
}

/* Row 2: Customer & Schedule */
.customer-schedule-row {
	display: grid;
	grid-template-columns: 1fr 1fr;
	gap: 24px;
}

/* Customer Card */
.customer-card {
	background: white;
	border-radius: 6px;
	box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);
	border: 1px solid #e9ecef;
	overflow: hidden;
	height: 100%;
}

.card-content-flex {
	height: 100%;
	display: flex;
	flex-direction: column;
	padding: 20px;
}

.customer-header {
	display: flex;
	align-items: center;
	gap: 12px;
	margin-bottom: 16px;
	padding-bottom: 16px;
	border-bottom: 1px solid #e9ecef;
}

.customer-avatar {
	width: 48px;
	height: 48px;
	border-radius: 50%;
	background: #0d6efd;
	color: white;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 18px;
	font-weight: 700;
	flex-shrink: 0;
}

.customer-info h3 {
	margin: 0;
	font-size: 16px;
	font-weight: 600;
	color: #212529;
}

.customer-type {
	font-size: 12px;
	color: #6c757d;
	font-weight: 500;
}

.customer-details {
	display: flex;
	flex-direction: column;
	gap: 10px;
}

.detail-row {
	display: flex;
	align-items: center;
	gap: 10px;
	padding: 0;
	background: transparent;
	border-radius: 0;
	transition: none;
}

.detail-row:hover {
	background: transparent;
}

.detail-icon {
	font-size: 16px;
	color: #6c757d;
	width: 20px;
	text-align: center;
	flex-shrink: 0;
}

.detail-text {
	font-size: 13px;
	color: #495057;
	font-weight: 400;
}

/* Map Card - Right Column Full Height */
.map-card {
	background: white;
	border-radius: 6px;
	box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);
	border: 1px solid #e9ecef;
	overflow: hidden;
	width: 100%;
	height: 100%;
	min-height: 500px;
}

.map-container {
	width: 100%;
	height: 100%;
	min-height: 500px;
	position: relative;
}

.map-placeholder {
	width: 100%;
	height: 100%;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	background: #f8f9fa;
	color: #adb5bd;
}

.placeholder-icon {
	font-size: 40px;
	margin-bottom: 8px;
}

.map-placeholder p {
	margin: 0;
	font-size: 13px;
	font-weight: 500;
}

/* Service Appointment Card */
.appointment-card {
	background: white;
	border-radius: 6px;
	box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);
	border: 1px solid #e9ecef;
	overflow: hidden;
	height: 100%;
}

.appointment-placeholder {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 20px;
	text-align: center;
	color: #adb5bd;
}

.appointment-placeholder .placeholder-icon {
	font-size: 32px;
	margin-bottom: 8px;
	opacity: 0.5;
}

.appointment-placeholder p {
	margin: 0;
	font-size: 12px;
	font-weight: 500;
}

.appointment-actions {
	margin-top: 16px;
	padding-top: 16px;
	border-top: 1px solid #e9ecef;
}

.appointment-btn {
	display: inline-flex;
	align-items: center;
	justify-content: center;
	width: 100%;
	padding: 8px 16px;
	border-radius: 4px;
	border: none;
	font-size: 12px;
	font-weight: 600;
	cursor: pointer;
	transition: all 0.2s;
	text-decoration: none;
	text-align: center;
}

.appointment-btn-view {
	background: #0d6efd;
	color: white;
}

.appointment-btn-view:hover {
	background: #0b5ed7;
	transform: translateY(-1px);
	box-shadow: 0 2px 4px rgba(0, 0, 0, 0.15);
}

.appointment-btn-schedule {
	background: #198754;
	color: white;
}

.appointment-btn-schedule:hover:not(:disabled) {
	background: #157347;
	transform: translateY(-1px);
	box-shadow: 0 2px 4px rgba(0, 0, 0, 0.15);
}

.appointment-btn-schedule:disabled {
	background: #e9ecef;
	color: #adb5bd;
	cursor: not-allowed;
	opacity: 0.6;
}

.status-badge {
	padding: 2px 8px;
	border-radius: 3px;
	font-size: 11px;
	font-weight: 600;
}

/* Timeline Card (deprecated - keeping for compatibility) */
.timeline-card {
	background: white;
	border-radius: 6px;
	box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);
	border: 1px solid #e9ecef;
	overflow: hidden;
	height: 100%;
}

.section-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	gap: 12px;
	padding: 16px 20px;
	border-bottom: 1px solid #e9ecef;
	background: #f8f9fa;
}

.section-header .header-left {
	display: flex;
	align-items: center;
	gap: 10px;
}

.section-icon {
	font-size: 18px;
}

.section-header h3 {
	margin: 0;
	font-size: 14px;
	font-weight: 600;
	color: #212529;
}

.timeline {
	display: grid;
	grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
	padding: 0;
	gap: 0;
	align-items: stretch;
}

.timeline-item {
	flex: 1;
	position: relative;
	padding: 16px 20px;
	background: white;
	border-radius: 0;
	border: none;
	border-right: 1px solid #e9ecef;
	transition: background 0.2s;
	min-height: 0;
	display: flex;
	flex-direction: column;
	justify-content: center;
}

.timeline-item:last-child {
	border-right: none;
}

.timeline-item.completed {
	background: #f0f9f4;
	border-right-color: #d1e7dd;
}

.timeline-item:hover {
	transform: none;
	box-shadow: none;
	background: #f8f9fa;
}

.timeline-item.completed:hover {
	background: #e8f5ec;
}

.timeline-marker {
	display: none;
}

.timeline-title {
	font-size: 11px;
	font-weight: 600;
	color: #6c757d;
	margin-bottom: 8px;
	text-transform: uppercase;
	letter-spacing: 0.5px;
}

.timeline-date {
	display: flex;
	gap: 6px;
	margin-bottom: 4px;
	align-items: baseline;
}

.date-label {
	font-size: 11px;
	color: #6c757d;
	font-weight: 500;
	min-width: 50px;
}

.date-value {
	font-size: 13px;
	color: #212529;
	font-weight: 600;
}

/* Tasks Card - Main Focus */
.tasks-card {
	background: white;
	border-radius: 6px;
	box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);
	border: 1px solid #e9ecef;
	overflow: hidden;
	width: 100%;
}

.task-count {
	padding: 3px 10px;
	background: #e9ecef;
	border-radius: 12px;
	font-size: 11px;
	font-weight: 600;
	color: #495057;
}

.task-filters {
	display: flex;
	gap: 6px;
	margin-left: auto;
}

.filter-btn {
	padding: 6px 14px;
	border-radius: 4px;
	border: 1px solid #ced4da;
	background: white;
	color: #495057;
	font-size: 12px;
	font-weight: 600;
	cursor: pointer;
	transition: all 0.2s;
}

.filter-btn:hover {
	border-color: #0d6efd;
	color: #0d6efd;
	background: #f8f9fa;
}

.filter-btn.active {
	background: #0d6efd;
	border-color: #0d6efd;
	color: white;
}

.tasks-list {
	padding: 0;
}

.task-item {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 16px 20px;
	border-bottom: 1px solid #f1f3f5;
	transition: all 0.2s;
}

.task-item:hover {
	background: #f8f9fa;
}

.task-item:last-child {
	border-bottom: none;
}

.task-item.completed {
	opacity: 0.7;
	background: #f8f9fa;
}

.task-item.completed .task-title {
	text-decoration: line-through;
	color: #6c757d;
}

.task-left {
	display: flex;
	align-items: flex-start;
	gap: 12px;
	flex: 1;
}

.task-checkbox {
	position: relative;
	margin-top: 2px;
}

.task-checkbox input[type="checkbox"] {
	position: absolute;
	opacity: 0;
	cursor: pointer;
}

.checkmark {
	position: relative;
	display: block;
	width: 20px;
	height: 20px;
	border-radius: 4px;
	border: 2px solid #ced4da;
	background: white;
	cursor: pointer;
	transition: all 0.2s;
}

.task-checkbox input:checked ~ .checkmark {
	background: #0d6efd;
	border-color: #0d6efd;
}

.task-checkbox input:checked ~ .checkmark::after {
	content: '✓';
	position: absolute;
	top: 50%;
	left: 50%;
	transform: translate(-50%, -50%);
	color: white;
	font-size: 12px;
	font-weight: 700;
}

.task-info {
	flex: 1;
}

.task-title-row {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 6px;
}

.task-title {
	margin: 0;
	font-size: 14px;
	font-weight: 600;
	color: #212529;
}

.task-id {
	font-size: 11px;
	color: #adb5bd;
	font-family: 'Courier New', monospace;
	font-weight: 500;
}

.task-meta {
	display: flex;
	gap: 8px;
	flex-wrap: wrap;
	align-items: center;
}

.task-badge {
	padding: 2px 8px;
	border-radius: 3px;
	font-size: 10px;
	font-weight: 600;
	text-transform: uppercase;
	letter-spacing: 0.3px;
}

.task-type {
	background: #e9ecef;
	color: #495057;
}

.task-weight {
	background: #d3d3f8;
	color: #3730a3;
}

.task-work-type {
	background: #fce7f3;
	color: #9f1239;
}

.task-priority.priority-high {
	background: #f8d7da;
	color: #842029;
}

.task-priority.priority-medium {
	background: #fff3cd;
	color: #664d03;
}

.task-priority.priority-low {
	background: #d1e7dd;
	color: #0f5132;
}

.task-due {
	display: flex;
	align-items: center;
	gap: 4px;
	font-size: 11px;
	color: #6c757d;
	font-weight: 500;
}

.task-due.task-due-not-set {
	color: #dc3545;
	font-style: italic;
}

.task-due.task-no-due {
	color: #adb5bd;
	font-style: italic;
}

.due-icon {
	font-size: 12px;
}

.task-right {
	margin-left: 16px;
}

.task-status-select {
	padding: 6px 12px;
	border-radius: 4px;
	border: 1px solid #ced4da;
	font-size: 12px;
	font-weight: 600;
	cursor: pointer;
	transition: all 0.2s;
	min-width: 130px;
	background: white;
}

.task-status-select:hover {
	border-color: #0d6efd;
}

.task-status-select:focus {
	outline: none;
	border-color: #0d6efd;
	box-shadow: 0 0 0 3px rgba(13, 110, 253, 0.1);
}

.task-status-select.status-completed {
	background: #d1e7dd;
	border-color: #198754;
	color: #0f5132;
}

.task-status-select.status-working {
	background: #fff3cd;
	border-color: #ffc107;
	color: #664d03;
}

.task-status-select.status-open {
	background: #cfe2ff;
	border-color: #0d6efd;
	color: #084298;
}

.no-tasks {
	padding: 48px 20px;
	text-align: center;
}

.no-tasks-icon {
	font-size: 40px;
	margin-bottom: 8px;
	opacity: 0.5;
}

.no-tasks p {
	margin: 0;
	color: #adb5bd;
	font-size: 13px;
	font-weight: 500;
}

/* Responsive Design */
@media (max-width: 1400px) {
	.top-section {
		grid-template-columns: 1fr;
		gap: 24px;
	}

	.map-card {
		min-height: 400px;
	}
	
	.map-container {
		min-height: 400px;
	}
}

@media (max-width: 1200px) {
	.metrics-bar {
		grid-template-columns: 1fr;
	}
	
	.info-bar {
		grid-template-columns: 1fr;
	}
	
	.stat-card {
		border-right: none;
		border-bottom: 1px solid #e9ecef;
	}
	
	.stat-card:last-child {
		border-bottom: none;
	}
	
	.info-card {
		border-right: none;
		border-bottom: 1px solid #e9ecef;
	}
	
	.info-card:last-child {
		border-bottom: none;
	}
}

@media (max-width: 768px) {
	.page-header {
		flex-direction: column;
		align-items: flex-start;
		gap: 12px;
		padding: 16px 20px;
	}

	.header-left {
		max-width: 100%;
	}

	.header-actions {
		flex-direction: row;
		width: 100%;
		gap: 8px;
	}

	.btn {
		flex: 1;
		justify-content: center;
		font-size: 12px;
		padding: 8px 12px;
	}

	.main-layout {
		padding: 16px 20px;
		gap: 16px;
	}

	.map-container {
		min-height: 300px;
	}

	.task-item {
		flex-direction: column;
		align-items: flex-start;
		gap: 12px;
		padding: 16px;
	}

	.task-right {
		margin-left: 0;
		width: 100%;
	}

	.task-status-select {
		width: 100%;
	}

	.section-header {
		flex-direction: column;
		align-items: flex-start;
		gap: 12px;
	}

	.task-filters {
		margin-left: 0;
		width: 100%;
	}

	.filter-btn {
		flex: 1;
	}
}

</style>
