<?php
/**
 * Appointments Management
 */

session_start();
require_once '../config/database.php';
// E-Mail-Benachrichtigungen entfernt - WhatsApp wird verwendet

// Check if user is logged in
if (!isset($_SESSION['admin_logged_in']) || !$_SESSION['admin_logged_in']) {
    header('Location: login.php');
    exit;
}

$db = new Database();
$conn = $db->getConnection();

// Get current user data with autohaus information
$current_user_id = $_SESSION['admin_user_id'] ?? null;
$current_user_name = 'Administrator'; // Default name
$current_user_role = 'admin';
$current_user_autohaus_id = null;
$current_user_autohaus_name = null;
$can_switch_autohaus = false;

if ($current_user_id) {
    $stmt = $conn->prepare("
        SELECT u.role, u.autohaus_id, u.can_switch_autohaus, a.name as autohaus_name, u.username
        FROM admin_users u
        LEFT JOIN autohaus a ON u.autohaus_id = a.id
        WHERE u.id = ?
    ");
    $stmt->execute([$current_user_id]);
    $user_data = $stmt->fetch(PDO::FETCH_ASSOC);
    $current_user_role = $user_data['role'] ?? 'admin';
    $current_user_autohaus_id = $user_data['autohaus_id'];
    $current_user_autohaus_name = $user_data['autohaus_name'];
    $current_user_name = $user_data['username'] ?? 'Administrator';
    $can_switch_autohaus = $user_data['can_switch_autohaus'] == 1;
}

// Get user theme preference
$current_theme = 'light';
if ($current_user_id) {
    $stmt = $conn->prepare("SELECT theme FROM admin_users WHERE id = ?");
    $stmt->execute([$current_user_id]);
    $theme_result = $stmt->fetch();
    $current_theme = $theme_result['theme'] ?? 'light';
}

$action = $_GET['action'] ?? 'list';
$appointment_id = $_GET['id'] ?? null;
$event_id = $_GET['event_id'] ?? null;

// Handle form submissions
if ($_POST) {
    $postAction = $_POST['action'] ?? $action;
    $postId = $_POST['id'] ?? $appointment_id;
    if (($postAction === 'update' || $postAction === 'update_order_number') && $postId) {
        handleAppointmentUpdate($conn, $postId);
    } elseif ($postAction === 'delete' && $postId) {
        handleAppointmentDelete($conn, $postId);
    } elseif ($postAction === 'copy' && $postId) {
        handleAppointmentCopy($conn, $postId);
    } elseif ($postAction === 'bulk_delete') {
        handleBulkDelete($conn);
    } elseif ($postAction === 'bulk_tire_order') {
        handleBulkTireOrder($conn);
    }
}

// Handle delete via GET links
if ($_SERVER['REQUEST_METHOD'] === 'GET' && $action === 'delete' && $appointment_id) {
    handleAppointmentDelete($conn, $appointment_id);
}

// Get appointments (filtered by autohaus)
$appointments = getAppointments($conn, $event_id, $current_user_autohaus_id, $current_user_role, $can_switch_autohaus);

// Debug: Ensure appointments is properly initialized
if (!is_array($appointments)) {
    error_log("ERROR: appointments is not an array: " . print_r($appointments, true));
    $appointments = [];
}

function getAppointments($conn, $event_id = null, $autohaus_id = null, $user_role = 'admin', $can_switch_autohaus = false) {
    $sql = "
        SELECT a.*, e.name as event_name, e.event_date, e.max_monteure,
               slot_stats.booked_count as booked_appointments,
               slot_stats.total_count as total_appointments,
               ah.name as autohaus_name
        FROM appointments a
        JOIN events e ON a.event_id = e.id
        LEFT JOIN autohaus ah ON a.autohaus_id = ah.id
        LEFT JOIN (
            SELECT 
                event_id, 
                slot_date, 
                slot_time,
                COUNT(*) as total_count,
                COUNT(CASE WHEN status IN ('booked', 'vorbereitet', 'completed') THEN 1 END) as booked_count
            FROM appointments 
            GROUP BY event_id, slot_date, slot_time
        ) slot_stats ON a.event_id = slot_stats.event_id 
                     AND a.slot_date = slot_stats.slot_date 
                     AND a.slot_time = slot_stats.slot_time
        WHERE 1=1
    ";
    
    $params = [];
    
    if ($event_id) {
        $sql .= " AND a.event_id = ?";
        $params[] = $event_id;
    }
    
    // If user is not admin or can't switch autohaus, filter by their autohaus
    if ($user_role !== 'admin' || !$can_switch_autohaus) {
        if ($autohaus_id) {
            $sql .= " AND a.autohaus_id = ?";
            $params[] = $autohaus_id;
        } else {
            // User has no autohaus assigned, show no appointments
            $sql .= " AND a.autohaus_id IS NULL";
        }
    }
    
    $sql .= " ORDER BY a.slot_date DESC, a.slot_time DESC";
    
    $stmt = $conn->prepare($sql);
    $stmt->execute($params);
    return $stmt->fetchAll();
}

function handleAppointmentUpdate($conn, $appointment_id) {
    global $error_message, $success_message;
    
    try {
        $action = $_POST['action'] ?? 'update';
        
        // Handle different actions
        if ($action === 'approve') {
            $status = 'approved';
            $orderNumber = $_POST['order_number'] ?? null;
            $adminNotes = $_POST['admin_notes'] ?? null;
            $approvedBy = $_SESSION['admin_user_id'] ?? 1;
            $stmt = $conn->prepare("
                UPDATE appointments 
                SET status = ?, order_number = ?, admin_notes = ?, 
                    approved_by = ?, approved_at = NOW()
                WHERE id = ?
            ");
            $stmt->execute([$status, $orderNumber, $adminNotes, $approvedBy, $appointment_id]);
            
            // WhatsApp-Benachrichtigung senden
            try {
                require_once '../api/autohaus_whatsapp_notifications.php';
                $whatsapp = new AutohausWhatsAppNotifications($autohaus_id ?? null);
                $whatsappResult = $whatsapp->sendAppointmentNotification($appointment_id, 'approved');
                
                if ($whatsappResult['success']) {
                    $_SESSION['success_message'] = 'Terminanfrage genehmigt - WhatsApp-Benachrichtigung gesendet';
                } else {
                    $_SESSION['success_message'] = 'Terminanfrage genehmigt - WhatsApp-Benachrichtigung fehlgeschlagen: ' . $whatsappResult['error'];
                }
            } catch (Exception $e) {
                $_SESSION['success_message'] = 'Terminanfrage genehmigt - WhatsApp-Benachrichtigung konnte nicht gesendet werden';
                error_log("WhatsApp-Benachrichtigung Fehler: " . $e->getMessage());
            }
            
        } elseif ($action === 'reject') {
            $status = 'rejected';
            $adminNotes = $_POST['admin_notes'] ?? null;
            $rejectionReason = $_POST['rejection_reason'] ?? 'Nicht verfügbar';
            $stmt = $conn->prepare("
                UPDATE appointments 
                SET status = ?, admin_notes = ?, rejection_reason = ?, approved_by = ?, approved_at = NOW()
                WHERE id = ?
            ");
            $approvedBy = $_SESSION['admin_user_id'] ?? 1;
            $stmt->execute([$status, $adminNotes, $rejectionReason, $approvedBy, $appointment_id]);
            
            // WhatsApp-Benachrichtigung senden
            try {
                require_once '../api/autohaus_whatsapp_notifications.php';
                $whatsapp = new AutohausWhatsAppNotifications($autohaus_id ?? null);
                $whatsappResult = $whatsapp->sendAppointmentNotification($appointment_id, 'rejected');
                
                if ($whatsappResult['success']) {
                    $_SESSION['success_message'] = 'Terminanfrage abgelehnt - WhatsApp-Benachrichtigung gesendet';
                } else {
                    $_SESSION['success_message'] = 'Terminanfrage abgelehnt - WhatsApp-Benachrichtigung fehlgeschlagen: ' . $whatsappResult['error'];
                }
            } catch (Exception $e) {
                $_SESSION['success_message'] = 'Terminanfrage abgelehnt - WhatsApp-Benachrichtigung konnte nicht gesendet werden';
                error_log("WhatsApp-Benachrichtigung Fehler: " . $e->getMessage());
            }
            
        } elseif ($action === 'reschedule') {
            $status = 'rescheduled';
            $newSlotDate = $_POST['new_slot_date'] ?? null;
            $newSlotTime = $_POST['new_slot_time'] ?? null;
            $rescheduleReason = $_POST['reschedule_reason'] ?? 'Termin verschoben';
            $adminNotes = $_POST['admin_notes'] ?? null;
            $approvedBy = $_SESSION['admin_user_id'] ?? 1;
            
            if ($newSlotDate && $newSlotTime) {
                $stmt = $conn->prepare("
                    UPDATE appointments 
                    SET status = ?, slot_date = ?, slot_time = ?, reschedule_reason = ?, 
                        admin_notes = ?, approved_by = ?, approved_at = NOW()
                    WHERE id = ?
                ");
                $stmt->execute([$status, $newSlotDate, $newSlotTime, $rescheduleReason, $adminNotes, $approvedBy, $appointment_id]);
                
                // WhatsApp-Benachrichtigung senden
                try {
                    require_once '../api/autohaus_whatsapp_notifications.php';
                    $whatsapp = new AutohausWhatsAppNotifications($autohaus_id ?? null);
                    $whatsappResult = $whatsapp->sendAppointmentNotification($appointment_id, 'rescheduled');
                    
                    if ($whatsappResult['success']) {
                        $_SESSION['success_message'] = 'Termin verschoben - WhatsApp-Benachrichtigung gesendet';
                    } else {
                        $_SESSION['success_message'] = 'Termin verschoben - WhatsApp-Benachrichtigung fehlgeschlagen: ' . $whatsappResult['error'];
                    }
                } catch (Exception $e) {
                    $_SESSION['success_message'] = 'Termin verschoben - WhatsApp-Benachrichtigung konnte nicht gesendet werden';
                    error_log("WhatsApp-Benachrichtigung Fehler: " . $e->getMessage());
                }
            } else {
                $_SESSION['error_message'] = 'Neues Datum und Zeit müssen angegeben werden';
            }
            
        } elseif ($action === 'mark_booked') {
            $status = 'booked';
            $approvedBy = $_SESSION['admin_user_id'] ?? 1;
            $stmt = $conn->prepare("
                UPDATE appointments 
                SET status = ?, approved_by = ?, approved_at = NOW()
                WHERE id = ?
            ");
            $stmt->execute([$status, $approvedBy, $appointment_id]);
            
            $_SESSION['success_message'] = 'Termin als gebucht markiert';
            
        } elseif ($action === 'update_order_number') {
            // Nur Auftragsnummer aktualisieren - Status bleibt unverändert
            $orderNumber = $_POST['order_number'] ?? null;
            
            // Debug: Log the values
            error_log("Updating order number: " . $orderNumber . " for appointment: " . $appointment_id);
            
            $stmt = $conn->prepare("
                UPDATE appointments 
                SET order_number = ?
                WHERE id = ?
            ");
            $result = $stmt->execute([$orderNumber, $appointment_id]);
            
            if ($result) {
                $_SESSION['success_message'] = 'Auftragsnummer aktualisiert';
                error_log("Order number update successful");
            } else {
                $_SESSION['error_message'] = 'Fehler beim Aktualisieren der Auftragsnummer';
                error_log("Order number update failed");
            }
            
        } else {
            // Full update with all fields
            $customerName = $_POST['customer_name'] ?? null;
            $licensePlate = $_POST['license_plate'] ?? null;
            $phone = $_POST['phone'] ?? null;
            $email = $_POST['email'] ?? null;
            $eventId = $_POST['event_id'] ?? null;
            $slotDate = $_POST['slot_date'] ?? null;
            $slotTime = $_POST['slot_time'] ?? null;
            $storageNumber = $_POST['storage_number'] ?? null;
            $bringsWheels = isset($_POST['brings_wheels']) ? (int)$_POST['brings_wheels'] : 0;
            $wheelsStorageAction = $_POST['wheels_storage_action'] ?? 'store';
            $seasonalCheck = $_POST['seasonal_check'] ?? 'none';
            $hasWheelLock = isset($_POST['has_wheel_lock']) ? (int)$_POST['has_wheel_lock'] : 0;
            $wiperBlades = isset($_POST['wiper_blades']) ? (int)$_POST['wiper_blades'] : 0;
            $infoText = $_POST['info_text'] ?? null;
            $status = $_POST['status'] ?? 'booked';
            $orderNumber = $_POST['order_number'] ?? null;
            $adminNotes = $_POST['admin_notes'] ?? null;
            
            // Status wird nicht automatisch geändert bei Auftragsnummer-Eingabe
            
            $stmt = $conn->prepare("
                UPDATE appointments 
                SET event_id = ?, customer_name = ?, license_plate = ?, phone = ?, email = ?, slot_date = ?, slot_time = ?,
                    storage_number = ?, brings_wheels = ?, wheels_storage_action = ?, seasonal_check = ?,
                    has_wheel_lock = ?, wiper_blades = ?, info_text = ?, status = ?, 
                    order_number = ?, admin_notes = ?
                WHERE id = ?
            ");
            $stmt->execute([
                $eventId, $customerName, $licensePlate, $phone, $email, $slotDate, $slotTime,
                $storageNumber, $bringsWheels, $wheelsStorageAction, $seasonalCheck,
                $hasWheelLock, $wiperBlades, $infoText, $status,
                $orderNumber, $adminNotes, $appointment_id
            ]);
            
            $_SESSION['success_message'] = 'Termin erfolgreich aktualisiert';
        }
        
        header('Location: appointments.php');
        exit;
        
    } catch (Exception $e) {
        $_SESSION['error_message'] = 'Fehler beim Aktualisieren: ' . $e->getMessage();
    }
}

function handleAppointmentDelete($conn, $appointment_id) {
    try {
        $stmt = $conn->prepare("DELETE FROM appointments WHERE id = ?");
        $stmt->execute([$appointment_id]);
        
        $_SESSION['success_message'] = 'Termin erfolgreich gelöscht';
        header('Location: appointments.php');
        exit;
        
    } catch (Exception $e) {
        $_SESSION['error_message'] = 'Fehler beim Löschen: ' . $e->getMessage();
    }
}

function handleAppointmentCopy($conn, $appointment_id) {
    try {
        // Get the original appointment
        $stmt = $conn->prepare("SELECT * FROM appointments WHERE id = ?");
        $stmt->execute([$appointment_id]);
        $originalAppointment = $stmt->fetch();
        
        if (!$originalAppointment) {
            $_SESSION['error_message'] = 'Termin nicht gefunden';
            header('Location: appointments.php');
            exit;
        }
        
        // Create a copy with modified data
        $stmt = $conn->prepare("
            INSERT INTO appointments (
                event_id, customer_name, license_plate, phone, slot_time, slot_date,
                storage_number, brings_wheels, wheels_storage_action, seasonal_check,
                info_text, has_wheel_lock, wiper_blades, status, source, created_at
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending', 'admin_copy', NOW())
        ");
        
        $stmt->execute([
            $originalAppointment['event_id'],
            $originalAppointment['customer_name'] . ' (Kopie)',
            $originalAppointment['license_plate'],
            $originalAppointment['phone'],
            $originalAppointment['slot_time'],
            $originalAppointment['slot_date'],
            $originalAppointment['storage_number'],
            $originalAppointment['brings_wheels'],
            $originalAppointment['wheels_storage_action'],
            $originalAppointment['seasonal_check'],
            $originalAppointment['info_text'],
            $originalAppointment['has_wheel_lock'],
            $originalAppointment['wiper_blades']
        ]);
        
        $_SESSION['success_message'] = 'Termin erfolgreich kopiert';
        header('Location: appointments.php');
        exit;
        
    } catch (Exception $e) {
        $_SESSION['error_message'] = 'Fehler beim Kopieren: ' . $e->getMessage();
    }
}

function handleBulkDelete($conn) {
    // Clear any previous output
    if (ob_get_level()) {
        ob_clean();
    }
    
    // Set proper headers for JSON response
    header('Content-Type: application/json');
    
    try {
        $appointment_ids = $_POST['appointment_ids'] ?? '';
        $appointments_json = $_POST['appointments'] ?? '';
        $deletion_reason = $_POST['deletion_reason'] ?? '';
        
        // Debug logging
        error_log("DEBUG: appointment_ids = " . $appointment_ids);
        error_log("DEBUG: appointments_json = " . $appointments_json);
        error_log("DEBUG: deletion_reason = " . $deletion_reason);
        
        if (empty($appointment_ids)) {
            echo json_encode(['success' => false, 'message' => 'Keine Termine ausgewählt']);
            exit;
        }
        
        $ids = explode(',', $appointment_ids);
        $appointments = json_decode($appointments_json, true);
        
        // Debug logging
        error_log("DEBUG: decoded appointments = " . print_r($appointments, true));
        error_log("DEBUG: json_last_error = " . json_last_error_msg());
        error_log("DEBUG: json_last_error_code = " . json_last_error());
        
        if (!$appointments || !is_array($appointments)) {
            $json_error = json_last_error_msg();
            $json_error_code = json_last_error();
            error_log("DEBUG: JSON parsing failed - Error: $json_error (Code: $json_error_code)");
            echo json_encode([
                'success' => false, 
                'message' => 'Ungültige Termindaten - JSON Fehler: ' . $json_error,
                'debug_info' => [
                    'json_error' => $json_error,
                    'json_error_code' => $json_error_code,
                    'raw_json' => substr($appointments_json, 0, 200) . '...'
                ]
            ]);
            exit;
        }
        
        // Validate appointment data structure
        foreach ($appointments as $index => $appointment) {
            if (!isset($appointment['id']) || !is_numeric($appointment['id'])) {
                error_log("DEBUG: Invalid appointment at index $index: " . print_r($appointment, true));
                echo json_encode([
                    'success' => false, 
                    'message' => "Ungültige Termindaten - Termin $index hat keine gültige ID",
                    'debug_info' => ['invalid_appointment' => $appointment]
                ]);
                exit;
            }
        }
        
        // Get current user info
        $deleted_by_user_id = $_SESSION['admin_user_id'] ?? null;
        $deleted_by_username = $_SESSION['admin_username'] ?? 'System';
        
        // Start transaction
        $conn->beginTransaction();
        
        $deleted_count = 0;
        $tire_cancelled_count = 0;
        $tire_cancellation_errors = [];
        
        foreach ($appointments as $appointment) {
            // Check if appointment has tire order that needs cancellation
            if ($appointment['tire_order_date'] && !$appointment['brings_wheels'] && $appointment['storage_number']) {
                // Debug: Log appointment data before cancellation
                error_log("DEBUG: Versuche Reifen-Stornierung für Termin: " . json_encode($appointment));
                
                // Try to cancel tire order
                $cancellation_result = cancelTireOrder($appointment);
                if ($cancellation_result['success']) {
                    $tire_cancelled_count++;
                } else {
                    $tire_cancellation_errors[] = [
                        'customer_name' => $appointment['customer_name'],
                        'storage_number' => $appointment['storage_number'],
                        'error' => $cancellation_result['error'],
                        'details' => $cancellation_result['details'] ?? 'Keine weiteren Details verfügbar',
                        'debug_info' => $cancellation_result['debug_info'] ?? null
                    ];
                }
            }
            
            // Save audit data before deletion
            saveAuditData($conn, $appointment, $deleted_by_user_id, $deleted_by_username, $deletion_reason, $tire_cancelled_count > 0);
            
            // Delete appointment
            $stmt = $conn->prepare("DELETE FROM appointments WHERE id = ?");
            $stmt->execute([$appointment['id']]);
            
            if ($stmt->rowCount() > 0) {
                $deleted_count++;
            }
        }
        
        $conn->commit();
        
        echo json_encode([
            'success' => true, 
            'deleted_count' => $deleted_count,
            'tire_cancelled_count' => $tire_cancelled_count,
            'tire_cancellation_errors' => $tire_cancellation_errors,
            'message' => "$deleted_count Termine erfolgreich gelöscht"
        ]);
        exit;
        
    } catch (Exception $e) {
        if ($conn->inTransaction()) {
            $conn->rollback();
        }
        
        // Log detailed error information
        error_log("DEBUG: Bulk delete exception - " . $e->getMessage());
        error_log("DEBUG: Bulk delete exception trace - " . $e->getTraceAsString());
        
        echo json_encode([
            'success' => false, 
            'message' => 'Fehler beim Löschen: ' . $e->getMessage(),
            'debug_info' => [
                'exception_message' => $e->getMessage(),
                'exception_file' => $e->getFile(),
                'exception_line' => $e->getLine(),
                'exception_trace' => $e->getTraceAsString()
            ]
        ]);
        exit;
    }
}

function cancelTireOrder($appointment) {
    try {
        // Debug: Logge alle Termindaten
        error_log("DEBUG: Vollständige Termindaten für Stornierung: " . json_encode($appointment));
        
        // Prüfe ob alle erforderlichen Felder vorhanden sind
        $required_fields = ['storage_number', 'event_date', 'event_name'];
        $missing_fields = [];
        
        foreach ($required_fields as $field) {
            if (empty($appointment[$field])) {
                $missing_fields[] = $field;
            }
        }
        
        if (!empty($missing_fields)) {
            error_log("DEBUG: Fehlende Felder für Stornierung: " . implode(', ', $missing_fields));
            return [
                'success' => false,
                'error' => 'Fehlende Parameter: ' . implode(', ', $missing_fields) . ' erforderlich',
                'details' => 'Termindaten unvollständig für Reifen-Stornierung',
                'debug_info' => [
                    'missing_fields' => $missing_fields,
                    'available_fields' => array_keys($appointment),
                    'appointment_data' => $appointment
                ]
            ];
        }
        
        // Debug: Logge die Anfrage
        error_log("DEBUG: Stornierungs-Anfrage für Einlagerungsnummer: " . $appointment['storage_number']);
        error_log("DEBUG: Event-Datum: " . $appointment['event_date']);
        error_log("DEBUG: Event-Name: " . $appointment['event_name']);
        
        // Direkter Aufruf der TireOrderService Klasse
        require_once '../api/tire_order.php';
        
        // Simuliere HTTP-Request durch direkten Aufruf der API-Logik
        $input = [
            'action' => 'cancel',
            'storage_number' => $appointment['storage_number'],
            'appointment_date' => $appointment['event_date'],
            'event_name' => $appointment['event_name']
        ];
        
        // Prüfe Parameter
        if (!$input || !isset($input['storage_number']) || !isset($input['appointment_date']) || !isset($input['event_name'])) {
            $result = [
                'success' => false,
                'error' => 'Fehlende Parameter für Stornierung: storage_number, appointment_date, event_name erforderlich'
            ];
        } else {
            $tireOrderService = new TireOrderService();
            $result = $tireOrderService->cancelTireOrder(
                $input['storage_number'],
                $input['appointment_date'],
                $input['event_name']
            );
        }
        
        // Debug: Logge das Ergebnis
        error_log("DEBUG: Stornierungs-Ergebnis: " . json_encode($result));
        
        return $result;
        
    } catch (Exception $e) {
        error_log("DEBUG: Exception in cancelTireOrder: " . $e->getMessage());
        error_log("DEBUG: Exception trace: " . $e->getTraceAsString());
        return [
            'success' => false, 
            'error' => 'Fehler bei der Stornierung: ' . $e->getMessage(),
            'details' => 'Unerwarteter Fehler in der cancelTireOrder Funktion: ' . $e->getFile() . ' Zeile ' . $e->getLine(),
            'debug_info' => [
                'exception_message' => $e->getMessage(),
                'exception_file' => $e->getFile(),
                'exception_line' => $e->getLine(),
                'appointment_data' => $appointment
            ]
        ];
    }
}

function saveAuditData($conn, $appointment, $deleted_by_user_id, $deleted_by_username, $deletion_reason, $tire_cancelled) {
    try {
        $stmt = $conn->prepare("
            INSERT INTO deleted_appointments_audit (
                original_appointment_id, customer_name, license_plate, phone, event_name,
                slot_date, slot_time, storage_number, tire_order_date, tire_cancelled,
                deleted_by_user_id, deleted_by_username, deletion_reason, admin_notes,
                created_at, updated_at
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        ");
        
        $stmt->execute([
            $appointment['id'],
            $appointment['customer_name'],
            $appointment['license_plate'],
            $appointment['phone'],
            $appointment['event_name'],
            $appointment['slot_date'],
            $appointment['slot_time'],
            $appointment['storage_number'],
            $appointment['tire_order_date'],
            $tire_cancelled ? 1 : 0,
            $deleted_by_user_id,
            $deleted_by_username,
            $deletion_reason,
            $appointment['admin_notes'],
            $appointment['created_at'] ?? date('Y-m-d H:i:s'),
            date('Y-m-d H:i:s')
        ]);
        
    } catch (Exception $e) {
        error_log("Fehler beim Speichern der Audit-Daten: " . $e->getMessage());
    }
}

function handleBulkTireOrder($conn) {
    try {
        $appointments_json = $_POST['appointments'] ?? '';
        
        if (empty($appointments_json)) {
            echo json_encode(['success' => false, 'message' => 'Keine Termine ausgewählt']);
            return;
        }
        
        $appointments = json_decode($appointments_json, true);
        $ordered_count = 0;
        
        foreach ($appointments as $appointment) {
            // Check if appointment is eligible for tire order
            if (!$appointment['brings_wheels'] && !empty($appointment['storage_number'])) {
                // Update appointment with tire order date
                $stmt = $conn->prepare("UPDATE appointments SET tire_order_date = NOW() WHERE id = ?");
                $stmt->execute([$appointment['id']]);
                $ordered_count++;
            }
        }
        
        echo json_encode([
            'success' => true, 
            'ordered_count' => $ordered_count,
            'message' => "Reifenbestellung für $ordered_count Termine erstellt"
        ]);
        
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => 'Fehler bei der Reifenbestellung: ' . $e->getMessage()]);
    }
}


// Get events for filter
$events = getEvents($conn);

function getEvents($conn) {
    $stmt = $conn->prepare("SELECT id, name, event_date FROM events ORDER BY event_date DESC");
    $stmt->execute();
    return $stmt->fetchAll();
}
?>

<!DOCTYPE html>
<html lang="de">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Termine verwalten - Boxenstop Admin</title>
    <link rel="stylesheet" href="../assets/css/style.css">
    <link rel="stylesheet" href="../assets/css/volvo-theme.css">
    <link rel="stylesheet" href="assets/css/admin.css">
    <link rel="stylesheet" href="assets/css/global-dark-theme.css">
    <link rel="stylesheet" href="assets/css/unified-sidebar.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&family=SF+Pro+Display:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
</head>
<body class="admin-body" data-theme="<?php echo htmlspecialchars($current_theme); ?>" data-user-id="<?php echo htmlspecialchars($current_user_id); ?>">
    <div class="admin-container">
        <!-- Include Unified Sidebar -->
        <?php include 'includes/sidebar.php'; ?>

        <!-- Main Content -->
        <main class="admin-main">
            <!-- Appointments Header with Hero Section -->
            <header class="appointments-header">
                <div class="appointments-hero">
                    <div class="appointments-hero-content">
                        <div class="appointments-title-section">
                            <h1 class="appointments-title">
                                <i class="fas fa-calendar-check"></i> Termine verwalten
                            </h1>
                            <p class="appointments-subtitle">Verwalten Sie alle Boxenstop Termine und Buchungen</p>
                            <div class="appointments-meta">
                                <div class="meta-item">
                                    <i class="fas fa-calendar-alt"></i>
                                    <span><?php echo count($appointments); ?> Termine</span>
                                </div>
                                <div class="meta-item">
                                    <i class="fas fa-building"></i>
                                    <span><?php echo $current_user_autohaus_name ?: 'Alle Autohäuser'; ?></span>
                                </div>
                                <div class="meta-item">
                                    <i class="fas fa-clock"></i>
                                    <span>Live Status-Updates</span>
                                </div>
                            </div>
                        </div>
                        <div class="appointments-actions">
                            <select id="event-filter" class="modern-select">
                                <option value="">Alle Events</option>
                                <?php foreach ($events as $event): ?>
                                    <option value="<?php echo $event['id']; ?>" 
                                            <?php echo $event_id == $event['id'] ? 'selected' : ''; ?>>
                                        <?php echo htmlspecialchars($event['name']); ?> 
                                        (<?php echo date('d.m.Y', strtotime($event['event_date'])); ?>)
                                    </option>
                                <?php endforeach; ?>
                            </select>
                            <button class="btn-primary" onclick="exportAppointments()">
                                <i class="fas fa-download"></i>
                                Exportieren
                            </button>
                        </div>
                    </div>
                </div>
            </header>

            <!-- Messages -->
            <!-- Appointments Content -->
            <div class="appointments-content">
                <!-- Messages -->
                <?php if (isset($_SESSION['success_message'])): ?>
                    <div class="alert alert-success">
                        <i class="fas fa-check-circle"></i>
                        <?php echo $_SESSION['success_message']; unset($_SESSION['success_message']); ?>
                    </div>
                <?php endif; ?>

                <?php if (isset($_SESSION['error_message'])): ?>
                    <div class="alert alert-error">
                        <i class="fas fa-exclamation-circle"></i>
                        <?php echo $_SESSION['error_message']; unset($_SESSION['error_message']); ?>
                    </div>
                <?php endif; ?>

                <!-- Appointments List -->
            <div class="content-card">
                <div class="card-header">
                    <h3>Alle Termine</h3>
                    <div class="header-actions">
                        <span class="appointment-count">
                            <?php echo count($appointments); ?> Termine
                        </span>
                        <?php 
                        $pendingCount = count(array_filter($appointments, function($apt) { return $apt['status'] === 'pending'; }));
                        $bookedCount = count(array_filter($appointments, function($apt) { return $apt['status'] === 'booked'; }));
                        if ($pendingCount > 0): ?>
                            <span class="pending-count">
                                <i class="fas fa-exclamation-triangle"></i>
                                <?php echo $pendingCount; ?> wartend
                            </span>
                        <?php endif; ?>
                        <?php if ($bookedCount > 0): ?>
                            <span class="booked-count">
                                <i class="fas fa-calendar-check"></i>
                                <?php echo $bookedCount; ?> gebucht
                            </span>
                        <?php endif; ?>
                    </div>
                </div>
                <div class="card-content">
                    <?php if (empty($appointments)): ?>
                        <div class="empty-state">
                            <i class="fas fa-calendar-times"></i>
                            <p>Keine Termine vorhanden</p>
                            <a href="../index.php" class="btn btn-primary">Termin buchen</a>
                        </div>
                    <?php else: ?>
                        <!-- Bulk Actions Toolbar -->
                        <div id="bulk-actions-toolbar" class="bulk-actions-toolbar" style="display: none;">
                            <div class="bulk-actions-content">
                                <span class="selected-count">
                                    <i class="fas fa-check-square"></i>
                                    <span id="selected-count-text">0 Termine ausgewählt</span>
                                </span>
                                <div class="bulk-actions-buttons">
                                    <button class="btn btn-sm btn-danger" onclick="bulkDeleteAppointments()" title="Markierte Termine löschen">
                                        <i class="fas fa-trash"></i>
                                        <span>Löschen</span>
                                    </button>
                                    <button class="btn btn-sm btn-primary" onclick="bulkOrderTires()" title="Reifen für markierte Termine bestellen">
                                        <i class="fas fa-tire"></i>
                                        <span>Reifen bestellen</span>
                                    </button>
                                    <button class="btn btn-sm btn-success" onclick="bulkExportAppointments()" title="Markierte Termine exportieren">
                                        <i class="fas fa-download"></i>
                                        <span>Exportieren</span>
                                    </button>
                        <button class="btn btn-sm btn-info" onclick="bulkPrintStorageLabels()" title="Einlagerungsetiketten drucken">
                            <i class="fas fa-print"></i>
                            <span>Etiketten drucken</span>
                        </button>
                        <a href="audit_log.php" class="btn btn-sm btn-warning" title="Audit Log - Gelöschte Termine anzeigen">
                            <i class="fas fa-history"></i>
                            <span>Audit Log</span>
                        </a>
                                </div>
                            </div>
                        </div>

                        <div class="appointments-table">
                            <table class="appointments-table">
                                <thead>
                                    <tr>
                                        <th width="50">
                                            <input type="checkbox" id="select-all-checkbox" onchange="toggleAllAppointments(this)">
                                        </th>
                                        <th data-sort="customer_name" width="180">Kunde</th>
                                        <th data-sort="license_plate" width="120">Kennzeichen</th>
                                        <th data-sort="event_name" width="200">Event</th>
                                        <th data-sort="slot_date" width="120">Datum</th>
                                        <th data-sort="slot_time" width="100">Zeit</th>
                                        <th data-sort="phone">Telefon</th>
                                        <th>Services</th>
                                        <th>Auslastung</th>
                                        <th data-sort="status">Status</th>
                                        <th>Angebote</th>
                                        <th>Aktionen</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($appointments as $appointment): ?>
                                        <tr class="<?php echo $appointment['status'] === 'pending' ? 'pending-row' : ''; ?>" data-appointment-id="<?php echo $appointment['id']; ?>">
                                            <td>
                                                <input type="checkbox" class="appointment-checkbox" value="<?php echo $appointment['id']; ?>" onchange="updateBulkActions()">
                                            </td>
                                            <td>
                                                <strong><?php echo htmlspecialchars($appointment['customer_name']); ?></strong>
                                                <?php if ($appointment['info_text']): ?>
                                                    <br><small class="text-muted"><?php echo htmlspecialchars(substr($appointment['info_text'], 0, 50)); ?>...</small>
                                                <?php endif; ?>
                                            </td>
                                            <td><?php echo htmlspecialchars($appointment['license_plate']); ?></td>
                                            <td>
                                                <strong><?php echo htmlspecialchars($appointment['event_name']); ?></strong>
                                                <br><small class="text-muted"><?php echo date('d.m.Y', strtotime($appointment['event_date'])); ?></small>
                                            </td>
                                            <td><?php echo date('d.m.Y', strtotime($appointment['slot_date'])); ?></td>
                                            <td><?php echo date('H:i', strtotime($appointment['slot_time'])); ?></td>
                                            <td>
                                                <a href="tel:<?php echo htmlspecialchars($appointment['phone']); ?>" class="phone-link">
                                                    <?php echo htmlspecialchars($appointment['phone']); ?>
                                                </a>
                                            </td>
                                            <td>
                                                <div class="services-info">
                                                    <?php if ($appointment['wiper_blades']): ?>
                                                        <span class="service-badge service-wiper">
                                                            <i class="fas fa-wind"></i> Scheibenwischer
                                                        </span>
                                                    <?php endif; ?>
                                                    <?php if ($appointment['seasonal_check'] !== 'none'): ?>
                                                        <span class="service-badge service-check">
                                                            <i class="fas fa-tools"></i> 
                                                            <?php echo $appointment['seasonal_check'] === 'spring' ? 'Frühjahres' : 'Winter'; ?>
                                                        </span>
                                                    <?php endif; ?>
                                                    <?php if (!$appointment['brings_wheels']): ?>
                                                        <span class="service-badge service-storage">
                                                            <i class="fas fa-warehouse"></i> Einlagerung
                                                        </span>
                                                    <?php endif; ?>
                                                    <?php if ($appointment['tire_order_date']): ?>
                                                        <span class="service-badge service-tire-ordered">
                                                            <i class="fas fa-tire"></i> Reifen bestellt
                                                        </span>
                                                    <?php endif; ?>
                                                </div>
                                            </td>
                                            <td>
                                                <div class="capacity-info">
                                                    <span class="capacity-text">
                                                        <?php echo $appointment['booked_appointments']; ?>/<?php echo $appointment['max_monteure']; ?>
                                                    </span>
                                                    <div class="capacity-bar">
                                                        <?php 
                                                        $percentage = $appointment['max_monteure'] > 0 ? 
                                                            ($appointment['booked_appointments'] / $appointment['max_monteure']) * 100 : 0;
                                                        $ratio = $appointment['max_monteure'] > 0 ? 
                                                            $appointment['booked_appointments'] / $appointment['max_monteure'] : 0;
                                                        
                                                        $capacityClass = 'low';
                                                        if ($ratio >= 1.0) {
                                                            $capacityClass = 'full';
                                                        } elseif ($ratio >= 0.75) {
                                                            $capacityClass = 'high';
                                                        } elseif ($ratio >= 0.4) {
                                                            $capacityClass = 'medium';
                                                        }
                                                        ?>
                                                        <div class="capacity-fill <?php echo $capacityClass; ?>" style="width: <?php echo $percentage; ?>%"></div>
                                                    </div>
                                                    <small class="capacity-details">
                                                        Max. <?php echo $appointment['max_monteure']; ?> Monteure
                                                    </small>
                                                </div>
                                            </td>
                                            <td>
                                                <div class="status-container">
                                                    <div class="order-number-section">
                                                        <label class="order-label">Auftragsnummer:</label>
                                                        <form method="POST" class="order-form" style="display:flex; gap:.5rem; align-items:center; margin-top:.25rem;">
                                                            <input type="hidden" name="action" value="update_order_number">
                                                            <input type="hidden" name="id" value="<?php echo $appointment['id']; ?>">
                                                            <input type="text" name="order_number" placeholder="Auftragsnr." value="<?php echo htmlspecialchars($appointment['order_number'] ?? ''); ?>" class="order-input">
                                                            <button type="submit" class="btn btn-sm btn-icon btn-success" title="Auftragsnummer speichern">
                                                                <i class="fas fa-save"></i>
                                                            </button>
                                                        </form>
                                                    </div>
                                                    <div class="status-section" style="margin-top:.5rem;">
                                                        <span class="status-badge status-<?php echo $appointment['status']; ?>">
                                                            <?php 
                                                            $status_labels = [
                                                                'pending' => 'Wartend',
                                                                'approved' => 'Genehmigt',
                                                                'rejected' => 'Abgelehnt',
                                                                'rescheduled' => 'Verschoben',
                                                                'booked' => 'Gebucht',
                                                                'vorbereitet' => 'Vorbereitet',
                                                                'completed' => 'Abgeschlossen',
                                                                'cancelled' => 'Storniert'
                                                            ];
                                                            echo $status_labels[$appointment['status']] ?? $appointment['status'];
                                                            ?>
                                                        </span>
                                                        <?php if ($appointment['status'] === 'pending'): ?>
                                                            <br><small class="text-warning"><i class="fas fa-exclamation-triangle"></i> Genehmigung erforderlich</small>
                                                        <?php endif; ?>
                                                    </div>
                                                </div>
                                            </td>
                                            <td class="offer-badges-cell">
                                                <!-- Badges werden hier dynamisch eingefügt -->
                                            </td>
                                            <td>
                                                <div class="action-buttons-container">
                                                    <!-- Primary Actions Row -->
                                                    <div class="action-row primary-actions">
                                                        <button class="ios-btn ios-btn-secondary" onclick="showAppointmentDetails(<?php echo htmlspecialchars(json_encode($appointment)); ?>)" title="Details anzeigen">
                                                            <i class="fas fa-magnifying-glass"></i>
                                                        </button>
                                                        
                                                        <button class="ios-btn ios-btn-primary" onclick="editAppointment(<?php echo htmlspecialchars(json_encode($appointment)); ?>)" title="Termin bearbeiten">
                                                            <i class="fas fa-pencil"></i>
                                                        </button>
                                                        
                                                        <button class="ios-btn ios-btn-accent" onclick="copyAppointment(<?php echo $appointment['id']; ?>)" title="Termin kopieren">
                                                            <i class="fas fa-clone"></i>
                                                        </button>
                                                        
                                                        <a href="appointments.php?action=delete&id=<?php echo $appointment['id']; ?>" 
                                                           class="ios-btn ios-btn-danger" 
                                                           onclick="return confirm('Termin wirklich löschen?')"
                                                           title="Termin löschen">
                                                            <i class="fas fa-trash-can"></i>
                                                        </a>
                                                    </div>
                                                    
                                                    <!-- Status Actions Row -->
                                                    <?php if ($appointment['status'] === 'pending'): ?>
                                                        <div class="action-row status-actions">
                                                            <button class="ios-btn ios-btn-success" onclick="approveAppointment(<?php echo $appointment['id']; ?>)" title="Terminanfrage genehmigen">
                                                                <i class="fas fa-check-circle"></i>
                                                                <span>Genehmigen</span>
                                                            </button>
                                                            <button class="ios-btn ios-btn-danger" onclick="rejectAppointment(<?php echo $appointment['id']; ?>)" title="Terminanfrage ablehnen">
                                                                <i class="fas fa-xmark-circle"></i>
                                                                <span>Ablehnen</span>
                                                            </button>
                                                            <button class="ios-btn ios-btn-warning" onclick="rescheduleAppointment(<?php echo $appointment['id']; ?>)" title="Termin verschieben">
                                                                <i class="fas fa-calendar-days"></i>
                                                                <span>Verschieben</span>
                                                            </button>
                                                        </div>
                                                    <?php elseif ($appointment['status'] === 'approved'): ?>
                                                        <div class="action-row status-actions">
                                                            <button class="ios-btn ios-btn-info" onclick="markAsBooked(<?php echo $appointment['id']; ?>)" title="Als gebucht markieren">
                                                                <i class="fas fa-calendar-check"></i>
                                                                <span>Als gebucht markieren</span>
                                                            </button>
                                                        </div>
                                                    <?php elseif ($appointment['status'] === 'booked'): ?>
                                                        <div class="action-row status-actions">
                                                            <span class="status-info">
                                                                <i class="fas fa-info-circle"></i>
                                                                <span>Direkt gebucht</span>
                                                            </span>
                                                        </div>
                                                    <?php endif; ?>
                                                    
                                                    <!-- Service Actions Row -->
                                                    <?php if (!$appointment['brings_wheels'] && $appointment['storage_number']): ?>
                                                        <div class="action-row service-actions">
                                                            <button class="ios-btn ios-btn-primary" onclick="orderTires(<?php echo htmlspecialchars(json_encode($appointment)); ?>)" title="Reifen bestellen">
                                                                <i class="fas fa-circle-dot"></i>
                                                                <span><?php echo $appointment['tire_order_date'] ? 'Erneut bestellen' : 'Reifen bestellen'; ?></span>
                                                            </button>
                                                            <button class="ios-btn ios-btn-info" onclick="printSingleStorageLabel(<?php echo htmlspecialchars(json_encode($appointment)); ?>)" title="Einlagerungsetikett drucken">
                                                                <i class="fas fa-print"></i>
                                                                <span>Etikett drucken</span>
                                                            </button>
                                                        </div>
                                                    <?php endif; ?>
                                                    
                                                    <!-- Tire Check Action Row -->
                                                    <div class="action-row tire-check-actions">
                                                        <button class="ios-btn ios-btn-success" onclick="showTireCheckModal(<?php echo htmlspecialchars(json_encode($appointment), ENT_QUOTES, 'UTF-8'); ?>)" title="Reifen prüfen">
                                                            <i class="fas fa-magnifying-glass-plus"></i>
                                                            <span>Reifen prüfen</span>
                                                        </button>
                                                    </div>
                                                </div>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </main>
    </div>

    <!-- Appointment Details Modal -->
    <div id="appointment-modal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3>Termin Details</h3>
                <button class="modal-close" onclick="closeAppointmentModal()">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            <div class="modal-body" id="appointment-details">
                <!-- Details will be loaded here -->
            </div>
        </div>
    </div>

    <!-- Tire Order Modal -->
    <div id="tire-order-modal" class="modal">
        <div class="modal-content tire-order-modal">
            <div class="modal-header">
                <h3>
                    <i class="fas fa-tire"></i>
                    Reifen bestellen
                </h3>
                <button class="modal-close" onclick="closeTireOrderModal()">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            <div class="modal-body">
                <div id="tire-order-content">
                    <!-- Content will be loaded here -->
                </div>
            </div>
        </div>
    </div>

    <!-- Edit Appointment Modal -->
    <div id="edit-appointment-modal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3>Termin bearbeiten</h3>
                <button class="modal-close" onclick="closeEditAppointmentModal()">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            <div class="modal-body">
                <form id="edit-appointment-form" method="POST">
                    <input type="hidden" name="action" value="update">
                    <input type="hidden" name="id" id="edit-appointment-id">
                    
                    <div class="form-sections">
                        <!-- Kundendaten -->
                        <div class="form-section">
                            <h4 class="section-title">
                                <i class="fas fa-user"></i>
                                Kundendaten
                            </h4>
                            <div class="form-grid">
                                <div class="form-group">
                                    <label for="edit-customer-name">Kunde *</label>
                                    <input type="text" id="edit-customer-name" name="customer_name" required>
                                </div>
                                
                                <div class="form-group">
                                    <label for="edit-license-plate">Kennzeichen *</label>
                                    <input type="text" id="edit-license-plate" name="license_plate" required>
                                </div>
                                
                                <div class="form-group">
                                    <label for="edit-phone">Telefon *</label>
                                    <input type="tel" id="edit-phone" name="phone" required>
                                </div>
                                
                                <div class="form-group">
                                    <label for="edit-email">E-Mail *</label>
                                    <input type="email" id="edit-email" name="email" required>
                                </div>
                            </div>
                        </div>

                        <!-- Termindaten -->
                        <div class="form-section">
                            <h4 class="section-title">
                                <i class="fas fa-calendar"></i>
                                Termindaten
                            </h4>
                            <div class="form-grid">
                                <div class="form-group">
                                    <label for="edit-event-id">Event *</label>
                                    <select id="edit-event-id" name="event_id" required onchange="setEventDate()">
                                        <option value="">Event auswählen...</option>
                                        <?php foreach ($events as $event): ?>
                                            <option value="<?php echo $event['id']; ?>" data-event-date="<?php echo $event['event_date']; ?>">
                                                <?php echo htmlspecialchars($event['name']); ?> 
                                                (<?php echo date('d.m.Y', strtotime($event['event_date'])); ?>)
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                
                                <div class="form-group">
                                    <label for="edit-slot-date">Datum *</label>
                                    <input type="date" id="edit-slot-date" name="slot_date" required onchange="loadAvailableSlots()">
                                    <small class="date-info" id="date-info" style="display: none; color: #28a745; margin-top: 0.25rem;">
                                        <i class="fas fa-info-circle"></i> Datum automatisch vom Event übernommen
                                    </small>
                                </div>
                                
                                <div class="form-group">
                                    <label for="edit-slot-time">Zeit *</label>
                                    <select id="edit-slot-time" name="slot_time" required>
                                        <option value="">Zeit auswählen...</option>
                                    </select>
                                    <small class="slot-info" id="slot-info" style="display: none; color: #666; margin-top: 0.25rem;">
                                        Verfügbare Zeiten werden geladen...
                                    </small>
                                </div>
                                
                                <div class="form-group">
                                    <label for="edit-status">Status</label>
                                    <select id="edit-status" name="status">
                                        <option value="pending">Wartend</option>
                                        <option value="booked">Gebucht</option>
                                        <option value="vorbereitet">Vorbereitet</option>
                                        <option value="completed">Abgeschlossen</option>
                                        <option value="cancelled">Storniert</option>
                                        <option value="rejected">Abgelehnt</option>
                                    </select>
                                </div>
                            </div>
                        </div>

                        <!-- Services -->
                        <div class="form-section">
                            <h4 class="section-title">
                                <i class="fas fa-tools"></i>
                                Services & Einlagerung
                            </h4>
                            <div class="form-grid">
                                <div class="form-group">
                                    <label for="edit-storage-number">Einlagerungsnummer</label>
                                    <input type="text" id="edit-storage-number" name="storage_number">
                                </div>
                                
                                <div class="form-group">
                                    <label for="edit-brings-wheels">Bringt Räder mit</label>
                                    <select id="edit-brings-wheels" name="brings_wheels">
                                        <option value="1">Ja</option>
                                        <option value="0">Nein</option>
                                    </select>
                                </div>
                                
                                <div class="form-group">
                                    <label for="edit-wheels-storage-action">Räder einlagern</label>
                                    <select id="edit-wheels-storage-action" name="wheels_storage_action">
                                        <option value="store">Einlagern</option>
                                        <option value="vehicle">In Fahrzeug legen</option>
                                    </select>
                                </div>
                                
                                <div class="form-group">
                                    <label for="edit-seasonal-check">Jahreszeiten-Check</label>
                                    <select id="edit-seasonal-check" name="seasonal_check">
                                        <option value="none">Kein Check</option>
                                        <option value="spring">Frühjahres-Check</option>
                                        <option value="winter">Winter-Check</option>
                                    </select>
                                </div>
                                
                                <div class="form-group">
                                    <label for="edit-has-wheel-lock">Radmutterschloss</label>
                                    <select id="edit-has-wheel-lock" name="has_wheel_lock">
                                        <option value="0">Nein</option>
                                        <option value="1">Ja</option>
                                    </select>
                                </div>
                                
                                <div class="form-group">
                                    <label for="edit-wiper-blades">Scheibenwischerblätter</label>
                                    <select id="edit-wiper-blades" name="wiper_blades">
                                        <option value="0">Nein</option>
                                        <option value="1">Ja (20% + 1L Scheibenklar)</option>
                                    </select>
                                </div>
                            </div>
                        </div>

                        <!-- Verwaltung -->
                        <div class="form-section">
                            <h4 class="section-title">
                                <i class="fas fa-cog"></i>
                                Verwaltung
                            </h4>
                            <div class="form-grid">
                                <div class="form-group">
                                    <label for="edit-order-number">Auftragsnummer</label>
                                    <input type="text" id="edit-order-number" name="order_number">
                                </div>
                                
                                <div class="form-group full-width">
                                    <label for="edit-info-text">Zusätzliche Infos</label>
                                    <textarea id="edit-info-text" name="info_text" rows="3"></textarea>
                                </div>
                                
                                <div class="form-group full-width">
                                    <label for="edit-admin-notes">Admin Notizen</label>
                                    <textarea id="edit-admin-notes" name="admin_notes" rows="3"></textarea>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="modal-actions">
                        <button type="button" class="btn btn-lg btn-secondary" onclick="closeEditAppointmentModal()">
                            <i class="fas fa-times"></i>
                            <span>Abbrechen</span>
                        </button>
                        <button type="submit" class="btn btn-lg btn-primary">
                            <i class="fas fa-save"></i>
                            <span>Speichern</span>
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Bulk Delete Modal -->
    <div id="bulk-delete-modal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3>
                    <i class="fas fa-trash"></i>
                    Termine löschen
                </h3>
                <button class="modal-close" onclick="closeBulkDeleteModal()">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            <div class="modal-body">
                <div class="warning-message">
                    <i class="fas fa-exclamation-triangle"></i>
                    <p>Möchten Sie die ausgewählten Termine wirklich löschen?</p>
                    <p><strong>Diese Aktion kann nicht rückgängig gemacht werden!</strong></p>
                </div>
                
                <div class="delete-summary">
                    <div class="summary-stats">
                        <div class="stat-item">
                            <i class="fas fa-calendar"></i>
                            <span id="delete-count">0</span> Termine ausgewählt
                        </div>
                        <div class="stat-item">
                            <i class="fas fa-tire"></i>
                            <span id="tire-orders-count">0</span> mit Reifenbestellung
                        </div>
                    </div>
                </div>
                
                <div class="delete-details">
                    <h4>Details der ausgewählten Termine:</h4>
                    <div id="bulk-delete-list" class="appointments-list">
                        <!-- Selected appointments will be listed here -->
                    </div>
                </div>
                
                <div class="tire-cancellation-section" id="tire-cancellation-section" style="display: none;">
                    <div class="cancellation-warning">
                        <i class="fas fa-tire"></i>
                        <h4>Reifenbestellungen stornieren</h4>
                        <p>Einige der ausgewählten Termine haben aktive Reifenbestellungen. Diese werden automatisch storniert.</p>
                    </div>
                    <div id="tire-cancellation-list">
                        <!-- Tire orders to be cancelled will be listed here -->
                    </div>
                </div>
                
                <div class="deletion-reason">
                    <label for="deletion-reason-input">
                        <i class="fas fa-comment"></i>
                        Grund für die Löschung (optional):
                    </label>
                    <textarea id="deletion-reason-input" rows="3" placeholder="z.B. Kunde hat abgesagt, Doppelbuchung, etc."></textarea>
                </div>
            </div>
            <div class="modal-actions">
                <button type="button" class="btn btn-lg btn-secondary" onclick="closeBulkDeleteModal()">
                    <i class="fas fa-times"></i>
                    <span>Abbrechen</span>
                </button>
                <button type="button" class="btn btn-lg btn-danger" onclick="confirmBulkDelete()">
                    <i class="fas fa-trash"></i>
                    <span>Löschen bestätigen</span>
                </button>
            </div>
        </div>
    </div>


    <!-- Storage Labels Modal -->
    <div id="storage-labels-modal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3>
                    <i class="fas fa-print"></i>
                    Einlagerungsetiketten drucken
                </h3>
                <button class="modal-close" onclick="closeStorageLabelsModal()">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            <div class="modal-body">
                <div class="labels-info">
                    <p>Einlagerungsetiketten für <span id="labels-count">0</span> ausgewählte Termine drucken:</p>
                </div>
                <div id="storage-labels-list">
                    <!-- Selected appointments for labels will be listed here -->
                </div>
                <div class="print-options">
                    <label>
                        <input type="checkbox" id="include-customer-info" checked>
                        Kundeninformationen einschließen
                    </label>
                    <label>
                        <input type="checkbox" id="include-storage-info" checked>
                        Einlagerungsinformationen einschließen
                    </label>
                </div>
            </div>
            <div class="modal-actions">
                <button type="button" class="btn btn-lg btn-secondary" onclick="closeStorageLabelsModal()">
                    <i class="fas fa-times"></i>
                    <span>Abbrechen</span>
                </button>
                <button type="button" class="btn btn-lg btn-primary" onclick="printStorageLabels()">
                    <i class="fas fa-print"></i>
                    <span>Etiketten drucken</span>
                </button>
            </div>
        </div>
    </div>

    <script src="../assets/js/main.js"></script>
    <script src="assets/js/admin.js"></script>
    <script>
        // Event filter
        document.getElementById('event-filter').addEventListener('change', function() {
            const eventId = this.value;
            if (eventId) {
                window.location.href = 'appointments.php?event_id=' + eventId;
            } else {
                window.location.href = 'appointments.php';
            }
        });

        // Show appointment details
        function showAppointmentDetails(appointment) {
            console.log('showAppointmentDetails aufgerufen mit:', appointment);
            const modal = document.getElementById('appointment-modal');
            const details = document.getElementById('appointment-details');
            
            if (!modal) {
                console.error('Modal nicht gefunden!');
                return;
            }
            
            if (!details) {
                console.error('Details-Element nicht gefunden!');
                return;
            }
            
            console.log('Modal gefunden:', modal);
            console.log('Details gefunden:', details);
            
            // Status mapping
            const statusMap = {
                'pending': { text: 'Wartend', icon: 'fas fa-clock', color: 'warning' },
                'approved': { text: 'Genehmigt', icon: 'fas fa-check-circle', color: 'info' },
                'rejected': { text: 'Abgelehnt', icon: 'fas fa-times-circle', color: 'danger' },
                'rescheduled': { text: 'Verschoben', icon: 'fas fa-calendar-alt', color: 'warning' },
                'booked': { text: 'Gebucht', icon: 'fas fa-calendar-check', color: 'success' },
                'vorbereitet': { text: 'Vorbereitet', icon: 'fas fa-tools', color: 'primary' },
                'completed': { text: 'Abgeschlossen', icon: 'fas fa-check-double', color: 'success' },
                'cancelled': { text: 'Storniert', icon: 'fas fa-ban', color: 'secondary' }
            };
            
            const status = statusMap[appointment.status] || { text: appointment.status, icon: 'fas fa-question', color: 'secondary' };
            
            details.innerHTML = `
                <div class="appointment-details-professional">
                    <!-- Header Section -->
                    <div class="detail-header">
                        <div class="customer-avatar">
                            <i class="fas fa-user"></i>
                    </div>
                        <div class="customer-info">
                            <h3>${appointment.customer_name}</h3>
                            <p class="customer-subtitle">
                                <i class="fas fa-car"></i> ${appointment.license_plate} • 
                                <i class="fas fa-phone"></i> <a href="tel:${appointment.phone}">${appointment.phone}</a>
                                ${appointment.email ? ` • <i class="fas fa-envelope"></i> <a href="mailto:${appointment.email}">${appointment.email}</a>` : ''}
                            </p>
                    </div>
                        <div class="status-section">
                            <div class="status-badge-large status-${status.color}">
                                <i class="${status.icon}"></i>
                                <span>${status.text}</span>
                    </div>
                    </div>
                    </div>
                    
                    <!-- Main Content Grid -->
                    <div class="detail-content-grid">
                        <!-- Event Information -->
                        <div class="detail-section">
                            <div class="section-header">
                                <i class="fas fa-calendar-alt"></i>
                                <h4>Event-Informationen</h4>
                            </div>
                            <div class="section-content">
                                <div class="info-item">
                                    <div class="info-label">
                                        <i class="fas fa-calendar"></i>
                                        <span>Event</span>
                                    </div>
                                    <div class="info-value">${appointment.event_name}</div>
                                </div>
                                <div class="info-item">
                                    <div class="info-label">
                                        <i class="fas fa-clock"></i>
                                        <span>Termin</span>
                                    </div>
                                    <div class="info-value">
                                        ${formatDate(appointment.slot_date)} um ${formatTime(appointment.slot_time)}
                                    </div>
                                </div>
                                <div class="info-item">
                                    <div class="info-label">
                                        <i class="fas fa-calendar-day"></i>
                                        <span>Event-Datum</span>
                                    </div>
                                    <div class="info-value">${formatDate(appointment.event_date)}</div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Vehicle Information -->
                        <div class="detail-section">
                            <div class="section-header">
                                <i class="fas fa-car"></i>
                                <h4>Fahrzeug-Informationen</h4>
                            </div>
                            <div class="section-content">
                                <div class="info-item">
                                    <div class="info-label">
                                        <i class="fas fa-id-card"></i>
                                        <span>Kennzeichen</span>
                                    </div>
                                    <div class="info-value">${appointment.license_plate}</div>
                                </div>
                                <div class="info-item">
                                    <div class="info-label">
                                        <i class="fas fa-tire"></i>
                                        <span>Bringt Räder mit</span>
                                    </div>
                                    <div class="info-value">
                                        <span class="boolean-value ${appointment.brings_wheels ? 'true' : 'false'}">
                                            <i class="fas fa-${appointment.brings_wheels ? 'check' : 'times'}"></i>
                                            ${appointment.brings_wheels ? 'Ja' : 'Nein'}
                                        </span>
                                    </div>
                    </div>
                    ${appointment.storage_number ? `
                                <div class="info-item">
                                    <div class="info-label">
                                        <i class="fas fa-warehouse"></i>
                                        <span>Einlagerungsnummer</span>
                                    </div>
                                    <div class="info-value storage-number">${appointment.storage_number}</div>
                    </div>
                    ` : ''}
                    </div>
                    </div>
                        
                        <!-- Services -->
                        <div class="detail-section">
                            <div class="section-header">
                                <i class="fas fa-tools"></i>
                                <h4>Services & Zubehör</h4>
                    </div>
                            <div class="section-content">
                                <div class="info-item">
                                    <div class="info-label">
                                        <i class="fas fa-warehouse"></i>
                                        <span>Räder einlagern</span>
                    </div>
                                    <div class="info-value">
                                        ${appointment.wheels_storage_action === 'store' ? 'Einlagern' : 'In Fahrzeug legen'}
                                    </div>
                                </div>
                                <div class="info-item">
                                    <div class="info-label">
                                        <i class="fas fa-snowflake"></i>
                                        <span>Jahreszeiten-Check</span>
                                    </div>
                                    <div class="info-value">
                                        ${appointment.seasonal_check === 'none' ? 'Kein Check' : 
                                          appointment.seasonal_check === 'spring' ? 'Frühjahres-Check' : 'Winter-Check'}
                                    </div>
                                </div>
                                <div class="info-item">
                                    <div class="info-label">
                                        <i class="fas fa-lock"></i>
                                        <span>Radmutterschloss</span>
                                    </div>
                                    <div class="info-value">
                                        <span class="boolean-value ${appointment.has_wheel_lock ? 'true' : 'false'}">
                                            <i class="fas fa-${appointment.has_wheel_lock ? 'check' : 'times'}"></i>
                                            ${appointment.has_wheel_lock ? 'Ja' : 'Nein'}
                                        </span>
                                    </div>
                                </div>
                                <div class="info-item">
                                    <div class="info-label">
                                        <i class="fas fa-wind"></i>
                                        <span>Scheibenwischerblätter</span>
                                    </div>
                                    <div class="info-value">
                                        <span class="boolean-value ${appointment.wiper_blades ? 'true' : 'false'}">
                                            <i class="fas fa-${appointment.wiper_blades ? 'check' : 'times'}"></i>
                                            ${appointment.wiper_blades ? 'Ja (20% + 1L Scheibenklar)' : 'Nein'}
                                        </span>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Tire Order Information -->
                        ${appointment.tire_order_date ? `
                        <div class="detail-section">
                            <div class="section-header">
                                <i class="fas fa-tire"></i>
                                <h4>Reifenbestellung</h4>
                            </div>
                            <div class="section-content">
                                <div class="tire-order-status">
                                    <div class="status-indicator success">
                                        <i class="fas fa-check-circle"></i>
                                        <span>Reifen bestellt</span>
                                    </div>
                                </div>
                                <div class="info-item">
                                    <div class="info-label">
                                        <i class="fas fa-calendar-check"></i>
                                        <span>Bestellt am</span>
                                    </div>
                                    <div class="info-value">${formatDateTime(appointment.tire_order_date)}</div>
                                </div>
                                <div class="info-item">
                                    <div class="info-label">
                                        <i class="fas fa-clock"></i>
                                        <span>Bestellzeit</span>
                                    </div>
                                    <div class="info-value">${formatTime(appointment.tire_order_date)}</div>
                                </div>
                                <div class="info-item">
                                    <div class="info-label">
                                        <i class="fas fa-calendar-day"></i>
                                        <span>Bestelldatum</span>
                                    </div>
                                    <div class="info-value">${formatDate(appointment.tire_order_date)}</div>
                                </div>
                                <div class="info-item">
                                    <div class="info-label">
                                        <i class="fas fa-user-tie"></i>
                                        <span>Bestellt von</span>
                                    </div>
                                    <div class="info-value">${appointment.tire_order_user || 'System'}</div>
                                </div>
                                ${appointment.tire_order_status ? `
                                <div class="info-item">
                                    <div class="info-label">
                                        <i class="fas fa-info-circle"></i>
                                        <span>Bestellstatus</span>
                                    </div>
                                    <div class="info-value">
                                        <span class="tire-status-badge status-${appointment.tire_order_status}">
                                            <i class="fas fa-${appointment.tire_order_status === 'bestellt' ? 'clock' : appointment.tire_order_status === 'geliefert' ? 'check-circle' : 'times-circle'}"></i>
                                            ${appointment.tire_order_status === 'bestellt' ? 'Bestellt' : appointment.tire_order_status === 'geliefert' ? 'Geliefert' : 'Storniert'}
                                        </span>
                                    </div>
                                </div>
                                ` : ''}
                                <div class="info-item">
                                    <div class="info-label">
                                        <i class="fas fa-warehouse"></i>
                                        <span>Einlagerungsnummer</span>
                                    </div>
                                    <div class="info-value storage-number">${appointment.storage_number}</div>
                                </div>
                            </div>
                        </div>
                        ` : ''}
                        
                        <!-- Additional Information -->
                        <div class="detail-section ${appointment.tire_order_date ? '' : 'full-width'}">
                            <div class="section-header">
                                <i class="fas fa-info-circle"></i>
                                <h4>Zusätzliche Informationen</h4>
                            </div>
                            <div class="section-content">
                                ${appointment.info_text ? `
                                <div class="info-item">
                                    <div class="info-label">
                                        <i class="fas fa-comment"></i>
                                        <span>Kundennotizen</span>
                                    </div>
                                    <div class="info-value info-text">${appointment.info_text}</div>
                                </div>
                                ` : ''}
                                <div class="info-item">
                                    <div class="info-label">
                                        <i class="fas fa-calendar-plus"></i>
                                        <span>Erstellt am</span>
                                    </div>
                                    <div class="info-value">${formatDateTime(appointment.created_at)}</div>
                                </div>
                                <div class="info-item">
                                    <div class="info-label">
                                        <i class="fas fa-edit"></i>
                                        <span>Zuletzt aktualisiert</span>
                                    </div>
                                    <div class="info-value">${formatDateTime(appointment.updated_at)}</div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            `;
            
            modal.style.display = 'block';
        }

        // Close appointment modal
        function closeAppointmentModal() {
            document.getElementById('appointment-modal').style.display = 'none';
        }

        // Edit appointment
        function editAppointment(appointment) {
            console.log('editAppointment aufgerufen mit:', appointment);
            const modal = document.getElementById('edit-appointment-modal');
            
            if (!modal) {
                console.error('Edit Modal nicht gefunden!');
                return;
            }
            
            console.log('Edit Modal gefunden:', modal);
            
            // Fill form with appointment data
            document.getElementById('edit-appointment-id').value = appointment.id;
            document.getElementById('edit-customer-name').value = appointment.customer_name;
            document.getElementById('edit-license-plate').value = appointment.license_plate;
            document.getElementById('edit-phone').value = appointment.phone;
            document.getElementById('edit-email').value = appointment.email || '';
            document.getElementById('edit-event-id').value = appointment.event_id;
            document.getElementById('edit-slot-date').value = appointment.slot_date;
            document.getElementById('edit-slot-time').value = appointment.slot_time;
            document.getElementById('edit-storage-number').value = appointment.storage_number || '';
            document.getElementById('edit-brings-wheels').value = appointment.brings_wheels ? '1' : '0';
            document.getElementById('edit-wheels-storage-action').value = appointment.wheels_storage_action || 'store';
            document.getElementById('edit-seasonal-check').value = appointment.seasonal_check || 'none';
            document.getElementById('edit-has-wheel-lock').value = appointment.has_wheel_lock ? '1' : '0';
            document.getElementById('edit-wiper-blades').value = appointment.wiper_blades ? '1' : '0';
            document.getElementById('edit-info-text').value = appointment.info_text || '';
            document.getElementById('edit-status').value = appointment.status;
            document.getElementById('edit-order-number').value = appointment.order_number || '';
            document.getElementById('edit-admin-notes').value = appointment.admin_notes || '';
            
            // Set the event date and load available slots
            setEventDate();
            
            modal.style.display = 'block';
        }

        // Close edit appointment modal
        function closeEditAppointmentModal() {
            document.getElementById('edit-appointment-modal').style.display = 'none';
        }

        // Copy appointment
        function copyAppointment(appointmentId) {
            if (!confirm('Termin kopieren? Es wird eine Kopie mit dem Status "Wartend" erstellt.')) {
                return;
            }
            
            const form = document.createElement('form');
            form.method = 'POST';
            form.innerHTML = `
                <input type="hidden" name="action" value="copy">
                <input type="hidden" name="id" value="${appointmentId}">
            `;
            document.body.appendChild(form);
            form.submit();
        }

        // Set event date when event is selected
        function setEventDate() {
            const eventSelect = document.getElementById('edit-event-id');
            const dateInput = document.getElementById('edit-slot-date');
            const dateInfo = document.getElementById('date-info');
            const selectedOption = eventSelect.options[eventSelect.selectedIndex];
            
            if (selectedOption.value && selectedOption.dataset.eventDate) {
                dateInput.value = selectedOption.dataset.eventDate;
                dateInfo.style.display = 'block';
                
                // Hide the info after 3 seconds
                setTimeout(() => {
                    dateInfo.style.display = 'none';
                }, 3000);
                
                // Load available slots after setting the date
                loadAvailableSlots();
            } else {
                dateInfo.style.display = 'none';
            }
        }

        // Load available slots for selected event and date
        function loadAvailableSlots() {
            const eventId = document.getElementById('edit-event-id').value;
            const date = document.getElementById('edit-slot-date').value;
            const slotTimeSelect = document.getElementById('edit-slot-time');
            const slotInfo = document.getElementById('slot-info');
            
            if (!eventId || !date) {
                slotTimeSelect.innerHTML = '<option value="">Zeit auswählen...</option>';
                slotInfo.style.display = 'none';
                return;
            }
            
            // Show loading state
            slotTimeSelect.innerHTML = '<option value="">Lade verfügbare Zeiten...</option>';
            slotTimeSelect.disabled = true;
            slotInfo.style.display = 'block';
            slotInfo.textContent = 'Verfügbare Zeiten werden geladen...';
            slotInfo.style.color = '#007bff';
            
            // Fetch available slots
            fetch(`../api/appointments.php?event_id=${eventId}&date=${date}`)
                .then(response => response.json())
                .then(data => {
                    slotTimeSelect.innerHTML = '<option value="">Zeit auswählen...</option>';
                    
                    if (data.success && data.available_slots) {
                        let availableCount = 0;
                        let totalCount = 0;
                        
                        data.available_slots.forEach(slot => {
                            const option = document.createElement('option');
                            option.value = slot.time;
                            option.textContent = `${slot.formatted_time} (${slot.available_count}/${slot.max_count} verfügbar)`;
                            
                            if (slot.available) {
                                availableCount += slot.available_count;
                            }
                            totalCount += slot.max_count;
                            
                            if (!slot.available) {
                                option.disabled = true;
                                option.textContent += ' - Ausgebucht';
                                option.style.color = '#dc3545';
                            }
                            
                            slotTimeSelect.appendChild(option);
                        });
                        
                        slotInfo.textContent = `${availableCount} von ${totalCount} Plätzen verfügbar`;
                        slotInfo.style.color = availableCount > 0 ? '#28a745' : '#dc3545';
                    } else {
                        slotTimeSelect.innerHTML = '<option value="">Keine Zeiten verfügbar</option>';
                        slotInfo.textContent = 'Keine Zeiten für dieses Event verfügbar';
                        slotInfo.style.color = '#dc3545';
                    }
                    
                    slotTimeSelect.disabled = false;
                })
                .catch(error => {
                    console.error('Error loading slots:', error);
                    slotTimeSelect.innerHTML = '<option value="">Fehler beim Laden</option>';
                    slotInfo.textContent = 'Fehler beim Laden der verfügbaren Zeiten';
                    slotInfo.style.color = '#dc3545';
                    slotTimeSelect.disabled = false;
                });
        }

        // Export appointments
        function exportAppointments() {
            const appointments = <?php echo json_encode($appointments, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP); ?>;
            const csvData = appointments.map(apt => ({
                'Kunde': apt.customer_name,
                'Kennzeichen': apt.license_plate,
                'Event': apt.event_name,
                'Datum': formatDate(apt.slot_date),
                'Zeit': formatTime(apt.slot_time),
                'Telefon': apt.phone,
                'Status': apt.status === 'booked' ? 'Gebucht' : apt.status === 'pending' ? 'Wartend' : apt.status === 'approved' ? 'Genehmigt' : apt.status === 'rejected' ? 'Abgelehnt' : apt.status === 'rescheduled' ? 'Verschoben' : apt.status === 'vorbereitet' ? 'Vorbereitet' : apt.status === 'completed' ? 'Abgeschlossen' : 'Storniert',
                'Bringt Räder mit': apt.brings_wheels ? 'Ja' : 'Nein',
                'Einlagerungsnummer': apt.storage_number || '',
                'Jahreszeiten-Check': apt.seasonal_check === 'none' ? 'Kein Check' : apt.seasonal_check === 'spring' ? 'Frühjahres-Check' : 'Winter-Check'
            }));
            
            exportToCSV(csvData, 'boxxenstopp-termine.csv');
        }

        // Close modal when clicking outside
        window.onclick = function(event) {
            const appointmentModal = document.getElementById('appointment-modal');
            const editModal = document.getElementById('edit-appointment-modal');
            const tireOrderModal = document.getElementById('tire-order-modal');
            
            if (event.target === appointmentModal) {
                closeAppointmentModal();
            }
            if (event.target === editModal) {
                closeEditAppointmentModal();
            }
            if (event.target === tireOrderModal) {
                closeTireOrderModal();
            }
        }
        
        // Format date and time
        function formatDateTime(dateTimeString) {
            if (!dateTimeString) return '';
            const date = new Date(dateTimeString);
            return date.toLocaleString('de-DE', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit'
            });
        }

        // Format date (YYYY-MM-DD to DD.MM.YYYY)
        function formatDate(dateString) {
            if (!dateString) return '';
            const date = new Date(dateString);
            if (isNaN(date.getTime())) return 'Ungültiges Datum';
            return date.toLocaleDateString('de-DE', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit'
            });
        }

        // Format time (HH:MM:SS to HH:MM)
        function formatTime(timeString) {
            if (!timeString) return '';
            const time = new Date('2000-01-01T' + timeString);
            if (isNaN(time.getTime())) return 'Ungültige Zeit';
            return time.toLocaleTimeString('de-DE', {
                hour: '2-digit',
                minute: '2-digit'
            });
        }

        // Approve appointment
        function approveAppointment(appointmentId) {
            if (!confirm('Termin genehmigen? Der Kunde erhält eine WhatsApp-Bestätigung.')) {
                return;
            }
            
            const form = document.createElement('form');
            form.method = 'POST';
            form.innerHTML = `
                <input type="hidden" name="action" value="update">
                <input type="hidden" name="action_type" value="approve">
                <input type="hidden" name="id" value="${appointmentId}">
            `;
            document.body.appendChild(form);
            form.submit();
        }
        
        // Reject appointment
        function rejectAppointment(appointmentId) {
            const reason = prompt('Grund für die Ablehnung:');
            if (reason === null) return;
            
            if (!confirm('Terminanfrage ablehnen? Der Kunde erhält eine WhatsApp-Benachrichtigung.')) {
                return;
            }
            
            const form = document.createElement('form');
            form.method = 'POST';
            form.innerHTML = `
                <input type="hidden" name="action" value="update">
                <input type="hidden" name="action_type" value="reject">
                <input type="hidden" name="id" value="${appointmentId}">
                <input type="hidden" name="rejection_reason" value="${reason}">
            `;
            document.body.appendChild(form);
            form.submit();
        }
        
        // Reschedule appointment
        function rescheduleAppointment(appointmentId) {
            const newDate = prompt('Neues Datum (YYYY-MM-DD):');
            if (newDate === null) return;
            
            const newTime = prompt('Neue Zeit (HH:MM):');
            if (newTime === null) return;
            
            const reason = prompt('Grund für die Verschiebung:');
            if (reason === null) return;
            
            if (!confirm('Termin verschieben? Der Kunde erhält eine Benachrichtigung.')) {
                return;
            }
            
            const form = document.createElement('form');
            form.method = 'POST';
            form.innerHTML = `
                <input type="hidden" name="action" value="update">
                <input type="hidden" name="action_type" value="reschedule">
                <input type="hidden" name="id" value="${appointmentId}">
                <input type="hidden" name="new_slot_date" value="${newDate}">
                <input type="hidden" name="new_slot_time" value="${newTime}">
                <input type="hidden" name="reschedule_reason" value="${reason}">
            `;
            document.body.appendChild(form);
            form.submit();
        }
        
        // Mark as booked
        function markAsBooked(appointmentId) {
            if (!confirm('Termin als gebucht markieren?')) {
                return;
            }
            
            const form = document.createElement('form');
            form.method = 'POST';
            form.innerHTML = `
                <input type="hidden" name="action" value="update">
                <input type="hidden" name="action_type" value="mark_booked">
                <input type="hidden" name="id" value="${appointmentId}">
            `;
            document.body.appendChild(form);
            form.submit();
        }
        
        

        // Order tires function
        function orderTires(appointment) {
            console.log('orderTires aufgerufen mit:', appointment);
            
            // Show confirmation modal
            showTireOrderModal(appointment);
        }

        // Show tire order modal
        // Progress Modal State
        let currentStep = 1;
        let tireOrderData = {};
        let recommendedDeliveryDate = null;

        function showTireOrderModal(appointment) {
            console.log('showTireOrderModal aufgerufen mit:', appointment);
            const modal = document.getElementById('tire-order-modal');
            const content = document.getElementById('tire-order-content');
            
            if (!modal) {
                console.error('Tire Order Modal nicht gefunden!');
                return;
            }
            
            if (!content) {
                console.error('Tire Order Content nicht gefunden!');
                return;
            }
            
            // Reset progress state
            currentStep = 1;
            tireOrderData = {
                appointment: appointment,
                autohaus: null,
                deliveryDate: null
            };
            
            showProgressStep();
            modal.style.display = 'block';
        }

        function showProgressStep() {
            const content = document.getElementById('tire-order-content');
            
            switch(currentStep) {
                case 1:
                    showAutohausSelectionStep();
                    break;
                case 2:
                    showDeliveryDateStep();
                    break;
                case 3:
                    showConfirmationStep();
                    break;
            }
        }

        function showAutohausSelectionStep() {
            const content = document.getElementById('tire-order-content');
            const appointment = tireOrderData.appointment;
            
            content.innerHTML = `
                <div class="progress-modal">
                    <div class="progress-header">
                        <div class="progress-steps">
                            <div class="step ${currentStep >= 1 ? 'active' : ''} ${currentStep > 1 ? 'completed' : ''}">
                                <div class="step-number">1</div>
                                <div class="step-label">Autohaus</div>
                            </div>
                            <div class="step ${currentStep >= 2 ? 'active' : ''} ${currentStep > 2 ? 'completed' : ''}">
                                <div class="step-number">2</div>
                                <div class="step-label">Liefertermin</div>
                            </div>
                            <div class="step ${currentStep >= 3 ? 'active' : ''}">
                                <div class="step-number">3</div>
                                <div class="step-label">Bestätigung</div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="step-content">
                        <div class="step-header">
                            <h3>
                                <i class="fas fa-building"></i>
                                Autohaus für Reifenlieferung auswählen
                            </h3>
                            <p>Wählen Sie das Autohaus aus, an das die Reifen geliefert werden sollen:</p>
                        </div>
                        
                        <div class="customer-summary">
                            <div class="summary-card">
                                <h4><i class="fas fa-user"></i> ${appointment.customer_name}</h4>
                                <p><i class="fas fa-car"></i> ${appointment.license_plate}</p>
                                <p><i class="fas fa-warehouse"></i> ${appointment.storage_number}</p>
                            </div>
                            <div class="summary-card">
                                <h4><i class="fas fa-calendar"></i> Termin</h4>
                                <p>${formatDate(appointment.slot_date)} um ${formatTime(appointment.slot_time)}</p>
                                <p><strong>Event:</strong> ${appointment.event_name}</p>
                            </div>
                        </div>
                        
                        <div class="autohaus-options" id="autohaus-options">
                            <div class="loading-autohaus">
                                <i class="fas fa-spinner fa-spin"></i>
                                Lade verfügbare Autohäuser...
                            </div>
                        </div>
                        
                        <div class="step-actions">
                            <button class="btn btn-secondary" onclick="closeTireOrderModal()">
                                <i class="fas fa-times"></i>
                                Abbrechen
                            </button>
                            <button class="btn btn-primary" id="next-step-btn" onclick="nextStep()" disabled>
                                Weiter
                                <i class="fas fa-arrow-right"></i>
                            </button>
                        </div>
                    </div>
                </div>
            `;
            
            // Lade verfügbare Autohäuser
            loadAutohausOptions();
        }

        function showDeliveryDateStep() {
            const content = document.getElementById('tire-order-content');
            const appointment = tireOrderData.appointment;
            const autohaus = tireOrderData.autohaus;
            
            content.innerHTML = `
                <div class="progress-modal">
                    <div class="progress-header">
                        <div class="progress-steps">
                            <div class="step completed">
                                <div class="step-number">1</div>
                                <div class="step-label">Autohaus</div>
                            </div>
                            <div class="step active">
                                <div class="step-number">2</div>
                                <div class="step-label">Liefertermin</div>
                            </div>
                            <div class="step">
                                <div class="step-number">3</div>
                                <div class="step-label">Bestätigung</div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="step-content">
                        <div class="step-header">
                            <h3>
                                <i class="fas fa-calendar-alt"></i>
                                Liefertermin auswählen
                            </h3>
                            <p>Wählen Sie den gewünschten Liefertermin für die Reifen aus:</p>
                        </div>
                        
                        <div class="selected-autohaus-info">
                            <div class="info-card">
                                <h4><i class="fas fa-building"></i> Gewähltes Autohaus</h4>
                                <p><strong>${autohaus.name}</strong></p>
                                <p><i class="fas fa-map-marker-alt"></i> ${autohaus.address}</p>
                                <p><i class="fas fa-phone"></i> ${autohaus.phone}</p>
                            </div>
                        </div>
                        
                        <div class="calendar-container">
                            <div class="calendar-wrapper">
                                <div class="calendar-header">
                                    <button type="button" class="calendar-nav-btn" onclick="changeMonth(-1)">
                                        <i class="fas fa-chevron-left"></i>
                                    </button>
                                    <h5 id="calendar-month-year"></h5>
                                    <button type="button" class="calendar-nav-btn" onclick="changeMonth(1)">
                                        <i class="fas fa-chevron-right"></i>
                                    </button>
                                </div>
                                <div class="calendar-grid" id="calendar-grid">
                                    <!-- Calendar will be generated here -->
                                </div>
                            </div>
                            <div class="selected-date-info">
                                <p><strong>Gewählter Liefertermin:</strong> <span id="selected-delivery-date">Kein Termin ausgewählt</span></p>
                                <p class="date-note">Verfügbare Liefertage werden live aus dem RESY-System geladen.</p>
                                <div class="recommended-date" id="recommended-date">
                                    <!-- Recommended date will be shown here -->
                                </div>
                            </div>
                        </div>
                        
                        <div class="step-actions">
                            <button class="btn btn-secondary" onclick="previousStep()">
                                <i class="fas fa-arrow-left"></i>
                                Zurück
                            </button>
                            <button class="btn btn-primary" id="next-step-btn" onclick="nextStep()" disabled>
                                Weiter
                                <i class="fas fa-arrow-right"></i>
                            </button>
                        </div>
                    </div>
                </div>
            `;
            
            // Initialisiere Kalender und lade verfügbare Termine
            setTimeout(() => {
                initializeCalendar();
                loadAvailableDeliveryDates();
            }, 100);
        }

        function showConfirmationStep() {
            const content = document.getElementById('tire-order-content');
            const appointment = tireOrderData.appointment;
            const autohaus = tireOrderData.autohaus;
            const deliveryDate = tireOrderData.deliveryDate;
            
            content.innerHTML = `
                <div class="progress-modal">
                    <div class="progress-header">
                        <div class="progress-steps">
                            <div class="step completed">
                                <div class="step-number">1</div>
                                <div class="step-label">Autohaus</div>
                            </div>
                            <div class="step completed">
                                <div class="step-number">2</div>
                                <div class="step-label">Liefertermin</div>
                            </div>
                            <div class="step active">
                                <div class="step-number">3</div>
                                <div class="step-label">Bestätigung</div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="step-content">
                        <div class="step-header">
                            <h3>
                                <i class="fas fa-check-circle"></i>
                                Bestellung bestätigen
                            </h3>
                            <p>Überprüfen Sie alle Angaben und bestätigen Sie die Reifenbestellung:</p>
                        </div>
                        
                        <div class="confirmation-summary">
                            <div class="summary-section">
                                <h4><i class="fas fa-user"></i> Kunde & Termin</h4>
                                <div class="summary-item">
                                    <span class="label">Kunde:</span>
                                    <span class="value">${appointment.customer_name}</span>
                                </div>
                                <div class="summary-item">
                                    <span class="label">Kennzeichen:</span>
                                    <span class="value">${appointment.license_plate}</span>
                                </div>
                                <div class="summary-item">
                                    <span class="label">Einlagerungsnummer:</span>
                                    <span class="value">${appointment.storage_number}</span>
                                </div>
                                <div class="summary-item">
                                    <span class="label">Event:</span>
                                    <span class="value">${appointment.event_name}</span>
                                </div>
                                <div class="summary-item">
                                    <span class="label">Termin:</span>
                                    <span class="value">${formatDate(appointment.slot_date)} um ${formatTime(appointment.slot_time)}</span>
                                </div>
                            </div>
                            
                            <div class="summary-section">
                                <h4><i class="fas fa-building"></i> Lieferung</h4>
                                <div class="summary-item">
                                    <span class="label">Autohaus:</span>
                                    <span class="value">${autohaus.name}</span>
                                </div>
                                <div class="summary-item">
                                    <span class="label">Adresse:</span>
                                    <span class="value">${autohaus.address}</span>
                                </div>
                                <div class="summary-item">
                                    <span class="label">Liefertermin:</span>
                                    <span class="value">${deliveryDate ? deliveryDate.toLocaleDateString('de-DE', { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' }) : 'Nicht ausgewählt'}</span>
                                </div>
                            </div>
                        </div>
                        
                        <div class="step-actions">
                            <button class="btn btn-secondary" onclick="previousStep()">
                                <i class="fas fa-arrow-left"></i>
                                Zurück
                            </button>
                            <button class="btn btn-success" onclick="confirmTireOrder(${JSON.stringify(appointment).replace(/"/g, '&quot;')})">
                                <i class="fas fa-tire"></i>
                                Reifen bestellen
                            </button>
                        </div>
                    </div>
                </div>
            `;
        }

        function nextStep() {
            if (currentStep < 3) {
                currentStep++;
                showProgressStep();
            }
        }

        function previousStep() {
            if (currentStep > 1) {
                currentStep--;
                showProgressStep();
            }
        }

        // Load autohaus options
        function loadAutohausOptions() {
            fetch('../api/get_autohauser.php', {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.success && data.autohauser) {
                    displayAutohausOptions(data.autohauser);
                } else {
                    showAutohausError('Fehler beim Laden der Autohäuser: ' + (data.error || 'Unbekannter Fehler'));
                }
            })
            .catch(error => {
                console.error('Error loading autohaus options:', error);
                showAutohausError('Fehler beim Laden der Autohäuser: ' + error.message);
            });
        }

        // Display autohaus options
        function displayAutohausOptions(autohauser) {
            const container = document.getElementById('autohaus-options');
            
            container.innerHTML = autohauser.map(autohaus => `
                <div class="autohaus-option" onclick="selectAutohausForOrder(${autohaus.id}, '${autohaus.name}', '${autohaus.short_name}')">
                    <div class="autohaus-option-header">
                        <h5>${autohaus.name}</h5>
                        <span class="autohaus-short">${autohaus.short_name}</span>
                    </div>
                    <div class="autohaus-option-details">
                        <p><i class="fas fa-map-marker-alt"></i> ${autohaus.address}</p>
                        <p><i class="fas fa-phone"></i> ${autohaus.phone}</p>
                    </div>
                </div>
            `).join('');
        }

        // Show autohaus error
        function showAutohausError(message) {
            const container = document.getElementById('autohaus-options');
            container.innerHTML = `
                <div class="autohaus-error">
                    <i class="fas fa-exclamation-triangle"></i>
                    <p>${message}</p>
                    <button class="btn btn-sm btn-outline-primary" onclick="loadAutohausOptions()">
                        <i class="fas fa-refresh"></i> Erneut versuchen
                    </button>
                </div>
            `;
        }

        // Calendar functionality
        let currentCalendarDate = new Date();
        let selectedDeliveryDate = null;

        function initializeCalendar() {
            generateCalendar(currentCalendarDate);
        }

        function generateCalendar(date) {
            const calendarGrid = document.getElementById('calendar-grid') || document.getElementById('bulk-calendar-grid');
            const monthYear = document.getElementById('calendar-month-year') || document.getElementById('bulk-calendar-month-year');
            
            if (!calendarGrid || !monthYear) return;

            const year = date.getFullYear();
            const month = date.getMonth();
            
            // Update month/year display
            const monthNames = [
                'Januar', 'Februar', 'März', 'April', 'Mai', 'Juni',
                'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember'
            ];
            monthYear.textContent = `${monthNames[month]} ${year}`;

            // Get first day of month and number of days
            const firstDay = new Date(year, month, 1);
            const lastDay = new Date(year, month + 1, 0);
            const daysInMonth = lastDay.getDate();
            const startingDayOfWeek = firstDay.getDay(); // 0 = Sunday, 1 = Monday, etc.

            // Day headers
            const dayHeaders = ['So', 'Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa'];
            let calendarHTML = dayHeaders.map(day => 
                `<div class="calendar-day-header">${day}</div>`
            ).join('');

            // Add empty cells for days before the first day of the month
            for (let i = 0; i < startingDayOfWeek; i++) {
                calendarHTML += '<div class="calendar-day disabled"></div>';
            }

            // Add days of the month
            for (let day = 1; day <= daysInMonth; day++) {
                const currentDate = new Date(year, month, day);
                const dayOfWeek = currentDate.getDay();
                const isPast = currentDate < new Date().setHours(0, 0, 0, 0);
                const isSelected = selectedDeliveryDate && 
                    currentDate.toDateString() === selectedDeliveryDate.toDateString();

                // Check if this date is available from RESY
                const dateString = currentDate.toISOString().split('T')[0];
                const availableDate = window.availableDeliveryDates ? 
                    window.availableDeliveryDates.find(d => d.date === dateString) : null;
                
                const isAvailable = availableDate !== null;
                const isPreferred = availableDate && availableDate.preferred;
                const isResyAvailable = availableDate && !availableDate.preferred;
                const isRecommended = recommendedDeliveryDate && recommendedDeliveryDate.date === dateString;
                if (isRecommended) {
                    console.log('Empfohlener Tag gefunden im Kalender:', dateString, recommendedDeliveryDate);
                }

                let dayClass = 'calendar-day';
                if (isPast) {
                    dayClass += ' disabled';
                } else if (isRecommended) {
                    dayClass += ' recommended';
                } else if (isPreferred) {
                    dayClass += ' preferred';
                } else if (isResyAvailable) {
                    dayClass += ' resy-available';
                } else if (!isAvailable) {
                    dayClass += ' disabled';
                }
                
                if (isSelected) dayClass += ' selected';

                calendarHTML += `
                    <button class="${dayClass}" 
                            ${isPast || !isAvailable ? 'disabled' : ''} 
                            onclick="${isPast || !isAvailable ? '' : `selectDeliveryDate(${year}, ${month}, ${day})`}"
                            title="${isRecommended ? '⭐ EMPFOHLENER TERMIN ⭐\n\n' + availableDate.label + '\n\n✨ Automatisch ausgewählt für optimale Lieferung!\n💡 Sie können den Termin manuell ändern.' : (availableDate ? availableDate.label : 'Nicht verfügbar')}">
                        ${day}
                    </button>
                `;
            }

            calendarGrid.innerHTML = calendarHTML;
        }

        function changeMonth(direction) {
            currentCalendarDate.setMonth(currentCalendarDate.getMonth() + direction);
            generateCalendar(currentCalendarDate);
        }

        function selectDeliveryDate(year, month, day) {
            selectedDeliveryDate = new Date(year, month, day);
            tireOrderData.deliveryDate = selectedDeliveryDate;
            generateCalendar(currentCalendarDate); // Regenerate to show selection
            
            // Update selected date display for both single and bulk orders
            const selectedDateElement = document.getElementById('selected-delivery-date') || document.getElementById('bulk-selected-delivery-date');
            if (selectedDateElement) {
                const formattedDate = selectedDeliveryDate.toLocaleDateString('de-DE', {
                    weekday: 'long',
                    year: 'numeric',
                    month: 'long',
                    day: 'numeric'
                });
                selectedDateElement.textContent = formattedDate;
            }
            
            // Enable next button
            const nextBtn = document.getElementById('next-step-btn');
            if (nextBtn) {
                nextBtn.disabled = false;
            }
        }

        function getSelectedDeliveryDate() {
            return selectedDeliveryDate ? selectedDeliveryDate.toISOString().split('T')[0] : null;
        }

        // Load available delivery dates from RESY
        function loadAvailableDeliveryDates() {
            if (!tireOrderData.autohaus) {
                console.error('Kein Autohaus ausgewählt');
                return;
            }

            const requestData = {
                action: 'get_available_dates',
                autohaus_id: tireOrderData.autohaus.id
            };

            // Show loading indicator
            const recommendedElement = document.getElementById('recommended-date');
            if (recommendedElement) {
                recommendedElement.innerHTML = `
                    <h5><i class="fas fa-spinner fa-spin"></i> Lade verfügbare Termine...</h5>
                    <p>Verbindung zum RESY-System wird hergestellt...</p>
                `;
            }

            fetch('../api/tire_order.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(requestData)
            })
            .then(response => {
                // Check if response is JSON
                const contentType = response.headers.get('content-type');
                if (!contentType || !contentType.includes('application/json')) {
                    return response.text().then(text => {
                        console.error('Non-JSON response:', text);
                        throw new Error('Server returned non-JSON response. Check PHP errors.');
                    });
                }
                return response.json();
            })
            .then(data => {
                if (data.success && data.available_dates) {
                    console.log('Verfügbare Termine geladen:', data.available_dates);
                    updateCalendarWithAvailableDates(data.available_dates);
                    showRecommendedDate(data.available_dates);
                } else {
                    console.warn('Keine verfügbaren Termine geladen:', data.error || 'Unbekannter Fehler');
                    showRecommendedDate([]);
                }
            })
            .catch(error => {
                console.error('Fehler beim Laden der verfügbaren Termine:', error);
                showRecommendedDate([]);
                
                // Show error message
                if (recommendedElement) {
                    recommendedElement.innerHTML = `
                        <h5><i class="fas fa-exclamation-triangle"></i> Fehler beim Laden</h5>
                        <p>Verfügbare Termine konnten nicht geladen werden. Verwende Standard-Termine.</p>
                    `;
                }
            });
        }

        // Update calendar with available dates from RESY
        function updateCalendarWithAvailableDates(availableDates) {
            // Store available dates globally for calendar generation
            window.availableDeliveryDates = availableDates;
            
            // Set recommended date first, then regenerate calendar
            showRecommendedDate(availableDates);
            
            // Wait a bit to ensure recommendedDeliveryDate is set, then regenerate calendar
            setTimeout(() => {
                generateCalendar(currentCalendarDate);
            }, 100);
        }

        // Show recommended delivery date
        function showRecommendedDate(availableDates) {
            const recommendedElement = document.getElementById('recommended-date');
            if (!recommendedElement) return;

            const appointment = tireOrderData.appointment;
            const appointmentDate = new Date(appointment.event_date);
            
            // Calculate recommended date (3 days before appointment, max 2-3 days)
            const recommendedDate = new Date(appointmentDate);
            recommendedDate.setDate(recommendedDate.getDate() - 3);
            
            // Find the best available date near the recommended date
            let bestDate = null;
            let bestDistance = Infinity;
            let preferredDate = null;
            
            availableDates.forEach(dateInfo => {
                const date = new Date(dateInfo.date);
                const distance = Math.abs(date - recommendedDate);
                
                // Prefer dates before the appointment
                if (date <= appointmentDate) {
                    if (dateInfo.preferred && !preferredDate) {
                        preferredDate = dateInfo;
                    }
                    
                    if (distance < bestDistance) {
                        bestDistance = distance;
                        bestDate = dateInfo;
                    }
                }
            });
            
            // Use preferred date if available, otherwise use best date
            const recommendedDateInfo = preferredDate || bestDate;
            
            // Speichere den empfohlenen Tag global
            recommendedDeliveryDate = recommendedDateInfo;
            console.log('Empfohlener Tag gesetzt:', recommendedDeliveryDate);
            
            if (recommendedDateInfo) {
                const formattedDate = new Date(recommendedDateInfo.date).toLocaleDateString('de-DE', {
                    weekday: 'long',
                    year: 'numeric',
                    month: 'long',
                    day: 'numeric'
                });
                
                const availabilityInfo = recommendedDateInfo.available_count ? 
                    ` (${recommendedDateInfo.available_count} Bestellungen frei)` : '';
                
                recommendedElement.innerHTML = `
                    <h5><i class="fas fa-star"></i> Empfohlener Liefertermin</h5>
                    <p><strong>${formattedDate}</strong>${availabilityInfo}</p>
                    <p>Automatisch ausgewählt für rechtzeitige Lieferung (3 Tage vor Termin).</p>
                    <p class="text-info">💡 Sie können den Termin manuell ändern, falls gewünscht</p>
                `;
                
                // Automatisch den empfohlenen Tag auswählen
                setTimeout(() => {
                    const year = new Date(recommendedDateInfo.date).getFullYear();
                    const month = new Date(recommendedDateInfo.date).getMonth() + 1;
                    const day = new Date(recommendedDateInfo.date).getDate();
                    selectDeliveryDate(year, month, day);
                }, 200);
            } else if (availableDates.length > 0) {
                // Show first available date if no good recommendation found
                const firstDate = availableDates[0];
                const formattedDate = new Date(firstDate.date).toLocaleDateString('de-DE', {
                    weekday: 'long',
                    year: 'numeric',
                    month: 'long',
                    day: 'numeric'
                });
                
                recommendedElement.innerHTML = `
                    <h5><i class="fas fa-info-circle"></i> Erster verfügbarer Termin</h5>
                    <p><strong>${formattedDate}</strong></p>
                    <p>Wählen Sie einen passenden Termin aus dem Kalender.</p>
                `;
            } else {
                recommendedElement.innerHTML = `
                    <h5><i class="fas fa-info-circle"></i> Empfehlung</h5>
                    <p>Bestellen Sie spätestens 2-3 Tage vor dem Termin für rechtzeitige Lieferung.</p>
                `;
            }
        }

        // Select autohaus for order
        function selectAutohausForOrder(autohausId, autohausName, autohausShort) {
            // Remove previous selection
            document.querySelectorAll('.autohaus-option').forEach(option => {
                option.classList.remove('selected');
            });
            
            // Mark selected option
            event.currentTarget.classList.add('selected');
            
            // Store selected autohaus in progress data
            tireOrderData.autohaus = {
                id: autohausId,
                name: autohausName,
                short_name: autohausShort,
                address: event.currentTarget.querySelector('.autohaus-option-details p:first-child')?.textContent?.replace('📍 ', '') || '',
                phone: event.currentTarget.querySelector('.autohaus-option-details p:last-child')?.textContent?.replace('📞 ', '') || ''
            };
            
            // Also store globally for compatibility
            window.selectedAutohaus = tireOrderData.autohaus;
            
            // Enable next button
            const nextBtn = document.getElementById('next-step-btn');
            if (nextBtn) {
                nextBtn.disabled = false;
            }
            
            // Remove any existing confirmation messages first
            const container = document.getElementById('autohaus-options');
            const existingConfirmations = container.querySelectorAll('.autohaus-selection-confirmed');
            existingConfirmations.forEach(confirmation => confirmation.remove());
            
            // Show selection confirmation
            const confirmation = document.createElement('div');
            confirmation.className = 'autohaus-selection-confirmed';
            confirmation.innerHTML = `
                <div class="selection-confirmed">
                    <i class="fas fa-check-circle"></i>
                    <span>Ausgewählt: <strong>${autohausName}</strong></span>
                </div>
            `;
            container.appendChild(confirmation);
        }

        // Confirm tire order
        function confirmTireOrder(appointment) {
            // Check if autohaus is selected
            if (!window.selectedAutohaus) {
                alert('Bitte wählen Sie ein Autohaus für die Reifenlieferung aus.');
                return;
            }
            
            // Check if delivery date is selected
            if (!selectedDeliveryDate) {
                alert('Bitte wählen Sie einen Liefertermin aus dem Kalender aus.');
                return;
            }
            
            const modal = document.getElementById('tire-order-modal');
            const content = document.getElementById('tire-order-content');
            
            // Show loading state with process steps
            content.innerHTML = `
                <div class="tire-order-loading">
                    <div class="loading-spinner">
                        <i class="fas fa-spinner fa-spin"></i>
                    </div>
                    <h4>Reifenbestellung wird verarbeitet...</h4>
                    <p>Bitte warten Sie einen Moment.</p>
                    
                    <div class="order-process">
                        <div class="process-step active">
                            <div class="step-icon">
                                <i class="fas fa-tire"></i>
                            </div>
                            <div class="step-content">
                                <h5>Reifenbestellung vorbereiten</h5>
                                <p>Daten werden validiert und vorbereitet</p>
                            </div>
                        </div>
                        
                        <div class="process-step">
                            <div class="step-icon">
                                <i class="fas fa-cog"></i>
                            </div>
                            <div class="step-content">
                                <h5>RESY-System kontaktieren</h5>
                                <p>Integration mit dem Reifensystem wird hergestellt</p>
                            </div>
                        </div>
                        
                        <div class="process-step">
                            <div class="step-icon">
                                <i class="fas fa-truck"></i>
                            </div>
                            <div class="step-content">
                                <h5>Lieferung planen</h5>
                                <p>Bestelltermin und Lieferung werden berechnet</p>
                            </div>
                        </div>
                        
                        <div class="process-step">
                            <div class="step-icon">
                                <i class="fas fa-check"></i>
                            </div>
                            <div class="step-content">
                                <h5>Bestellung abschließen</h5>
                                <p>Reifenbestellung wird finalisiert</p>
                            </div>
                        </div>
                    </div>
                </div>
            `;

            // Prepare data
            const orderData = {
                storage_number: appointment.storage_number,
                appointment_date: appointment.event_date,
                event_name: appointment.event_name,
                autohaus_id: window.selectedAutohaus.id,
                selected_delivery_date: getSelectedDeliveryDate()
            };

            console.log('Sende Reifenbestellung:', orderData);

            // Animate process steps
            animateOrderProcess();

            // Send order request
            fetch('../api/tire_order.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(orderData)
            })
            .then(response => {
                console.log('API Response Status:', response.status);
                console.log('API Response Headers:', response.headers);
                
                // Check if response is JSON
                const contentType = response.headers.get('content-type');
                if (!contentType || !contentType.includes('application/json')) {
                    return response.text().then(text => {
                        console.error('Non-JSON response:', text);
                        throw new Error('Server returned non-JSON response: ' + text.substring(0, 200));
                    });
                }
                
                if (!response.ok) {
                    return response.json().then(errorData => {
                        throw new Error('HTTP ' + response.status + ': ' + (errorData.error || response.statusText));
                    });
                }
                return response.json();
            })
            .then(result => {
                console.log('API Response:', result);
                if (result.success) {
                    showTireOrderSuccess(result, appointment);
                } else {
                    showTireOrderError(result, appointment);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showTireOrderError({ 
                    success: false, 
                    error: error.message,
                    details: 'Fehler bei der Reifenbestellung'
                }, appointment);
            });
        }

        // Show success result
        function showTireOrderSuccess(result, appointment) {
            const content = document.getElementById('tire-order-content');
            
            let deliveryInfo = '';
            const orderDate = result.order_date ? new Date(result.order_date) : new Date();
            const eventDate = new Date(result.event_date || appointment.event_date);
            
            if (orderDate && eventDate) {
                        const daysDiff = Math.ceil((eventDate - orderDate) / (1000 * 60 * 60 * 24));
                        
                        if (daysDiff >= 3) {
                    deliveryInfo = `
                        <div class="delivery-info success">
                            <i class="fas fa-check-circle"></i>
                            <span>Reifen werden ${daysDiff} Tage VOR dem Event geliefert</span>
                        </div>
                    `;
                        } else if (daysDiff > 0) {
                    deliveryInfo = `
                        <div class="delivery-info warning">
                            <i class="fas fa-exclamation-triangle"></i>
                            <span>Reifen werden nur ${daysDiff} Tage VOR dem Event geliefert (weniger als 3 Tage)</span>
                        </div>
                    `;
                        } else {
                    deliveryInfo = `
                        <div class="delivery-info error">
                            <i class="fas fa-times-circle"></i>
                            <span>Reifen werden NACH dem Event geliefert</span>
                        </div>
                    `;
                }
            }

            let resyInfo = '';
                    if (result.resy_result) {
                resyInfo = `
                    <div class="resy-info">
                        <h5><i class="fas fa-cog"></i> RESY-System</h5>
                        <p>${result.resy_result.message}</p>
                        ${result.resy_result.lgs_id ? `<p><strong>LGS-ID:</strong> ${result.resy_result.lgs_id}</p>` : ''}
                    </div>
                `;
            }

            let warningInfo = '';
                    if (result.warning) {
                warningInfo = `
                    <div class="warning-info">
                        <i class="fas fa-exclamation-triangle"></i>
                        <span>${result.warning}</span>
                    </div>
                `;
            }

            content.innerHTML = `
                <div class="tire-order-result success">
                    <div class="result-header">
                        <div class="success-icon">
                            <i class="fas fa-check-circle"></i>
                        </div>
                        <h4>Reifenbestellung erfolgreich!</h4>
                    </div>
                    
                    <div class="result-message">
                        <p>${result.message}</p>
                    </div>
                    
                    <div class="result-details">
                        <div class="detail-item">
                            <span class="label">Event-Datum:</span>
                            <span class="value">${formatDate(result.event_date || appointment.event_date)}</span>
                        </div>
                        <div class="detail-item">
                            <span class="label">Bestelltermin:</span>
                            <span class="value">${formatDate(result.order_date || new Date().toISOString().split('T')[0])}</span>
                        </div>
                    </div>
                    
                    ${deliveryInfo}
                    ${resyInfo}
                    ${warningInfo}
                    
                    <div class="result-actions">
                        <button class="btn btn-primary" onclick="closeTireOrderModal(); location.reload();">
                            <i class="fas fa-check"></i>
                            Schließen
                        </button>
                    </div>
                </div>
            `;
        }

        // Show error result
        function showTireOrderError(result, appointment) {
            const content = document.getElementById('tire-order-content');
            
            let resyError = '';
                    if (result.resy_result && !result.resy_result.success) {
                resyError = `
                    <div class="resy-error">
                        <h5><i class="fas fa-cog"></i> RESY-System Fehler</h5>
                        <p>${result.resy_result.error}</p>
                    </div>
                `;
            }

            content.innerHTML = `
                <div class="tire-order-result error">
                    <div class="result-header">
                        <div class="error-icon">
                            <i class="fas fa-times-circle"></i>
                        </div>
                        <h4>Fehler bei der Reifenbestellung</h4>
                    </div>
                    
                    <div class="result-message">
                        <p>${result.error}</p>
                    </div>
                    
                    ${resyError}
                    
                    <div class="result-actions">
                        <button class="btn btn-secondary" onclick="showTireOrderModal(${JSON.stringify(appointment).replace(/"/g, '&quot;')})">
                            <i class="fas fa-redo"></i>
                            Erneut versuchen
                        </button>
                        <button class="btn btn-primary" onclick="closeTireOrderModal()">
                            <i class="fas fa-times"></i>
                            Schließen
                        </button>
                    </div>
                </div>
            `;
        }

        // Animate order process steps
        function animateOrderProcess() {
            const steps = document.querySelectorAll('.process-step');
            let currentStep = 0;
            
            const stepInterval = setInterval(() => {
                if (currentStep < steps.length) {
                    // Mark current step as completed
                    if (currentStep > 0) {
                        steps[currentStep - 1].classList.remove('active');
                        steps[currentStep - 1].classList.add('completed');
                    }
                    
                    // Activate next step
                    if (currentStep < steps.length) {
                        steps[currentStep].classList.add('active');
                    }
                    
                    currentStep++;
                } else {
                    clearInterval(stepInterval);
                }
            }, 800); // Change step every 800ms
        }

        // Close tire order modal
        function closeTireOrderModal() {
            document.getElementById('tire-order-modal').style.display = 'none';
            
            // Reset autohaus selection
            window.selectedAutohaus = null;
            window.selectedBulkAutohaus = null;
            
            // Clear any existing confirmation messages
            const confirmations = document.querySelectorAll('.autohaus-selection-confirmed');
            confirmations.forEach(confirmation => confirmation.remove());
            
            // Reset autohaus option selections
            const autohausOptions = document.querySelectorAll('.autohaus-option');
            autohausOptions.forEach(option => option.classList.remove('selected'));
            
            // Disable confirm buttons
            const confirmBtn = document.getElementById('confirm-order-btn');
            const bulkConfirmBtn = document.getElementById('confirm-bulk-order-btn');
            if (confirmBtn) confirmBtn.disabled = true;
            if (bulkConfirmBtn) bulkConfirmBtn.disabled = true;
        }

        // ===== BULK ACTIONS FUNCTIONS =====
        
        // Toggle all appointments selection
        function toggleAllAppointments(checkbox) {
            const appointmentCheckboxes = document.querySelectorAll('.appointment-checkbox');
            appointmentCheckboxes.forEach(cb => {
                cb.checked = checkbox.checked;
            });
            updateBulkActions();
        }

        // Update bulk actions toolbar visibility and count
        function updateBulkActions() {
            const selectedCheckboxes = document.querySelectorAll('.appointment-checkbox:checked');
            const toolbar = document.getElementById('bulk-actions-toolbar');
            const countText = document.getElementById('selected-count-text');
            
            if (selectedCheckboxes.length > 0) {
                toolbar.style.display = 'block';
                countText.textContent = `${selectedCheckboxes.length} Termine ausgewählt`;
            } else {
                toolbar.style.display = 'none';
            }
        }

        // Get selected appointment IDs
        function getSelectedAppointmentIds() {
            const selectedCheckboxes = document.querySelectorAll('.appointment-checkbox:checked');
            return Array.from(selectedCheckboxes).map(cb => cb.value);
        }

        // Get selected appointment data
        function getSelectedAppointments() {
            const selectedIds = getSelectedAppointmentIds();
            const appointments = <?php echo json_encode($appointments, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP); ?>;
            
            // Debug: Log appointments data
            console.log('Appointments data:', appointments);
            console.log('Selected IDs:', selectedIds);
            
            if (!appointments || !Array.isArray(appointments)) {
                console.error('Invalid appointments data:', appointments);
                return [];
            }
            
            const selectedAppointments = appointments.filter(apt => selectedIds.includes(apt.id.toString()));
            
            // Debug: Log selected appointments with required fields
            console.log('Selected appointments:', selectedAppointments);
            selectedAppointments.forEach((apt, index) => {
                console.log(`Appointment ${index}:`, {
                    id: apt.id,
                    storage_number: apt.storage_number,
                    event_date: apt.event_date,
                    event_name: apt.event_name,
                    brings_wheels: apt.brings_wheels,
                    tire_order_date: apt.tire_order_date
                });
            });
            
            return selectedAppointments;
        }

        // Bulk delete appointments
        function bulkDeleteAppointments() {
            const selectedAppointments = getSelectedAppointments();
            if (selectedAppointments.length === 0) {
                alert('Bitte wählen Sie mindestens einen Termin aus.');
                return;
            }

            const modal = document.getElementById('bulk-delete-modal');
            const list = document.getElementById('bulk-delete-list');
            const count = document.getElementById('delete-count');
            const tireCount = document.getElementById('tire-orders-count');
            const tireSection = document.getElementById('tire-cancellation-section');
            const tireList = document.getElementById('tire-cancellation-list');
            
            // Filter appointments with tire orders
            const appointmentsWithTireOrders = selectedAppointments.filter(apt => 
                apt.tire_order_date && !apt.brings_wheels && apt.storage_number
            );
            
            // Update counts
            count.textContent = selectedAppointments.length;
            tireCount.textContent = appointmentsWithTireOrders.length;
            
            // Show tire cancellation section if needed
            if (appointmentsWithTireOrders.length > 0) {
                tireSection.style.display = 'block';
                tireList.innerHTML = appointmentsWithTireOrders.map(apt => `
                    <div class="tire-order-item">
                        <div class="tire-order-info">
                            <strong>${apt.customer_name}</strong> - ${apt.license_plate}
                        </div>
                        <div class="tire-order-details">
                            <span class="storage-number">Einlagerungsnummer: ${apt.storage_number}</span>
                            <span class="order-date">Bestellt: ${new Date(apt.tire_order_date).toLocaleString('de-DE')}</span>
                        </div>
                    </div>
                `).join('');
            } else {
                tireSection.style.display = 'none';
            }
            
            // Show appointment details
            list.innerHTML = selectedAppointments.map(apt => `
                <div class="appointment-item">
                    <div class="appointment-info">
                        <strong>${apt.customer_name}</strong>
                        <span class="license-plate">${apt.license_plate}</span>
                    </div>
                    <div class="appointment-details">
                        <div class="detail-row">
                            <span class="label">Event:</span>
                            <span class="value">${apt.event_name}</span>
                        </div>
                        <div class="detail-row">
                            <span class="label">Datum:</span>
                            <span class="value">${new Date(apt.slot_date).toLocaleDateString('de-DE')} ${new Date(apt.slot_time).toLocaleTimeString('de-DE', {hour: '2-digit', minute: '2-digit'})}</span>
                        </div>
                        <div class="detail-row">
                            <span class="label">Status:</span>
                            <span class="value status-${apt.status}">${apt.status}</span>
                        </div>
                        ${apt.tire_order_date ? `
                            <div class="detail-row">
                                <span class="label">Reifenbestellung:</span>
                                <span class="value tire-ordered">Bestellt am ${new Date(apt.tire_order_date).toLocaleString('de-DE')}</span>
                            </div>
                        ` : ''}
                        ${apt.storage_number ? `
                            <div class="detail-row">
                                <span class="label">Einlagerungsnummer:</span>
                                <span class="value">${apt.storage_number}</span>
                            </div>
                        ` : ''}
                    </div>
                </div>
            `).join('');

            modal.style.display = 'block';
        }

        // Confirm bulk delete
        function confirmBulkDelete() {
            const selectedAppointments = getSelectedAppointments();
            const selectedIds = getSelectedAppointmentIds();
            const deletionReason = document.getElementById('deletion-reason-input').value;
            
            // Show loading state
            const modal = document.getElementById('bulk-delete-modal');
            const content = modal.querySelector('.modal-body');
            const originalContent = content.innerHTML;
            
            content.innerHTML = `
                <div class="delete-loading">
                    <div class="loading-spinner">
                        <i class="fas fa-spinner fa-spin"></i>
                    </div>
                    <h4>Termine werden gelöscht...</h4>
                    <p>Bitte warten Sie einen Moment.</p>
                    
                    <div class="delete-process">
                        <div class="process-step active">
                            <div class="step-icon">
                                <i class="fas fa-database"></i>
                            </div>
                            <div class="step-content">
                                <h5>Audit-Daten speichern</h5>
                                <p>Löschvorgang wird protokolliert</p>
                            </div>
                        </div>
                        
                        <div class="process-step">
                            <div class="step-icon">
                                <i class="fas fa-tire"></i>
                            </div>
                            <div class="step-content">
                                <h5>Reifenbestellungen prüfen</h5>
                                <p>Stornierung von Reifenbestellungen</p>
                            </div>
                        </div>
                        
                        <div class="process-step">
                            <div class="step-icon">
                                <i class="fas fa-trash"></i>
                            </div>
                            <div class="step-content">
                                <h5>Termine löschen</h5>
                                <p>Ausgewählte Termine werden entfernt</p>
                            </div>
                        </div>
                    </div>
                </div>
            `;
            
            // Animate process steps
            animateDeleteProcess();
            
            // Send AJAX request to delete appointments with audit data
            const formData = new FormData();
            formData.append('action', 'bulk_delete');
            formData.append('appointment_ids', selectedIds.join(','));
            formData.append('appointments', JSON.stringify(selectedAppointments));
            formData.append('deletion_reason', deletionReason);
            
            // Debug logging
            console.log('Sending data:', {
                appointment_ids: selectedIds.join(','),
                appointments: selectedAppointments,
                deletion_reason: deletionReason
            });
            
            fetch('appointments.php', {
                method: 'POST',
                body: formData
            })
            .then(response => {
                console.log('Response status:', response.status);
                console.log('Response headers:', response.headers);
                
                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                }
                
                return response.text().then(text => {
                    console.log('Raw response:', text);
                    try {
                        return JSON.parse(text);
                    } catch (e) {
                        console.error('JSON parse error:', e);
                        console.error('Response text:', text);
                        throw new Error('Ungültige JSON-Antwort vom Server: ' + text.substring(0, 200));
                    }
                });
            })
            .then(data => {
                console.log('Parsed response:', data);
                if (data.success) {
                    showDeleteSuccess(data);
                } else {
                    showDeleteError(data);
                }
            })
            .catch(error => {
                console.error('Fetch error:', error);
                showDeleteError({ 
                    message: 'Fehler beim Löschen der Termine: ' + error.message,
                    debug_info: {
                        error_type: 'fetch_error',
                        error_message: error.message,
                        error_stack: error.stack
                    }
                });
            });
        }
        
        // Show delete success
        function showDeleteSuccess(data) {
            const modal = document.getElementById('bulk-delete-modal');
            const content = modal.querySelector('.modal-body');
            
            let resultHtml = `
                <div class="delete-result">
                    <div class="result-header success">
                        <div class="result-icon">
                            <i class="fas fa-check-circle"></i>
                        </div>
                        <h4>Löschvorgang erfolgreich abgeschlossen</h4>
                    </div>
                    
                    <div class="result-summary">
                        <div class="summary-item success">
                            <i class="fas fa-trash"></i>
                            <span>Gelöscht: ${data.deleted_count} Termine</span>
                        </div>
                        ${data.tire_cancelled_count > 0 ? `
                            <div class="summary-item success">
                                <i class="fas fa-tire"></i>
                                <span>Storniert: ${data.tire_cancelled_count} Reifenbestellungen</span>
                            </div>
                        ` : ''}
                    </div>
            `;
            
            if (data.tire_cancellation_errors && data.tire_cancellation_errors.length > 0) {
                resultHtml += `
                    <div class="error-details">
                        <h5>Reifen-Stornierungen mit Fehlern:</h5>
                        <div class="error-list">
                            ${data.tire_cancellation_errors.map(error => `
                                <div class="error-item">
                                    <strong>${error.customer_name}</strong> - ${error.storage_number}
                                    <br><small><strong>Fehler:</strong> ${error.error}</small>
                                    <br><small><strong>Details:</strong> ${error.details}</small>
                                </div>
                            `).join('')}
                        </div>
                    </div>
                `;
            }
            
            resultHtml += `
                    <div class="result-actions">
                        <button class="btn btn-primary" onclick="closeBulkDeleteModal(); location.reload();">
                            <i class="fas fa-check"></i>
                            Schließen
                        </button>
                    </div>
                </div>
            `;
            
            content.innerHTML = resultHtml;
        }
        
        // Show delete error
        function showDeleteError(data) {
            const modal = document.getElementById('bulk-delete-modal');
            const content = modal.querySelector('.modal-body');
            
            let debugInfoHtml = '';
            if (data.debug_info) {
                debugInfoHtml = `
                    <div class="debug-info" style="margin-top: 20px; padding: 15px; background-color: #f8f9fa; border-radius: 5px; border-left: 4px solid #dc3545;">
                        <h6><i class="fas fa-bug"></i> Debug-Informationen:</h6>
                        <pre style="font-size: 12px; color: #666; margin: 10px 0;">${JSON.stringify(data.debug_info, null, 2)}</pre>
                    </div>
                `;
            }
            
            content.innerHTML = `
                <div class="delete-result">
                    <div class="result-header error">
                        <div class="result-icon">
                            <i class="fas fa-exclamation-triangle"></i>
                        </div>
                        <h4>Fehler beim Löschen</h4>
                    </div>
                    
                    <div class="result-message">
                        <p>${data.message || 'Ein unbekannter Fehler ist aufgetreten.'}</p>
                        ${debugInfoHtml}
                    </div>
                    
                    <div class="result-actions">
                        <button class="btn btn-secondary" onclick="closeBulkDeleteModal()">
                            <i class="fas fa-times"></i>
                            Schließen
                        </button>
                    </div>
                </div>
            `;
        }
        
        // Animate delete process
        function animateDeleteProcess() {
            const steps = document.querySelectorAll('.process-step');
            let currentStep = 0;
            
            const stepInterval = setInterval(() => {
                if (currentStep < steps.length) {
                    steps[currentStep].classList.add('active');
                    currentStep++;
                } else {
                    clearInterval(stepInterval);
                }
            }, 800);
        }

        // Close bulk delete modal
        function closeBulkDeleteModal() {
            document.getElementById('bulk-delete-modal').style.display = 'none';
        }

        // Bulk tire order
        function bulkOrderTires() {
            const selectedAppointments = getSelectedAppointments();
            if (selectedAppointments.length === 0) {
                alert('Bitte wählen Sie mindestens einen Termin aus.');
                return;
            }

            // Filter appointments that are eligible for tire order
            const eligibleAppointments = selectedAppointments.filter(apt => 
                !apt.brings_wheels && apt.storage_number
            );

            if (eligibleAppointments.length === 0) {
                alert('Keine der ausgewählten Termine ist für eine Reifenbestellung geeignet.\n\nTermine müssen eine Einlagerungsnummer haben und der Kunde darf keine eigenen Reifen mitbringen.');
                return;
            }

            // Use the existing tire order modal for bulk operations
            showBulkTireOrderModal(eligibleAppointments);
        }

        // Show bulk tire order modal using the same system as single orders
        function showBulkTireOrderModal(appointments) {
            const modal = document.getElementById('tire-order-modal');
            const content = document.getElementById('tire-order-content');
            
            content.innerHTML = `
                <div class="tire-order-confirmation">
                    <div class="order-header">
                        <div class="customer-info">
                            <h4>
                                <i class="fas fa-tire"></i>
                                Reifenbestellung für ${appointments.length} Termine
                            </h4>
                        </div>
                    </div>
                    
                    <div class="order-details">
                        <div class="appointments-list">
                            ${appointments.map(apt => `
                                <div class="appointment-item">
                                    <div class="appointment-info">
                                        <strong>${apt.customer_name}</strong>
                                        <span class="license-plate">${apt.license_plate}</span>
                                    </div>
                                    <div class="appointment-details">
                                        <div class="detail-row">
                                            <span class="label">Event:</span>
                                            <span class="value">${apt.event_name}</span>
                                        </div>
                                        <div class="detail-row">
                                            <span class="label">Datum:</span>
                                            <span class="value">${new Date(apt.slot_date).toLocaleDateString('de-DE')}</span>
                                        </div>
                                        <div class="detail-row">
                                            <span class="label">Einlagerungsnummer:</span>
                                            <span class="value">${apt.storage_number}</span>
                                        </div>
                                    </div>
                                </div>
                            `).join('')}
                        </div>
                    </div>
                    
                    <div class="autohaus-selection">
                        <h4>
                            <i class="fas fa-building"></i>
                            Autohaus für Reifenlieferung auswählen
                        </h4>
                        <p class="selection-info">Wählen Sie das Autohaus aus, an das die Reifen für alle Termine geliefert werden sollen:</p>
                        <div class="autohaus-options" id="bulk-autohaus-options">
                            <div class="loading-autohaus">
                                <i class="fas fa-spinner fa-spin"></i>
                                Lade verfügbare Autohäuser...
                            </div>
                        </div>
                    </div>
                    
                    <div class="delivery-date-selection">
                        <h4>
                            <i class="fas fa-calendar-alt"></i>
                            Liefertermin auswählen
                        </h4>
                        <p class="selection-info">Wählen Sie den gewünschten Liefertermin für alle Reifen aus:</p>
                        <div class="calendar-container">
                            <div class="calendar-wrapper">
                                <div class="calendar-header">
                                    <button type="button" class="calendar-nav-btn" onclick="changeMonth(-1)">
                                        <i class="fas fa-chevron-left"></i>
                                    </button>
                                    <h5 id="bulk-calendar-month-year"></h5>
                                    <button type="button" class="calendar-nav-btn" onclick="changeMonth(1)">
                                        <i class="fas fa-chevron-right"></i>
                                    </button>
                                </div>
                                <div class="calendar-grid" id="bulk-calendar-grid">
                                    <!-- Calendar will be generated here -->
                                </div>
                            </div>
                            <div class="selected-date-info">
                                <p><strong>Gewählter Liefertermin:</strong> <span id="bulk-selected-delivery-date">Kein Termin ausgewählt</span></p>
                                <p class="date-note">Reifen werden normalerweise an Dienstagen und Donnerstagen geliefert.</p>
                            </div>
                        </div>
                    </div>
                    
                    <div class="order-actions">
                        <button class="btn btn-secondary" onclick="closeTireOrderModal()">
                            <i class="fas fa-times"></i>
                            Abbrechen
                        </button>
                        <button class="btn btn-primary" id="confirm-bulk-order-btn" onclick="confirmBulkTireOrder(${JSON.stringify(appointments).replace(/"/g, '&quot;')})" disabled>
                            <i class="fas fa-tire"></i>
                            Reifen für alle Termine bestellen
                        </button>
                    </div>
                </div>
            `;
            
            modal.style.display = 'block';
            
            // Lade verfügbare Autohäuser für Bulk-Bestellung
            loadBulkAutohausOptions();
            
            // Initialisiere Kalender für Bulk-Bestellung
            setTimeout(() => {
                initializeCalendar();
            }, 100);
        }

        // Load autohaus options for bulk order
        function loadBulkAutohausOptions() {
            fetch('../api/get_autohauser.php', {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.success && data.autohauser) {
                    displayBulkAutohausOptions(data.autohauser);
                } else {
                    showBulkAutohausError('Fehler beim Laden der Autohäuser: ' + (data.error || 'Unbekannter Fehler'));
                }
            })
            .catch(error => {
                console.error('Error loading autohaus options:', error);
                showBulkAutohausError('Fehler beim Laden der Autohäuser: ' + error.message);
            });
        }

        // Display autohaus options for bulk order
        function displayBulkAutohausOptions(autohauser) {
            const container = document.getElementById('bulk-autohaus-options');
            
            container.innerHTML = autohauser.map(autohaus => `
                <div class="autohaus-option" onclick="selectBulkAutohausForOrder(${autohaus.id}, '${autohaus.name}', '${autohaus.short_name}')">
                    <div class="autohaus-option-header">
                        <h5>${autohaus.name}</h5>
                        <span class="autohaus-short">${autohaus.short_name}</span>
                    </div>
                    <div class="autohaus-option-details">
                        <p><i class="fas fa-map-marker-alt"></i> ${autohaus.address}</p>
                        <p><i class="fas fa-phone"></i> ${autohaus.phone}</p>
                    </div>
                </div>
            `).join('');
        }

        // Show autohaus error for bulk order
        function showBulkAutohausError(message) {
            const container = document.getElementById('bulk-autohaus-options');
            container.innerHTML = `
                <div class="autohaus-error">
                    <i class="fas fa-exclamation-triangle"></i>
                    <p>${message}</p>
                    <button class="btn btn-sm btn-outline-primary" onclick="loadBulkAutohausOptions()">
                        <i class="fas fa-refresh"></i> Erneut versuchen
                    </button>
                </div>
            `;
        }

        // Select autohaus for bulk order
        function selectBulkAutohausForOrder(autohausId, autohausName, autohausShort) {
            // Remove previous selection
            document.querySelectorAll('#bulk-autohaus-options .autohaus-option').forEach(option => {
                option.classList.remove('selected');
            });
            
            // Mark selected option
            event.currentTarget.classList.add('selected');
            
            // Store selection
            window.selectedBulkAutohaus = {
                id: autohausId,
                name: autohausName,
                short: autohausShort
            };
            
            // Enable confirm button
            document.getElementById('confirm-bulk-order-btn').disabled = false;
            
            // Remove any existing confirmation messages first
            const container = document.getElementById('bulk-autohaus-options');
            const existingConfirmations = container.querySelectorAll('.autohaus-selection-confirmed');
            existingConfirmations.forEach(confirmation => confirmation.remove());
            
            // Show selection confirmation
            const confirmation = document.createElement('div');
            confirmation.className = 'autohaus-selection-confirmed';
            confirmation.innerHTML = `
                <div class="selection-confirmed">
                    <i class="fas fa-check-circle"></i>
                    <span>Ausgewählt: <strong>${autohausName}</strong></span>
                </div>
            `;
            container.appendChild(confirmation);
        }

        // Confirm bulk tire order using the same process as single orders
        function confirmBulkTireOrder(appointments) {
            // Check if autohaus is selected
            if (!window.selectedBulkAutohaus) {
                alert('Bitte wählen Sie ein Autohaus für die Reifenlieferung aus.');
                return;
            }
            
            // Check if delivery date is selected
            if (!selectedDeliveryDate) {
                alert('Bitte wählen Sie einen Liefertermin aus dem Kalender aus.');
                return;
            }
            
            const modal = document.getElementById('tire-order-modal');
            const content = document.getElementById('tire-order-content');
            
            // Show loading state with process steps
            content.innerHTML = `
                <div class="tire-order-loading">
                    <div class="loading-spinner">
                        <i class="fas fa-spinner fa-spin"></i>
                    </div>
                    <h4>Reifenbestellung für ${appointments.length} Termine wird verarbeitet...</h4>
                    <p>Bitte warten Sie einen Moment.</p>
                    
                    <div class="order-process">
                        <div class="process-step active">
                            <div class="step-icon">
                                <i class="fas fa-tire"></i>
                            </div>
                            <div class="step-content">
                                <h5>Reifenbestellungen vorbereiten</h5>
                                <p>Daten für ${appointments.length} Termine werden validiert</p>
                            </div>
                        </div>
                        
                        <div class="process-step">
                            <div class="step-icon">
                                <i class="fas fa-cog"></i>
                            </div>
                            <div class="step-content">
                                <h5>RESY-System kontaktieren</h5>
                                <p>Integration mit dem Reifensystem wird hergestellt</p>
                            </div>
                        </div>
                        
                        <div class="process-step">
                            <div class="step-icon">
                                <i class="fas fa-truck"></i>
                            </div>
                            <div class="step-content">
                                <h5>Lieferungen planen</h5>
                                <p>Bestelltermine und Lieferungen werden berechnet</p>
                            </div>
                        </div>
                        
                        <div class="process-step">
                            <div class="step-icon">
                                <i class="fas fa-check"></i>
                            </div>
                            <div class="step-content">
                                <h5>Bestellungen abschließen</h5>
                                <p>Alle Reifenbestellungen werden finalisiert</p>
                            </div>
                        </div>
                    </div>
                </div>
            `;

            // Animate process steps
            animateOrderProcess();

            // Process each appointment individually
            processBulkTireOrders(appointments, 0, [], []);
        }

        // Process bulk tire orders one by one
        function processBulkTireOrders(appointments, currentIndex, successfulOrders, failedOrders) {
            if (currentIndex >= appointments.length) {
                // All orders processed, show results
                showBulkTireOrderResults(successfulOrders, failedOrders);
                return;
            }

            const appointment = appointments[currentIndex];
            const orderData = {
                storage_number: appointment.storage_number,
                appointment_date: appointment.event_date,
                event_name: appointment.event_name,
                autohaus_id: window.selectedBulkAutohaus.id,
                selected_delivery_date: getSelectedDeliveryDate()
            };

            console.log(`Verarbeite Reifenbestellung ${currentIndex + 1}/${appointments.length}:`, orderData);

            // Send order request for current appointment
            fetch('../api/tire_order.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(orderData)
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('HTTP ' + response.status + ': ' + response.statusText);
                }
                return response.json();
            })
            .then(result => {
                if (result.success) {
                    successfulOrders.push({ appointment, result });
                } else {
                    failedOrders.push({ appointment, error: result.error || 'Unbekannter Fehler' });
                }
                
                // Process next appointment
                processBulkTireOrders(appointments, currentIndex + 1, successfulOrders, failedOrders);
            })
            .catch(error => {
                console.error('Error:', error);
                failedOrders.push({ appointment, error: error.message });
                
                // Process next appointment
                processBulkTireOrders(appointments, currentIndex + 1, successfulOrders, failedOrders);
            });
        }

        // Show bulk tire order results
        function showBulkTireOrderResults(successfulOrders, failedOrders) {
            const modal = document.getElementById('tire-order-modal');
            const content = document.getElementById('tire-order-content');
            
            let resultHtml = `
                <div class="tire-order-result">
                    <div class="result-header">
                        <div class="result-icon">
                            <i class="fas fa-${successfulOrders.length > 0 ? 'check-circle' : 'exclamation-triangle'}"></i>
                        </div>
                        <h4>Bulk-Reifenbestellung abgeschlossen</h4>
                    </div>
                    
                    <div class="result-summary">
                        <div class="summary-item success">
                            <i class="fas fa-check"></i>
                            <span>Erfolgreich: ${successfulOrders.length} Termine</span>
                        </div>
                        ${failedOrders.length > 0 ? `
                            <div class="summary-item error">
                                <i class="fas fa-times"></i>
                                <span>Fehlgeschlagen: ${failedOrders.length} Termine</span>
                            </div>
                        ` : ''}
                    </div>
            `;

            if (successfulOrders.length > 0) {
                resultHtml += `
                    <div class="success-details">
                        <h5>Erfolgreich bestellt:</h5>
                        <div class="appointments-list">
                            ${successfulOrders.map(({ appointment, result }) => `
                                <div class="appointment-item success">
                                    <div class="appointment-info">
                                        <strong>${appointment.customer_name}</strong>
                                        <span class="license-plate">${appointment.license_plate}</span>
                                    </div>
                                    <div class="appointment-details">
                                        <div class="detail-row">
                                            <span class="label">Einlagerungsnummer:</span>
                                            <span class="value">${appointment.storage_number}</span>
                                        </div>
                                        ${result.order_number ? `
                                            <div class="detail-row">
                                                <span class="label">Bestellnummer:</span>
                                                <span class="value">${result.order_number}</span>
                                            </div>
                                        ` : ''}
                                    </div>
                                </div>
                            `).join('')}
                        </div>
                    </div>
                `;
            }

            if (failedOrders.length > 0) {
                resultHtml += `
                    <div class="error-details">
                        <h5>Fehlgeschlagene Bestellungen:</h5>
                        <div class="appointments-list">
                            ${failedOrders.map(({ appointment, error }) => `
                                <div class="appointment-item error">
                                    <div class="appointment-info">
                                        <strong>${appointment.customer_name}</strong>
                                        <span class="license-plate">${appointment.license_plate}</span>
                                    </div>
                                    <div class="appointment-details">
                                        <div class="detail-row">
                                            <span class="label">Einlagerungsnummer:</span>
                                            <span class="value">${appointment.storage_number}</span>
                                        </div>
                                        <div class="detail-row error">
                                            <span class="label">Fehler:</span>
                                            <span class="value">${error}</span>
                                        </div>
                                    </div>
                                </div>
                            `).join('')}
                        </div>
                    </div>
                `;
            }

            resultHtml += `
                    <div class="result-actions">
                        <button class="btn btn-primary" onclick="closeTireOrderModal(); location.reload();">
                            <i class="fas fa-check"></i>
                            Schließen
                        </button>
                    </div>
                </div>
            `;

            content.innerHTML = resultHtml;
        }


        // Bulk export appointments
        function bulkExportAppointments() {
            const selectedAppointments = getSelectedAppointments();
            if (selectedAppointments.length === 0) {
                alert('Bitte wählen Sie mindestens einen Termin aus.');
                return;
            }

            // Create CSV data for selected appointments
            const csvData = selectedAppointments.map(apt => ({
                'Kunde': apt.customer_name,
                'Kennzeichen': apt.license_plate,
                'Event': apt.event_name,
                'Datum': new Date(apt.slot_date).toLocaleDateString('de-DE'),
                'Zeit': new Date(apt.slot_time).toLocaleTimeString('de-DE', {hour: '2-digit', minute: '2-digit'}),
                'Telefon': apt.phone,
                'Status': apt.status,
                'Services': [
                    apt.wiper_blades ? 'Scheibenwischer' : '',
                    apt.seasonal_check !== 'none' ? (apt.seasonal_check === 'spring' ? 'Frühjahrescheck' : 'Wintercheck') : ''
                ].filter(s => s).join(', '),
                'Einlagerungsnummer': apt.storage_number || '',
                'Admin Notizen': apt.admin_notes || ''
            }));

            // Convert to CSV
            const headers = Object.keys(csvData[0]);
            const csvContent = [
                headers.join(','),
                ...csvData.map(row => headers.map(header => `"${row[header]}"`).join(','))
            ].join('\n');

            // Download CSV
            const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
            const link = document.createElement('a');
            const url = URL.createObjectURL(blob);
            link.setAttribute('href', url);
            link.setAttribute('download', `termine_export_${new Date().toISOString().split('T')[0]}.csv`);
            link.style.visibility = 'hidden';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }

        // Bulk print storage labels
        function bulkPrintStorageLabels() {
            const selectedAppointments = getSelectedAppointments();
            if (selectedAppointments.length === 0) {
                alert('Bitte wählen Sie mindestens einen Termin aus.');
                return;
            }

            const modal = document.getElementById('storage-labels-modal');
            const count = document.getElementById('labels-count');
            const list = document.getElementById('storage-labels-list');
            
            count.textContent = selectedAppointments.length;
            list.innerHTML = selectedAppointments.map(apt => `
                <div class="appointment-item">
                    <strong>${apt.customer_name}</strong> - ${apt.license_plate}
                    <br><small>Einlagerungsnummer: ${apt.storage_number || 'Nicht vergeben'}</small>
                </div>
            `).join('');

            modal.style.display = 'block';
        }

        // Print storage labels
        function printStorageLabels() {
            const selectedAppointments = getSelectedAppointments();
            const includeCustomerInfo = document.getElementById('include-customer-info').checked;
            const includeStorageInfo = document.getElementById('include-storage-info').checked;
            
            // Create print content
            let printContent = '<html><head><title>Einlagerungsetiketten</title></head><body>';
            
            selectedAppointments.forEach(apt => {
                printContent += '<div style="page-break-after: always; border: 2px solid #000; padding: 20px; margin: 10px; width: 300px;">';
                printContent += '<h3>Einlagerungsetikett</h3>';
                
                if (includeCustomerInfo) {
                    printContent += `<p><strong>Kunde:</strong> ${apt.customer_name}</p>`;
                    printContent += `<p><strong>Kennzeichen:</strong> ${apt.license_plate}</p>`;
                }
                
                if (includeStorageInfo && apt.storage_number) {
                    printContent += `<p><strong>Einlagerungsnummer:</strong> ${apt.storage_number}</p>`;
                }
                
                printContent += `<p><strong>Datum:</strong> ${new Date().toLocaleDateString('de-DE')}</p>`;
                printContent += '</div>';
            });
            
            printContent += '</body></html>';
            
            // Open print window
            const printWindow = window.open('', '_blank');
            printWindow.document.write(printContent);
            printWindow.document.close();
        }

        // Print single storage label
        function printSingleStorageLabel(appointment) {
            // Create print content for single appointment
            let printContent = '<html><head><title>Einlagerungsetikett</title></head><body>';
            
            printContent += '<div style="page-break-after: always; border: 2px solid #000; padding: 20px; margin: 10px; width: 300px;">';
            printContent += '<h3>Einlagerungsetikett</h3>';
            printContent += `<p><strong>Kunde:</strong> ${appointment.customer_name}</p>`;
            printContent += `<p><strong>Kennzeichen:</strong> ${appointment.license_plate}</p>`;
            
            if (appointment.storage_number) {
                printContent += `<p><strong>Einlagerungsnummer:</strong> ${appointment.storage_number}</p>`;
            }
            
            printContent += `<p><strong>Datum:</strong> ${new Date().toLocaleDateString('de-DE')}</p>`;
            printContent += '</div>';
            printContent += '</body></html>';
            
            // Open print window
            const printWindow = window.open('', '_blank');
            printWindow.document.write(printContent);
            printWindow.document.close();
            printWindow.print();
        }

        // Close storage labels modal
        function closeStorageLabelsModal() {
            document.getElementById('storage-labels-modal').style.display = 'none';
        }

        // Update modal click handlers
        window.onclick = function(event) {
            const appointmentModal = document.getElementById('appointment-modal');
            const editModal = document.getElementById('edit-appointment-modal');
            const tireOrderModal = document.getElementById('tire-order-modal');
            const bulkDeleteModal = document.getElementById('bulk-delete-modal');
            const storageLabelsModal = document.getElementById('storage-labels-modal');
            
            if (event.target === appointmentModal) {
                closeAppointmentModal();
            }
            if (event.target === editModal) {
                closeEditAppointmentModal();
            }
            if (event.target === tireOrderModal) {
                closeTireOrderModal();
            }
            if (event.target === bulkDeleteModal) {
                closeBulkDeleteModal();
            }
            if (event.target === storageLabelsModal) {
                closeStorageLabelsModal();
            }
        }

        // Smart Offer Studio - Modern & Professional
        let tireCount = 0;
        let selectedServices = [];
        let newTires = [];

        // Tab Management
        function switchTab(tabName) {
            // Remove active class from all tabs
            document.querySelectorAll('.quick-btn').forEach(btn => btn.classList.remove('active'));
            document.querySelectorAll('.tab-pane').forEach(pane => pane.classList.remove('active'));
            
            // Add active class to selected tab
            document.querySelector(`[data-tab="${tabName}"]`).classList.add('active');
            document.getElementById(`${tabName}-tab`).classList.add('active');
        }

        // Tire Builder Functions
        function addTireBuilder() {
            tireCount++;
            const container = document.getElementById('tireBuilderContainer');
            
            const tireDiv = document.createElement('div');
            tireDiv.className = 'tire-builder-item';
            tireDiv.id = 'tire_builder_' + tireCount;
            tireDiv.innerHTML = `
                <div class="tire-builder-row">
                    <input type="text" placeholder="Hersteller & Modell" onchange="updateTireBuilder(${tireCount})">
                    <input type="text" placeholder="EU-Label" onchange="updateTireBuilder(${tireCount})">
                </div>
                <div class="tire-builder-row">
                    <input type="text" placeholder="Felgenmaße + Index" onchange="updateTireBuilder(${tireCount})">
                    <input type="number" placeholder="Einzelpreis (€)" step="0.01" onchange="updateTireBuilder(${tireCount})">
                </div>
                <div class="tire-builder-row">
                    <input type="number" placeholder="Montage (€)" step="0.01" onchange="updateTireBuilder(${tireCount})">
                    <input type="number" placeholder="Anzahl" min="1" value="4" onchange="updateTireBuilder(${tireCount})">
                </div>
                <div class="tire-builder-row">
                    <input type="number" placeholder="Gesamtpreis (€)" readonly id="total_${tireCount}">
                    <button class="btn btn-secondary" onclick="removeTireBuilder(${tireCount})">Entfernen</button>
                </div>
            `;
            
            container.appendChild(tireDiv);
            updateTireBuilder(tireCount);
        }

        function updateTireBuilder(tireId) {
            const container = document.getElementById('tire_builder_' + tireId);
            const inputs = container.querySelectorAll('input');
            
            const brand = inputs[0].value;
            const euLabel = inputs[1].value;
            const size = inputs[2].value;
            const price = parseFloat(inputs[3].value) || 0;
            const mounting = parseFloat(inputs[4].value) || 0;
            const quantity = parseInt(inputs[5].value) || 1;
            
            const total = (price + mounting) * quantity;
            inputs[6].value = total.toFixed(2);
            
            // Update newTires array
            newTires = newTires.filter(tire => tire.id !== tireId);
            if (brand && size) {
                newTires.push({
                    id: tireId,
                    brand: brand,
                    euLabel: euLabel,
                    size: size,
                    price: price,
                    mounting: mounting,
                    quantity: quantity,
                    total: total
                });
            }
            
            console.log('Updated newTires:', newTires);
            updateOfferSummary();
            updateLivePreview();
        }

        function removeTireBuilder(tireId) {
            document.getElementById('tire_builder_' + tireId).remove();
            newTires = newTires.filter(tire => tire.id !== tireId);
            updateOfferSummary();
            updateLivePreview();
        }

        // Service Management
        function toggleService(serviceId) {
            const service = document.getElementById('service_' + serviceId);
            if (service.classList.contains('selected')) {
                service.classList.remove('selected');
                selectedServices = selectedServices.filter(id => id != serviceId);
            } else {
                service.classList.add('selected');
                selectedServices.push(serviceId);
            }
            updateOfferSummary();
            updateLivePreview();
        }

        // Canvas Rendering Function
        function renderOfferToCanvas(canvas) {
            const ctx = canvas.getContext('2d');
            const width = canvas.width;
            const height = canvas.height;
            
            // Clear canvas
            ctx.clearRect(0, 0, width, height);
            
            // Set background
            ctx.fillStyle = '#ffffff';
            ctx.fillRect(0, 0, width, height);
            
            // Set font styles
            const titleFont = 'bold 16px Arial';
            const headerFont = 'bold 14px Arial';
            const normalFont = '12px Arial';
            const smallFont = '10px Arial';
            
            let yPosition = 50;
            const lineHeight = 20;
            const margin = 50;
            
            // Company header
            ctx.font = titleFont;
            ctx.fillStyle = '#000000';
            ctx.fillText('B&E Autocentrum GmbH', margin, yPosition);
            yPosition += lineHeight + 10;
            
            // Date
            ctx.font = normalFont;
            ctx.fillText('Kiel, ' + new Date().toLocaleDateString('de-DE'), margin, yPosition);
            yPosition += lineHeight + 20;
            
            // Greeting
            ctx.fillText('Sehr geehrte Damen und Herren,', margin, yPosition);
            yPosition += lineHeight + 20;
            
            // Main text paragraphs
            const paragraphs = [
                'die Vorbereitungen für unseren nächsten Boxenstopp laufen bereits und dabei ist uns leider aufgefallen, dass die bei uns eingelagerten Reifen ersetzt werden müssten.',
                'Daher erhalten Sie mit diesem Schreiben das beigefügte Angebot.'
            ];
            
            paragraphs.forEach(paragraph => {
                ctx.fillText(paragraph, margin, yPosition);
                yPosition += lineHeight + 10;
            });
            
            yPosition += 10;
            
            // Selected tires section
            ctx.font = headerFont;
            ctx.fillText('Auszutauschender Reifen:', margin, yPosition);
            yPosition += lineHeight + 5;
            
            ctx.font = normalFont;
            const selectedTireCards = document.querySelectorAll('.tire-card.selected');
            if (selectedTireCards.length > 0) {
                selectedTireCards.forEach(card => {
                    const brand = card.querySelector('.tire-brand')?.textContent || 'Unbekannt';
                    const model = card.querySelector('.tire-model')?.textContent || 'Unbekannt';
                    const size = card.querySelector('.tire-size')?.textContent || 'Unbekannt';
                    const position = card.querySelector('.tire-position')?.textContent || 'Unbekannt';
                    const recommendation = card.querySelector('.tire-recommendation')?.textContent || 'Unbekannt';
                    
                    const tireText = '- ' + brand + ' ' + model + ' (' + size + ') - Position: ' + position + ' - ' + recommendation;
                    ctx.fillText(tireText, margin, yPosition);
                    yPosition += lineHeight;
                });
            } else {
                ctx.fillText('Keine Reifen ausgewählt', margin, yPosition);
                yPosition += lineHeight;
            }
            
            yPosition += 10;
            
            // New tires section
            ctx.font = headerFont;
            ctx.fillText('Neue Reifen:', margin, yPosition);
            yPosition += lineHeight + 5;
            
            ctx.font = normalFont;
            if (typeof newTires !== 'undefined' && newTires.length > 0) {
                newTires.forEach(tire => {
                    const tireText = '- ' + tire.brand + ' (' + tire.size + ') - ' + tire.quantity + 'x ' + tire.price.toFixed(2).replace('.', ',') + '€';
                    ctx.fillText(tireText, margin, yPosition);
                    yPosition += lineHeight;
                });
            } else {
                ctx.fillText('Keine neuen Reifen hinzugefügt', margin, yPosition);
                yPosition += lineHeight;
            }
            
            yPosition += 10;
            
            // Costs section
            ctx.font = headerFont;
            ctx.fillText('Kosten inkl. Reifenmontage:', margin, yPosition);
            yPosition += lineHeight + 5;
            
            ctx.font = normalFont;
            ctx.fillText('Zzgl.', margin, yPosition);
            yPosition += lineHeight;
            ctx.fillText('Rädermontage                    49,99€', margin, yPosition);
            yPosition += lineHeight;
            ctx.fillText('Einlagerung der Sommerreifen     85,00€', margin, yPosition);
            yPosition += lineHeight;
            
            // Services
            if (typeof selectedServices !== 'undefined' && selectedServices.length > 0) {
                selectedServices.forEach(serviceId => {
                    const service = availableServices.find(s => s.id == serviceId);
                    if (service) {
                        const serviceText = service.service_name.padEnd(30) + service.price.toFixed(2).replace('.', ',') + '€';
                        ctx.fillText(serviceText, margin, yPosition);
                        yPosition += lineHeight;
                    }
                });
            } else {
                ctx.fillText('Keine Services ausgewählt', margin, yPosition);
                yPosition += lineHeight;
            }
            
            yPosition += 20;
            
            // Contact info
            ctx.fillText('Für Rückfragen stehen wir Ihnen gerne unter Tel: 0431/54 63 00 zur Verfügung.', margin, yPosition);
            yPosition += lineHeight + 20;
            
            // Signature
            ctx.fillText('Mit freundlichem Gruß', margin, yPosition);
            yPosition += lineHeight;
            ctx.fillText('Deniz Uludag', margin, yPosition);
            yPosition += lineHeight;
            ctx.fillText('B&E Autocentrum GmbH', margin, yPosition);
            yPosition += lineHeight + 20;
            
            // Disclaimer
            ctx.font = smallFont;
            ctx.fillStyle = '#dc2626';
            ctx.fillText('Dieses Dokument wurde maschinell erstellt und ist ohne Unterschrift gültig', margin, yPosition);
        }

        // Switch between edit and preview tabs
        function switchEditorTab(tab) {
            const editor = document.getElementById('offerEditor');
            const canvas = document.getElementById('offerCanvas');
            const editBtn = document.querySelector('.tab-btn[onclick*="edit"]');
            const previewBtn = document.querySelector('.tab-btn[onclick*="preview"]');
            
            if (tab === 'edit') {
                editor.style.display = 'block';
                canvas.style.display = 'none';
                editBtn.classList.add('active');
                previewBtn.classList.remove('active');
            } else {
                editor.style.display = 'none';
                canvas.style.display = 'block';
                previewBtn.classList.add('active');
                editBtn.classList.remove('active');
                
                // Update canvas with current editor content
                if (canvas) {
                    renderOfferToCanvas(canvas);
                }
            }
        }

        // Live Preview
        function updateLivePreview() {
            // Update Canvas with current data
            const canvas = document.getElementById('offerCanvas');
            if (canvas && canvas.style.display !== 'none') {
                renderOfferToCanvas(canvas);
            }
            
            // Update Rich Text Editor with current data (fallback)
            const editor = document.getElementById('offerEditor');
            if (!editor) {
                console.log('offerEditor not found');
                return;
            }
            
            // Get current appointment data
            const appointment = window.currentAppointment || {};
            
            // Create complete offer content
            let offerContent = `
                <p><strong>B&E Autocentrum GmbH</strong></p>
                <p>Kiel, ${new Date().toLocaleDateString('de-DE')}</p>
                <br>
                <p>Sehr geehrte Damen und Herren,</p>
                <br>
                <p>die Vorbereitungen für unseren nächsten Boxenstopp laufen bereits und dabei ist uns leider aufgefallen, dass die bei uns eingelagerten Reifen ersetzt werden müssten.</p>
                <br>
                <p>Daher erhalten Sie mit diesem Schreiben das beigefügte Angebot.</p>
                <br>
                <p><strong>Auszutauschender Reifen:</strong></p>
            `;
            
            // Add selected tires (austauschbedürftige Reifen)
            const selectedTireCards = document.querySelectorAll('.tire-card.selected');
            if (selectedTireCards.length > 0) {
                selectedTireCards.forEach(card => {
                    const brand = card.querySelector('.tire-brand')?.textContent || 'Unbekannt';
                    const model = card.querySelector('.tire-model')?.textContent || 'Unbekannt';
                    const size = card.querySelector('.tire-size')?.textContent || 'Unbekannt';
                    const position = card.querySelector('.tire-position')?.textContent || 'Unbekannt';
                    const recommendation = card.querySelector('.tire-recommendation')?.textContent || 'Unbekannt';
                    
                    offerContent += `<p>- ${brand} ${model} (${size}) - Position: ${position} - ${recommendation}</p>`;
                });
            } else {
                offerContent += `<p>Keine Reifen ausgewählt</p>`;
            }
            
            offerContent += `<br><p><strong>Neue Reifen:</strong></p>`;
            
            // Add new tires
            if (typeof newTires !== 'undefined' && newTires.length > 0) {
                newTires.forEach(tire => {
                    offerContent += `<p>- ${tire.brand} (${tire.size}) - ${tire.quantity}x ${tire.price.toFixed(2).replace('.', ',')}€</p>`;
                });
            } else {
                offerContent += `<p>Keine neuen Reifen hinzugefügt</p>`;
            }
            
            offerContent += `
                <br>
                <p><strong>Kosten inkl. Reifenmontage:</strong></p>
                <p>Zzgl.</p>
                <p>Rädermontage                    49,99€</p>
                <p>Einlagerung der Sommerreifen     85,00€</p>
            `;
            
            // Add services
            if (typeof selectedServices !== 'undefined' && selectedServices.length > 0) {
                selectedServices.forEach(serviceId => {
                    const service = availableServices.find(s => s.id == serviceId);
                    if (service) {
                        offerContent += `<p>${service.service_name.padEnd(30)}${service.price.toFixed(2).replace('.', ',')}€</p>`;
                    }
                });
            } else {
                offerContent += `<p>Keine Services ausgewählt</p>`;
            }
            
            offerContent += `
                <br>
                <p>Für Rückfragen stehen wir Ihnen gerne unter Tel: 0431/54 63 00 zur Verfügung.</p>
                <br>
                <p>Mit freundlichem Gruß<br>Deniz Uludag<br>B&E Autocentrum GmbH</p>
                <br>
                <p style="font-size: 0.8em; color: #dc2626;">Dieses Dokument wurde maschinell erstellt und ist ohne Unterschrift gültig</p>
            `;
            
            // Update the editor with complete content
            editor.innerHTML = offerContent;
            
            // Also update the offer letter modal if it's open
            const letterContent = document.getElementById('letterContent');
            if (letterContent) {
                letterContent.innerHTML = offerContent;
            }
        }

        // Offer Summary
        function updateOfferSummary() {
            const totalTires = (typeof newTires !== 'undefined') ? newTires.length : 0;
            const totalServices = (typeof selectedServices !== 'undefined') ? selectedServices.length : 0;
            
            let totalPrice = 0;
            if (typeof newTires !== 'undefined') {
                totalPrice += newTires.reduce((sum, tire) => sum + (tire.total || 0), 0);
            }
            if (typeof selectedServices !== 'undefined' && typeof availableServices !== 'undefined') {
                totalPrice += selectedServices.reduce((sum, serviceId) => {
                    const service = availableServices.find(s => s.id == serviceId);
                    return sum + (service ? service.price : 0);
                }, 0);
            }
            
            const totalTiresElement = document.getElementById('totalTires');
            const totalServicesElement = document.getElementById('totalServices');
            const totalPriceElement = document.getElementById('totalPrice');
            
            if (totalTiresElement) totalTiresElement.textContent = totalTires + ' Reifen';
            if (totalServicesElement) totalServicesElement.textContent = totalServices + ' Services';
            if (totalPriceElement) totalPriceElement.textContent = totalPrice.toFixed(2).replace('.', ',') + '€';
        }

        // Editor Functions
        function formatText(command, value) {
            document.execCommand(command, false, value);
            updateLivePreview();
        }

        // Utility Functions
        function refreshPreview() {
            updateLivePreview();
        }

        function toggleFullscreen() {
            // Toggle fullscreen mode
            if (!document.fullscreenElement) {
                document.documentElement.requestFullscreen();
            } else {
                document.exitFullscreen();
            }
        }

        function resetOffer() {
            newTires = [];
            selectedServices = [];
            document.getElementById('tireBuilderContainer').innerHTML = '';
            document.querySelectorAll('.service-item').forEach(item => item.classList.remove('selected'));
            updateOfferSummary();
            updateLivePreview();
        }

        async function generateOfferPDF() {
            // Show loading state
            const pdfButton = document.querySelector('.btn-primary');
            const originalText = pdfButton ? pdfButton.innerHTML : 'PDF erstellen';
            
            try {
                if (pdfButton) {
                    pdfButton.innerHTML = '<i class="fas fa-spinner fa-spin"></i> PDF wird erstellt...';
                    pdfButton.disabled = true;
                }
                
                // Get current appointment data
                const appointment = window.currentAppointment || {};
                const appointmentId = appointment.id || window.currentAppointmentId;
                
                if (!appointmentId) {
                    throw new Error('Keine Termin-ID gefunden');
                }
                
                // Get the current content from the rich text editor
                const editor = document.getElementById('offerEditor');
                const offerContent = editor ? editor.innerHTML : '';
                
                console.log('Current offer content:', offerContent);
                
                // Collect all offer data
                const offerData = {
                    appointmentId: appointmentId,
                    selectedTires: getSelectedTiresData(),
                    newTires: newTires || [],
                    selectedServices: selectedServices || [],
                    offerContent: offerContent
                };
                
                console.log('Sending offer data:', offerData);
                
                // Get canvas data from preview
                const canvas = document.getElementById('offerCanvas');
                let canvasData = null;
                if (canvas && canvas.style.display !== 'none') {
                    canvasData = canvas.toDataURL('image/png');
                    console.log('Canvas data length:', canvasData.length);
                } else {
                    console.log('Canvas not available or hidden');
                }
                
                // Add canvas data to offer data
                offerData.canvasData = canvasData;
                
                // Debug: Log all data being sent
                console.log('Canvas data available:', !!canvasData);
                console.log('Selected tires:', offerData.selectedTires);
                console.log('New tires:', offerData.newTires);
                console.log('Selected services:', offerData.selectedServices);
                
                // Send to backend - use professional TCPDF generation
                const response = await fetch('../api/generate_professional_pdf.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(offerData)
                });
                
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                
                // Get PDF blob
                const blob = await response.blob();
                
                // Create download link
                const url = window.URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = `Angebot_${appointment.customer_name || 'Kunde'}_${new Date().toISOString().split('T')[0]}.pdf`;
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
                window.URL.revokeObjectURL(url);
                
                // Show success message
                showNotification('PDF erfolgreich erstellt und heruntergeladen!', 'success');
                
                // Track offer creation - filename will be generated by backend
                const customerName = (appointment.customer_name || 'Kunde').replace(/[^a-zA-Z0-9._-]/g, '_');
                const filename = `Angebot_${customerName}_${new Date().toISOString().split('T')[0]}.pdf`;
                
                // Create tracking data with correct field names
                const trackingData = {
                    appointment_id: appointmentId,
                    user_id: 1,
                    username: 'Current User',
                    offer_type: 'created',
                    offer_data: offerData,
                    pdf_filename: filename
                };
                
                await trackOffer('created', offerData, filename);
                
            } catch (error) {
                console.error('PDF generation error:', error);
                showNotification('Fehler beim Erstellen des PDFs: ' + error.message, 'error');
            } finally {
                // Reset button state
                const pdfButton = document.querySelector('.btn-primary');
                pdfButton.innerHTML = originalText;
                pdfButton.disabled = false;
            }
        }
        
        function getSelectedTiresData() {
            const selectedTires = [];
            const selectedTireCards = document.querySelectorAll('.tire-card.selected');
            
            selectedTireCards.forEach(card => {
                const tireData = {
                    position: card.querySelector('.tire-position')?.textContent || '',
                    brand: card.querySelector('.tire-brand')?.textContent || '',
                    model: card.querySelector('.tire-model')?.textContent || '',
                    size: card.querySelector('.tire-size')?.textContent || '',
                    dot: card.querySelector('.tire-dot')?.textContent || '',
                    recommendation: card.querySelector('.tire-recommendation')?.textContent || '',
                    profileInner: card.querySelector('.tire-profile-inner')?.textContent || '',
                    profileMiddle: card.querySelector('.tire-profile-middle')?.textContent || '',
                    profileOuter: card.querySelector('.tire-profile-outer')?.textContent || ''
                };
                selectedTires.push(tireData);
            });
            
            return selectedTires;
        }
        
        function getOfferContent() {
            const editor = document.getElementById('offerEditor');
            if (!editor) return '';
            
            // Get the HTML content from the rich text editor
            return editor.innerHTML;
        }
        
        function showNotification(message, type = 'info') {
            // Create notification element
            const notification = document.createElement('div');
            notification.className = `notification notification-${type}`;
            notification.innerHTML = `
                <div class="notification-content">
                    <i class="fas fa-${type === 'success' ? 'check-circle' : type === 'error' ? 'exclamation-circle' : 'info-circle'}"></i>
                    <span>${message}</span>
                </div>
            `;
            
            // Add styles
            notification.style.cssText = `
                position: fixed;
                top: 20px;
                right: 20px;
                background: ${type === 'success' ? '#10b981' : type === 'error' ? '#ef4444' : '#3b82f6'};
                color: white;
                padding: 12px 20px;
                border-radius: 6px;
                box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
                z-index: 10000;
                font-weight: 500;
                max-width: 400px;
                animation: slideIn 0.3s ease-out;
            `;
            
            // Add animation styles
            const style = document.createElement('style');
            style.textContent = `
                @keyframes slideIn {
                    from { transform: translateX(100%); opacity: 0; }
                    to { transform: translateX(0); opacity: 1; }
                }
                .notification-content {
                    display: flex;
                    align-items: center;
                    gap: 8px;
                }
            `;
            document.head.appendChild(style);
            
            // Add to page
            document.body.appendChild(notification);
            
            // Remove after 5 seconds
            setTimeout(() => {
                notification.style.animation = 'slideIn 0.3s ease-out reverse';
                setTimeout(() => {
                    if (notification.parentNode) {
                        notification.parentNode.removeChild(notification);
                    }
                }, 300);
            }, 5000);
        }

        function sendOfferEmail() {
            // Send email
            console.log('Sending email...');
        }

        function saveOfferDraft() {
            // Save draft
            console.log('Saving draft...');
        }

        // Tire Check Modal Functions
        function showTireCheckModal() {
            const modal = document.getElementById('tireCheckModal');
            if (modal) {
                modal.classList.remove('hidden');
                document.body.style.overflow = 'hidden';
            }
        }

        function closeTireCheckModal() {
            const modal = document.getElementById('tireCheckModal');
            if (modal) {
                modal.classList.add('hidden');
                document.body.style.overflow = 'auto';
            }
        }

        // Tire Card Functions
        function toggleTireCard(tireId) {
            const tireCard = document.getElementById('tire_' + tireId);
            if (tireCard) {
                tireCard.classList.toggle('selected');
                
                // Update selected tires count
                updateSelectedTiresCount();
                
                // Show/hide tire offer button
                const selectedTiresButton = document.getElementById('selectedTiresButton');
                const selectedCount = document.querySelectorAll('.tire-card.selected').length;
                
                if (selectedCount > 0) {
                    selectedTiresButton.style.display = 'inline-flex';
                    document.getElementById('selectedTiresCount').textContent = selectedCount + ' Reifen ausgewählt';
                } else {
                    selectedTiresButton.style.display = 'none';
                }
                
                // Auto-update tire quantities in new tires section
                updateTireQuantitiesFromSelection();
            }
        }

        function updateSelectedTiresCount() {
            const selectedTires = document.querySelectorAll('.tire-card.selected');
            const selectedTiresButton = document.getElementById('selectedTiresButton');
            const selectedTiresCount = document.getElementById('selectedTiresCount');
            
            if (selectedTires.length > 0) {
                selectedTiresButton.style.display = 'inline-flex';
                selectedTiresCount.textContent = selectedTires.length + ' Reifen ausgewählt';
            } else {
                selectedTiresButton.style.display = 'none';
            }
        }
        
        // Auto-update tire quantities based on selected tires
        function updateTireQuantitiesFromSelection() {
            const selectedCount = document.querySelectorAll('.tire-card.selected').length;
            
            // Update all quantity inputs in new tires section
            const quantityInputs = document.querySelectorAll('input[id$="_quantity"]');
            quantityInputs.forEach(input => {
                if (selectedCount > 0) {
                    // Set to selected count but keep it editable
                    input.value = selectedCount;
                    
                    // Add visual indicator that it was auto-set
                    input.style.backgroundColor = '#e8f5e8';
                    input.title = 'Automatisch gesetzt basierend auf ausgewählten Reifen (änderbar)';
                    
                    // Trigger change event to update totals
                    input.dispatchEvent(new Event('change'));
                } else {
                    // Reset to 0 if no tires selected
                    input.value = 0;
                    input.style.backgroundColor = '';
                    input.title = '';
                    input.dispatchEvent(new Event('change'));
                }
            });
            
            console.log(`Auto-updated tire quantities to ${selectedCount} based on selected tires`);
        }
        
        // Track offer creation/sending - DATABASE ONLY
        async function trackOffer(offerType, offerData, filename = null, emailRecipient = null, emailSubject = null) {
            try {
                const appointment = window.currentAppointment || {};
                const appointmentId = appointment.id || window.currentAppointmentId;
                
                if (!appointmentId) {
                    console.warn('Keine Termin-ID für Tracking verfügbar');
                    return;
                }
                
                const offerRecord = {
                    appointment_id: appointmentId,
                    user_id: 1,
                    username: 'Current User',
                    offer_type: offerType,
                    offer_data: offerData,
                    pdf_filename: filename,
                    email_recipient: emailRecipient,
                    email_subject: emailSubject
                };
                
                // Save to database only
                const response = await fetch('../api/track_offer.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(offerRecord)
                });
                
                const result = await response.json();
                if (result.success) {
                    console.log(`✅ Angebot ${offerType} in Datenbank gespeichert`);
                    
                    // Update badge display
                    updateOfferBadges(appointmentId);
                } else {
                    throw new Error(result.error || 'Unbekannter Fehler beim Speichern');
                }
                
            } catch (error) {
                console.error('Fehler beim Tracking des Angebots:', error);
                showNotification('Fehler beim Speichern des Angebots: ' + error.message, 'error');
            }
        }
        
        // Update offer badges for appointment - DATABASE ONLY
        async function updateOfferBadges(appointmentId) {
            try {
                // Load from database only
                const response = await fetch(`../api/get_offer_details.php?appointmentId=${appointmentId}`);
                const data = await response.json();
                
                if (data.success && data.offers && data.offers.length > 0) {
                    // Use database data
                    const appointmentRow = document.querySelector(`tr[data-appointment-id="${appointmentId}"]`);
                    if (appointmentRow) {
                        addOfferBadge(appointmentRow, data.offers);
                    }
                } else {
                    // No offers found, remove any existing badge
                    const appointmentRow = document.querySelector(`tr[data-appointment-id="${appointmentId}"]`);
                    if (appointmentRow) {
                        const existingBadge = appointmentRow.querySelector('.offer-badge');
                        if (existingBadge) {
                            existingBadge.remove();
                        }
                    }
                }
            } catch (error) {
                console.error('Fehler beim Aktualisieren der Angebot-Badges:', error);
            }
        }
        
        // Add offer badge to appointment row
        function addOfferBadge(appointmentRow, offers) {
            // Remove existing badge if any
            const existingBadge = appointmentRow.querySelector('.offer-badge');
            if (existingBadge) {
                existingBadge.remove();
            }
            
            // Create new badge
            const badge = document.createElement('span');
            badge.className = 'offer-badge';
            
            // Determine badge content based on offers
            const hasCreated = offers.some(offer => offer.offer_type === 'created');
            const hasSent = offers.some(offer => offer.offer_type === 'sent');
            const hasAccepted = offers.some(offer => offer.offer_type === 'sent' && offer.customer_accepted);
            
            // Check for status updates from Teams reactions
            const statusUpdate = offers.find(offer => offer.status_update)?.status_update;
            
            if (statusUpdate) {
                // Show status update from Teams reaction
                switch (statusUpdate) {
                    case 'Neue Reifen bestellt':
                        badge.innerHTML = '<i class="fas fa-shopping-cart"></i> Reifen bestellt';
                        badge.className += ' badge-tire-ordered';
                        badge.title = 'Neue Reifen wurden bestellt';
                        break;
                    case 'Arbeit abgeschlossen':
                        badge.innerHTML = '<i class="fas fa-tools"></i> Arbeit fertig';
                        badge.className += ' badge-work-completed';
                        badge.title = 'Arbeit wurde abgeschlossen';
                        break;
                    case 'Kunde benachrichtigt':
                        badge.innerHTML = '<i class="fas fa-bell"></i> Kunde informiert';
                        badge.className += ' badge-customer-notified';
                        badge.title = 'Kunde wurde benachrichtigt';
                        break;
                    default:
                        badge.innerHTML = '<i class="fas fa-info-circle"></i> ' + statusUpdate;
                        badge.className += ' badge-status-update';
                        badge.title = 'Status: ' + statusUpdate;
                }
            } else if (hasAccepted) {
                badge.innerHTML = '<i class="fas fa-check-circle"></i> Angenommen';
                badge.className += ' badge-accepted';
                badge.title = 'Angebot vom Kunden angenommen';
            } else if (hasSent) {
                badge.innerHTML = '<i class="fas fa-envelope"></i> Verschickt';
                badge.className += ' badge-sent';
                badge.title = 'Angebot per Email verschickt';
            } else if (hasCreated) {
                badge.innerHTML = '<i class="fas fa-file-pdf"></i> Erstellt';
                badge.className += ' badge-created';
                badge.title = 'Angebot erstellt';
            }
            
            // Add click handler
            badge.onclick = () => showOfferDetails(offers);
            
            // Add to the dedicated badges cell
            let badgesCell = appointmentRow.querySelector('.offer-badges-cell');
            if (!badgesCell) {
                // Fallback: try to find the badges cell by position (second to last td)
                const cells = appointmentRow.querySelectorAll('td');
                badgesCell = cells[cells.length - 2]; // Second to last cell
            }
            
            if (badgesCell) {
                // Clear existing badges first
                badgesCell.innerHTML = '';
                
                // Add the badge
                badgesCell.appendChild(badge);
                
                // Style the badges cell
                badgesCell.style.textAlign = 'center';
                badgesCell.style.verticalAlign = 'middle';
                badgesCell.style.padding = '8px';
            }
        }
        
        // Show offer details modal
        function showOfferDetails(offers) {
            // Remove existing modal if any
            const existingModal = document.querySelector('.offer-details-modal');
            if (existingModal) {
                existingModal.remove();
            }
            
            const modal = document.createElement('div');
            modal.className = 'modal offer-details-modal';
            modal.style.display = 'flex';
            modal.innerHTML = `
                <div class="modal-content">
                    <div class="modal-header">
                        <h3><i class="fas fa-file-contract"></i> Angebot-Details</h3>
                        <button class="close-btn" onclick="closeOfferDetailsModal()">
                            <i class="fas fa-times"></i>
                        </button>
                    </div>
                    <div class="modal-body">
                        ${generateOfferDetailsHTML(offers)}
                    </div>
                </div>
            `;
            
            // Add click outside to close
            modal.onclick = function(e) {
                if (e.target === modal) {
                    closeOfferDetailsModal();
                }
            };
            
            document.body.appendChild(modal);
            
            // Load customer selections for sent offers
            offers.forEach(offer => {
                if (offer.offer_type === 'sent') {
                    refreshCustomerSelection(offer.appointment_id);
                    
                    // Send Teams notification if offer was accepted and not already sent
                    if (offer.customer_accepted && !offer.teams_notification_sent) {
                        console.log('📢 Sende Teams-Nachricht für Appointment:', offer.appointment_id);
                        sendTeamsNotification(offer.appointment_id);
                    } else if (offer.customer_accepted && offer.teams_notification_sent) {
                        console.log('✅ Teams-Nachricht bereits gesendet für Appointment:', offer.appointment_id);
                    }
                }
            });
            
            // Add escape key handler
            const escapeHandler = function(e) {
                if (e.key === 'Escape') {
                    closeOfferDetailsModal();
                    document.removeEventListener('keydown', escapeHandler);
                }
            };
            document.addEventListener('keydown', escapeHandler);
        }
        
        // Close offer details modal
        function closeOfferDetailsModal() {
            const modal = document.querySelector('.offer-details-modal');
            if (modal) {
                modal.remove();
            }
        }
        
        // Generate HTML for offer details
        function generateOfferDetailsHTML(offers) {
            let html = '<div class="offer-details">';
            
            offers.forEach((offer, index) => {
                const typeText = offer.offer_type === 'sent' ? 'Verschickt' : 'Erstellt';
                const typeIcon = offer.offer_type === 'sent' ? 'fa-envelope' : 'fa-file-pdf';
                const typeClass = offer.offer_type === 'sent' ? 'sent' : 'created';
                
                html += `
                    <div class="offer-item ${typeClass}">
                        <div class="offer-header">
                            <i class="fas ${typeIcon}"></i>
                            <span class="offer-type">${typeText}</span>
                            <span class="offer-date">${offer.created_at_formatted}</span>
                        </div>
                        <div class="offer-info">
                            <p><strong>Erstellt von:</strong> ${offer.username}</p>
                            <p><strong>Datum:</strong> ${offer.created_at_formatted}</p>
                            ${offer.email_recipient ? `<p><strong>Email an:</strong> ${offer.email_recipient}</p>` : ''}
                            ${offer.pdf_filename ? `
                                <p><strong>PDF-Datei:</strong> ${offer.pdf_filename}</p>
                                <button class="btn btn-sm btn-primary" onclick="viewPDF('${offer.pdf_filename}', ${offer.id})">
                                    <i class="fas fa-eye"></i> PDF anzeigen
                                </button>
                            ` : ''}
                        </div>
                        ${offer.offer_data ? `
                            <div class="offer-data">
                                <h4>Angebot-Inhalt:</h4>
                                <div class="offer-summary">
                                    ${generateOfferSummaryHTML(offer.offer_data)}
                                </div>
                            </div>
                        ` : ''}
                        ${offer.offer_type === 'sent' ? `
                            <div class="customer-selection">
                                <h4><i class="fas fa-user-check"></i> Kundenauswahl:</h4>
                                <div class="selection-status">
                                    <span class="status-waiting">
                                        <i class="fas fa-clock"></i> Warte auf Kundenauswahl
                                    </span>
                                    <button class="btn btn-sm btn-success" onclick="refreshCustomerSelection(${offer.appointment_id})">
                                        <i class="fas fa-sync"></i> Aktualisieren
                                    </button>
                                </div>
                                <div id="customer-selection-${offer.appointment_id}" class="customer-selection-content">
                                    <!-- Kundenauswahl wird hier dynamisch geladen -->
                                </div>
                            </div>
                        ` : ''}
                    </div>
                `;
            });
            
            html += '</div>';
            return html;
        }
        
        // Generate offer summary HTML
        function generateOfferSummaryHTML(offerData) {
            let html = '';
            
            if (offerData.selectedTires && offerData.selectedTires.length > 0) {
                html += '<p><strong>Ausgewählte Reifen:</strong> ' + offerData.selectedTires.length + '</p>';
            }
            
            if (offerData.newTires && offerData.newTires.length > 0) {
                html += '<p><strong>Neue Reifen:</strong> ' + offerData.newTires.length + '</p>';
            }
            
            if (offerData.selectedServices && offerData.selectedServices.length > 0) {
                html += '<p><strong>Services:</strong> ' + offerData.selectedServices.length + '</p>';
            }
            
            return html || '<p>Keine Details verfügbar</p>';
        }
        
        // View PDF in new window
        function viewPDF(filename, offerId) {
            
            // Create PDF viewer modal
            const pdfModal = document.createElement('div');
            pdfModal.className = 'modal pdf-viewer-modal';
            pdfModal.style.display = 'flex';
            pdfModal.innerHTML = `
                <div class="modal-content pdf-viewer-content">
                    <div class="modal-header">
                        <h3><i class="fas fa-file-pdf"></i> PDF-Viewer: ${filename}</h3>
                        <button class="close-btn" onclick="closePDFViewer()">
                            <i class="fas fa-times"></i>
                        </button>
                    </div>
                    <div class="modal-body pdf-viewer-body">
                        <div class="pdf-controls">
                            <button class="btn btn-primary" onclick="downloadPDF('${filename}')">
                                <i class="fas fa-download"></i> Herunterladen
                            </button>
                            <button class="btn btn-secondary" onclick="printPDF('${filename}')">
                                <i class="fas fa-print"></i> Drucken
                            </button>
                        </div>
                        <div class="pdf-container">
                            <iframe src="../api/view_pdf.php?filename=${encodeURIComponent(filename)}" 
                                    width="100%" 
                                    height="700px" 
                                    frameborder="0">
                                <p>PDF kann nicht angezeigt werden. <a href="../api/view_pdf.php?filename=${encodeURIComponent(filename)}" target="_blank">Hier klicken zum Öffnen</a></p>
                            </iframe>
                        </div>
                    </div>
                </div>
            `;
            
            // Add click outside to close
            pdfModal.onclick = function(e) {
                if (e.target === pdfModal) {
                    closePDFViewer();
                }
            };
            
            document.body.appendChild(pdfModal);
        }
        
        // Close PDF viewer
        function closePDFViewer() {
            const modal = document.querySelector('.pdf-viewer-modal');
            if (modal) {
                modal.remove();
            }
        }
        
        // Download PDF
        function downloadPDF(filename) {
            window.open(`../api/download_pdf.php?filename=${filename}`, '_blank');
        }
        
        // Print PDF
        function printPDF(filename) {
            window.open(`../api/view_pdf.php?filename=${filename}`, '_blank');
        }
        
        // Refresh customer selection
        async function refreshCustomerSelection(offerId) {
            const container = document.getElementById(`customer-selection-${offerId}`);
            if (!container) return;
            
            container.innerHTML = '<div class="loading"><i class="fas fa-spinner fa-spin"></i> Lade Kundenauswahl...</div>';
            
            try {
                const response = await fetch(`../api/get_customer_selection.php?appointmentId=${offerId}`);
                const data = await response.json();
                
                if (data.success && data.selection) {
                    const selection = data.selection;
                    const tireSelection = JSON.parse(selection.tire_selection || '[]');
                    const serviceSelection = JSON.parse(selection.service_selection || '[]');
                    const notes = selection.customer_notes || '';
                    
                    let html = `
                        <div class="customer-selection-result">
                            <div class="selection-status-success">
                                <i class="fas fa-check-circle text-success"></i>
                                <span><strong>Kunde hat Auswahl getroffen</strong></span>
                                <small class="text-muted">(${formatDate(selection.created_at)})</small>
                            </div>
                    `;
                    
                    if (tireSelection.length > 0) {
                        html += `
                            <div class="selection-section">
                                <h5><i class="fas fa-tire"></i> Ausgewählte Reifen:</h5>
                                <ul class="selection-list">
                        `;
                        tireSelection.forEach(tire => {
                            html += `<li>${tire}</li>`;
                        });
                        html += `</ul></div>`;
                    }
                    
                    if (serviceSelection.length > 0) {
                        html += `
                            <div class="selection-section">
                                <h5><i class="fas fa-cogs"></i> Ausgewählte Zusatzleistungen:</h5>
                                <ul class="selection-list">
                        `;
                        serviceSelection.forEach(service => {
                            html += `<li>${service}</li>`;
                        });
                        html += `</ul></div>`;
                    }
                    
                    if (notes) {
                        html += `
                            <div class="selection-section">
                                <h5><i class="fas fa-comment"></i> Kundenanmerkungen:</h5>
                                <div class="customer-notes">${notes}</div>
                            </div>
                        `;
                    }
                    
                    html += `</div>`;
                    container.innerHTML = html;
                } else {
                    container.innerHTML = `
                        <div class="customer-selection-result">
                            <div class="selection-item">
                                <i class="fas fa-clock text-warning"></i>
                                <span>Warte auf Kundenauswahl</span>
                            </div>
                            <div class="selection-note">
                                <small class="text-muted">
                                    <i class="fas fa-info-circle"></i>
                                    Der Kunde kann in der Email auswählen, welche Reifen er möchte.
                                </small>
                            </div>
                        </div>
                    `;
                }
            } catch (error) {
                console.error('Fehler beim Laden der Kundenauswahl:', error);
                container.innerHTML = `
                    <div class="customer-selection-result">
                        <div class="selection-item text-danger">
                            <i class="fas fa-exclamation-triangle"></i>
                            <span>Fehler beim Laden der Kundenauswahl</span>
                        </div>
                    </div>
                `;
            }
        }
    </script>

    <style>
        /* Apple-Volvo Hybrid Design System */
        :root {
            /* Volvo Brand Colors */
            --volvo-blue: #0066CC;
            --volvo-blue-dark: #004C99;
            --volvo-blue-light: #E6F2FF;
            --volvo-gray: #2C3E50;
            --volvo-gray-light: #ECF0F1;
            --volvo-accent: #F39C12;
            
            /* Apple-inspired Neutrals */
            --apple-white: #FFFFFF;
            --apple-gray-1: #F2F2F7;
            --apple-gray-2: #E5E5EA;
            --apple-gray-3: #D1D1D6;
            --apple-gray-4: #C7C7CC;
            --apple-gray-5: #AEAEB2;
            --apple-gray-6: #8E8E93;
            --apple-gray-7: #636366;
            --apple-gray-8: #48484A;
            --apple-gray-9: #3A3A3C;
            --apple-gray-10: #1C1C1E;
            
            /* Design System Variables */
            --color-primary: var(--volvo-blue);
            --color-primary-dark: var(--volvo-blue-dark);
            --color-primary-light: var(--volvo-blue-light);
            --color-accent: var(--volvo-accent);
            
            --surface-primary: var(--apple-white);
            --surface-secondary: var(--apple-gray-1);
            --surface-tertiary: var(--apple-gray-2);
            --surface-quaternary: var(--apple-gray-3);
            
            --text-primary: var(--apple-gray-10);
            --text-secondary: var(--apple-gray-7);
            --text-tertiary: var(--apple-gray-6);
            --text-quaternary: var(--apple-gray-5);
            
            --border-color: var(--apple-gray-3);
            --border-color-light: var(--apple-gray-2);
            --border-color-dark: var(--apple-gray-4);
            
            /* Typography */
            --font-family: 'SF Pro Display', 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            --font-size-xs: 12px;
            --font-size-sm: 14px;
            --font-size-base: 16px;
            --font-size-lg: 18px;
            --font-size-xl: 20px;
            --font-size-2xl: 24px;
            --font-size-3xl: 30px;
            --font-size-4xl: 36px;
            
            --font-weight-light: 300;
            --font-weight-normal: 400;
            --font-weight-medium: 500;
            --font-weight-semibold: 600;
            --font-weight-bold: 700;
            --font-weight-extrabold: 800;
            
            /* Spacing (8pt Grid) */
            --spacing-xs: 4px;
            --spacing-sm: 8px;
            --spacing-md: 16px;
            --spacing-lg: 24px;
            --spacing-xl: 32px;
            --spacing-2xl: 48px;
            --spacing-3xl: 64px;
            --spacing-4xl: 96px;
            
            /* Border Radius */
            --border-radius: 8px;
            --border-radius-sm: 6px;
            --border-radius-lg: 12px;
            --border-radius-xl: 16px;
            --border-radius-2xl: 24px;
            --border-radius-full: 50%;
            
            /* Shadows */
            --shadow-sm: 0 1px 2px rgba(0, 0, 0, 0.05);
            --shadow: 0 1px 3px rgba(0, 0, 0, 0.1), 0 1px 2px rgba(0, 0, 0, 0.06);
            --shadow-md: 0 4px 6px rgba(0, 0, 0, 0.07), 0 2px 4px rgba(0, 0, 0, 0.06);
            --shadow-lg: 0 10px 15px rgba(0, 0, 0, 0.1), 0 4px 6px rgba(0, 0, 0, 0.05);
            --shadow-xl: 0 20px 25px rgba(0, 0, 0, 0.1), 0 10px 10px rgba(0, 0, 0, 0.04);
            --shadow-2xl: 0 25px 50px rgba(0, 0, 0, 0.25);
            
            /* Transitions */
            --transition-fast: 150ms cubic-bezier(0.4, 0, 0.2, 1);
            --transition-normal: 300ms cubic-bezier(0.4, 0, 0.2, 1);
            --transition-slow: 500ms cubic-bezier(0.4, 0, 0.2, 1);
        }

        /* Dark Theme Variables */
        [data-theme="dark"] {
            --surface-primary: var(--apple-gray-10);
            --surface-secondary: var(--apple-gray-9);
            --surface-tertiary: var(--apple-gray-8);
            --surface-quaternary: var(--apple-gray-7);
            
            --text-primary: var(--apple-white);
            --text-secondary: var(--apple-gray-3);
            --text-tertiary: var(--apple-gray-4);
            --text-quaternary: var(--apple-gray-5);
            
            --border-color: var(--apple-gray-7);
            --border-color-light: var(--apple-gray-8);
            --border-color-dark: var(--apple-gray-6);
        }

        /* Base Styles */
        body {
            font-family: var(--font-family);
            background: linear-gradient(135deg, var(--surface-secondary) 0%, var(--surface-tertiary) 100%);
            color: var(--text-primary);
            line-height: 1.6;
            min-height: 100vh;
            transition: all var(--transition-normal);
            -webkit-font-smoothing: antialiased;
            -moz-osx-font-smoothing: grayscale;
        }

        .admin-container {
            display: flex;
            min-height: 100vh;
        }

        /* Layout */
        .admin-main {
            flex: 1;
            padding: var(--spacing-xl);
            overflow-y: auto;
            background: var(--surface-secondary);
            transition: margin-left var(--transition-normal);
            min-height: 100vh;
        }

        .modern-sidebar.collapsed + .admin-main {
            margin-left: 80px;
        }

        /* Appointments Header */
        .appointments-header {
            margin-bottom: var(--spacing-2xl);
        }

        .appointments-hero {
            background: linear-gradient(135deg, var(--color-primary) 0%, var(--color-primary-dark) 100%);
            border-radius: var(--border-radius-xl);
            padding: var(--spacing-3xl);
            position: relative;
            overflow: hidden;
            box-shadow: var(--shadow-xl);
        }

        .appointments-hero::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><defs><pattern id="grid" width="10" height="10" patternUnits="userSpaceOnUse"><path d="M 10 0 L 0 0 0 10" fill="none" stroke="rgba(255,255,255,0.1)" stroke-width="0.5"/></pattern></defs><rect width="100" height="100" fill="url(%23grid)"/></svg>');
            opacity: 0.3;
        }

        .appointments-hero-content {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            position: relative;
            z-index: 1;
        }

        .appointments-title-section {
            flex: 1;
        }

        .appointments-title {
            font-size: var(--font-size-4xl);
            font-weight: var(--font-weight-bold);
            color: var(--apple-white);
            margin: 0 0 var(--spacing-md) 0;
            display: flex;
            align-items: center;
            gap: var(--spacing-md);
        }

        .appointments-title i {
            font-size: var(--font-size-3xl);
            opacity: 0.9;
        }

        .appointments-subtitle {
            font-size: var(--font-size-lg);
            color: rgba(255, 255, 255, 0.8);
            margin: 0 0 var(--spacing-lg) 0;
            font-weight: var(--font-weight-normal);
        }

        .appointments-meta {
            display: flex;
            gap: var(--spacing-xl);
            flex-wrap: wrap;
        }

        .meta-item {
            display: flex;
            align-items: center;
            gap: var(--spacing-sm);
            color: rgba(255, 255, 255, 0.9);
            font-size: var(--font-size-sm);
            font-weight: var(--font-weight-medium);
        }

        .meta-item i {
            font-size: var(--font-size-base);
            opacity: 0.8;
        }

        .appointments-actions {
            display: flex;
            gap: var(--spacing-md);
            align-items: center;
        }

        .modern-select {
            background: rgba(255, 255, 255, 0.15);
            border: 1px solid rgba(255, 255, 255, 0.2);
            border-radius: var(--border-radius);
            padding: var(--spacing-sm) var(--spacing-md);
            color: var(--apple-white);
            font-size: var(--font-size-sm);
            font-weight: var(--font-weight-medium);
            backdrop-filter: blur(10px);
            transition: all var(--transition-normal);
        }

        .modern-select:focus {
            outline: none;
            border-color: rgba(255, 255, 255, 0.4);
            background: rgba(255, 255, 255, 0.25);
        }

        .modern-select option {
            background: var(--surface-primary);
            color: var(--text-primary);
        }

        .btn-primary {
            background: rgba(255, 255, 255, 0.2);
            border: 1px solid rgba(255, 255, 255, 0.3);
            border-radius: var(--border-radius);
            padding: var(--spacing-sm) var(--spacing-lg);
            color: var(--apple-white);
            font-size: var(--font-size-sm);
            font-weight: var(--font-weight-semibold);
            font-family: var(--font-family);
            cursor: pointer;
            transition: all var(--transition-normal);
            display: flex;
            align-items: center;
            gap: var(--spacing-sm);
            backdrop-filter: blur(10px);
        }

        .btn-primary:hover {
            background: rgba(255, 255, 255, 0.3);
            border-color: rgba(255, 255, 255, 0.5);
            transform: translateY(-1px);
        }

        /* Appointments Content */
        .appointments-content {
            background: var(--surface-primary);
            border-radius: var(--border-radius-xl);
            padding: var(--spacing-2xl);
            box-shadow: var(--shadow-lg);
            border: 1px solid var(--border-color-light);
        }

        /* Content Card */
        .content-card {
            background: var(--surface-primary);
            border-radius: var(--border-radius-lg);
            box-shadow: var(--shadow-md);
            border: 1px solid var(--border-color-light);
            overflow: hidden;
        }

        .card-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: var(--spacing-lg) var(--spacing-xl);
            border-bottom: 1px solid var(--border-color-light);
            background: var(--surface-secondary);
        }

        .card-header h3 {
            margin: 0;
            font-size: var(--font-size-xl);
            font-weight: var(--font-weight-semibold);
            color: var(--text-primary);
            font-family: var(--font-family);
        }

        .header-actions {
            display: flex;
            align-items: center;
            gap: var(--spacing-md);
        }

        .appointment-count {
            font-size: var(--font-size-sm);
            color: var(--text-secondary);
            font-weight: var(--font-weight-medium);
        }

        /* Appointments Table */
        .appointments-table {
            width: 100%;
            border-collapse: collapse;
            font-size: var(--font-size-sm);
        }

        .appointments-table th {
            background: var(--surface-tertiary);
            color: var(--text-primary);
            font-weight: var(--font-weight-semibold);
            padding: var(--spacing-md) var(--spacing-sm);
            text-align: left;
            border-bottom: 2px solid var(--border-color);
            font-family: var(--font-family);
            white-space: nowrap;
        }

        .appointments-table td {
            padding: var(--spacing-md) var(--spacing-sm);
            border-bottom: 1px solid var(--border-color-light);
            color: var(--text-primary);
            vertical-align: middle;
        }

        .appointments-table tbody tr:hover {
            background: var(--surface-secondary);
        }

        .appointments-table tbody tr:nth-child(even) {
            background: var(--surface-primary);
        }

        .appointments-table tbody tr:nth-child(even):hover {
            background: var(--surface-secondary);
        }

        /* Alert Styles */
        .alert {
            padding: var(--spacing-md) var(--spacing-lg);
            border-radius: var(--border-radius);
            margin-bottom: var(--spacing-lg);
            display: flex;
            align-items: center;
            gap: var(--spacing-sm);
            font-weight: var(--font-weight-medium);
            font-size: var(--font-size-sm);
        }

        .alert-success {
            background: #D1FAE5;
            color: #065F46;
            border: 1px solid #A7F3D0;
        }

        .alert-error {
            background: #FEE2E2;
            color: #991B1B;
            border: 1px solid #FECACA;
        }

        /* iOS 26 Button Design */
        .ios-btn {
            display: inline-flex;
            align-items: center;
            gap: var(--spacing-xs);
            padding: var(--spacing-sm) var(--spacing-md);
            border: none;
            border-radius: var(--border-radius-lg);
            font-family: var(--font-family);
            font-size: var(--font-size-xs);
            font-weight: var(--font-weight-semibold);
            cursor: pointer;
            transition: all var(--transition-fast);
            position: relative;
            overflow: hidden;
            backdrop-filter: blur(20px);
            box-shadow: var(--shadow-sm);
            text-decoration: none;
            min-height: 32px;
        }

        .ios-btn::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: linear-gradient(135deg, rgba(255,255,255,0.1) 0%, rgba(255,255,255,0.05) 100%);
            opacity: 0;
            transition: opacity var(--transition-fast);
        }

        .ios-btn:hover::before {
            opacity: 1;
        }

        .ios-btn:active {
            transform: scale(0.95);
        }

        .ios-btn i {
            font-size: var(--font-size-sm);
            transition: transform var(--transition-fast);
        }

        .ios-btn:hover i {
            transform: scale(1.1);
        }

        /* iOS Button Variants */
        .ios-btn-primary {
            background: linear-gradient(135deg, var(--color-primary) 0%, var(--color-primary-dark) 100%);
            color: var(--apple-white);
            box-shadow: 0 4px 12px rgba(0, 102, 204, 0.3);
        }

        .ios-btn-primary:hover {
            box-shadow: 0 6px 16px rgba(0, 102, 204, 0.4);
            transform: translateY(-1px);
        }

        .ios-btn-secondary {
            background: rgba(142, 142, 147, 0.12);
            color: var(--text-primary);
            border: 1px solid rgba(142, 142, 147, 0.2);
        }

        .ios-btn-secondary:hover {
            background: rgba(142, 142, 147, 0.18);
            border-color: rgba(142, 142, 147, 0.3);
        }

        .ios-btn-success {
            background: linear-gradient(135deg, #34C759 0%, #30A46C 100%);
            color: var(--apple-white);
            box-shadow: 0 4px 12px rgba(52, 199, 89, 0.3);
        }

        .ios-btn-success:hover {
            box-shadow: 0 6px 16px rgba(52, 199, 89, 0.4);
        }

        .ios-btn-danger {
            background: linear-gradient(135deg, #FF3B30 0%, #D70015 100%);
            color: var(--apple-white);
            box-shadow: 0 4px 12px rgba(255, 59, 48, 0.3);
        }

        .ios-btn-danger:hover {
            box-shadow: 0 6px 16px rgba(255, 59, 48, 0.4);
        }

        .ios-btn-warning {
            background: linear-gradient(135deg, #FF9500 0%, #FF6B00 100%);
            color: var(--apple-white);
            box-shadow: 0 4px 12px rgba(255, 149, 0, 0.3);
        }

        .ios-btn-warning:hover {
            box-shadow: 0 6px 16px rgba(255, 149, 0, 0.4);
        }

        .ios-btn-info {
            background: linear-gradient(135deg, #007AFF 0%, #0051D5 100%);
            color: var(--apple-white);
            box-shadow: 0 4px 12px rgba(0, 122, 255, 0.3);
        }

        .ios-btn-info:hover {
            box-shadow: 0 6px 16px rgba(0, 122, 255, 0.4);
        }

        .ios-btn-accent {
            background: linear-gradient(135deg, var(--color-accent) 0%, #E67E22 100%);
            color: var(--apple-white);
            box-shadow: 0 4px 12px rgba(243, 156, 18, 0.3);
        }

        .ios-btn-accent:hover {
            box-shadow: 0 6px 16px rgba(243, 156, 18, 0.4);
        }

        /* Action Buttons Container */
        .action-buttons-container {
            display: flex;
            flex-direction: column;
            gap: var(--spacing-sm);
            min-width: 200px;
        }

        .action-row {
            display: flex;
            gap: var(--spacing-xs);
            flex-wrap: wrap;
        }

        .action-row.primary-actions {
            margin-bottom: var(--spacing-xs);
        }

        .action-row.status-actions .ios-btn {
            flex: 1;
            min-width: 0;
        }

        .action-row.service-actions .ios-btn {
            flex: 1;
            min-width: 0;
        }

        .action-row.tire-check-actions .ios-btn {
            width: 100%;
        }

        /* Status Info */
        .status-info {
            display: flex;
            align-items: center;
            gap: var(--spacing-xs);
            padding: var(--spacing-sm) var(--spacing-md);
            background: rgba(52, 199, 89, 0.1);
            color: #34C759;
            border-radius: var(--border-radius-lg);
            font-size: var(--font-size-xs);
            font-weight: var(--font-weight-medium);
            border: 1px solid rgba(52, 199, 89, 0.2);
        }

        /* Responsive Design */
        @media (max-width: 1200px) {
            .appointments-hero-content {
                flex-direction: column;
                gap: var(--spacing-lg);
            }
            
            .appointments-actions {
                width: 100%;
                justify-content: flex-start;
            }
        }

        @media (max-width: 768px) {
            .admin-main {
                padding: var(--spacing-md);
            }
            
            .appointments-hero {
                padding: var(--spacing-xl);
            }
            
            .appointments-title {
                font-size: var(--font-size-2xl);
            }
            
            .appointments-meta {
                gap: var(--spacing-md);
            }
            
            .appointments-table {
                font-size: var(--font-size-xs);
            }
            
            .appointments-table th,
            .appointments-table td {
                padding: var(--spacing-sm);
            }
            
            .action-buttons-container {
                min-width: 150px;
            }
            
            .ios-btn {
                padding: var(--spacing-xs) var(--spacing-sm);
                font-size: 10px;
                min-height: 28px;
            }
            
            .ios-btn span {
                display: none;
            }
            
            .action-row {
                gap: 2px;
            }
            
            .action-row.status-actions .ios-btn,
            .action-row.service-actions .ios-btn {
                flex: none;
                min-width: auto;
            }
        }

        /* Smart Offer Studio - Modern & Professional */
        .offer-studio {
            position: fixed;
            top: 0;
            left: 0;
            width: 100vw;
            height: 100vh;
            background: #ffffff;
            z-index: 9999;
            display: flex;
            flex-direction: column;
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
        }

        /* Studio Header */
        .studio-header {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(20px);
            border-bottom: 1px solid rgba(255, 255, 255, 0.2);
            padding: 20px 30px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
        }

        .studio-brand {
            display: flex;
            align-items: center;
            gap: 15px;
        }

        .brand-icon {
            width: 50px;
            height: 50px;
            background: linear-gradient(135deg, #667eea, #764ba2);
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 24px;
        }

        .brand-text h1 {
            margin: 0;
            font-size: 28px;
            font-weight: 700;
            color: #1a1a1a;
            letter-spacing: -0.5px;
        }

        .brand-text p {
            margin: 0;
            color: #666;
            font-size: 14px;
            font-weight: 500;
        }

        .studio-actions {
            display: flex;
            gap: 12px;
            align-items: center;
        }

        .action-btn {
            display: flex;
            align-items: center;
            gap: 8px;
            padding: 8px 16px;
            border: 1px solid #d1d5db;
            border-radius: 6px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.2s ease;
            font-size: 14px;
            background: white;
        }

        .action-btn.save {
            background: #059669;
            color: white;
            border-color: #059669;
        }

        .action-btn.save:hover {
            background: #047857;
            border-color: #047857;
        }

        .action-btn.close {
            background: #dc2626;
            color: white;
            border-color: #dc2626;
            padding: 8px;
            border-radius: 6px;
        }

        .action-btn.close:hover {
            background: #b91c1c;
            border-color: #b91c1c;
        }

        /* Studio Workspace */
        .studio-workspace {
            flex: 1;
            display: flex;
            overflow: hidden;
            background: rgba(255, 255, 255, 0.1);
            backdrop-filter: blur(10px);
        }

        /* Builder Panel */
        .builder-panel {
            width: 600px;
            background: #ffffff;
            border-right: 1px solid #d1d5db;
            display: flex;
            flex-direction: column;
        }

        /* Quick Actions */
        .quick-actions {
            display: flex;
            background: rgba(255, 255, 255, 0.1);
            border-bottom: 1px solid rgba(255, 255, 255, 0.2);
        }

        .quick-btn {
            flex: 1;
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 2px;
            padding: 8px 15px;
            background: transparent;
            border: none;
            cursor: pointer;
            transition: all 0.2s ease;
            color: #666;
            font-weight: 500;
            font-size: 11px;
        }

        .quick-btn:hover {
            background: rgba(255, 255, 255, 0.1);
            color: #333;
        }

        .quick-btn.active {
            background: rgba(255, 255, 255, 0.2);
            color: #667eea;
            border-bottom: 3px solid #667eea;
        }

        .quick-btn i {
            font-size: 14px;
        }

        /* Tab Content */
        .tab-content {
            flex: 1;
            overflow-y: auto;
            padding: 20px;
        }

        .tab-pane {
            display: none;
        }

        .tab-pane.active {
            display: block;
        }

        /* Cards */
        .card {
            background: white;
            border-radius: 8px;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
            margin-bottom: 16px;
            overflow: hidden;
            border: 1px solid #e5e7eb;
        }

        .card-header {
            background: #f8fafc;
            padding: 16px 20px;
            border-bottom: 1px solid #e5e7eb;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .card-header h3 {
            margin: 0;
            font-size: 16px;
            font-weight: 600;
            color: #1a1a1a;
        }

        .badge {
            background: #3b82f6;
            color: white;
            padding: 3px 8px;
            border-radius: 4px;
            font-size: 11px;
            font-weight: 500;
        }

        .card-body {
            padding: 16px 20px;
        }

        /* Tire Grid */
        .tire-grid {
            display: grid;
            gap: 12px;
        }

        .tire-item {
            background: #f8fafc;
            border: 2px solid #e2e8f0;
            border-radius: 12px;
            padding: 16px;
            transition: all 0.3s ease;
        }

        .tire-item:hover {
            border-color: #667eea;
            background: #f0f4ff;
        }

        .tire-info {
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .tire-details h4 {
            margin: 0 0 4px 0;
            font-size: 14px;
            font-weight: 600;
            color: #1a1a1a;
        }

        .tire-details p {
            margin: 0;
            font-size: 12px;
            color: #666;
        }

        .tire-price {
            font-weight: 700;
            color: #10b981;
            font-size: 16px;
        }

        /* Tire Builder */
        .tire-builder {
            display: flex;
            flex-direction: column;
            gap: 16px;
        }

        .tire-builder-item {
            background: #f8fafc;
            border: 2px solid #e2e8f0;
            border-radius: 12px;
            padding: 20px;
            transition: all 0.3s ease;
        }

        .tire-builder-item:hover {
            border-color: #667eea;
        }

        .tire-builder-row {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 12px;
            margin-bottom: 12px;
        }

        .tire-builder-row.full {
            grid-template-columns: 1fr;
        }

        .tire-builder input {
            padding: 10px 12px;
            border: 1px solid #d1d5db;
            border-radius: 4px;
            font-size: 14px;
            transition: all 0.2s ease;
            background: white;
            height: 40px;
            box-sizing: border-box;
        }

        .tire-builder input:focus {
            outline: none;
            border-color: #3b82f6;
            box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.1);
        }

        .btn-add {
            background: #3b82f6;
            color: white;
            border: none;
            padding: 10px 16px;
            border-radius: 6px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.2s ease;
            display: flex;
            align-items: center;
            gap: 6px;
            font-size: 14px;
        }

        .btn-add:hover {
            background: #2563eb;
        }

        /* Services Grid */
        .services-grid {
            display: grid;
            gap: 12px;
        }

        .service-item {
            background: white;
            border: 1px solid #d1d5db;
            border-radius: 6px;
            padding: 12px 16px;
            cursor: pointer;
            transition: all 0.2s ease;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .service-item:hover {
            border-color: #3b82f6;
            background: #f8fafc;
        }

        .service-item.selected {
            border-color: #10b981;
            background: #ecfdf5;
            position: relative;
        }

        .service-item.selected::after {
            content: "✓";
            position: absolute;
            top: 8px;
            right: 8px;
            background: #10b981;
            color: white;
            width: 20px;
            height: 20px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 12px;
            font-weight: bold;
        }

        .service-name {
            font-weight: 600;
            color: #1a1a1a;
        }

        .service-price {
            font-weight: 700;
            color: #10b981;
        }

        /* Search Box */
        .search-box {
            position: relative;
            width: 200px;
        }

        .search-box input {
            width: 100%;
            padding: 10px 16px 10px 40px;
            border: 2px solid #e2e8f0;
            border-radius: 8px;
            font-size: 14px;
        }

        .search-box i {
            position: absolute;
            left: 12px;
            top: 50%;
            transform: translateY(-50%);
            color: #666;
        }

        /* Editor Panel */
        .editor-panel {
            flex: 1;
            background: #ffffff;
            display: flex;
            flex-direction: column;
        }

        .editor-header {
            background: linear-gradient(135deg, #f8fafc, #e2e8f0);
            padding: 20px 30px;
            border-bottom: 1px solid #e2e8f0;
        }

        .editor-header h3 {
            margin: 0 0 15px 0;
            font-size: 20px;
            font-weight: 700;
            color: #1a1a1a;
        }

        .editor-toolbar {
            display: flex;
            gap: 15px;
            align-items: center;
        }

        .toolbar-group {
            display: flex;
            gap: 8px;
            align-items: center;
        }

        .tool-btn {
            width: 36px;
            height: 36px;
            border: 2px solid #e2e8f0;
            background: white;
            border-radius: 8px;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.3s ease;
            color: #666;
        }

        .tool-btn:hover {
            border-color: #667eea;
            color: #667eea;
            background: #f0f4ff;
        }

        .tool-btn.active {
            border-color: #667eea;
            background: #667eea;
            color: white;
        }

        .editor-content {
            flex: 1;
            padding: 30px;
            overflow-y: auto;
        }
        
        .editor-tabs {
            display: flex;
            margin-bottom: 20px;
            border-bottom: 2px solid #e9ecef;
        }
        
        .tab-btn {
            padding: 12px 20px;
            border: none;
            background: transparent;
            color: #6c757d;
            cursor: pointer;
            border-bottom: 2px solid transparent;
            transition: all 0.3s ease;
            font-weight: 500;
        }
        
        .tab-btn:hover {
            color: #495057;
            background: #f8f9fa;
        }
        
        .tab-btn.active {
            color: #007bff;
            border-bottom-color: #007bff;
            background: #f8f9fa;
        }
        
        .tab-btn i {
            margin-right: 8px;
        }
        
        /* Offer Badge Styles */
        .offer-badge {
            display: inline-flex !important;
            align-items: center;
            gap: 4px;
            padding: 6px 10px;
            border-radius: 12px;
            font-size: 11px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            margin: 4px 8px 4px 0;
            position: relative;
            z-index: 10;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        
        .offer-badge i {
            font-size: 10px;
        }
        
        .badge-created {
            background: #e3f2fd;
            color: #1976d2;
            border: 1px solid #bbdefb;
        }
        
        .badge-created:hover {
            background: #bbdefb;
            transform: translateY(-1px);
        }
        
        .badge-sent {
            background: #e8f5e8;
            color: #2e7d32;
            border: 1px solid #c8e6c9;
        }
        
        .badge-sent:hover {
            background: #c8e6c9;
            transform: translateY(-1px);
        }
        
        .badge-accepted {
            background: #e3f2fd;
            color: #1976d2;
            border: 1px solid #bbdefb;
            animation: pulse-accepted 2s infinite;
        }
        
        .badge-accepted:hover {
            background: #bbdefb;
            transform: translateY(-1px);
        }
        
        @keyframes pulse-accepted {
            0% { box-shadow: 0 0 0 0 rgba(25, 118, 210, 0.7); }
            70% { box-shadow: 0 0 0 10px rgba(25, 118, 210, 0); }
            100% { box-shadow: 0 0 0 0 rgba(25, 118, 210, 0); }
        }
        
        /* Teams Reaction Badges */
        .badge-tire-ordered {
            background: #fff3e0;
            color: #f57c00;
            border: 1px solid #ffcc02;
            animation: pulse-tire-ordered 2s infinite;
        }
        
        .badge-tire-ordered:hover {
            background: #ffe0b2;
            transform: translateY(-1px);
        }
        
        .badge-work-completed {
            background: #e8f5e8;
            color: #2e7d32;
            border: 1px solid #4caf50;
            animation: pulse-work-completed 2s infinite;
        }
        
        .badge-work-completed:hover {
            background: #c8e6c9;
            transform: translateY(-1px);
        }
        
        .badge-customer-notified {
            background: #f3e5f5;
            color: #7b1fa2;
            border: 1px solid #9c27b0;
            animation: pulse-customer-notified 2s infinite;
        }
        
        .badge-customer-notified:hover {
            background: #e1bee7;
            transform: translateY(-1px);
        }
        
        .badge-status-update {
            background: #e0f2f1;
            color: #00695c;
            border: 1px solid #26a69a;
            animation: pulse-status-update 2s infinite;
        }
        
        .badge-status-update:hover {
            background: #b2dfdb;
            transform: translateY(-1px);
        }
        
        @keyframes pulse-tire-ordered {
            0% { box-shadow: 0 0 0 0 rgba(245, 124, 0, 0.7); }
            70% { box-shadow: 0 0 0 10px rgba(245, 124, 0, 0); }
            100% { box-shadow: 0 0 0 0 rgba(245, 124, 0, 0); }
        }
        
        @keyframes pulse-work-completed {
            0% { box-shadow: 0 0 0 0 rgba(46, 125, 50, 0.7); }
            70% { box-shadow: 0 0 0 10px rgba(46, 125, 50, 0); }
            100% { box-shadow: 0 0 0 0 rgba(46, 125, 50, 0); }
        }
        
        @keyframes pulse-customer-notified {
            0% { box-shadow: 0 0 0 0 rgba(123, 31, 162, 0.7); }
            70% { box-shadow: 0 0 0 10px rgba(123, 31, 162, 0); }
            100% { box-shadow: 0 0 0 0 rgba(123, 31, 162, 0); }
        }
        
        @keyframes pulse-status-update {
            0% { box-shadow: 0 0 0 0 rgba(0, 105, 92, 0.7); }
            70% { box-shadow: 0 0 0 10px rgba(0, 105, 92, 0); }
            100% { box-shadow: 0 0 0 0 rgba(0, 105, 92, 0); }
        }
        
        /* Offer Details Modal */
        .offer-details-modal {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 10000;
        }
        
        .offer-details-modal .modal-content {
            background: white;
            border-radius: 12px;
            max-width: 600px;
            width: 90%;
            max-height: 80vh;
            overflow-y: auto;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.2);
        }
        
        .offer-details-modal .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 20px;
            border-bottom: 1px solid #e0e0e0;
        }
        
        .offer-details-modal .modal-header h3 {
            margin: 0;
            color: #333;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        
        .offer-details-modal .close-btn {
            background: none;
            border: none;
            font-size: 18px;
            cursor: pointer;
            color: #666;
            padding: 4px;
        }
        
        .offer-details-modal .close-btn:hover {
            color: #333;
        }
        
        .offer-details-modal .modal-body {
            padding: 20px;
        }
        
        .offer-item {
            border: 1px solid #e0e0e0;
            border-radius: 8px;
            margin-bottom: 16px;
            overflow: hidden;
        }
        
        .offer-item.sent {
            border-left: 4px solid #4caf50;
        }
        
        .offer-item.created {
            border-left: 4px solid #2196f3;
        }
        
        .offer-header {
            display: flex;
            align-items: center;
            gap: 8px;
            padding: 12px 16px;
            background: #f8f9fa;
            font-weight: 600;
        }
        
        .offer-header i {
            font-size: 14px;
        }
        
        .offer-item.sent .offer-header i {
            color: #4caf50;
        }
        
        .offer-item.created .offer-header i {
            color: #2196f3;
        }
        
        .offer-date {
            margin-left: auto;
            font-size: 12px;
            color: #666;
            font-weight: normal;
        }
        
        .offer-info {
            padding: 16px;
        }
        
        .offer-info p {
            margin: 8px 0;
            font-size: 14px;
        }
        
        .offer-data {
            padding: 16px;
            background: #f8f9fa;
            border-top: 1px solid #e0e0e0;
        }
        
        .offer-data h4 {
            margin: 0 0 12px 0;
            font-size: 14px;
            color: #333;
        }
        
        .offer-summary p {
            margin: 4px 0;
            font-size: 13px;
            color: #666;
        }
        
        /* Offer Badges Cell */
        .offer-badges-cell {
            text-align: center !important;
            vertical-align: middle !important;
            padding: 8px !important;
            min-width: 120px;
            max-width: 150px;
        }
        
        .offer-badges-cell .offer-badge {
            margin: 2px 0 !important;
            display: block !important;
            width: 100%;
            text-align: center;
        }
        
        /* PDF Viewer Modal */
        .pdf-viewer-modal {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.8);
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 10001;
        }
        
        .pdf-viewer-content {
            background: white;
            border-radius: 12px;
            max-width: 95%;
            max-height: 95%;
            width: 1200px;
            height: 800px;
            overflow: hidden;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.3);
        }
        
        .pdf-viewer-body {
            padding: 0;
        }
        
        .pdf-controls {
            padding: 15px 20px;
            background: #f8f9fa;
            border-bottom: 1px solid #e0e0e0;
            display: flex;
            gap: 10px;
        }
        
        .pdf-container {
            height: 700px;
            overflow: hidden;
        }
        
        .pdf-container iframe {
            border: none;
            width: 100%;
            height: 100%;
        }
        
        /* Customer Selection */
        .customer-selection {
            margin-top: 15px;
            padding: 15px;
            background: #f8f9fa;
            border-radius: 8px;
            border-left: 4px solid #28a745;
        }
        
        .customer-selection h4 {
            margin: 0 0 10px 0;
            color: #28a745;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        
        .selection-status {
            display: flex;
            align-items: center;
            gap: 10px;
            margin-bottom: 10px;
        }
        
        .status-waiting {
            color: #6c757d;
            font-style: italic;
        }
        
        .customer-selection-content {
            margin-top: 10px;
        }
        
        .loading {
            text-align: center;
            color: #6c757d;
            padding: 20px;
        }
        
        .customer-selection-result {
            background: white;
            padding: 15px;
            border-radius: 6px;
            border: 1px solid #e0e0e0;
        }
        
        .selection-item {
            display: flex;
            align-items: center;
            gap: 8px;
            margin-bottom: 10px;
        }
        
        .selection-status-success {
            display: flex;
            align-items: center;
            gap: 10px;
            margin-bottom: 15px;
            padding: 10px;
            background-color: #d4edda;
            border-radius: 5px;
            border: 1px solid #c3e6cb;
        }
        
        .selection-section {
            margin: 15px 0;
            padding: 10px;
            background-color: #f8f9fa;
            border-radius: 5px;
            border: 1px solid #e0e0e0;
        }
        
        .selection-section h5 {
            color: #2c3e50;
            margin-bottom: 10px;
            font-size: 14px;
        }
        
        .selection-list {
            margin: 0;
            padding-left: 20px;
        }
        
        .selection-list li {
            margin: 5px 0;
            color: #495057;
        }
        
        .customer-notes {
            background-color: #f8f9fa;
            padding: 10px;
            border-radius: 5px;
            border: 1px solid #e0e0e0;
            font-style: italic;
            color: #6c757d;
        }
        
        .selection-note {
            margin-top: 10px;
            padding: 10px;
            background: #e3f2fd;
            border-radius: 4px;
            border-left: 3px solid #2196f3;
        }

        .rich-editor {
            min-height: 500px;
            padding: 30px;
            border: 2px solid #e2e8f0;
            border-radius: 12px;
            background: white;
            font-family: 'Times New Roman', serif;
            font-size: 14px;
            line-height: 1.6;
            outline: none;
            transition: all 0.3s ease;
        }

        .rich-editor:focus {
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }

        /* Live Preview */
        .live-preview {
            background: white;
            border: 2px solid #e2e8f0;
            border-radius: 12px;
            padding: 30px;
            min-height: 400px;
            font-family: 'Times New Roman', serif;
            line-height: 1.6;
            font-size: 14px;
        }

        .preview-controls {
            display: flex;
            gap: 8px;
        }

        .btn-refresh, .btn-fullscreen {
            width: 36px;
            height: 36px;
            border: 2px solid #e2e8f0;
            background: white;
            border-radius: 8px;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.3s ease;
            color: #666;
        }

        .btn-refresh:hover, .btn-fullscreen:hover {
            border-color: #667eea;
            color: #667eea;
        }

        /* Studio Footer */
        .studio-footer {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(20px);
            border-top: 1px solid rgba(255, 255, 255, 0.2);
            padding: 20px 30px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .offer-summary {
            display: flex;
            gap: 30px;
            align-items: center;
        }

        .summary-item {
            display: flex;
            align-items: center;
            gap: 8px;
            font-weight: 600;
            color: #666;
        }

        .summary-item.total {
            color: #10b981;
            font-size: 18px;
        }

        .summary-item i {
            font-size: 16px;
        }

        .footer-right {
            display: flex;
            gap: 12px;
        }

        .btn {
            display: flex;
            align-items: center;
            gap: 8px;
            padding: 8px 16px;
            border: 1px solid #d1d5db;
            border-radius: 6px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.2s ease;
            font-size: 14px;
            background: white;
        }

        .btn-secondary {
            background: #6b7280;
            color: white;
            border-color: #6b7280;
        }

        .btn-secondary:hover {
            background: #4b5563;
            border-color: #4b5563;
        }

        .btn-primary {
            background: #3b82f6;
            color: white;
            border-color: #3b82f6;
        }

        .btn-primary:hover {
            background: #2563eb;
            border-color: #2563eb;
        }

        .btn-success {
            background: #059669;
            color: white;
            border-color: #059669;
        }

        .btn-success:hover {
            background: #047857;
            border-color: #047857;
        }

        /* Force Light Mode - Dark Mode disabled */
        .offer-studio {
            background: #ffffff !important;
        }
        
        .studio-header {
            background: #ffffff !important;
            border-bottom-color: #e5e7eb !important;
        }
        
        .brand-text h1 {
            color: #1a1a1a !important;
        }
        
        .brand-text p {
            color: #666 !important;
        }
        
        .builder-panel {
            background: #ffffff !important;
            border-right-color: #e5e7eb !important;
        }
        
        .editor-panel {
            background: #ffffff !important;
        }
        
        .card {
            background: #ffffff !important;
            border-color: #e5e7eb !important;
        }
        
        .card-header {
            background: #f8fafc !important;
            border-bottom-color: #e5e7eb !important;
        }
        
        .card-header h3 {
            color: #1a1a1a !important;
        }
        
        .tire-builder input {
            background: #ffffff !important;
            border-color: #d1d5db !important;
            color: #1a1a1a !important;
        }
        
        .tire-builder input:focus {
            border-color: #3b82f6 !important;
            background: #ffffff !important;
        }
        
        .service-item {
            background: #ffffff !important;
            border-color: #d1d5db !important;
            color: #1a1a1a !important;
        }
        
        .service-item:hover {
            background: #f8fafc !important;
            border-color: #3b82f6 !important;
        }
        
        .service-item.selected {
            background: #ecfdf5 !important;
            border-color: #10b981 !important;
        }
        
        .service-name {
            color: #1a1a1a !important;
        }
        
        .rich-editor {
            background: #ffffff !important;
            border-color: #d1d5db !important;
            color: #1a1a1a !important;
        }
        
        .studio-footer {
            background: #ffffff !important;
            border-top-color: #e5e7eb !important;
        }
        
        .summary-item {
            color: #666 !important;
        }

        /* Bulk Actions Styles */
        .bulk-actions-toolbar {
            background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
            border: 2px solid #007bff;
            border-radius: 8px;
            padding: 1rem;
            margin-bottom: 1rem;
            box-shadow: 0 4px 6px rgba(0, 123, 255, 0.1);
            animation: slideDown 0.3s ease-out;
        }

        @keyframes slideDown {
            from {
                opacity: 0;
                transform: translateY(-10px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .bulk-actions-content {
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 1rem;
        }

        .selected-count {
            display: flex;
            align-items: center;
            gap: 0.5rem;
            font-weight: 600;
            color: #007bff;
        }

        .selected-count i {
            font-size: 1.2rem;
        }

        .bulk-actions-buttons {
            display: flex;
            gap: 0.5rem;
            flex-wrap: wrap;
        }

        .bulk-actions-buttons .btn {
            display: flex;
            align-items: center;
            gap: 0.5rem;
            padding: 0.5rem 1rem;
            font-weight: 500;
            border-radius: 6px;
            transition: all 0.2s ease;
        }

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

        .bulk-actions-buttons .btn-danger:hover {
            background-color: #dc3545;
            border-color: #dc3545;
        }

        .bulk-actions-buttons .btn-primary:hover {
            background-color: #0056b3;
            border-color: #0056b3;
        }

        .bulk-actions-buttons .btn-success:hover {
            background-color: #28a745;
            border-color: #28a745;
        }

        .bulk-actions-buttons .btn-info:hover {
            background-color: #17a2b8;
            border-color: #17a2b8;
        }

        /* Checkbox Styles */
        .appointment-checkbox {
            width: 18px;
            height: 18px;
            cursor: pointer;
            accent-color: #007bff;
        }

        #select-all-checkbox {
            width: 20px;
            height: 20px;
            cursor: pointer;
            accent-color: #007bff;
        }

        /* Modal Styles for Bulk Operations */
        .warning-message {
            background: #fff3cd;
            border: 1px solid #ffeaa7;
            border-radius: 6px;
            padding: 1rem;
            margin-bottom: 1rem;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        .warning-message i {
            color: #856404;
            font-size: 1.2rem;
        }

        .warning-message p {
            margin: 0;
            color: #856404;
        }

        .appointment-item {
            background: #f8f9fa;
            border: 1px solid #dee2e6;
            border-radius: 4px;
            padding: 0.75rem;
            margin-bottom: 0.5rem;
        }

        .bulk-order-info, .labels-info {
            background: #e7f3ff;
            border: 1px solid #b3d9ff;
            border-radius: 6px;
            padding: 1rem;
            margin-bottom: 1rem;
        }

        .bulk-order-info p, .labels-info p {
            margin: 0;
            color: #0066cc;
            font-weight: 500;
        }

        .print-options {
            background: #f8f9fa;
            border: 1px solid #dee2e6;
            border-radius: 6px;
            padding: 1rem;
            margin-top: 1rem;
        }

        .print-options label {
            display: flex;
            align-items: center;
            gap: 0.5rem;
            margin-bottom: 0.5rem;
            cursor: pointer;
        }

        .print-options input[type="checkbox"] {
            width: 16px;
            height: 16px;
            accent-color: #007bff;
        }

        /* Bulk Tire Order Styles */
        .appointments-list {
            max-height: 300px;
            overflow-y: auto;
            margin-bottom: 1rem;
        }

        .appointment-item {
            background: #f8f9fa;
            border: 1px solid #dee2e6;
            border-radius: 6px;
            padding: 1rem;
            margin-bottom: 0.75rem;
            transition: all 0.2s ease;
        }

        .appointment-item:hover {
            background: #e9ecef;
            border-color: #007bff;
        }

        .appointment-item.success {
            background: #d4edda;
            border-color: #28a745;
        }

        .appointment-item.error {
            background: #f8d7da;
            border-color: #dc3545;
        }

        .appointment-info {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 0.5rem;
        }

        .appointment-info strong {
            color: #495057;
            font-size: 1rem;
        }

        .license-plate {
            background: #007bff;
            color: white;
            padding: 0.25rem 0.5rem;
            border-radius: 4px;
            font-size: 0.875rem;
            font-weight: 600;
        }

        .appointment-details {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 0.5rem;
        }

        .detail-row {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 0.25rem 0;
        }

        .detail-row .label {
            font-weight: 500;
            color: #6c757d;
            font-size: 0.875rem;
        }

        .detail-row .value {
            color: #495057;
            font-size: 0.875rem;
        }

        .detail-row.error .value {
            color: #dc3545;
            font-weight: 500;
        }

        .result-summary {
            display: flex;
            gap: 1rem;
            margin-bottom: 1rem;
            flex-wrap: wrap;
        }

        .summary-item {
            display: flex;
            align-items: center;
            gap: 0.5rem;
            padding: 0.5rem 1rem;
            border-radius: 6px;
            font-weight: 500;
        }

        .summary-item.success {
            background: #d4edda;
            color: #155724;
        }

        .summary-item.error {
            background: #f8d7da;
            color: #721c24;
        }

        .success-details, .error-details {
            margin-bottom: 1rem;
        }

        .success-details h5, .error-details h5 {
            color: #495057;
            margin-bottom: 0.75rem;
            font-size: 1rem;
        }

        /* Enhanced Delete Modal Styles */
        .delete-summary {
            background: #f8f9fa;
            border: 1px solid #dee2e6;
            border-radius: 6px;
            padding: 1rem;
            margin-bottom: 1rem;
        }

        .summary-stats {
            display: flex;
            gap: 2rem;
            flex-wrap: wrap;
        }

        .stat-item {
            display: flex;
            align-items: center;
            gap: 0.5rem;
            font-weight: 500;
            color: #495057;
        }

        .stat-item i {
            color: #007bff;
            font-size: 1.1rem;
        }

        .delete-details h4 {
            color: #495057;
            margin-bottom: 1rem;
            font-size: 1.1rem;
        }

        .tire-cancellation-section {
            background: #fff3cd;
            border: 1px solid #ffeaa7;
            border-radius: 6px;
            padding: 1rem;
            margin: 1rem 0;
        }

        .cancellation-warning {
            display: flex;
            align-items: center;
            gap: 0.5rem;
            margin-bottom: 1rem;
        }

        .cancellation-warning i {
            color: #856404;
            font-size: 1.2rem;
        }

        .cancellation-warning h4 {
            color: #856404;
            margin: 0;
            font-size: 1rem;
        }

        .cancellation-warning p {
            color: #856404;
            margin: 0.5rem 0 0 0;
            font-size: 0.9rem;
        }

        .tire-order-item {
            background: #f8f9fa;
            border: 1px solid #dee2e6;
            border-radius: 4px;
            padding: 0.75rem;
            margin-bottom: 0.5rem;
        }

        .tire-order-info {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 0.5rem;
        }

        .tire-order-details {
            display: flex;
            gap: 1rem;
            flex-wrap: wrap;
        }

        .tire-order-details span {
            font-size: 0.875rem;
            color: #6c757d;
        }

        .deletion-reason {
            margin-top: 1rem;
        }

        .deletion-reason label {
            display: flex;
            align-items: center;
            gap: 0.5rem;
            margin-bottom: 0.5rem;
            font-weight: 500;
            color: #495057;
        }

        .deletion-reason textarea {
            width: 100%;
            padding: 0.75rem;
            border: 1px solid #ced4da;
            border-radius: 4px;
            font-family: inherit;
            resize: vertical;
        }

        .delete-loading {
            text-align: center;
            padding: 2rem;
        }

        .delete-process {
            margin-top: 2rem;
        }

        .process-step {
            display: flex;
            align-items: center;
            gap: 1rem;
            padding: 1rem;
            margin-bottom: 0.5rem;
            background: #f8f9fa;
            border-radius: 6px;
            opacity: 0.5;
            transition: all 0.3s ease;
        }

        .process-step.active {
            opacity: 1;
            background: #e7f3ff;
            border: 1px solid #b3d9ff;
        }

        .step-icon {
            width: 40px;
            height: 40px;
            background: #007bff;
            color: white;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.2rem;
        }

        .process-step.active .step-icon {
            background: #0056b3;
        }

        .step-content h5 {
            margin: 0 0 0.25rem 0;
            color: #495057;
        }

        .step-content p {
            margin: 0;
            color: #6c757d;
            font-size: 0.9rem;
        }

        .delete-result {
            text-align: center;
            padding: 2rem;
        }

        .result-header {
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 1rem;
            margin-bottom: 2rem;
        }

        .result-header.success .result-icon {
            color: #28a745;
            font-size: 3rem;
        }

        .result-header.error .result-icon {
            color: #dc3545;
            font-size: 3rem;
        }

        .result-header h4 {
            margin: 0;
            color: #495057;
        }

        .result-message {
            background: #f8f9fa;
            border: 1px solid #dee2e6;
            border-radius: 6px;
            padding: 1rem;
            margin-bottom: 2rem;
        }

        .error-list {
            max-height: 200px;
            overflow-y: auto;
        }

        .error-item {
            background: #f8d7da;
            border: 1px solid #f5c6cb;
            border-radius: 4px;
            padding: 0.75rem;
            margin-bottom: 0.5rem;
        }

        .error-item strong {
            color: #721c24;
        }

        .error-item small {
            color: #721c24;
        }

        .status-pending {
            color: #ffc107;
            font-weight: 500;
        }

        .status-approved {
            color: #28a745;
            font-weight: 500;
        }

        .status-booked {
            color: #007bff;
            font-weight: 500;
        }

        .tire-ordered {
            color: #28a745;
            font-weight: 500;
        }

        /* Responsive Design for Bulk Actions */
        @media (max-width: 768px) {
            .bulk-actions-content {
                flex-direction: column;
                align-items: stretch;
            }

            .bulk-actions-buttons {
                justify-content: center;
            }

            .bulk-actions-buttons .btn {
                flex: 1;
                min-width: 120px;
            }

            .appointment-details {
                grid-template-columns: 1fr;
            }

            .appointment-info {
                flex-direction: column;
                align-items: flex-start;
                gap: 0.5rem;
            }

            .result-summary {
                flex-direction: column;
            }

            .summary-stats {
                flex-direction: column;
                gap: 1rem;
            }

            .tire-order-details {
                flex-direction: column;
                gap: 0.5rem;
            }

            .process-step {
                flex-direction: column;
                text-align: center;
            }
        }

        .form-select {
            padding: 0.5rem 1rem;
            border: 2px solid #e9ecef;
            border-radius: 8px;
            background: white;
            font-size: 0.9rem;
        }
        
        .appointment-count {
            color: var(--f1-red);
            font-weight: 600;
        }
        
        .phone-link {
            color: var(--volvo-blue);
            text-decoration: none;
        }
        
        .phone-link:hover {
            text-decoration: underline;
        }
        
        .email-link {
            color: var(--volvo-blue);
            text-decoration: none;
        }
        
        .email-link:hover {
            text-decoration: underline;
        }
        
        
        .status-form {
            display: inline-block;
        }
        
        .status-select {
            padding: 0.25rem 0.5rem;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 0.85rem;
        }
        
        .text-muted {
            color: #666;
            font-size: 0.85rem;
        }
        
        .appointments-table {
            overflow-x: auto;
        }
        
        .appointments-table table {
            width: 100%;
            border-collapse: collapse;
            min-width: 800px;
        }
        
        .appointments-table th,
        .appointments-table td {
            padding: 1rem;
            text-align: left;
            border-bottom: 1px solid #eee;
        }
        
        .appointments-table th {
            background: #f8f9fa;
            font-weight: 600;
            color: var(--volvo-blue);
            cursor: pointer;
        }
        
        .appointments-table th:hover {
            background: #e9ecef;
        }
        
        .appointments-table tr:hover {
            background: #f8f9fa;
        }
        
        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.6);
            backdrop-filter: blur(8px);
        }
        
        .modal-content {
            background-color: white;
            margin: 2% auto;
            padding: 0;
            border-radius: 16px;
            width: 95%;
            max-width: 1000px;
            max-height: 90vh;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
            display: flex;
            flex-direction: column;
        }
        
        #edit-appointment-modal .modal-content {
            max-width: 1600px;
            width: 98%;
            max-height: 95vh;
        }
        
        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 2rem;
            border-bottom: 1px solid #eee;
            background: #f8f9fa;
            border-radius: 16px 16px 0 0;
        }
        
        .modal-header h3 {
            margin: 0;
            color: var(--volvo-blue);
        }
        
        .modal-close {
            background: none;
            border: none;
            font-size: 1.5rem;
            cursor: pointer;
            color: #666;
        }
        
        .modal-body {
            padding: 2rem;
            overflow-y: auto;
            flex: 1;
        }
        
        #edit-appointment-modal .modal-body {
            padding: 1.5rem;
        }
        
        /* Professional Appointment Details */
        .appointment-details-professional {
            display: flex;
            flex-direction: column;
            gap: 0;
        }

        .detail-header {
            display: flex;
            align-items: center;
            gap: 1.5rem;
            padding: 2rem;
            background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
            border-radius: 16px 16px 0 0;
            border-bottom: 1px solid #dee2e6;
        }

        .customer-avatar {
            width: 80px;
            height: 80px;
            border-radius: 50%;
            background: linear-gradient(135deg, var(--volvo-blue) 0%, #1e3a8a 100%);
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 2rem;
            color: white;
            box-shadow: 0 4px 12px rgba(0, 123, 255, 0.3);
        }

        .customer-info {
            flex: 1;
        }

        .customer-info h3 {
            margin: 0 0 0.5rem 0;
            font-size: 1.5rem;
            font-weight: 700;
            color: #212529;
        }

        .customer-subtitle {
            margin: 0;
            color: #6c757d;
            font-size: 1rem;
            display: flex;
            align-items: center;
            gap: 1rem;
        }
        
        .customer-subtitle i {
            color: var(--volvo-blue);
            width: 16px;
        }

        .customer-subtitle a {
            color: var(--volvo-blue);
            text-decoration: none;
            font-weight: 500;
        }

        .customer-subtitle a:hover {
            text-decoration: underline;
        }

        .status-section {
            display: flex;
            align-items: center;
        }

        .status-badge-large {
            display: flex;
            align-items: center;
            gap: 0.5rem;
            padding: 0.75rem 1.5rem;
            border-radius: 25px;
            font-weight: 600;
            font-size: 1rem;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        }

        .status-badge-large.status-success {
            background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
            color: white;
        }

        .status-badge-large.status-warning {
            background: linear-gradient(135deg, #ffc107 0%, #fd7e14 100%);
            color: #212529;
        }

        .status-badge-large.status-danger {
            background: linear-gradient(135deg, #dc3545 0%, #c82333 100%);
            color: white;
        }

        .status-badge-large.status-info {
            background: linear-gradient(135deg, #17a2b8 0%, #138496 100%);
            color: white;
        }

        .status-badge-large.status-primary {
            background: linear-gradient(135deg, #007bff 0%, #0056b3 100%);
            color: white;
        }

        .status-badge-large.status-secondary {
            background: linear-gradient(135deg, #6c757d 0%, #5a6268 100%);
            color: white;
        }

        .detail-content-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 0;
            padding: 0;
        }

        .detail-section {
            padding: 2rem;
            border-bottom: 1px solid #f1f3f4;
            border-right: 1px solid #f1f3f4;
        }

        .detail-section.full-width {
            grid-column: 1 / -1;
            border-right: none;
        }

        .detail-section:last-child {
            border-bottom: none;
        }

        .section-header {
            display: flex;
            align-items: center;
            gap: 0.75rem;
            margin-bottom: 1.5rem;
            padding-bottom: 0.75rem;
            border-bottom: 2px solid var(--volvo-blue);
        }

        .section-header i {
            font-size: 1.25rem;
            color: var(--volvo-blue);
        }

        .section-header h4 {
            margin: 0;
            font-size: 1.1rem;
            font-weight: 600;
            color: var(--volvo-blue);
        }

        .section-content {
            display: flex;
            flex-direction: column;
            gap: 1rem;
        }

        .info-item {
            display: flex;
            flex-direction: column;
            gap: 0.5rem;
        }

        .info-label {
            display: flex;
            align-items: center;
            gap: 0.5rem;
            font-size: 0.9rem;
            font-weight: 600;
            color: #495057;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .info-label i {
            font-size: 0.8rem;
            color: var(--volvo-blue);
            width: 16px;
        }

        .info-value {
            font-size: 1rem;
            color: #212529;
            font-weight: 500;
            padding-left: 1.5rem;
        }

        .info-text {
            background: #f8f9fa;
            padding: 1rem;
            border-radius: 8px;
            border-left: 4px solid var(--volvo-blue);
            font-style: italic;
        }

        .storage-number {
            font-family: 'Courier New', monospace;
            font-weight: 700;
            color: var(--volvo-blue);
            background: #e7f3ff;
            padding: 0.5rem;
            border-radius: 6px;
            text-align: center;
        }

        .boolean-value {
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
            padding: 0.25rem 0.75rem;
            border-radius: 20px;
            font-weight: 600;
            font-size: 0.9rem;
        }

        .boolean-value.true {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }

        .boolean-value.false {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }

        .boolean-value i {
            font-size: 0.8rem;
        }

        /* Tire Order Section */
        .tire-order-status {
            margin-bottom: 1.5rem;
            padding: 1rem;
            background: linear-gradient(135deg, #d4edda 0%, #c3e6cb 100%);
            border-radius: 12px;
            border: 1px solid #c3e6cb;
        }

        .status-indicator {
            display: flex;
            align-items: center;
            gap: 0.75rem;
            font-weight: 600;
            font-size: 1.1rem;
        }

        .status-indicator.success {
            color: #155724;
        }

        .status-indicator i {
            font-size: 1.25rem;
        }

        .tire-order-section {
            background: #f8f9fa;
            border: 1px solid #e9ecef;
            border-radius: 12px;
            padding: 1.5rem;
            margin-bottom: 1rem;
        }

        .tire-order-header {
            display: flex;
            align-items: center;
            gap: 0.75rem;
            margin-bottom: 1rem;
            padding-bottom: 0.75rem;
            border-bottom: 2px solid var(--volvo-blue);
        }

        .tire-order-header i {
            font-size: 1.25rem;
            color: var(--volvo-blue);
        }

        .tire-order-header h4 {
            margin: 0;
            font-size: 1.1rem;
            font-weight: 600;
            color: var(--volvo-blue);
        }

        /* Tire Status Badges */
        .tire-status-badge {
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
            padding: 0.5rem 1rem;
            border-radius: 20px;
            font-weight: 600;
            font-size: 0.9rem;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .tire-status-badge.status-bestellt {
            background: linear-gradient(135deg, #ffc107 0%, #fd7e14 100%);
            color: #212529;
            border: 1px solid #ffeaa7;
        }

        .tire-status-badge.status-geliefert {
            background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
            color: white;
            border: 1px solid #c3e6cb;
        }

        .tire-status-badge.status-storniert {
            background: linear-gradient(135deg, #dc3545 0%, #c82333 100%);
            color: white;
            border: 1px solid #f5c6cb;
        }

        .tire-status-badge i {
            font-size: 0.8rem;
        }

        /* Responsive Design */
        @media (max-width: 1024px) {
            .detail-content-grid {
                grid-template-columns: 1fr;
            }
            
            .detail-section {
                border-right: none;
            }
        }

        @media (max-width: 768px) {
            .detail-header {
                flex-direction: column;
                text-align: center;
                gap: 1rem;
            }

            .customer-avatar {
                width: 60px;
                height: 60px;
                font-size: 1.5rem;
            }

            .customer-info h3 {
                font-size: 1.25rem;
            }

            .customer-subtitle {
                flex-direction: column;
                gap: 0.5rem;
            }

            .status-badge-large {
                padding: 0.5rem 1rem;
                font-size: 0.9rem;
            }

            .detail-section {
                padding: 1.5rem;
            }

            .section-header {
                margin-bottom: 1rem;
            }
        }
        
        .action-buttons {
            display: flex;
            gap: 0.5rem;
            align-items: center;
        }
        
        .btn-primary {
            background: var(--volvo-blue);
            border-color: var(--volvo-blue);
        }
        
        .btn-primary:hover {
            background: #1e3a8a;
            border-color: #1e3a8a;
        }
        
        .btn-primary:disabled {
            opacity: 0.6;
            cursor: not-allowed;
        }
        
        .service-tire-ordered {
            background: #28a745 !important;
            color: white !important;
        }
        
        .service-tire-ordered i {
            color: white !important;
        }
        
        .capacity-info {
            display: flex;
            flex-direction: column;
            gap: 0.25rem;
            min-width: 120px;
        }
        
        .capacity-text {
            font-weight: 600;
            color: var(--volvo-blue);
            font-size: 0.9rem;
        }
        
        .capacity-bar {
            width: 100%;
            height: 8px;
            background: #e9ecef;
            border-radius: 4px;
            overflow: hidden;
        }
        
        .capacity-fill {
            height: 100%;
            transition: width 0.3s ease;
        }
        
        .capacity-fill.low {
            background: linear-gradient(90deg, #28a745 0%, #20c997 100%);
        }
        
        .capacity-fill.medium {
            background: linear-gradient(90deg, #ffc107 0%, #fd7e14 100%);
        }
        
        .capacity-fill.high {
            background: linear-gradient(90deg, #fd7e14 0%, #dc3545 100%);
        }
        
        .capacity-fill.full {
            background: linear-gradient(90deg, #dc3545 0%, #6f42c1 100%);
        }
        
        .capacity-details {
            color: #666;
            font-size: 0.75rem;
        }
        
        .status-badge {
            padding: 0.25rem 0.5rem;
            border-radius: 4px;
            font-size: 0.75rem;
            font-weight: 600;
            text-transform: uppercase;
        }
        
        .status-pending {
            background: #fff3cd;
            color: #856404;
            border: 1px solid #ffeaa7;
        }
        
        .status-booked {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        
        .status-vorbereitet {
            background: #cce5ff;
            color: #004085;
            border: 1px solid #b3d7ff;
        }
        
        .status-completed {
            background: #d1ecf1;
            color: #0c5460;
            border: 1px solid #bee5eb;
        }
        
        .status-cancelled {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        
        .status-rejected {
            background: #f5c6cb;
            color: #721c24;
            border: 1px solid #f1b0b7;
        }
        
        .status-approved {
            background: #d1ecf1;
            color: #0c5460;
            border: 1px solid #bee5eb;
        }
        
        .status-rescheduled {
            background: #fff3cd;
            color: #856404;
            border: 1px solid #ffeaa7;
        }
        
        .pending-count {
            background: #ffc107;
            color: #212529;
            padding: 0.25rem 0.75rem;
            border-radius: 20px;
            font-size: 0.85rem;
            font-weight: 600;
            margin-left: 1rem;
            display: inline-flex;
            align-items: center;
            gap: 0.25rem;
        }
        
        .pending-row {
            background: #fff3cd !important;
            border-left: 4px solid #ffc107;
        }
        
        .pending-row:hover {
            background: #ffeaa7 !important;
        }
        
        .booked-count {
            background: #28a745;
            color: white;
            padding: 0.25rem 0.75rem;
            border-radius: 20px;
            font-size: 0.85rem;
            font-weight: 600;
            margin-left: 1rem;
            display: inline-flex;
            align-items: center;
            gap: 0.25rem;
        }
        
        .status-info {
            display: flex;
            align-items: center;
            gap: 0.25rem;
            color: #28a745;
            font-size: 0.8rem;
            font-weight: 500;
            padding: 0.25rem 0.5rem;
            background: #d4edda;
            border-radius: 4px;
            border: 1px solid #c3e6cb;
        }

        /* Tire Order Modal Styles */
        .tire-order-modal .modal-content {
            max-width: 800px;
            width: 95%;
            max-height: 90vh;
            animation: modalSlideIn 0.3s ease-out;
        }

        @keyframes modalSlideIn {
            from {
                opacity: 0;
                transform: translateY(-50px) scale(0.95);
            }
            to {
                opacity: 1;
                transform: translateY(0) scale(1);
            }
        }

        .tire-order-confirmation {
            display: flex;
            flex-direction: column;
            gap: 1.5rem;
        }

        .order-header {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 1.5rem;
            padding: 1.5rem;
            background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
            border-radius: 12px;
            border: 1px solid #dee2e6;
        }

        .customer-info, .appointment-info {
            display: flex;
            flex-direction: column;
            gap: 0.5rem;
        }

        .customer-info h4, .appointment-info h4 {
            display: flex;
            align-items: center;
            gap: 0.5rem;
            margin: 0;
            color: var(--volvo-blue);
            font-size: 1.1rem;
            font-weight: 600;
        }

        .customer-details, .appointment-details {
            margin: 0;
            color: #6c757d;
            font-size: 0.9rem;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        .order-summary {
            background: white;
            border: 1px solid #e9ecef;
            border-radius: 12px;
            padding: 1.5rem;
        }

        .order-summary h4 {
            display: flex;
            align-items: center;
            gap: 0.5rem;
            margin: 0 0 1rem 0;
            color: var(--volvo-blue);
            font-size: 1rem;
            font-weight: 600;
        }

        .summary-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 0.75rem 0;
            border-bottom: 1px solid #f8f9fa;
        }

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

        .summary-item .label {
            font-weight: 500;
            color: #495057;
        }

        .summary-item .value {
            font-weight: 600;
            color: var(--volvo-blue);
        }

        .order-actions {
            display: flex;
            gap: 1rem;
            justify-content: flex-end;
            padding-top: 1rem;
            border-top: 1px solid #e9ecef;
        }

        /* Progress Modal Styles */
        .progress-modal {
            display: flex;
            flex-direction: column;
            gap: 1.5rem;
        }

        .progress-header {
            padding: 1.5rem;
            background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
            border-radius: 12px;
            border: 1px solid #dee2e6;
        }

        .progress-steps {
            display: flex;
            justify-content: space-between;
            align-items: center;
            position: relative;
        }

        .progress-steps::before {
            content: '';
            position: absolute;
            top: 50%;
            left: 0;
            right: 0;
            height: 2px;
            background: #dee2e6;
            z-index: 1;
        }

        .step {
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 0.5rem;
            position: relative;
            z-index: 2;
            background: white;
            padding: 0 1rem;
        }

        .step-number {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 600;
            font-size: 1.1rem;
            background: #dee2e6;
            color: #6c757d;
            transition: all 0.3s ease;
        }

        .step.active .step-number {
            background: var(--volvo-blue);
            color: white;
        }

        .step.completed .step-number {
            background: #28a745;
            color: white;
        }

        .step.completed .step-number::after {
            content: '✓';
            font-size: 1.2rem;
        }

        .step-label {
            font-size: 0.9rem;
            font-weight: 500;
            color: #6c757d;
            text-align: center;
        }

        .step.active .step-label {
            color: var(--volvo-blue);
            font-weight: 600;
        }

        .step.completed .step-label {
            color: #28a745;
            font-weight: 600;
        }

        .step-content {
            flex: 1;
            display: flex;
            flex-direction: column;
            gap: 1.5rem;
        }

        .step-header {
            text-align: center;
            margin-bottom: 1rem;
        }

        .step-header h3 {
            margin: 0 0 0.5rem 0;
            color: var(--volvo-blue);
            font-size: 1.5rem;
        }

        .step-header p {
            margin: 0;
            color: #6c757d;
            font-size: 1rem;
        }

        .customer-summary {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 1rem;
        }

        .summary-card {
            background: white;
            border: 1px solid #dee2e6;
            border-radius: 8px;
            padding: 1rem;
        }

        .summary-card h4 {
            margin: 0 0 0.5rem 0;
            color: var(--volvo-blue);
            font-size: 1rem;
        }

        .summary-card p {
            margin: 0.25rem 0;
            font-size: 0.9rem;
            color: #495057;
        }

        .selected-autohaus-info {
            margin-bottom: 1rem;
        }

        .info-card {
            background: white;
            border: 1px solid #dee2e6;
            border-radius: 8px;
            padding: 1rem;
        }

        .info-card h4 {
            margin: 0 0 0.5rem 0;
            color: var(--volvo-blue);
            font-size: 1rem;
        }

        .info-card p {
            margin: 0.25rem 0;
            font-size: 0.9rem;
            color: #495057;
        }

        .confirmation-summary {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 1.5rem;
        }

        .summary-section {
            background: white;
            border: 1px solid #dee2e6;
            border-radius: 8px;
            padding: 1.5rem;
        }

        .summary-section h4 {
            margin: 0 0 1rem 0;
            color: var(--volvo-blue);
            font-size: 1.1rem;
            border-bottom: 2px solid #e9ecef;
            padding-bottom: 0.5rem;
        }

        .summary-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 0.5rem 0;
            border-bottom: 1px solid #f8f9fa;
        }

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

        .summary-item .label {
            font-weight: 500;
            color: #6c757d;
        }

        .summary-item .value {
            font-weight: 600;
            color: #495057;
        }

        .step-actions {
            display: flex;
            gap: 1rem;
            justify-content: space-between;
            padding-top: 1rem;
            border-top: 1px solid #e9ecef;
        }

        /* Calendar Styles */
        .delivery-date-selection {
            padding: 1.5rem;
            background: #f8f9fa;
            border-radius: 12px;
            border: 1px solid #dee2e6;
        }

        .calendar-container {
            display: flex;
            gap: 2rem;
            align-items: flex-start;
        }

        .calendar-wrapper {
            flex: 1;
            background: white;
            border-radius: 8px;
            border: 1px solid #dee2e6;
            overflow: hidden;
        }

        .calendar-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 1rem;
            background: var(--volvo-blue);
            color: white;
        }

        .calendar-nav-btn {
            background: rgba(255, 255, 255, 0.2);
            border: none;
            color: white;
            padding: 0.5rem;
            border-radius: 4px;
            cursor: pointer;
            transition: background-color 0.2s;
        }

        .calendar-nav-btn:hover {
            background: rgba(255, 255, 255, 0.3);
        }

        .calendar-header h5 {
            margin: 0;
            font-size: 1.1rem;
            font-weight: 600;
        }

        .calendar-grid {
            display: grid;
            grid-template-columns: repeat(7, 1fr);
            gap: 1px;
            background: #dee2e6;
        }

        .calendar-day-header {
            background: #f8f9fa;
            padding: 0.75rem 0.5rem;
            text-align: center;
            font-weight: 600;
            font-size: 0.9rem;
            color: #6c757d;
        }

        .calendar-day {
            background: white;
            padding: 0.75rem 0.5rem;
            text-align: center;
            cursor: pointer;
            transition: all 0.2s;
            border: none;
            font-size: 0.9rem;
        }

        .calendar-day:hover {
            background: #e3f2fd;
        }

        .calendar-day.selected {
            background: var(--volvo-blue);
            color: white;
            font-weight: 600;
        }

        .calendar-day.disabled {
            background: #f8f9fa;
            color: #adb5bd;
            cursor: not-allowed;
        }

        .calendar-day.disabled:hover {
            background: #f8f9fa;
        }

        .calendar-day.preferred {
            background: #d4edda;
            color: #155724;
            font-weight: 600;
        }

        .calendar-day.preferred:hover {
            background: #c3e6cb;
        }

        .calendar-day.preferred.selected {
            background: var(--volvo-blue);
            color: white;
        }

        .calendar-day.resy-available {
            background: #e3f2fd;
            color: #1976d2;
            font-weight: 500;
        }

        .calendar-day.resy-available:hover {
            background: #bbdefb;
        }

        .calendar-day.resy-available.selected {
            background: var(--volvo-blue);
            color: white;
        }

        .calendar-day.recommended {
            position: relative;
            background: linear-gradient(135deg, #ffd700 0%, #ffed4e 100%);
            color: #1a202c;
            font-weight: 700;
            border: 2px solid #f59e0b;
            box-shadow: 0 0 15px rgba(255, 215, 0, 0.6);
            animation: starGlow 2s ease-in-out infinite alternate;
        }

        .calendar-day.recommended::before {
            content: "⭐";
            position: absolute;
            top: -8px;
            right: -8px;
            font-size: 16px;
            background: #ff6b6b;
            border-radius: 50%;
            width: 24px;
            height: 24px;
            display: flex;
            align-items: center;
            justify-content: center;
            box-shadow: 0 2px 8px rgba(255, 107, 107, 0.4);
            animation: starPulse 1.5s ease-in-out infinite;
        }

        .calendar-day.recommended:hover {
            background: linear-gradient(135deg, #ffed4e 0%, #fbbf24 100%);
            transform: translateY(-3px) scale(1.05);
            box-shadow: 0 0 25px rgba(255, 215, 0, 0.8);
        }

        .calendar-day.recommended.selected {
            background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
            color: white;
            box-shadow: 0 0 30px rgba(255, 215, 0, 1);
        }

        @keyframes starGlow {
            0% { box-shadow: 0 0 15px rgba(255, 215, 0, 0.6); }
            100% { box-shadow: 0 0 25px rgba(255, 215, 0, 0.9); }
        }

        @keyframes starPulse {
            0% { transform: scale(1); }
            50% { transform: scale(1.1); }
            100% { transform: scale(1); }
        }

        .selected-date-info {
            flex: 0 0 250px;
            padding: 1rem;
            background: white;
            border-radius: 8px;
            border: 1px solid #dee2e6;
        }

        .selected-date-info p {
            margin: 0 0 0.5rem 0;
            font-size: 0.9rem;
        }

        .date-note {
            font-style: italic;
            color: #6c757d;
            font-size: 0.8rem !important;
        }

        #selected-delivery-date {
            color: var(--volvo-blue);
            font-weight: 600;
        }

        /* Recommended Date Styles */
        .recommended-date {
            margin-top: 1rem;
            padding: 1rem;
            background: #fff3cd;
            border: 1px solid #ffeaa7;
            border-radius: 8px;
        }

        .recommended-date h5 {
            margin: 0 0 0.5rem 0;
            color: #856404;
            font-size: 1rem;
        }

        .recommended-date p {
            margin: 0;
            color: #856404;
            font-size: 0.9rem;
        }

        /* Dark Mode Styles - Professional Design */
        [data-theme="dark"] .progress-header {
            background: linear-gradient(135deg, #1a202c 0%, #2d3748 100%);
            border-color: #4a5568;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.3);
        }

        [data-theme="dark"] .step {
            background: transparent;
        }

        [data-theme="dark"] .step-number {
            background: linear-gradient(135deg, #4a5568 0%, #718096 100%);
            color: #e2e8f0;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
        }

        [data-theme="dark"] .step.active .step-number {
            background: linear-gradient(135deg, var(--volvo-blue) 0%, #2563eb 100%);
            color: white;
            box-shadow: 0 4px 8px rgba(59, 130, 246, 0.3);
        }

        [data-theme="dark"] .step.completed .step-number {
            background: linear-gradient(135deg, #38a169 0%, #48bb78 100%);
            color: white;
            box-shadow: 0 4px 8px rgba(56, 161, 105, 0.3);
        }

        [data-theme="dark"] .step-label {
            color: #a0aec0;
            font-weight: 500;
        }

        [data-theme="dark"] .step.active .step-label {
            color: #e2e8f0;
            font-weight: 600;
        }

        [data-theme="dark"] .step.completed .step-label {
            color: #68d391;
            font-weight: 600;
        }

        [data-theme="dark"] .step-header h3 {
            color: #e2e8f0;
            text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
        }

        [data-theme="dark"] .step-header p {
            color: #a0aec0;
        }

        [data-theme="dark"] .summary-card,
        [data-theme="dark"] .info-card,
        [data-theme="dark"] .summary-section {
            background: linear-gradient(135deg, #2d3748 0%, #4a5568 100%);
            border-color: #718096;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.2);
        }

        [data-theme="dark"] .summary-card h4,
        [data-theme="dark"] .info-card h4,
        [data-theme="dark"] .summary-section h4 {
            color: #e2e8f0;
            border-color: #718096;
            text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
        }

        [data-theme="dark"] .summary-card p,
        [data-theme="dark"] .info-card p {
            color: #cbd5e0;
        }

        [data-theme="dark"] .summary-item .label {
            color: #a0aec0;
            font-weight: 500;
        }

        [data-theme="dark"] .summary-item .value {
            color: #e2e8f0;
            font-weight: 600;
        }

        [data-theme="dark"] .step-actions {
            border-color: #718096;
        }

        [data-theme="dark"] .delivery-date-selection {
            background: linear-gradient(135deg, #2d3748 0%, #4a5568 100%);
            border-color: #718096;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.2);
        }

        [data-theme="dark"] .calendar-wrapper {
            background: linear-gradient(135deg, #1a202c 0%, #2d3748 100%);
            border-color: #718096;
            box-shadow: 0 8px 16px rgba(0, 0, 0, 0.3);
            border-radius: 12px;
            overflow: hidden;
        }

        [data-theme="dark"] .calendar-header {
            background: linear-gradient(135deg, var(--volvo-blue) 0%, #2563eb 100%);
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
        }

        [data-theme="dark"] .calendar-nav-btn {
            background: rgba(255, 255, 255, 0.15);
            backdrop-filter: blur(10px);
            border: 1px solid rgba(255, 255, 255, 0.2);
        }

        [data-theme="dark"] .calendar-nav-btn:hover {
            background: rgba(255, 255, 255, 0.25);
            transform: translateY(-1px);
        }

        [data-theme="dark"] .calendar-day-header {
            background: linear-gradient(135deg, #4a5568 0%, #718096 100%);
            color: #e2e8f0;
            font-weight: 600;
            text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
        }

        [data-theme="dark"] .calendar-day {
            background: linear-gradient(135deg, #2d3748 0%, #4a5568 100%);
            color: #e2e8f0;
            border: 1px solid rgba(113, 128, 150, 0.2);
            transition: all 0.2s ease;
        }

        [data-theme="dark"] .calendar-day:hover {
            background: linear-gradient(135deg, #4a5568 0%, #718096 100%);
            transform: translateY(-1px);
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
        }

        [data-theme="dark"] .calendar-day.disabled {
            background: linear-gradient(135deg, #1a202c 0%, #2d3748 100%);
            color: #718096;
            opacity: 0.5;
        }

        [data-theme="dark"] .calendar-day.preferred {
            background: linear-gradient(135deg, #2f855a 0%, #38a169 100%);
            color: #f0fff4;
            font-weight: 600;
            box-shadow: 0 2px 4px rgba(47, 133, 90, 0.3);
        }

        [data-theme="dark"] .calendar-day.preferred:hover {
            background: linear-gradient(135deg, #38a169 0%, #48bb78 100%);
            transform: translateY(-2px);
            box-shadow: 0 6px 12px rgba(47, 133, 90, 0.4);
        }

        [data-theme="dark"] .calendar-day.resy-available {
            background: linear-gradient(135deg, #2b6cb0 0%, #3182ce 100%);
            color: #bee3f8;
            font-weight: 500;
            box-shadow: 0 2px 4px rgba(43, 108, 176, 0.3);
        }

        [data-theme="dark"] .calendar-day.resy-available:hover {
            background: linear-gradient(135deg, #3182ce 0%, #4299e1 100%);
            transform: translateY(-2px);
            box-shadow: 0 6px 12px rgba(43, 108, 176, 0.4);
        }

        [data-theme="dark"] .calendar-day.recommended {
            background: linear-gradient(135deg, #ffd700 0%, #ffed4e 100%);
            color: #1a202c;
            font-weight: 700;
            border: 2px solid #f59e0b;
            box-shadow: 0 0 20px rgba(255, 215, 0, 0.8);
            animation: starGlowDark 2s ease-in-out infinite alternate;
        }

        [data-theme="dark"] .calendar-day.recommended::before {
            content: "⭐";
            position: absolute;
            top: -8px;
            right: -8px;
            font-size: 16px;
            background: #ff6b6b;
            border-radius: 50%;
            width: 24px;
            height: 24px;
            display: flex;
            align-items: center;
            justify-content: center;
            box-shadow: 0 2px 12px rgba(255, 107, 107, 0.6);
            animation: starPulseDark 1.5s ease-in-out infinite;
        }

        [data-theme="dark"] .calendar-day.recommended:hover {
            background: linear-gradient(135deg, #ffed4e 0%, #fbbf24 100%);
            transform: translateY(-3px) scale(1.05);
            box-shadow: 0 0 30px rgba(255, 215, 0, 1);
        }

        [data-theme="dark"] .calendar-day.recommended.selected {
            background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
            color: white;
            box-shadow: 0 0 35px rgba(255, 215, 0, 1.2);
        }

        @keyframes starGlowDark {
            0% { box-shadow: 0 0 20px rgba(255, 215, 0, 0.8); }
            100% { box-shadow: 0 0 35px rgba(255, 215, 0, 1.2); }
        }

        @keyframes starPulseDark {
            0% { transform: scale(1); }
            50% { transform: scale(1.15); }
            100% { transform: scale(1); }
        }

        [data-theme="dark"] .calendar-day.selected {
            background: linear-gradient(135deg, var(--volvo-blue) 0%, #2563eb 100%) !important;
            color: white !important;
            font-weight: 700;
            transform: translateY(-2px);
            box-shadow: 0 8px 16px rgba(59, 130, 246, 0.5);
            border: 2px solid rgba(255, 255, 255, 0.3);
        }

        [data-theme="dark"] .selected-date-info {
            background: linear-gradient(135deg, #2d3748 0%, #4a5568 100%);
            border-color: #718096;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.2);
        }

        [data-theme="dark"] .selected-date-info p {
            color: #e2e8f0;
        }

        [data-theme="dark"] .date-note {
            color: #a0aec0 !important;
        }

        [data-theme="dark"] .recommended-date {
            background: linear-gradient(135deg, #744210 0%, #975a16 100%);
            border-color: #d69e2e;
            box-shadow: 0 4px 6px rgba(116, 66, 16, 0.3);
        }

        [data-theme="dark"] .recommended-date h5,
        [data-theme="dark"] .recommended-date p {
            color: #f6e05e;
            text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
        }

        /* Loading State */
        .tire-order-loading {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            padding: 3rem;
            text-align: center;
        }

        .loading-spinner {
            font-size: 3rem;
            color: var(--volvo-blue);
            margin-bottom: 1rem;
        }

        .tire-order-loading h4 {
            margin: 0 0 0.5rem 0;
            color: var(--volvo-blue);
        }

        .tire-order-loading p {
            margin: 0;
            color: #6c757d;
        }

        /* Order Process Steps */
        .order-process {
            margin-top: 2rem;
            display: flex;
            flex-direction: column;
            gap: 1rem;
        }

        .process-step {
            display: flex;
            align-items: center;
            gap: 1rem;
            padding: 1rem;
            border-radius: 8px;
            background: #f8f9fa;
            border: 2px solid #e9ecef;
            transition: all 0.3s ease;
            opacity: 0.5;
        }

        .process-step.active {
            background: linear-gradient(135deg, #e7f3ff 0%, #b3d7ff 100%);
            border-color: var(--volvo-blue);
            opacity: 1;
            transform: translateX(5px);
            box-shadow: 0 2px 8px rgba(0, 123, 255, 0.2);
        }

        .process-step.completed {
            background: linear-gradient(135deg, #d4edda 0%, #c3e6cb 100%);
            border-color: #28a745;
            opacity: 1;
        }

        .step-icon {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.2rem;
            color: white;
            background: #6c757d;
            transition: all 0.3s ease;
        }

        .process-step.active .step-icon {
            background: var(--volvo-blue);
            animation: pulse 1.5s infinite;
        }

        .process-step.completed .step-icon {
            background: #28a745;
        }

        .process-step.completed .step-icon i {
            transform: scale(0);
            animation: checkmark 0.3s ease 0.2s forwards;
        }

        .process-step.completed .step-icon i:before {
            content: "\f00c"; /* FontAwesome check icon */
        }

        .step-content h5 {
            margin: 0 0 0.25rem 0;
            font-size: 1rem;
            font-weight: 600;
            color: #495057;
        }

        .process-step.active .step-content h5 {
            color: var(--volvo-blue);
        }

        .process-step.completed .step-content h5 {
            color: #155724;
        }

        .step-content p {
            margin: 0;
            font-size: 0.9rem;
            color: #6c757d;
        }

        .process-step.completed .step-content p {
            color: #155724;
        }

        @keyframes pulse {
            0% { transform: scale(1); }
            50% { transform: scale(1.1); }
            100% { transform: scale(1); }
        }

        @keyframes checkmark {
            0% { transform: scale(0); }
            100% { transform: scale(1); }
        }

        /* Result States */
        .tire-order-result {
            display: flex;
            flex-direction: column;
            gap: 1.5rem;
        }

        .result-header {
            display: flex;
            align-items: center;
            gap: 1rem;
            padding: 1.5rem;
            border-radius: 12px;
            text-align: center;
        }

        .tire-order-result.success .result-header {
            background: linear-gradient(135deg, #d4edda 0%, #c3e6cb 100%);
            border: 1px solid #c3e6cb;
        }

        .tire-order-result.error .result-header {
            background: linear-gradient(135deg, #f8d7da 0%, #f5c6cb 100%);
            border: 1px solid #f5c6cb;
        }

        .success-icon, .error-icon {
            font-size: 3rem;
        }

        .success-icon {
            color: #28a745;
        }

        .error-icon {
            color: #dc3545;
        }

        .result-header h4 {
            margin: 0;
            font-size: 1.5rem;
            font-weight: 600;
        }

        .tire-order-result.success .result-header h4 {
            color: #155724;
        }

        .tire-order-result.error .result-header h4 {
            color: #721c24;
        }

        .result-message {
            background: white;
            border: 1px solid #e9ecef;
            border-radius: 12px;
            padding: 1.5rem;
        }

        .result-message p {
            margin: 0;
            font-size: 1.1rem;
            line-height: 1.5;
        }

        .result-details {
            background: #f8f9fa;
            border: 1px solid #e9ecef;
            border-radius: 12px;
            padding: 1.5rem;
        }

        .detail-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 0.5rem 0;
        }

        .detail-item .label {
            font-weight: 500;
            color: #495057;
        }

        .detail-item .value {
            font-weight: 600;
            color: var(--volvo-blue);
        }

        /* Delivery Info */
        .delivery-info {
            display: flex;
            align-items: center;
            gap: 0.75rem;
            padding: 1rem;
            border-radius: 8px;
            font-weight: 500;
        }

        .delivery-info.success {
            background: #d4edda;
            border: 1px solid #c3e6cb;
            color: #155724;
        }

        .delivery-info.warning {
            background: #fff3cd;
            border: 1px solid #ffeaa7;
            color: #856404;
        }

        .delivery-info.error {
            background: #f8d7da;
            border: 1px solid #f5c6cb;
            color: #721c24;
        }

        .delivery-info i {
            font-size: 1.2rem;
        }

        /* RESY Info */
        .resy-info, .resy-error {
            background: #e7f3ff;
            border: 1px solid #b3d7ff;
            border-radius: 8px;
            padding: 1rem;
        }

        .resy-error {
            background: #f8d7da;
            border-color: #f5c6cb;
        }

        .resy-info h5, .resy-error h5 {
            margin: 0 0 0.5rem 0;
            display: flex;
            align-items: center;
            gap: 0.5rem;
            color: var(--volvo-blue);
            font-size: 0.9rem;
            font-weight: 600;
        }

        .resy-info p, .resy-error p {
            margin: 0.25rem 0;
            font-size: 0.9rem;
        }

        /* Warning Info */
        .warning-info {
            display: flex;
            align-items: center;
            gap: 0.75rem;
            padding: 1rem;
            background: #fff3cd;
            border: 1px solid #ffeaa7;
            border-radius: 8px;
            color: #856404;
            font-weight: 500;
        }

        .warning-info i {
            font-size: 1.2rem;
        }

        .result-actions {
            display: flex;
            gap: 1rem;
            justify-content: flex-end;
            padding-top: 1rem;
            border-top: 1px solid #e9ecef;
        }

        /* Responsive Design */
        @media (max-width: 768px) {
            .tire-order-modal .modal-content {
                width: 98%;
                margin: 1% auto;
            }

            .order-header {
                grid-template-columns: 1fr;
                gap: 1rem;
            }

            .calendar-container {
                flex-direction: column;
                gap: 1rem;
            }

            .selected-date-info {
                flex: none;
            }

            .calendar-day {
                padding: 0.5rem 0.25rem;
                font-size: 0.8rem;
            }

            .calendar-day-header {
                padding: 0.5rem 0.25rem;
                font-size: 0.8rem;
            }

            .order-actions, .result-actions {
                flex-direction: column;
            }

            .order-actions .btn, .result-actions .btn {
                width: 100%;
            }
        }
        
        
        .btn-success {
            background: #28a745;
            border-color: #28a745;
        }
        
        .btn-success:hover {
            background: #218838;
            border-color: #1e7e34;
        }
        
        .btn-warning {
            background: #ffc107;
            border-color: #ffc107;
            color: #212529;
        }
        
        .btn-warning:hover {
            background: #e0a800;
            border-color: #d39e00;
        }
        
        .btn-info {
            background: #17a2b8;
            border-color: #17a2b8;
            color: white;
        }
        
        .btn-info:hover {
            background: #138496;
            border-color: #117a8b;
        }
        
        /* Edit Modal Styles */
        .form-grid {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 1rem;
            margin-bottom: 0;
        }
        
        @media (max-width: 1024px) {
            .form-grid {
                grid-template-columns: repeat(2, 1fr);
            }
        }
        
        @media (max-width: 768px) {
            .form-grid {
                grid-template-columns: 1fr;
            }
        }
        
        .form-group {
            display: flex;
            flex-direction: column;
        }
        
        .form-group.full-width {
            grid-column: 1 / -1;
        }
        
        .form-group label {
            font-weight: 600;
            color: var(--volvo-blue);
            margin-bottom: 0.5rem;
            font-size: 0.9rem;
            display: flex;
            align-items: center;
            gap: 0.25rem;
        }
        
        .form-group label::after {
            content: '';
            flex: 1;
            height: 1px;
            background: linear-gradient(to right, #e9ecef, transparent);
            margin-left: 0.5rem;
        }
        
        .form-group input,
        .form-group select,
        .form-group textarea {
            padding: 0.875rem;
            border: 2px solid #e9ecef;
            border-radius: 10px;
            font-size: 0.95rem;
            transition: all 0.3s ease;
            background: #fafbfc;
        }
        
        .form-group input:focus,
        .form-group select:focus,
        .form-group textarea:focus {
            outline: none;
            border-color: var(--volvo-blue);
            background: white;
            box-shadow: 0 0 0 3px rgba(0, 123, 255, 0.1);
            transform: translateY(-1px);
        }
        
        .form-group input:hover,
        .form-group select:hover,
        .form-group textarea:hover {
            border-color: #ced4da;
            background: white;
        }
        
        .modal-actions {
            display: flex;
            justify-content: flex-end;
            gap: 1rem;
            padding: 1.5rem 2rem;
            border-top: 1px solid #eee;
            background: #f8f9fa;
            border-radius: 0 0 16px 16px;
            flex-shrink: 0;
        }
        
        .modal-actions .btn {
            padding: 0.75rem 1.5rem;
            font-weight: 600;
            min-width: 120px;
        }
        
        .modal-actions .btn i {
            margin-right: 0.5rem;
        }
        
        /* Form Sections */
        .form-sections {
            display: flex;
            flex-direction: column;
            gap: 1.5rem;
        }
        
        .form-section {
            background: #f8f9fa;
            border-radius: 12px;
            padding: 1.25rem;
            border: 1px solid #e9ecef;
        }
        
        .section-title {
            display: flex;
            align-items: center;
            gap: 0.75rem;
            margin: 0 0 1rem 0;
            padding-bottom: 0.5rem;
            border-bottom: 2px solid var(--volvo-blue);
            color: var(--volvo-blue);
            font-size: 1rem;
            font-weight: 600;
        }
        
        .section-title i {
            font-size: 1.2rem;
            color: var(--volvo-blue);
        }
        
        .form-section .form-grid {
            margin-bottom: 0;
        }
        
        /* Responsive adjustments for sections */
        @media (max-width: 768px) {
            .form-sections {
                gap: 1.5rem;
            }
            
            .form-section {
                padding: 1rem;
            }
            
            .section-title {
                font-size: 1rem;
                margin-bottom: 1rem;
            }
        }
        
        .order-label {
            font-size: 0.8rem;
            font-weight: 600;
            color: #495057;
            margin-bottom: 0.25rem;
            display: block;
        }
        
        .order-input {
            font-size: 0.85rem;
            padding: 0.25rem 0.5rem;
            border: 1px solid #ced4da;
            border-radius: 4px;
            width: 120px;
        }
        
        .order-input:focus {
            border-color: #007bff;
            box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.25);
            outline: none;
        }
        
        .status-container {
            display: flex;
            flex-direction: column;
            gap: 0.5rem;
        }
        
        /* Action Buttons Styling */
        .action-buttons-container {
            display: flex;
            flex-direction: column;
            gap: 0.5rem;
            min-width: 200px;
        }
        
        .action-row {
            display: flex;
            gap: 0.25rem;
            align-items: center;
            flex-wrap: wrap;
        }
        
        .primary-actions {
            justify-content: flex-start;
        }
        
        .status-actions {
            justify-content: center;
            padding: 0.25rem 0;
            border-top: 1px solid #e9ecef;
            border-bottom: 1px solid #e9ecef;
        }
        
        .service-actions {
            justify-content: center;
            padding: 0.25rem 0;
        }
        
        .action-row .btn {
            margin: 0;
            flex-shrink: 0;
        }
        
        .action-row .btn-icon {
            width: 32px;
            height: 32px;
            padding: 0;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 6px;
            transition: all 0.2s ease;
        }
        
        .action-row .btn-icon:hover {
            transform: translateY(-1px);
            box-shadow: 0 2px 8px rgba(0,0,0,0.15);
        }
        
        .action-row .btn:not(.btn-icon) {
            padding: 0.375rem 0.75rem;
            font-size: 0.8rem;
            border-radius: 6px;
            font-weight: 500;
            transition: all 0.2s ease;
        }
        
        .action-row .btn:not(.btn-icon):hover {
            transform: translateY(-1px);
            box-shadow: 0 2px 8px rgba(0,0,0,0.15);
        }
        
        /* Button Color Variations */
        .btn-secondary {
            background: #6c757d;
            border-color: #6c757d;
            color: white;
        }
        
        .btn-secondary:hover {
            background: #5a6268;
            border-color: #545b62;
        }
        
        .btn-info {
            background: #17a2b8;
            border-color: #17a2b8;
            color: white;
        }
        
        .btn-info:hover {
            background: #138496;
            border-color: #117a8b;
        }
        
        .btn-warning {
            background: #ffc107;
            border-color: #ffc107;
            color: #212529;
        }
        
        .btn-warning:hover {
            background: #e0a800;
            border-color: #d39e00;
        }
        
        .btn-success {
            background: #28a745;
            border-color: #28a745;
            color: white;
        }
        
        .btn-success:hover {
            background: #218838;
            border-color: #1e7e34;
        }
        
        .btn-danger {
            background: #dc3545;
            border-color: #dc3545;
            color: white;
        }
        
        .btn-danger:hover {
            background: #c82333;
            border-color: #bd2130;
        }
        
        .btn-primary {
            background: #007bff;
            border-color: #007bff;
            color: white;
        }
        
        .btn-primary:hover {
            background: #0056b3;
            border-color: #004085;
        }
        
        /* Professional Modal Styles - REMOVED DUPLICATE */
        
        /* Professional Content Styles */
        .tire-status-section {
            margin-bottom: 2rem;
            padding: 1.5rem;
            background: #ffffff;
            border-radius: 12px;
            border: 1px solid #e9ecef;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
        }
        
        .tire-status-section h6 {
            color: #495057;
            font-weight: 700;
            font-size: 1rem;
            margin-bottom: 1rem;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }
        
        .tire-status-section h6 i {
            color: #007bff;
            font-size: 1.1rem;
        }
        
        .info-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 1rem;
        }
        
        .info-item {
            background: #f8f9fa;
            padding: 1rem;
            border-radius: 8px;
            border-left: 4px solid #007bff;
        }
        
        .info-label {
            font-size: 0.8rem;
            color: #6c757d;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            margin-bottom: 0.25rem;
        }
        
        .info-value {
            font-size: 1rem;
            color: #495057;
            font-weight: 600;
        }
        
        .recommendation-card {
            background: linear-gradient(135deg, #fff3cd 0%, #ffeaa7 100%);
            border: 2px solid #ffc107;
            border-radius: 12px;
            padding: 1.5rem;
            margin-top: 1.5rem;
            position: relative;
            overflow: hidden;
        }
        
        .recommendation-card::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 4px;
            background: linear-gradient(90deg, #ffc107, #ff8c00);
        }
        
        .recommendation-card.warning {
            background: linear-gradient(135deg, #f8d7da 0%, #f5c6cb 100%);
            border-color: #dc3545;
        }
        
        .recommendation-card.warning::before {
            background: linear-gradient(90deg, #dc3545, #c82333);
        }
        
        .recommendation-card.success {
            background: linear-gradient(135deg, #d4edda 0%, #c3e6cb 100%);
            border-color: #28a745;
        }
        
        .recommendation-card.success::before {
            background: linear-gradient(90deg, #28a745, #20c997);
        }
        
        .recommendation-header {
            display: flex;
            align-items: center;
            gap: 0.75rem;
            margin-bottom: 1rem;
        }
        
        .recommendation-header h6 {
            margin: 0;
            font-size: 1.1rem;
            font-weight: 700;
            color: #495057;
        }
        
        .recommendation-header i {
            font-size: 1.25rem;
            color: #ffc107;
        }
        
        .recommendation-card.warning .recommendation-header i {
            color: #dc3545;
        }
        
        .recommendation-card.success .recommendation-header i {
            color: #28a745;
        }
        
        .recommendation-text {
            font-size: 1rem;
            color: #495057;
            line-height: 1.5;
            margin-bottom: 1.5rem;
        }
        
        .recommendation-actions {
            display: flex;
            gap: 1rem;
            flex-wrap: wrap;
        }
        
        .btn-recommendation {
            background: linear-gradient(135deg, #007bff 0%, #0056b3 100%);
            color: white;
            border: none;
            padding: 0.75rem 1.5rem;
            border-radius: 8px;
            font-weight: 600;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }
        
        .btn-recommendation:hover {
            background: linear-gradient(135deg, #0056b3 0%, #004085 100%);
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(0, 123, 255, 0.3);
        }
        
        .loading-spinner {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            padding: 3rem;
            color: #6c757d;
        }
        
        .spinner-border {
            width: 3rem;
            height: 3rem;
            border: 0.3rem solid #e9ecef;
            border-top: 0.3rem solid #007bff;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin-bottom: 1rem;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        .error-alert {
            background: linear-gradient(135deg, #f8d7da 0%, #f5c6cb 100%);
            border: 2px solid #dc3545;
            border-radius: 12px;
            padding: 1.5rem;
            color: #721c24;
        }
        
        .error-alert-header {
            display: flex;
            align-items: center;
            gap: 0.75rem;
            font-weight: 700;
            margin-bottom: 0.5rem;
        }
        
        .error-alert i {
            color: #dc3545;
            font-size: 1.25rem;
        }
        
        /* Responsive Design */
        @media (max-width: 768px) {
            .action-buttons-container {
                min-width: 150px;
            }
            
            .action-row {
                flex-direction: column;
                gap: 0.5rem;
            }
            
            .action-row .btn:not(.btn-icon) {
                width: 100%;
                justify-content: center;
            }
            
            .modal-dialog {
                margin: 0.5rem;
                max-width: calc(100% - 1rem);
            }
        }
        
        /* Modernes Design für Kategorien */
        .data-category {
            margin-bottom: 30px;
            background: white;
            border-radius: 12px;
            padding: 20px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.05);
            border: 1px solid #f0f0f0;
        }
        
        .category-title {
            color: #2c3e50;
            font-size: 1.2rem;
            font-weight: 600;
            margin: 0 0 20px 0;
            padding-bottom: 10px;
            border-bottom: 2px solid #e9ecef;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .category-title i {
            color: #667eea;
        }
        
        .category-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 15px;
        }
        
        .info-item.modern {
            background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);
            border-radius: 8px;
            padding: 15px;
            border: 1px solid #e9ecef;
            transition: all 0.3s ease;
            position: relative;
            overflow: hidden;
        }
        
        .info-item.modern::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            width: 4px;
            height: 100%;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        }
        
        .info-item.modern:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(0,0,0,0.1);
            border-color: #667eea;
        }
        
        .info-item.modern .info-label {
            font-weight: 600;
            color: #495057;
            margin-bottom: 8px;
            display: flex;
            align-items: center;
            gap: 8px;
            font-size: 0.9rem;
        }
        
        .info-item.modern .info-label i {
            color: #667eea;
            width: 16px;
            text-align: center;
        }
        
        .info-item.modern .info-value {
            color: #2c3e50;
            font-size: 1rem;
            font-weight: 500;
            word-break: break-word;
        }
        
        .no-data-message {
            text-align: center;
            padding: 60px 20px;
            color: #6c757d;
        }
        
        .no-data-message i {
            font-size: 3rem;
            color: #ffc107;
            margin-bottom: 20px;
        }
        
        .no-data-message h3 {
            color: #495057;
            margin-bottom: 10px;
        }
        
        /* Professionelles Design */
        .professional-category {
            background: white;
            border-radius: 16px;
            margin-bottom: 24px;
            border-left: 6px solid #3498db;
            box-shadow: 0 8px 32px rgba(0,0,0,0.08);
            overflow: hidden;
            transition: all 0.3s ease;
        }
        
        .professional-category:hover {
            transform: translateY(-4px);
            box-shadow: 0 16px 48px rgba(0,0,0,0.12);
        }
        
        .category-header {
            background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);
            padding: 20px 24px;
            border-bottom: 1px solid #e9ecef;
            display: flex;
            align-items: center;
            gap: 16px;
        }
        
        .category-icon {
            width: 48px;
            height: 48px;
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 20px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
        }
        
        .category-info {
            flex: 1;
        }
        
        .category-title {
            margin: 0;
            font-size: 1.4rem;
            font-weight: 700;
            color: #2c3e50;
            line-height: 1.2;
        }
        
        .category-count {
            color: #6c757d;
            font-size: 0.9rem;
            font-weight: 500;
            margin-top: 4px;
            display: block;
        }
        
        .category-content {
            padding: 20px 24px;
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
            gap: 16px;
        }
        
        .professional-item {
            background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
            border-radius: 12px;
            padding: 16px;
            border: 1px solid #e9ecef;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            gap: 12px;
            position: relative;
            overflow: hidden;
        }
        
        .professional-item::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            width: 4px;
            height: 100%;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            opacity: 0;
            transition: opacity 0.3s ease;
        }
        
        .professional-item:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(0,0,0,0.1);
            border-color: #667eea;
        }
        
        .professional-item:hover::before {
            opacity: 1;
        }
        
        .professional-item.priority-high {
            border-left: 4px solid #e74c3c;
            background: linear-gradient(135deg, #fff5f5 0%, #ffffff 100%);
        }
        
        .professional-item.priority-medium {
            border-left: 4px solid #f39c12;
            background: linear-gradient(135deg, #fffbf0 0%, #ffffff 100%);
        }
        
        .professional-item.priority-low {
            border-left: 4px solid #95a5a6;
            background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);
        }
        
        .item-icon {
            width: 40px;
            height: 40px;
            border-radius: 10px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 16px;
            flex-shrink: 0;
        }
        
        .item-content {
            flex: 1;
            min-width: 0;
        }
        
        .item-label {
            font-size: 0.85rem;
            font-weight: 600;
            color: #495057;
            margin-bottom: 4px;
            line-height: 1.2;
        }
        
        .item-value {
            font-size: 1rem;
            font-weight: 500;
            color: #2c3e50;
            word-break: break-word;
            line-height: 1.3;
        }
        
        .no-data-professional {
            text-align: center;
            padding: 80px 20px;
            background: white;
            border-radius: 16px;
            box-shadow: 0 8px 32px rgba(0,0,0,0.08);
        }
        
        .no-data-icon {
            width: 80px;
            height: 80px;
            border-radius: 50%;
            background: linear-gradient(135deg, #ffc107 0%, #ff8c00 100%);
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 24px;
            font-size: 2rem;
            color: white;
        }
        
        .no-data-professional h3 {
            color: #2c3e50;
            font-size: 1.5rem;
            font-weight: 700;
            margin-bottom: 12px;
        }
        
        .no-data-professional p {
            color: #6c757d;
            font-size: 1rem;
            line-height: 1.5;
        }
        
        /* Minimalistisches Dashboard Design */
        .tire-dashboard {
            background: #ffffff;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 4px 20px rgba(0,0,0,0.08);
            border: 1px solid #e5e5e5;
        }
        
        .dashboard-header {
            background: #f8f9fa;
            color: #333333;
            padding: 24px;
            border-bottom: 1px solid #e5e5e5;
        }
        
        .header-main {
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 20px;
        }
        
        .main-info {
            display: flex;
            align-items: center;
            gap: 20px;
        }
        
        .tire-title {
            margin: 0;
            font-size: 1.5rem;
            font-weight: 600;
            color: #333333;
        }
        
        .status-badge {
            display: inline-flex;
            align-items: center;
            gap: 6px;
            padding: 6px 12px;
            border-radius: 4px;
            font-weight: 500;
            font-size: 0.85rem;
        }
        
        .status-stored {
            background: #e8f5e8;
            color: #2d5a2d;
            border: 1px solid #c3e6c3;
        }
        
        .status-other {
            background: #fff3cd;
            color: #856404;
            border: 1px solid #ffeaa7;
        }
        
        .quick-stats {
            display: flex;
            gap: 30px;
            flex-wrap: wrap;
        }
        
        .stat-item {
            text-align: center;
            min-width: 120px;
        }
        
        .stat-value {
            font-size: 1.2rem;
            font-weight: 600;
            color: #333333;
            margin-bottom: 4px;
        }
        
        .stat-label {
            font-size: 0.8rem;
            color: #666666;
            font-weight: 500;
        }
        
        .tire-overview {
            padding: 24px;
            background: #ffffff;
            border-bottom: 1px solid #e5e5e5;
        }
        
        .section-title {
            margin: 0 0 16px 0;
            font-size: 1.1rem;
            font-weight: 600;
            color: #333333;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        
        .section-title i {
            color: #666666;
        }
        
        .tire-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
        }
        
        .tire-position {
            background: #f8f9fa;
            border-radius: 6px;
            padding: 16px;
            text-align: center;
            border: 1px solid #e5e5e5;
            transition: all 0.2s ease;
        }
        
        .tire-position:hover {
            background: #f0f0f0;
        }
        
        .position-label {
            font-size: 1rem;
            font-weight: 600;
            color: #333333;
            margin-bottom: 8px;
            padding: 4px 8px;
            background: #e5e5e5;
            color: #333333;
            border-radius: 4px;
            display: inline-block;
        }
        
        .tire-model {
            font-size: 1rem;
            font-weight: 600;
            color: #2c3e50;
            margin-bottom: 8px;
        }
        
        .tire-depth {
            font-size: 0.9rem;
            color: #6c757d;
        }
        
        .detail-sections {
            padding: 24px;
        }
        
        .detail-section {
            margin-bottom: 20px;
            background: #ffffff;
            border-radius: 6px;
            padding: 20px;
            border: 1px solid #e5e5e5;
        }
        
        .detail-title {
            margin: 0 0 16px 0;
            font-size: 1rem;
            font-weight: 600;
            color: #333333;
            display: flex;
            align-items: center;
            gap: 8px;
            padding-bottom: 8px;
            border-bottom: 1px solid #e5e5e5;
        }
        
        .detail-title i {
            color: #666666;
        }
        
        .detail-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 16px;
        }
        
        .detail-item {
            display: flex;
            align-items: center;
            gap: 10px;
            padding: 10px;
            background: #f8f9fa;
            border-radius: 4px;
            transition: all 0.2s ease;
        }
        
        .detail-item:hover {
            background: #f0f0f0;
        }
        
        .detail-icon {
            width: 24px;
            height: 24px;
            border-radius: 4px;
            background: #e5e5e5;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #666666;
            font-size: 12px;
            flex-shrink: 0;
        }
        
        .detail-content {
            flex: 1;
            min-width: 0;
        }
        
        .detail-label {
            font-size: 0.8rem;
            font-weight: 600;
            color: #6c757d;
            margin-bottom: 2px;
        }
        
        .detail-value {
            font-size: 0.95rem;
            font-weight: 500;
            color: #2c3e50;
            word-break: break-word;
        }
        
        /* Responsive Design */
        @media (max-width: 768px) {
            .header-main {
                flex-direction: column;
                align-items: flex-start;
            }
            
            .quick-stats {
                width: 100%;
                justify-content: space-between;
            }
            
            .tire-grid {
                grid-template-columns: repeat(2, 1fr);
            }
            
            .detail-grid {
                grid-template-columns: 1fr;
            }
            
            .dashboard-header {
                padding: 20px;
            }
            
            .tire-overview,
            .detail-sections {
                padding: 20px;
            }
            
            .tire-title {
                font-size: 1.5rem;
            }
        }
        
        @media (max-width: 480px) {
            .tire-grid {
                grid-template-columns: 1fr;
            }
            
            .quick-stats {
                flex-direction: column;
                gap: 15px;
            }
        }
    </style>
    
    <!-- Reifenanalyse Modal Styles -->
    <style>
        :root {
            --bg: #f5f7fb;
            --surface: #ffffff;
            --surface-2: #f9fbff;
            --text: #0b1220;
            --muted: #5b6577;
            --line: #e7ecf4;
            --brand: #2563eb;
            --ok: #16a34a;
            --mid: #f59e0b;
            --warn: #ef4444;
            --vio: #8b5cf6;
            --radius: 18px;
            --shadow: 0 10px 30px rgba(12,18,32,.12);
        }
        
        .modal-backdrop {
            position: fixed !important;
            inset: 0 !important;
            background: rgba(3,10,20,.35) !important;
            display: grid !important;
            place-items: center !important;
            padding: 20px !important;
            z-index: 9999 !important;
            width: 100vw !important;
            height: 100vh !important;
            top: 0 !important;
            left: 0 !important;
            right: 0 !important;
            bottom: 0 !important;
        }
        
        .modal-backdrop.hidden {
            display: none !important;
        }
        
        /* REMOVED DUPLICATE MODAL STYLES */
        
        /* Tire Check Modal Styles */
        .tire-check-modal {
            background: #1a1a1a;
            border-radius: 20px;
            width: 95vw;
            max-width: 1400px;
            max-height: 90vh;
            overflow: hidden;
            box-shadow: 0 20px 60px rgba(0,0,0,0.5);
        }
        
        /* RESY Data Section Styles */
        .resy-data-section {
            margin: 20px 0;
            padding: 20px;
            background: rgba(255, 255, 255, 0.05);
            border-radius: 15px;
            border: 1px solid rgba(255, 255, 255, 0.1);
        }
        
        .resy-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 25px;
            padding-bottom: 15px;
            border-bottom: 2px solid rgba(255, 255, 255, 0.1);
        }
        
        .resy-header h4 {
            color: #ffffff;
            margin: 0;
            font-size: 1.3em;
            font-weight: 600;
        }
        
        .resy-header h4 i {
            color: #4CAF50;
            margin-right: 8px;
        }
        
        .resy-controls {
            display: flex;
            gap: 10px;
        }
        
        .fields-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 20px;
            margin-bottom: 25px;
        }
        
        .fields-fullwidth {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
        }
        
        @media (max-width: 768px) {
            .fields-grid {
                grid-template-columns: 1fr;
            }
            .fields-fullwidth {
                grid-template-columns: 1fr;
            }
        }
        
        .field-group {
            display: flex;
            flex-direction: column;
            background: rgba(255, 255, 255, 0.03);
            padding: 15px;
            border-radius: 10px;
            border: 1px solid rgba(255, 255, 255, 0.08);
            transition: all 0.3s ease;
        }
        
        .field-group:hover {
            background: rgba(255, 255, 255, 0.05);
            border-color: rgba(255, 255, 255, 0.15);
        }
        
        .field-group label {
            color: #ffffff;
            font-weight: 600;
            margin-bottom: 8px;
            font-size: 0.95em;
            display: flex;
            align-items: center;
        }
        
        .field-group label i {
            color: #4CAF50;
            margin-right: 8px;
            width: 16px;
        }
        
        .field-group .form-control {
            background: rgba(255, 255, 255, 0.08);
            border: 1px solid rgba(255, 255, 255, 0.15);
            border-radius: 8px;
            color: #ffffff;
            padding: 12px 15px;
            font-size: 0.95em;
            transition: all 0.3s ease;
        }
        
        .field-group .form-control:focus {
            outline: none;
            border-color: #4CAF50;
            box-shadow: 0 0 0 3px rgba(76, 175, 80, 0.2);
            background: rgba(255, 255, 255, 0.12);
        }
        
        .field-group .form-control::placeholder {
            color: rgba(255, 255, 255, 0.5);
            font-style: italic;
        }
        
        .field-group textarea.form-control {
            min-height: 80px;
            resize: vertical;
            font-family: inherit;
        }
        
        .field-status {
            margin-top: 5px;
            font-size: 0.8em;
            font-weight: 500;
        }
        
        .field-status.success {
            color: #4CAF50;
        }
        
        .field-status.error {
            color: #f44336;
        }
        
        .field-status.loading {
            color: #ff9800;
        }
        
        .resy-progress {
            margin-top: 20px;
        }
        
        .progress-bar {
            width: 100%;
            height: 8px;
            background: rgba(255, 255, 255, 0.1);
            border-radius: 4px;
            overflow: hidden;
        }
        
        .progress-fill {
            height: 100%;
            background: linear-gradient(90deg, #4CAF50, #8BC34A);
            width: 0%;
            transition: width 0.3s ease;
        }
        
        .progress-text {
            color: #ffffff;
            font-size: 0.9em;
            margin-top: 8px;
            text-align: center;
        }
        
        .tire-check-modal .modal-header {
            background: #2a2a2a;
            padding: 20px 30px;
            border-bottom: 1px solid #333;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .tire-check-modal .modal-header h3 {
            color: #fff;
            margin: 0;
            font-size: 1.5rem;
            font-weight: 600;
        }
        
        .tire-check-modal .btn-close {
            background: none;
            border: none;
            color: #999;
            font-size: 1.2rem;
            cursor: pointer;
            padding: 5px;
            border-radius: 50%;
            transition: all 0.2s;
        }
        
        .tire-check-modal .btn-close:hover {
            background: #333;
            color: #fff;
        }
        
        .tire-check-modal .modal-body {
            padding: 30px;
            max-height: calc(90vh - 140px);
            overflow-y: auto;
        }
        
        .customer-info {
            text-align: center;
            margin-bottom: 30px;
            padding-bottom: 20px;
            border-bottom: 1px solid #333;
        }
        
        .customer-info h4 {
            color: #fff;
            margin: 0 0 5px 0;
            font-size: 1.3rem;
        }
        
        .customer-info p {
            color: #999;
            margin: 0;
            font-size: 1rem;
        }
        
        .selection-info {
            margin-top: 10px;
            padding: 8px 12px;
            background: rgba(37, 99, 235, 0.1);
            border: 1px solid rgba(37, 99, 235, 0.3);
            border-radius: 8px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .selection-count {
            color: #2563eb;
            font-weight: 600;
            font-size: 0.9rem;
        }
        
        .selection-positions {
            color: #2563eb;
            font-size: 0.8rem;
            font-weight: 500;
        }
        
        .tire-check-container {
            display: flex;
            gap: 15px;
            justify-content: center;
            align-items: flex-start;
            flex-wrap: nowrap;
            padding: 20px;
            overflow-x: auto;
        }
        
        .tire-card {
            position: relative;
            width: 280px;
            background: #2a2a2a;
            border-radius: 15px;
            border: 1px solid #333;
            overflow: hidden;
            box-shadow: 0 10px 30px rgba(0,0,0,0.3);
            flex-shrink: 0;
            transition: all 0.3s ease;
            cursor: pointer;
        }
        
        .tire-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 15px 40px rgba(0,0,0,0.4);
        }
        
        .tire-card.selected {
            border: 2px solid #2563eb;
            box-shadow: 0 15px 40px rgba(37, 99, 235, 0.3);
            transform: translateY(-2px);
            background: linear-gradient(135deg, #2a2a2a 0%, #1a1a2e 100%);
        }
        
        .tire-card.selected::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: linear-gradient(135deg, rgba(37, 99, 235, 0.1) 0%, rgba(37, 99, 235, 0.05) 100%);
            border-radius: 15px;
            z-index: 1;
        }
        
        .tire-card.selected .tire-card-content {
            position: relative;
            z-index: 2;
        }
        
        /* Reifenstatus-Farbkodierung */
        .tire-card.tire-good {
            border-left: 4px solid #28a745;
            background: linear-gradient(135deg, #2a2a2a 0%, #1e3a1e 100%);
        }
        
        .tire-card.tire-warning {
            border-left: 4px solid #ffc107;
            background: linear-gradient(135deg, #2a2a2a 0%, #3a2a1e 100%);
        }
        
        .tire-card.tire-bad {
            border-left: 4px solid #dc3545;
            background: linear-gradient(135deg, #2a2a2a 0%, #3a1e1e 100%);
        }
        
        .tire-card.tire-good .tire-position {
            background: #28a745;
        }
        
        .tire-card.tire-warning .tire-position {
            background: #ffc107;
            color: #212529;
        }
        
        .tire-card.tire-bad .tire-position {
            background: #dc3545;
        }
        
        /* Tire Card Footer */
        .tire-card-footer {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 8px 12px;
            background: rgba(255, 255, 255, 0.05);
            border-top: 1px solid rgba(255, 255, 255, 0.1);
            border-radius: 0 0 15px 15px;
            margin-top: 10px;
        }
        
        .tire-status-badge {
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 11px;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }
        
        .tire-status-badge.status-success {
            background: #28a745;
            color: white;
        }
        
        .tire-status-badge.status-warning {
            background: #ffc107;
            color: #212529;
        }
        
        .tire-status-badge.status-danger {
            background: #dc3545;
            color: white;
        }
        
        /* Reifenbilder-Styles */
        .tire-images {
            margin-top: 15px;
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
            align-items: center;
        }
        
        .tire-image-placeholder {
            width: 60px;
            height: 60px;
            border: 2px dashed #ccc;
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
            background-color: #f8f9fa;
            text-align: center;
        }
        
        .placeholder-content {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            height: 100%;
            font-size: 10px;
        }
        
        .tire-image {
            width: 60px;
            height: 60px;
            object-fit: cover;
            border-radius: 8px;
            border: 2px solid #444;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        
        .tire-image:hover {
            transform: scale(1.1);
            border-color: #2563eb;
            box-shadow: 0 4px 12px rgba(37, 99, 235, 0.3);
        }
        
        .tire-more-images-btn {
            background: #6c757d;
            color: white;
            border: none;
            padding: 8px 12px;
            border-radius: 6px;
            font-size: 11px;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        
        .tire-more-images-btn:hover {
            background: #5a6268;
            transform: translateY(-1px);
        }
        
        /* Bild-Modal-Styles */
        .image-modal {
            display: none;
            position: fixed;
            z-index: 10000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.9);
            backdrop-filter: blur(5px);
        }
        
        .image-modal-content {
            position: relative;
            margin: 5% auto;
            padding: 20px;
            width: 90%;
            max-width: 800px;
            background: #2a2a2a;
            border-radius: 15px;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.5);
        }
        
        .image-modal-content img {
            width: 100%;
            height: auto;
            border-radius: 10px;
            max-height: 70vh;
            object-fit: contain;
        }
        
        .image-modal-close {
            position: absolute;
            top: 15px;
            right: 20px;
            color: #fff;
            font-size: 28px;
            font-weight: bold;
            cursor: pointer;
            z-index: 10001;
            background: rgba(0, 0, 0, 0.5);
            width: 40px;
            height: 40px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.3s ease;
        }
        
        .image-modal-close:hover {
            background: rgba(255, 0, 0, 0.7);
            transform: scale(1.1);
        }
        
        .image-modal-title {
            color: #fff;
            text-align: center;
            margin-top: 15px;
            font-size: 16px;
            font-weight: 600;
        }
        
        .all-images-modal {
            max-width: 1200px;
        }
        
        .all-images-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
            gap: 15px;
            margin-top: 20px;
        }
        
        .all-image-item {
            text-align: center;
        }
        
        .all-image-item img {
            width: 100%;
            height: 120px;
            object-fit: cover;
            border-radius: 8px;
            border: 2px solid #444;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        
        .all-image-item img:hover {
            transform: scale(1.05);
            border-color: #2563eb;
            box-shadow: 0 4px 12px rgba(37, 99, 235, 0.3);
        }
        
        .image-info {
            color: #ccc;
            font-size: 12px;
            margin-top: 5px;
        }
        
        .tire-card-checkbox {
            position: absolute;
            top: 15px;
            right: 15px;
            z-index: 10;
            pointer-events: none;
        }
        
        .tire-checkbox {
            display: none;
        }
        
        .checkbox-label {
            display: block;
            width: 28px;
            height: 28px;
            background: rgba(255, 255, 255, 0.1);
            border: 2px solid rgba(255, 255, 255, 0.3);
            border-radius: 6px;
            cursor: pointer;
            position: relative;
            transition: all 0.3s ease;
        }
        
        .checkbox-label:hover {
            background: rgba(255, 255, 255, 0.2);
            border-color: rgba(255, 255, 255, 0.5);
        }
        
        .tire-checkbox:checked + .checkbox-label {
            background: #2563eb;
            border-color: #2563eb;
        }
        
        .checkmark {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%) scale(0);
            width: 14px;
            height: 14px;
            transition: transform 0.2s ease;
        }
        
        .checkmark::before {
            content: '';
            position: absolute;
            top: 2px;
            left: 5px;
            width: 5px;
            height: 9px;
            border: solid white;
            border-width: 0 2px 2px 0;
            transform: rotate(45deg);
        }
        
        .tire-checkbox:checked + .checkbox-label .checkmark {
            transform: translate(-50%, -50%) scale(1);
        }
        
        .tire-card.selected .tire-card-content {
            opacity: 0.9;
        }
        
        .tire-card-content {
            padding: 20px;
        }
        
        .tire-header {
            display: flex;
            gap: 10px;
            margin-bottom: 15px;
            flex-wrap: wrap;
        }
        
        .tire-position {
            background: #666;
            color: #fff;
            padding: 6px 12px;
            border-radius: 12px;
            font-size: 1rem;
            font-weight: 600;
        }
        
        .tire-dot {
            background: #666;
            color: #fff;
            padding: 6px 12px;
            border-radius: 12px;
            font-size: 1rem;
            font-weight: 600;
        }
        
        .tire-type {
            color: #fff;
            font-size: 1.1rem;
            font-weight: 500;
        }
        
        .tire-info {
            margin-bottom: 10px;
        }
        
        .tire-spec {
            display: flex;
            justify-content: space-between;
            margin-bottom: 5px;
        }
        
        .tire-spec .label {
            color: #999;
            font-size: 1rem;
        }
        
        .tire-spec .value {
            color: #fff;
            font-weight: 600;
            font-size: 1rem;
        }
        
        .tire-visual {
            margin-bottom: 10px;
            display: flex;
            justify-content: center;
        }
        
        
        .tread-analysis {
            margin-bottom: 10px;
        }
        
        .analysis-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 10px;
        }
        
        .analysis-header h5 {
            color: #fff;
            margin: 0;
            font-size: 1.1rem;
            font-weight: 600;
        }
        
        .analysis-header i {
            color: #16a34a;
            font-size: 1rem;
        }
        
        .tread-bars {
            margin-bottom: 8px;
        }
        
        .tread-bar {
            display: flex;
            align-items: center;
            margin-bottom: 8px;
            gap: 10px;
        }
        
        .bar-fill {
            width: 50px;
            height: 10px;
            border-radius: 5px;
            position: relative;
        }
        
        .tread-bar.excellent .bar-fill {
            background: #16a34a;
        }
        
        .tread-bar.good .bar-fill {
            background: #2563eb;
        }
        
        .tread-bar.satisfactory .bar-fill {
            background: #f59e0b;
        }
        
        .bar-label {
            color: #fff;
            font-size: 1rem;
            font-weight: 600;
            min-width: 50px;
        }
        
        .bar-status {
            color: #16a34a;
            font-size: 0.75rem;
            font-weight: 500;
        }
        
        .position-indicator {
            background: #2563eb;
            color: #fff;
            padding: 2px 6px;
            border-radius: 8px;
            font-size: 0.7rem;
            font-weight: 600;
            margin-left: auto;
        }
        
        .position-label {
            color: #16a34a;
            font-size: 0.75rem;
            margin-left: 5px;
        }
        
        .tread-legend {
            margin-bottom: 8px;
        }
        
        .legend-item {
            display: flex;
            justify-content: space-between;
            margin-bottom: 3px;
        }
        
        .legend-item.excellent .legend-label,
        .legend-item.excellent .legend-value {
            color: #16a34a;
        }
        
        .legend-item.good .legend-label,
        .legend-item.good .legend-value {
            color: #999;
        }
        
        .legend-item.satisfactory .legend-label,
        .legend-item.satisfactory .legend-value {
            color: #999;
        }
        
        .legend-label,
        .legend-value {
            font-size: 0.9rem;
        }
        
        .tire-summary {
            border-top: 1px solid #333;
            padding-top: 10px;
        }
        
        .summary-item {
            display: flex;
            justify-content: space-between;
            margin-bottom: 5px;
        }
        
        .summary-label {
            color: #999;
            font-size: 1rem;
        }
        
        .summary-value {
            color: #fff;
            font-weight: 600;
            font-size: 1rem;
        }
        
        .summary-value.excellent {
            color: #16a34a;
        }
        
        /* Light Theme Styles for Tire Cards */
        body.light-theme .tire-check-modal {
            background: #ffffff;
        }
        
        body.light-theme .tire-check-modal .modal-header {
            background: #f8f9fa;
            border-bottom: 1px solid #dee2e6;
        }
        
        body.light-theme .tire-check-modal .modal-header h3 {
            color: #212529;
        }
        
        body.light-theme .tire-check-modal .btn-close {
            color: #6c757d;
        }
        
        body.light-theme .tire-check-modal .btn-close:hover {
            background: #e9ecef;
            color: #212529;
        }
        
        body.light-theme .customer-info {
            border-bottom: 1px solid #dee2e6;
        }
        
        body.light-theme .customer-info h4 {
            color: #212529;
        }
        
        body.light-theme .customer-info p {
            color: #495057;
        }
        
        body.light-theme .tire-card {
            background: #ffffff;
            border: 1px solid #dee2e6;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
        }
        
        /* Light Theme Reifenstatus-Farbkodierung */
        body.light-theme .tire-card.tire-good {
            border-left: 4px solid #28a745;
            background: linear-gradient(135deg, #ffffff 0%, #f8fff8 100%);
        }
        
        body.light-theme .tire-card.tire-warning {
            border-left: 4px solid #ffc107;
            background: linear-gradient(135deg, #ffffff 0%, #fffbf0 100%);
        }
        
        body.light-theme .tire-card.tire-bad {
            border-left: 4px solid #dc3545;
            background: linear-gradient(135deg, #ffffff 0%, #fff5f5 100%);
        }
        
        body.light-theme .tire-card.tire-good .tire-position {
            background: #28a745;
            color: white;
        }
        
        body.light-theme .tire-card.tire-warning .tire-position {
            background: #ffc107;
            color: #212529;
        }
        
        body.light-theme .tire-card.tire-bad .tire-position {
            background: #dc3545;
            color: white;
        }
        
        /* Light Theme Reifenbilder-Styles */
        body.light-theme .tire-image {
            border: 2px solid #dee2e6;
        }
        
        body.light-theme .tire-image:hover {
            border-color: #007bff;
        }
        
        body.light-theme .tire-more-images-btn {
            background: #6c757d;
            color: white;
        }
        
        body.light-theme .tire-more-images-btn:hover {
            background: #5a6268;
        }
        
        body.light-theme .image-modal-content {
            background: #ffffff;
        }
        
        body.light-theme .image-modal-title {
            color: #212529;
        }
        
        body.light-theme .all-image-item img {
            border: 2px solid #dee2e6;
        }
        
        body.light-theme .all-image-item img:hover {
            border-color: #007bff;
        }
        
        body.light-theme .image-info {
            color: #6c757d;
        }
        
        body.light-theme .tire-position {
            background: #6c757d;
            color: #fff;
        }
        
        body.light-theme .tire-dot {
            background: #6c757d;
            color: #fff;
        }
        
        body.light-theme .tire-type {
            color: #212529;
        }
        
        body.light-theme .tire-spec .label {
            color: #6c757d;
        }
        
        body.light-theme .tire-spec .value {
            color: #212529;
        }
        
        body.light-theme .analysis-header h5 {
            color: #212529;
        }
        
        body.light-theme .bar-label {
            color: #212529;
        }
        
        body.light-theme .legend-item.excellent .legend-label,
        body.light-theme .legend-item.excellent .legend-value {
            color: #16a34a;
        }
        
        body.light-theme .legend-item.good .legend-label,
        body.light-theme .legend-item.good .legend-value {
            color: #6c757d;
        }
        
        body.light-theme .legend-item.satisfactory .legend-label,
        body.light-theme .legend-item.satisfactory .legend-value {
            color: #6c757d;
        }
        
        body.light-theme .tire-summary {
            border-top: 1px solid #dee2e6;
        }
        
        body.light-theme .summary-label {
            color: #6c757d;
        }
        
        body.light-theme .summary-value {
            color: #212529;
        }
        
        body.light-theme .summary-value.excellent {
            color: #16a34a;
        }
        
        /* RESY-loaded tire styling */
        .tire-card.resy-loaded {
            border: 2px solid #16a34a;
            box-shadow: 0 0 10px rgba(22, 163, 74, 0.3);
        }
        
        .tire-card.resy-loaded .tire-position {
            background: #16a34a;
        }
        
        .resy-badge {
            background: #16a34a;
            color: white;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 0.75rem;
            font-weight: 600;
            white-space: nowrap;
        }
        
        body.light-theme .tire-check-modal .modal-footer {
            background: #f8f9fa;
            border-top: 1px solid #dee2e6;
        }
        
        body.light-theme .tire-check-modal .btn-secondary {
            background: #6c757d;
            color: white;
        }
        
        /* Light Theme RESY Data Section */
        body.light-theme .resy-data-section {
            background: #f8f9fa;
            border: 1px solid #dee2e6;
        }
        
        body.light-theme .resy-header h4 {
            color: #212529;
        }
        
        body.light-theme .resy-header h4 i {
            color: #28a745;
        }
        
        body.light-theme .field-group {
            background: #ffffff;
            border: 1px solid #dee2e6;
        }
        
        body.light-theme .field-group:hover {
            background: #f8f9fa;
            border-color: #adb5bd;
        }
        
        body.light-theme .field-group label {
            color: #212529;
        }
        
        body.light-theme .field-group label i {
            color: #28a745;
        }
        
        body.light-theme .field-group .form-control {
            background: #ffffff;
            border: 1px solid #ced4da;
            color: #212529;
        }
        
        body.light-theme .field-group .form-control:focus {
            border-color: #28a745;
            box-shadow: 0 0 0 3px rgba(40, 167, 69, 0.2);
            background: #ffffff;
        }
        
        body.light-theme .field-group .form-control::placeholder {
            color: #6c757d;
        }
        
        body.light-theme .field-status.success {
            color: #28a745;
        }
        
        body.light-theme .field-status.error {
            color: #dc3545;
        }
        
        body.light-theme .field-status.loading {
            color: #ffc107;
        }
        
        body.light-theme .progress-bar {
            background: #e9ecef;
        }
        
        body.light-theme .progress-fill {
            background: linear-gradient(90deg, #28a745, #20c997);
        }
        
        body.light-theme .progress-text {
            color: #212529;
        }
        
        body.light-theme .resy-controls .btn {
            background: #28a745;
            color: white;
            border: none;
        }
        
        body.light-theme .resy-controls .btn:hover {
            background: #218838;
        }
        
        body.light-theme .resy-controls .btn-danger {
            background: #dc3545;
        }
        
        body.light-theme .resy-controls .btn-danger:hover {
            background: #c82333;
        }
        
        /* Tire Type Image Styles */
        .tire-image-container {
            display: flex;
            justify-content: center;
            align-items: center;
            height: 120px;
            background: transparent;
            border-radius: 12px;
            margin: 10px 0;
        }
        
        .tire-type-image {
            max-width: 100px;
            max-height: 100px;
            object-fit: contain;
            filter: drop-shadow(0 4px 8px rgba(0,0,0,0.2));
            transition: all 0.3s ease;
        }
        
        .tire-type-image:hover {
            transform: scale(1.05);
            filter: drop-shadow(0 6px 12px rgba(0,0,0,0.3));
        }
        
        /* Light Theme Reifenbilder */
        body.light-theme .tire-image-container {
            background: transparent;
        }
        
        /* Tire Condition Info Styles */
        .tire-condition-info {
            margin: 20px;
            padding: 20px;
            background: rgba(255, 255, 255, 0.05);
            border-radius: 15px;
            border: 1px solid rgba(255, 255, 255, 0.1);
        }
        
        .tire-condition-info h4 {
            color: #ffffff;
            margin: 0 0 15px 0;
            font-size: 1.1em;
            font-weight: 600;
        }
        
        .condition-legend {
            display: flex;
            gap: 20px;
            flex-wrap: wrap;
        }
        
        .condition-item {
            display: flex;
            align-items: center;
            gap: 8px;
            padding: 8px 12px;
            background: rgba(255, 255, 255, 0.03);
            border-radius: 8px;
            border: 1px solid rgba(255, 255, 255, 0.08);
        }
        
        .condition-color {
            width: 12px;
            height: 12px;
            border-radius: 50%;
        }
        
        .condition-excellent .condition-color {
            background: #28a745; /* Grün für "Keine Fehler" */
        }
        
        .condition-good .condition-color {
            background: #ffc107; /* Gelb für "Leichte Fehler" */
        }
        
        .condition-satisfactory .condition-color {
            background: #dc3545; /* Rot für "Austausch notwendig" */
        }
        
        .condition-label {
            color: #ffffff;
            font-weight: 500;
            font-size: 0.9em;
        }
        
        .condition-value {
            color: rgba(255, 255, 255, 0.7);
            font-size: 0.85em;
        }
        
        /* Light Theme Zustandsinfo */
        body.light-theme .tire-condition-info {
            background: #f8f9fa;
            border: 1px solid #dee2e6;
        }
        
        body.light-theme .tire-condition-info h4 {
            color: #212529;
        }
        
        body.light-theme .condition-item {
            background: #ffffff;
            border: 1px solid #dee2e6;
        }
        
        body.light-theme .condition-label {
            color: #212529;
        }
        
        body.light-theme .condition-value {
            color: #6c757d;
        }
        
        /* Light Theme Tire Card Footer */
        body.light-theme .tire-card-footer {
            background: #f8f9fa;
            border-top: 1px solid #dee2e6;
        }
        
        body.light-theme .tire-check-modal .btn-secondary:hover {
            background: #5a6268;
        }
        
        body.light-theme .tire-check-modal .btn-primary {
            background: #007bff;
            color: #fff;
        }
        
        body.light-theme .tire-check-modal .btn-primary:hover {
            background: #0056b3;
        }
        
        body.light-theme .tire-card:hover {
            box-shadow: 0 15px 40px rgba(0,0,0,0.15);
        }
        
        body.light-theme .tire-card.selected {
            border: 2px solid #007bff;
            box-shadow: 0 15px 40px rgba(0, 123, 255, 0.3);
        }
        
        body.light-theme .checkbox-label {
            background: rgba(0, 0, 0, 0.05);
            border: 2px solid rgba(0, 0, 0, 0.2);
        }
        
        body.light-theme .checkbox-label:hover {
            background: rgba(0, 0, 0, 0.1);
            border-color: rgba(0, 0, 0, 0.3);
        }
        
        body.light-theme .tire-checkbox:checked + .checkbox-label {
            background: #007bff;
            border-color: #007bff;
        }
        
        body.light-theme .selection-info {
            background: rgba(0, 123, 255, 0.1);
            border: 1px solid rgba(0, 123, 255, 0.3);
        }
        
        body.light-theme .selection-count,
        body.light-theme .selection-positions {
            color: #007bff;
        }
        
        
        .tire-check-modal .modal-footer {
            background: #2a2a2a;
            padding: 20px 30px;
            border-top: 1px solid #333;
            display: flex;
            justify-content: flex-end;
            gap: 15px;
        }
        
        .tire-check-modal .btn {
            padding: 10px 20px;
            border-radius: 8px;
            border: none;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.2s;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        
        .tire-check-modal .btn-secondary {
            background: #333;
            color: #fff;
        }
        
        .tire-check-modal .btn-secondary:hover {
            background: #444;
        }
        
        .tire-check-modal .btn-primary {
            background: #2563eb;
            color: #fff;
        }
        
        .tire-check-modal .btn-primary:hover {
            background: #1d4ed8;
        }

        /* Tire Offer Modal Styles */
        .tire-offer-modal {
            background: #1a1a1a;
            border-radius: 20px;
            width: 95vw;
            max-width: 1200px;
            max-height: 90vh;
            margin: 5vh auto;
            box-shadow: 0 25px 50px rgba(0,0,0,0.5);
            overflow: hidden;
            position: relative;
        }

        .tire-offer-modal .modal-header {
            background: #2a2a2a;
            padding: 20px 30px;
            border-bottom: 1px solid #333;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .tire-offer-modal .modal-header h3 {
            color: #fff;
            margin: 0;
            font-size: 1.5rem;
            font-weight: 600;
        }

        .tire-offer-modal .modal-body {
            padding: 30px;
            max-height: calc(90vh - 140px);
            overflow-y: auto;
        }

        .offer-content {
            display: flex;
            flex-direction: column;
            gap: 30px;
        }

        .selected-tires-summary,
        .new-tires-section,
        .additional-services-section {
            background: #2a2a2a;
            border-radius: 12px;
            padding: 20px;
            border: 1px solid #333;
        }

        .section-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }

        .section-header h4 {
            color: #fff;
            margin: 0;
            font-size: 1.2rem;
            font-weight: 600;
        }

        .selected-tires-list,
        .new-tires-list,
        .additional-services-list {
            display: flex;
            flex-direction: column;
            gap: 15px;
        }

        .selected-tire-item,
        .new-tire-item,
        .service-item {
            background: #333;
            border-radius: 8px;
            padding: 15px;
            border: 1px solid #444;
        }

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

        .tire-info {
            color: #fff;
        }

        .tire-position {
            font-weight: 600;
            color: #60a5fa;
        }

        .tire-status {
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 0.8rem;
            font-weight: 600;
        }

        .tire-status.danger {
            background: #dc2626;
            color: #fff;
        }

        .tire-status.warning {
            background: #d97706;
            color: #fff;
        }

        .new-tire-form {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 15px;
            margin-bottom: 15px;
        }

        .form-group {
            display: flex;
            flex-direction: column;
        }

        .form-group label {
            color: #fff;
            margin-bottom: 5px;
            font-size: 0.9rem;
            font-weight: 500;
        }

        .form-group input,
        .form-group select {
            background: #444;
            border: 1px solid #555;
            border-radius: 6px;
            padding: 8px 12px;
            color: #fff;
            font-size: 0.9rem;
        }

        .form-group input:focus,
        .form-group select:focus {
            outline: none;
            border-color: #60a5fa;
            box-shadow: 0 0 0 2px rgba(96, 165, 250, 0.2);
        }

        .form-group.full-width {
            grid-column: 1 / -1;
        }

        .suggestion-container {
            position: relative;
        }

        .suggestions-dropdown {
            position: absolute;
            top: 100%;
            left: 0;
            right: 0;
            background: #444;
            border: 1px solid #555;
            border-radius: 6px;
            max-height: 200px;
            overflow-y: auto;
            z-index: 1000;
            box-shadow: 0 4px 12px rgba(0,0,0,0.3);
        }

        .suggestion-item {
            padding: 8px 12px;
            cursor: pointer;
            border-bottom: 1px solid #555;
            color: #fff;
            font-size: 0.9rem;
        }

        .suggestion-item:hover {
            background: #555;
        }

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

        .suggestion-brand {
            font-weight: 600;
            color: #60a5fa;
        }

        .suggestion-details {
            font-size: 0.8rem;
            color: #999;
            margin-top: 2px;
        }

        .tire-actions {
            display: flex;
            gap: 10px;
            margin-top: 10px;
        }

        .btn-sm {
            padding: 6px 12px;
            font-size: 0.8rem;
        }

        .btn-danger {
            background: #dc2626;
            color: #fff;
        }

        .btn-danger:hover {
            background: #b91c1c;
        }

        .service-checkbox {
            display: flex;
            align-items: center;
            gap: 10px;
            padding: 10px;
            background: #333;
            border-radius: 6px;
            cursor: pointer;
            transition: background-color 0.2s;
        }

        .service-checkbox:hover {
            background: #444;
        }

        .service-checkbox input[type="checkbox"] {
            margin: 0;
        }

        .service-info {
            flex: 1;
        }

        .service-name {
            color: #fff;
            font-weight: 500;
        }

        .service-description {
            color: #999;
            font-size: 0.8rem;
            margin-top: 2px;
        }

        .service-price {
            color: #60a5fa;
            font-weight: 600;
        }

        /* Offer Letter Modal Styles */
        .offer-letter-modal {
            background: #1a1a1a;
            border-radius: 20px;
            width: 95vw;
            max-width: 1400px;
            max-height: 90vh;
            margin: 5vh auto;
            box-shadow: 0 25px 50px rgba(0,0,0,0.5);
            overflow: hidden;
            position: relative;
        }

        .offer-letter-modal .modal-header {
            background: #2a2a2a;
            padding: 20px 30px;
            border-bottom: 1px solid #333;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .offer-letter-modal .modal-header h3 {
            color: #fff;
            margin: 0;
            font-size: 1.5rem;
            font-weight: 600;
        }

        .offer-letter-modal .modal-body {
            padding: 30px;
            max-height: calc(90vh - 140px);
            overflow-y: auto;
        }

        .offer-letter-content {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 30px;
            height: calc(90vh - 200px);
        }

        .letter-editor,
        .letter-preview {
            background: #2a2a2a;
            border-radius: 12px;
            padding: 20px;
            border: 1px solid #333;
            display: flex;
            flex-direction: column;
        }

        .editor-header,
        .preview-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
        }

        .editor-header h4,
        .preview-header h4 {
            color: #fff;
            margin: 0;
            font-size: 1.1rem;
            font-weight: 600;
        }


        .editor-toolbar {
            display: flex;
            align-items: center;
            gap: 5px;
            padding: 10px;
            background: #333;
            border: 1px solid #555;
            border-bottom: none;
            border-radius: 8px 8px 0 0;
            flex-wrap: wrap;
        }

        .toolbar-btn {
            background: #444;
            border: 1px solid #555;
            color: #fff;
            padding: 6px 8px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 0.8rem;
            transition: all 0.2s ease;
            min-width: 32px;
            height: 32px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .toolbar-btn:hover {
            background: #555;
            border-color: #666;
        }

        .toolbar-btn:active {
            background: #666;
        }

        .toolbar-separator {
            width: 1px;
            height: 20px;
            background: #555;
            margin: 0 5px;
        }

        .letter-editor-content {
            flex: 1;
            background: #333;
            border: 1px solid #555;
            border-radius: 0 0 8px 8px;
            padding: 15px;
            color: #fff;
            font-family: 'Times New Roman', serif;
            font-size: 0.9rem;
            line-height: 1.6;
            min-height: 300px;
            overflow-y: auto;
            outline: none;
        }

        .letter-editor-content:focus {
            border-color: #60a5fa;
            box-shadow: 0 0 0 2px rgba(96, 165, 250, 0.2);
        }

        .letter-editor-content[contenteditable="true"]:empty:before {
            content: attr(placeholder);
            color: #999;
            font-style: italic;
        }

        .letter-textarea {
            flex: 1;
            background: #333;
            border: 1px solid #555;
            border-radius: 8px;
            padding: 15px;
            color: #fff;
            font-family: 'Courier New', monospace;
            font-size: 0.9rem;
            line-height: 1.5;
            resize: none;
        }

        .letter-textarea:focus {
            outline: none;
            border-color: #60a5fa;
            box-shadow: 0 0 0 2px rgba(96, 165, 250, 0.2);
        }

        .letter-preview-content {
            flex: 1;
            background: #fff;
            border-radius: 8px;
            padding: 20px;
            overflow-y: auto;
            font-family: 'Times New Roman', serif;
            font-size: 0.9rem;
            line-height: 1.6;
            color: #333;
        }

        .letter-preview-content h1,
        .letter-preview-content h2,
        .letter-preview-content h3 {
            color: #333;
            margin-top: 0;
        }

        .letter-preview-content p {
            margin-bottom: 10px;
        }

        .letter-preview-content .placeholder {
            background: #f0f0f0;
            padding: 2px 4px;
            border-radius: 3px;
            color: #666;
            font-style: italic;
        }

        /* Light Theme Styles for New Modals */
        body.light-theme .tire-offer-modal {
            background: #ffffff;
        }

        body.light-theme .tire-offer-modal .modal-header {
            background: #f8f9fa;
            border-bottom: 1px solid #dee2e6;
        }

        body.light-theme .tire-offer-modal .modal-header h3 {
            color: #212529;
        }

        body.light-theme .selected-tires-summary,
        body.light-theme .new-tires-section,
        body.light-theme .additional-services-section {
            background: #f8f9fa;
            border: 1px solid #dee2e6;
        }

        body.light-theme .section-header h4 {
            color: #212529;
        }

        body.light-theme .selected-tire-item,
        body.light-theme .new-tire-item,
        body.light-theme .service-item {
            background: #ffffff;
            border: 1px solid #dee2e6;
        }

        body.light-theme .tire-info {
            color: #212529;
        }

        body.light-theme .form-group label {
            color: #212529;
        }

        body.light-theme .form-group input,
        body.light-theme .form-group select {
            background: #ffffff;
            border: 1px solid #ced4da;
            color: #212529;
        }

        body.light-theme .form-group input:focus,
        body.light-theme .form-group select:focus {
            border-color: #007bff;
            box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.2);
        }

        body.light-theme .suggestions-dropdown {
            background: #ffffff;
            border: 1px solid #ced4da;
        }

        body.light-theme .suggestion-item {
            color: #212529;
            border-bottom: 1px solid #dee2e6;
        }

        body.light-theme .suggestion-item:hover {
            background: #f8f9fa;
        }

        body.light-theme .suggestion-brand {
            color: #007bff;
        }

        body.light-theme .suggestion-details {
            color: #6c757d;
        }

        body.light-theme .service-checkbox {
            background: #ffffff;
            border: 1px solid #dee2e6;
        }

        body.light-theme .service-checkbox:hover {
            background: #f8f9fa;
        }

        body.light-theme .service-name {
            color: #212529;
        }

        body.light-theme .service-description {
            color: #6c757d;
        }

        body.light-theme .offer-letter-modal {
            background: #ffffff;
        }

        body.light-theme .offer-letter-modal .modal-header {
            background: #f8f9fa;
            border-bottom: 1px solid #dee2e6;
        }

        body.light-theme .offer-letter-modal .modal-header h3 {
            color: #212529;
        }

        body.light-theme .letter-editor,
        body.light-theme .letter-preview {
            background: #f8f9fa;
            border: 1px solid #dee2e6;
        }

        body.light-theme .editor-header h4,
        body.light-theme .preview-header h4 {
            color: #212529;
        }


        body.light-theme .editor-toolbar {
            background: #f8f9fa;
            border: 1px solid #dee2e6;
        }

        body.light-theme .toolbar-btn {
            background: #ffffff;
            border: 1px solid #ced4da;
            color: #212529;
        }

        body.light-theme .toolbar-btn:hover {
            background: #e9ecef;
            border-color: #adb5bd;
        }

        body.light-theme .toolbar-btn:active {
            background: #dee2e6;
        }

        body.light-theme .toolbar-separator {
            background: #ced4da;
        }

        body.light-theme .letter-editor-content {
            background: #ffffff;
            border: 1px solid #ced4da;
            color: #212529;
        }

        body.light-theme .letter-editor-content:focus {
            border-color: #007bff;
            box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.2);
        }

        body.light-theme .letter-editor-content[contenteditable="true"]:empty:before {
            color: #6c757d;
        }

        body.light-theme .letter-textarea {
            background: #ffffff;
            border: 1px solid #ced4da;
            color: #212529;
        }

        body.light-theme .letter-textarea:focus {
            border-color: #007bff;
            box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.2);
        }

        body.light-theme .letter-preview-content {
            background: #ffffff;
            color: #212529;
        }

        body.light-theme .letter-preview-content h1,
        body.light-theme .letter-preview-content h2,
        body.light-theme .letter-preview-content h3 {
            color: #212529;
        }

        body.light-theme .letter-preview-content .placeholder {
            background: #e9ecef;
            color: #6c757d;
        }

        /* Improved Close Button Design */
        .modal-header .btn-close {
            background: #dc2626 !important;
            border: none !important;
            color: #fff !important;
            font-size: 1rem !important;
            cursor: pointer !important;
            padding: 8px !important;
            border-radius: 50% !important;
            width: 36px !important;
            height: 36px !important;
            display: flex !important;
            align-items: center !important;
            justify-content: center !important;
            transition: all 0.2s ease !important;
            box-shadow: 0 2px 4px rgba(0,0,0,0.2) !important;
        }

        .modal-header .btn-close:hover {
            background: #b91c1c !important;
            transform: scale(1.05) !important;
            box-shadow: 0 4px 8px rgba(0,0,0,0.3) !important;
        }

        body.light-theme .modal-header .btn-close {
            background: #dc2626 !important;
            color: #fff !important;
        }

        body.light-theme .modal-header .btn-close:hover {
            background: #b91c1c !important;
        }
        
        /* Responsive Design */
        @media (max-width: 1400px) {
            .tire-card {
                width: 260px;
            }
            
            .tire-check-container {
                gap: 12px;
            }
        }
        
        @media (max-width: 1200px) {
            .tire-card {
                width: 240px;
            }
            
            .tire-check-container {
                gap: 10px;
            }
        }
        
        @media (max-width: 1000px) {
            .tire-card {
                width: 220px;
            }
            
            .tire-check-container {
                gap: 8px;
            }
        }
        
        @media (max-width: 768px) {
            .tire-check-modal {
                width: 98vw;
                height: 95vh;
            }
            
            .tire-check-container {
                flex-direction: row;
                gap: 8px;
                padding: 10px;
                overflow-x: auto;
            }
            
            .tire-card {
                width: 200px;
                min-width: 200px;
            }
        }
        
        @media (max-width: 480px) {
            .tire-check-container {
                padding: 10px;
                gap: 10px;
            }
            
            .tire-card {
                width: 100%;
            }
        }
    </style>
    
    <!-- Tire Check Modal -->
    <div id="tireCheckModal" class="modal-backdrop hidden">
        <div class="tire-check-modal">
            <div class="modal-header">
                <h3>Reifenprüfung</h3>
                <button class="btn-close" onclick="closeTireCheckModal()">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            
            <div class="modal-body">
                <div class="customer-info">
                    <h4 id="tireCheckCustomerName"></h4>
                    <p id="tireCheckLicensePlate"></p>
                    <div class="selection-info" id="selectionInfo" style="display: none;">
                        <span class="selection-count">0 Reifen ausgewählt</span>
                        <span class="selection-positions"></span>
                    </div>
                </div>
                
                <!-- RESY Datenauslese Bereich -->
                <div class="resy-data-section">
                    <div class="resy-header">
                        <h4><i class="fas fa-database"></i> RESY Datenauslese</h4>
                        <div class="resy-controls">
                            <button class="btn btn-success btn-sm" onclick="startResyDataExtraction()" id="resyExtractBtn">
                                <i class="fas fa-download"></i> Daten laden
                            </button>
                            <button class="btn btn-secondary btn-sm" onclick="clearResyData()" id="resyClearBtn">
                                <i class="fas fa-trash"></i> Löschen
                            </button>
                        </div>
                    </div>
                    
                    <div class="resy-fields" id="resyFields">
                        <div class="fields-grid">
                            <div class="field-group">
                                <label><i class="fas fa-user"></i> Fahrzeughalter:</label>
                                <input type="text" id="fahrzeughalter" class="form-control" readonly placeholder="Wird automatisch ausgefüllt">
                                <span class="field-status" id="fahrzeughalter-status"></span>
                            </div>
                            
                            <div class="field-group">
                                <label><i class="fas fa-car"></i> Kennzeichen:</label>
                                <input type="text" id="kennzeichen" class="form-control" readonly placeholder="Wird automatisch ausgefüllt">
                                <span class="field-status" id="kennzeichen-status"></span>
                            </div>
                            
                            <div class="field-group">
                                <label><i class="fas fa-barcode"></i> FIN:</label>
                                <input type="text" id="fin" class="form-control" readonly placeholder="Wird automatisch ausgefüllt">
                                <span class="field-status" id="fin-status"></span>
                            </div>
                            
                            <div class="field-group">
                                <label><i class="fas fa-hashtag"></i> Eingangsnummer:</label>
                                <input type="text" id="eingangsnummer" class="form-control" readonly placeholder="Wird automatisch ausgefüllt">
                                <span class="field-status" id="eingangsnummer-status"></span>
                            </div>
                            
                            <div class="field-group">
                                <label><i class="fas fa-warehouse"></i> Ladestelle:</label>
                                <input type="text" id="ladestelle" class="form-control" readonly placeholder="Wird automatisch ausgefüllt">
                                <span class="field-status" id="ladestelle-status"></span>
                            </div>
                            
                            <div class="field-group">
                                <label><i class="fas fa-calendar-alt"></i> Rücklieferungsdatum:</label>
                                <input type="text" id="ruecklieferungsdatum" class="form-control" readonly placeholder="Wird automatisch ausgefüllt">
                                <span class="field-status" id="ruecklieferungsdatum-status"></span>
                            </div>
                        </div>
                        
                        <div class="fields-fullwidth">
                            <div class="field-group">
                                <label><i class="fas fa-comment"></i> Bemerkung:</label>
                                <textarea id="bemerkung" class="form-control" readonly placeholder="Wird automatisch ausgefüllt"></textarea>
                                <span class="field-status" id="bemerkung-status"></span>
                            </div>
                            
                            <div class="field-group">
                                <label><i class="fas fa-reply"></i> Rückgabe Bemerkung:</label>
                                <textarea id="rueckgabe_bemerkung" class="form-control" readonly placeholder="Wird automatisch ausgefüllt"></textarea>
                                <span class="field-status" id="rueckgabe_bemerkung-status"></span>
                            </div>
                        </div>
                    </div>
                    
                    <div class="resy-progress" id="resyProgress" style="display: none;">
                        <div class="progress-bar">
                            <div class="progress-fill" id="progressFill"></div>
                        </div>
                        <div class="progress-text" id="progressText">Initialisierung...</div>
                    </div>
                </div>
                
                <div class="tire-check-container">
                    <!-- Tire Cards arranged horizontally -->
                    <div class="tire-card tire-front-left" data-position="VL" onclick="toggleTireCard('VL')">
                        <div class="tire-card-checkbox">
                            <input type="checkbox" id="tire-vl" class="tire-checkbox">
                            <label for="tire-vl" class="checkbox-label">
                                <span class="checkmark"></span>
                            </label>
                        </div>
                        <div class="tire-card-content">
                             <div class="tire-header">
                                 <span class="tire-position">VL</span>
                                 <span class="tire-type">Winterreifen</span>
                             </div>
                            
                            <div class="tire-info">
                                <div class="tire-spec">
                                    <span class="label">Marke:</span>
                                    <span class="value tire-brand">Michelin</span>
                                </div>
                                <div class="tire-spec">
                                    <span class="label">Modell:</span>
                                    <span class="value tire-model">Pilot Alpin 5 SUV</span>
                                </div>
                                <div class="tire-spec">
                                    <span class="label">Größe:</span>
                                    <span class="value tire-size">235/55R19</span>
                                </div>
                                <div class="tire-spec">
                                    <span class="label">DOT:</span>
                                    <span class="value tire-dot">2722</span>
                                </div>
                            </div>
                            
                             <div class="tire-visual">
                                 <div class="tire-image-container">
                                     <img src="../assets/images/winterreifen.png" alt="Winterreifen" class="tire-type-image" data-tire-type="winter">
                                 </div>
                             </div>
                            
                            <div class="tread-analysis">
                                <div class="analysis-header">
                                    <h5>Profiltiefe-Analyse</h5>
                                    <i class="fas fa-check-circle"></i>
                                </div>
                                
                                <div class="tread-bars">
                                    <div class="tread-bar excellent">
                                        <div class="bar-fill"></div>
                                        <span class="bar-label tire-profile-inner">6.0 mm</span>
                                        <span class="bar-status">Ausgezeichnet</span>
                                    </div>
                                    <div class="tread-bar good">
                                        <div class="bar-fill"></div>
                                        <span class="bar-label tire-profile-middle">4.7 mm</span>
                                    </div>
                                    <div class="tread-bar excellent">
                                        <div class="bar-fill"></div>
                                        <span class="bar-label tire-profile-outer">5.8 mm</span>
                                        <span class="position-indicator">A</span>
                                        <span class="position-label">Außen</span>
                                    </div>
                                </div>
                                
                            </div>
                            
                            <div class="tire-summary">
                                <div class="summary-item">
                                    <span class="summary-label">Zustand:</span>
                                    <span class="summary-value excellent tire-recommendation">Sehr gut</span>
                                </div>
                            </div>
                            
                            <!-- Tire Card Footer für Badges -->
                            <div class="tire-card-footer">
                                <div class="tire-status-badge status-success">Sehr gut</div>
                                <div class="resy-badge">✓ RESY</div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="tire-card tire-front-right" data-position="VR" onclick="toggleTireCard('VR')">
                        <div class="tire-card-checkbox">
                            <input type="checkbox" id="tire-vr" class="tire-checkbox">
                            <label for="tire-vr" class="checkbox-label">
                                <span class="checkmark"></span>
                            </label>
                        </div>
                        <div class="tire-card-content">
                             <div class="tire-header">
                                 <span class="tire-position">VR</span>
                                 <span class="tire-type">Winterreifen</span>
                             </div>
                            
                            <div class="tire-info">
                                <div class="tire-spec">
                                    <span class="label">Marke:</span>
                                    <span class="value tire-brand">Michelin</span>
                                </div>
                                <div class="tire-spec">
                                    <span class="label">Modell:</span>
                                    <span class="value tire-model">Pilot Alpin 5 SUV</span>
                                </div>
                                <div class="tire-spec">
                                    <span class="label">Größe:</span>
                                    <span class="value tire-size">235/55R19</span>
                                </div>
                                <div class="tire-spec">
                                    <span class="label">DOT:</span>
                                    <span class="value tire-dot">2722</span>
                                </div>
                            </div>
                            
                            <div class="tire-visual">
                                <div class="tire-image-container">
                                    <img src="../assets/images/winterreifen.png" alt="Winterreifen" class="tire-type-image" data-tire-type="winter">
                                </div>
                            </div>
                            
                            <div class="tread-analysis">
                                <div class="analysis-header">
                                    <h5>Profiltiefe-Analyse</h5>
                                    <i class="fas fa-check-circle"></i>
                                </div>
                                
                                <div class="tread-bars">
                                    <div class="tread-bar excellent">
                                        <div class="bar-fill"></div>
                                        <span class="bar-label tire-profile-outer">5.8 mm</span>
                                        <span class="bar-status">Ausgezeichnet</span>
                                    </div>
                                    <div class="tread-bar good">
                                        <div class="bar-fill"></div>
                                        <span class="bar-label tire-profile-middle">4.2 mm</span>
                                    </div>
                                    <div class="tread-bar excellent">
                                        <div class="bar-fill"></div>
                                        <span class="bar-label tire-profile-outer">5.5 mm</span>
                                        <span class="position-indicator">A</span>
                                        <span class="position-label">Außen</span>
                                    </div>
                                </div>
                                
                            </div>
                            
                            <div class="tire-summary">
                                <div class="summary-item">
                                    <span class="summary-label">Zustand:</span>
                                    <span class="summary-value excellent tire-recommendation">Sehr gut</span>
                                </div>
                            </div>
                            
                            <!-- Tire Card Footer für Badges -->
                            <div class="tire-card-footer">
                                <div class="tire-status-badge status-success">Sehr gut</div>
                                <div class="resy-badge">✓ RESY</div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="tire-card tire-rear-left" data-position="HL" onclick="toggleTireCard('HL')">
                        <div class="tire-card-checkbox">
                            <input type="checkbox" id="tire-hl" class="tire-checkbox">
                            <label for="tire-hl" class="checkbox-label">
                                <span class="checkmark"></span>
                            </label>
                        </div>
                        <div class="tire-card-content">
                             <div class="tire-header">
                                 <span class="tire-position">HL</span>
                                 <span class="tire-type">Winterreifen</span>
                             </div>
                            
                            <div class="tire-info">
                                <div class="tire-spec">
                                    <span class="label">Marke:</span>
                                    <span class="value tire-brand">Michelin</span>
                                </div>
                                <div class="tire-spec">
                                    <span class="label">Modell:</span>
                                    <span class="value tire-model">Pilot Alpin 5 SUV</span>
                                </div>
                                <div class="tire-spec">
                                    <span class="label">Größe:</span>
                                    <span class="value tire-size">235/55R19</span>
                                </div>
                                <div class="tire-spec">
                                    <span class="label">DOT:</span>
                                    <span class="value tire-dot">2722</span>
                                </div>
                            </div>
                            
                             <div class="tire-visual">
                                 <div class="tire-image-container">
                                     <img src="../assets/images/winterreifen.png" alt="Winterreifen" class="tire-type-image" data-tire-type="winter">
                                 </div>
                             </div>
                            
                            <div class="tread-analysis">
                                <div class="analysis-header">
                                    <h5>Profiltiefe-Analyse</h5>
                                    <i class="fas fa-check-circle"></i>
                                </div>
                                
                                <div class="tread-bars">
                                    <div class="tread-bar excellent">
                                        <div class="bar-fill"></div>
                                        <span class="bar-label tire-profile-inner">6.2 mm</span>
                                        <span class="bar-status">Ausgezeichnet</span>
                                    </div>
                                    <div class="tread-bar good">
                                        <div class="bar-fill"></div>
                                        <span class="bar-label tire-profile-middle">4.8 mm</span>
                                    </div>
                                    <div class="tread-bar excellent">
                                        <div class="bar-fill"></div>
                                        <span class="bar-label tire-profile-outer">5.9 mm</span>
                                        <span class="position-indicator">A</span>
                                        <span class="position-label">Außen</span>
                                    </div>
                                </div>
                                
                            </div>
                            
                            <div class="tire-summary">
                                <div class="summary-item">
                                    <span class="summary-label">Zustand:</span>
                                    <span class="summary-value excellent tire-recommendation">Sehr gut</span>
                                </div>
                            </div>
                            
                            <!-- Tire Card Footer für Badges -->
                            <div class="tire-card-footer">
                                <div class="tire-status-badge status-success">Sehr gut</div>
                                <div class="resy-badge">✓ RESY</div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="tire-card tire-rear-right" data-position="HR" onclick="toggleTireCard('HR')">
                        <div class="tire-card-checkbox">
                            <input type="checkbox" id="tire-hr" class="tire-checkbox">
                            <label for="tire-hr" class="checkbox-label">
                                <span class="checkmark"></span>
                            </label>
                        </div>
                        <div class="tire-card-content">
                             <div class="tire-header">
                                 <span class="tire-position">HR</span>
                                 <span class="tire-type">Winterreifen</span>
                             </div>
                            
                            <div class="tire-info">
                                <div class="tire-spec">
                                    <span class="label">Marke:</span>
                                    <span class="value tire-brand">Michelin</span>
                                </div>
                                <div class="tire-spec">
                                    <span class="label">Modell:</span>
                                    <span class="value tire-model">Pilot Alpin 5 SUV</span>
                                </div>
                                <div class="tire-spec">
                                    <span class="label">Größe:</span>
                                    <span class="value tire-size">235/55R19</span>
                                </div>
                                <div class="tire-spec">
                                    <span class="label">DOT:</span>
                                    <span class="value tire-dot">2722</span>
                                </div>
                            </div>
                            
                             <div class="tire-visual">
                                 <div class="tire-image-container">
                                     <img src="../assets/images/winterreifen.png" alt="Winterreifen" class="tire-type-image" data-tire-type="winter">
                                 </div>
                             </div>
                            
                            <div class="tread-analysis">
                                <div class="analysis-header">
                                    <h5>Profiltiefe-Analyse</h5>
                                    <i class="fas fa-check-circle"></i>
                                </div>
                                
                                <div class="tread-bars">
                                    <div class="tread-bar excellent">
                                        <div class="bar-fill"></div>
                                        <span class="bar-label tire-profile-outer">5.9 mm</span>
                                        <span class="bar-status">Ausgezeichnet</span>
                                    </div>
                                    <div class="tread-bar good">
                                        <div class="bar-fill"></div>
                                        <span class="bar-label tire-profile-middle">4.5 mm</span>
                                    </div>
                                    <div class="tread-bar excellent">
                                        <div class="bar-fill"></div>
                                        <span class="bar-label tire-profile-outer">5.7 mm</span>
                                        <span class="position-indicator">A</span>
                                        <span class="position-label">Außen</span>
                                    </div>
                                </div>
                                
                            </div>
                            
                            <div class="tire-summary">
                                <div class="summary-item">
                                    <span class="summary-label">Zustand:</span>
                                    <span class="summary-value excellent tire-recommendation">Sehr gut</span>
                                </div>
                            </div>
                            
                            <!-- Tire Card Footer für Badges -->
                            <div class="tire-card-footer">
                                <div class="tire-status-badge status-success">Sehr gut</div>
                                <div class="resy-badge">✓ RESY</div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Allgemeine Zustandsinfo -->
                <div class="tire-condition-info">
                    <h4>Zustandsbewertung</h4>
                    <div class="condition-legend">
                        <div class="condition-item condition-excellent">
                            <div class="condition-color"></div>
                            <span class="condition-label">Keine Fehler:</span>
                            <span class="condition-value">Sehr gut (4+mm)</span>
                        </div>
                        <div class="condition-item condition-good">
                            <div class="condition-color"></div>
                            <span class="condition-label">Leichte Fehler:</span>
                            <span class="condition-value">Befriedigend (2-4mm)</span>
                        </div>
                        <div class="condition-item condition-satisfactory">
                            <div class="condition-color"></div>
                            <span class="condition-label">Austausch notwendig:</span>
                            <span class="condition-value">Kritisch (<2mm)</span>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="modal-footer">
                <button class="btn btn-secondary" onclick="closeTireCheckModal()">
                    <i class="fas fa-times"></i>
                    Schließen
                </button>
                <button class="btn btn-primary" onclick="exportTireCheck()">
                    <i class="fas fa-download"></i>
                    Bericht exportieren
                </button>
                <button id="selectedTiresButton" class="btn btn-success" onclick="openTireOfferModal()" style="display: none;">
                    <i class="fas fa-file-invoice"></i>
                    <span id="selectedTiresCount">0 Reifen ausgewählt</span>
                </button>
            </div>
        </div>
    </div>

    <!-- Smart Offer Studio -->
    <div id="tireOfferModal" class="modal-backdrop hidden">
        <div class="offer-studio">
            <!-- Studio Header -->
            <div class="studio-header">
                <div class="studio-brand">
                    <div class="brand-icon">
                        <i class="fas fa-file-contract"></i>
                    </div>
                    <div class="brand-text">
                        <h1>Smart Offer Studio</h1>
                        <p>Professionelle Angebotserstellung</p>
                    </div>
                </div>
                <div class="studio-actions">
                    <button class="action-btn save" onclick="saveOfferDraft()">
                        <i class="fas fa-save"></i>
                        <span>Speichern</span>
                    </button>
                    <button class="action-btn close" onclick="closeTireOfferModal()">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
            </div>

            <!-- Studio Workspace -->
            <div class="studio-workspace">
                <!-- Left Panel: Smart Builder -->
                <div class="builder-panel">
                    <!-- Quick Actions -->
                    <div class="quick-actions">
                        <button class="quick-btn active" data-tab="tires" onclick="switchTab('tires')">
                            <i class="fas fa-circle"></i>
                            <span>Reifen</span>
                        </button>
                        <button class="quick-btn" data-tab="services" onclick="switchTab('services')">
                            <i class="fas fa-tools"></i>
                            <span>Services</span>
                        </button>
                    </div>

                    <!-- Tab Content -->
                    <div class="tab-content">
                        <!-- Tires Tab -->
                        <div class="tab-pane active" id="tires-tab">
                            <!-- Selected Tires Card -->
                            <div class="card selected-tires-card">
                                <div class="card-header">
                                    <h3>Ausgewählte Reifen</h3>
                                    <span class="badge" id="selectedTiresCount">0</span>
                                </div>
                                <div class="card-body">
                                    <div id="selectedTiresList" class="tire-grid">
                                        <!-- Selected tires will appear here -->
                                    </div>
                                </div>
                            </div>

                            <!-- New Tires Builder -->
                            <div class="card new-tires-card">
                                <div class="card-header">
                                    <h3>Neue Reifen hinzufügen</h3>
                                    <button class="btn-add" onclick="addTireBuilder()">
                                        <i class="fas fa-plus"></i>
                                        <span>Reifen hinzufügen</span>
                                    </button>
                                </div>
                                <div class="card-body">
                                    <div id="tireBuilderContainer" class="tire-builder">
                                        <!-- Tire builders will be added here -->
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Services Tab -->
                        <div class="tab-pane" id="services-tab">
                            <div class="card services-card">
                                <div class="card-header">
                                    <h3>Zusatzleistungen</h3>
                                    <div class="search-box">
                                        <input type="text" id="serviceSearch" placeholder="Service suchen...">
                                        <i class="fas fa-search"></i>
                                    </div>
                                </div>
                                <div class="card-body">
                                    <div id="servicesGrid" class="services-grid">
                                        <!-- Services will be loaded here -->
                                    </div>
                                </div>
                            </div>
                        </div>

                    </div>
                </div>

                <!-- Right Panel: Professional Editor -->
                <div class="editor-panel">
                    <div class="editor-header">
                        <h3>Angebot bearbeiten</h3>
                        <div class="editor-toolbar">
                            <div class="toolbar-group">
                                <button class="tool-btn" onclick="formatText('bold')" title="Fett">
                                    <i class="fas fa-bold"></i>
                                </button>
                                <button class="tool-btn" onclick="formatText('italic')" title="Kursiv">
                                    <i class="fas fa-italic"></i>
                                </button>
                                <button class="tool-btn" onclick="formatText('underline')" title="Unterstrichen">
                                    <i class="fas fa-underline"></i>
                                </button>
                            </div>
                            <div class="toolbar-group">
                                <select onchange="formatText('fontSize', this.value)">
                                    <option value="">Schriftgröße</option>
                                    <option value="12px">12px</option>
                                    <option value="14px" selected>14px</option>
                                    <option value="16px">16px</option>
                                    <option value="18px">18px</option>
                                </select>
                            </div>
                            <div class="toolbar-group">
                                <input type="color" onchange="formatText('foreColor', this.value)" value="#000000">
                            </div>
                            <div class="toolbar-group">
                                <button class="tool-btn" onclick="formatText('justifyLeft')" title="Linksbündig">
                                    <i class="fas fa-align-left"></i>
                                </button>
                                <button class="tool-btn" onclick="formatText('justifyCenter')" title="Zentriert">
                                    <i class="fas fa-align-center"></i>
                                </button>
                                <button class="tool-btn" onclick="formatText('justifyRight')" title="Rechtsbündig">
                                    <i class="fas fa-align-right"></i>
                                </button>
                            </div>
                        </div>
                    </div>
                    <div class="editor-content">
                        <!-- Tabs for switching between edit and preview -->
                        <div class="editor-tabs">
                            <button class="tab-btn active" onclick="switchEditorTab('edit')">
                                <i class="fas fa-edit"></i> Bearbeiten
                            </button>
                            <button class="tab-btn" onclick="switchEditorTab('preview')">
                                <i class="fas fa-eye"></i> Vorschau
                            </button>
                        </div>
                        
                        <!-- Editable rich text editor -->
                        <div id="offerEditor" class="rich-editor" contenteditable="true">
                            <!-- Rich text editor content -->
                        </div>
                        
                        <!-- Canvas for pixel-perfect preview -->
                        <canvas id="offerCanvas" width="595" height="842" style="border: 1px solid #ddd; background: white; max-width: 100%; height: auto; margin-bottom: 20px; display: none;"></canvas>
                    </div>
                </div>
            </div>

            <!-- Studio Footer -->
            <div class="studio-footer">
                <div class="footer-left">
                    <div class="offer-summary">
                        <span class="summary-item">
                            <i class="fas fa-tire"></i>
                            <span id="totalTires">0 Reifen</span>
                        </span>
                        <span class="summary-item">
                            <i class="fas fa-tools"></i>
                            <span id="totalServices">0 Services</span>
                        </span>
                        <span class="summary-item total">
                            <i class="fas fa-euro-sign"></i>
                            <span id="totalPrice">0,00€</span>
                        </span>
                    </div>
                </div>
                <div class="footer-right">
                    <button class="btn btn-secondary" onclick="resetOffer()">
                        <i class="fas fa-undo"></i>
                        Zurücksetzen
                    </button>
                    <button class="btn btn-primary" onclick="generateOfferPDF()">
                        <i class="fas fa-file-pdf"></i>
                        PDF erstellen
                    </button>
                    <button class="btn btn-success" onclick="sendOfferEmail()">
                        <i class="fas fa-envelope"></i>
                        E-Mail senden
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Offer Letter Modal -->
    <div id="offerLetterModal" class="modal-backdrop hidden">
        <div class="offer-letter-modal">
            <div class="modal-header">
                <h3>Angebotsschreiben</h3>
                <button class="btn-close" onclick="closeOfferLetterModal()">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            
            <div class="modal-body">
                <div class="offer-letter-content">
                    <div class="letter-editor">
                        <div class="editor-header">
                            <h4>Text-Editor</h4>
                            <div class="editor-actions">
                                <button class="btn btn-sm btn-primary" onclick="updateOfferLetterContent()">
                                    <i class="fas fa-sync"></i> Aktualisieren
                                </button>
                                <button class="btn btn-sm btn-outline-secondary" onclick="resetLetterTemplate()">
                                    <i class="fas fa-undo"></i> Zurücksetzen
                                </button>
                            </div>
                        </div>
                        
                        <!-- Rich Text Editor Toolbar -->
                        <div class="editor-toolbar">
                            <button class="toolbar-btn" onclick="formatText('bold')" title="Fett">
                                <i class="fas fa-bold"></i>
                            </button>
                            <button class="toolbar-btn" onclick="formatText('italic')" title="Kursiv">
                                <i class="fas fa-italic"></i>
                            </button>
                            <button class="toolbar-btn" onclick="formatText('underline')" title="Unterstrichen">
                                <i class="fas fa-underline"></i>
                            </button>
                            <div class="toolbar-separator"></div>
                            <button class="toolbar-btn" onclick="formatText('fontSize', '14')" title="Größer">
                                <i class="fas fa-text-height"></i>
                            </button>
                            <button class="toolbar-btn" onclick="formatText('fontSize', '10')" title="Kleiner">
                                <i class="fas fa-text-height" style="font-size: 0.8em;"></i>
                            </button>
                            <div class="toolbar-separator"></div>
                            <button class="toolbar-btn" onclick="formatText('foreColor', '#000000')" title="Schwarzer Text">
                                <i class="fas fa-font" style="color: #000000;"></i>
                            </button>
                            <button class="toolbar-btn" onclick="formatText('foreColor', '#dc2626')" title="Roter Text">
                                <i class="fas fa-font" style="color: #dc2626;"></i>
                            </button>
                            <button class="toolbar-btn" onclick="formatText('foreColor', '#2563eb')" title="Blauer Text">
                                <i class="fas fa-font" style="color: #2563eb;"></i>
                            </button>
                            <div class="toolbar-separator"></div>
                            <button class="toolbar-btn" onclick="formatText('justifyLeft')" title="Linksbündig">
                                <i class="fas fa-align-left"></i>
                            </button>
                            <button class="toolbar-btn" onclick="formatText('justifyCenter')" title="Zentriert">
                                <i class="fas fa-align-center"></i>
                            </button>
                            <button class="toolbar-btn" onclick="formatText('justifyRight')" title="Rechtsbündig">
                                <i class="fas fa-align-right"></i>
                            </button>
                        </div>
                        
                        <div id="letterContent" class="letter-editor-content" contenteditable="true" placeholder="Angebotsschreiben wird hier angezeigt..."></div>
                    </div>
                    
                    <div class="letter-preview">
                        <div class="preview-header">
                            <h4>Vorschau</h4>
                            <div class="preview-actions">
                                <button class="btn btn-sm btn-outline-primary" onclick="refreshPreviewImmediate()">
                                    <i class="fas fa-sync"></i> Aktualisieren
                                </button>
                            </div>
                        </div>
                        <div id="letterPreview" class="letter-preview-content">
                            <!-- Preview will be generated here -->
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="modal-footer">
                <button class="btn btn-secondary" onclick="goBackToTireOffer()">
                    <i class="fas fa-arrow-left"></i>
                    Zurück
                </button>
                <button class="btn btn-outline-secondary" onclick="closeOfferLetterModal()">
                    <i class="fas fa-times"></i>
                    Abbrechen
                </button>
                <button class="btn btn-outline-primary" onclick="downloadOfferPDF()">
                    <i class="fas fa-download"></i>
                    PDF herunterladen
                </button>
                <button class="btn btn-primary" onclick="sendOfferEmail()">
                    <i class="fas fa-envelope"></i>
                    E-Mail versenden
                </button>
            </div>
        </div>
    </div>
                            
    <script src="../assets/js/main.js"></script>
    <script src="assets/js/admin.js"></script>
    <script src="assets/js/unified-sidebar.js"></script>
    
    <script>
        // Appointment management functions
        
        // Tire Check Modal Functions
        function showTireCheckModal(appointment) {
            const modal = document.getElementById('tireCheckModal');
            const customerName = document.getElementById('tireCheckCustomerName');
            const licensePlate = document.getElementById('tireCheckLicensePlate');
            
            // Set customer information
            customerName.textContent = appointment.customer_name;
            licensePlate.textContent = `Kennzeichen: ${appointment.license_plate}`;
            
            // Store appointment data for RESY extraction
            window.currentAppointment = appointment;
            
            // Load tire data (mock data for now)
            loadTireData(appointment);
            
            // Automatisch RESY-Datenauslese starten
            setTimeout(() => {
                startResyDataExtraction();
            }, 500);
            
            modal.classList.remove('hidden');
            document.body.style.overflow = 'hidden';
        }
        
        function closeTireCheckModal() {
            const modal = document.getElementById('tireCheckModal');
            modal.classList.add('hidden');
            document.body.style.overflow = 'auto';
        }
        
        function loadTireData(appointment) {
            // Mock tire data - in real implementation, this would come from an API
            const mockTireData = {
                VL: {
                    brand: 'Michelin',
                    model: 'Pilot Alpin 5 SUV',
                    size: '235/55R19',
                    dot: '2722',
                    type: 'Winterreifen',
                    treadDepths: [6.0, 4.7, 5.8],
                    average: 5.5,
                    condition: 'Sehr gut'
                },
                VR: {
                    brand: 'Michelin',
                    model: 'Pilot Alpin 5 SUV',
                    size: '235/55R19',
                    dot: '2722',
                    type: 'Winterreifen',
                    treadDepths: [5.8, 4.2, 5.5],
                    average: 5.2,
                    condition: 'Sehr gut'
                },
                HL: {
                    brand: 'Michelin',
                    model: 'Pilot Alpin 5 SUV',
                    size: '235/55R19',
                    dot: '2722',
                    type: 'Winterreifen',
                    treadDepths: [6.2, 4.8, 5.9],
                    average: 5.6,
                    condition: 'Sehr gut'
                },
                HR: {
                    brand: 'Michelin',
                    model: 'Pilot Alpin 5 SUV',
                    size: '235/55R19',
                    dot: '2722',
                    type: 'Winterreifen',
                    treadDepths: [5.9, 4.5, 5.7],
                    average: 5.4,
                    condition: 'Sehr gut'
                }
            };
            
            // Update each tire card with the data
            Object.keys(mockTireData).forEach(position => {
                const tireCard = document.querySelector(`[data-position="${position}"]`);
                if (tireCard) {
                    const data = mockTireData[position];
                    
                    // Update tire specifications
                    const specs = tireCard.querySelectorAll('.tire-spec');
                    if (specs.length >= 4) {
                        specs[0].querySelector('.value').textContent = data.brand;
                        specs[1].querySelector('.value').textContent = data.model;
                        specs[2].querySelector('.value').textContent = data.size;
                        specs[3].querySelector('.value').textContent = data.dot;
                    }
                    
                    // Update tread depth bars
                    const bars = tireCard.querySelectorAll('.tread-bar');
                    if (bars.length >= 3) {
                        bars[0].querySelector('.bar-label').textContent = `${data.treadDepths[0]} mm`;
                        bars[1].querySelector('.bar-label').textContent = `${data.treadDepths[1]} mm`;
                        bars[2].querySelector('.bar-label').textContent = `${data.treadDepths[2]} mm`;
                    }
                    
                    // Update summary
                    const summaryItems = tireCard.querySelectorAll('.summary-item');
                    if (summaryItems.length >= 1) {
                        summaryItems[0].querySelector('.summary-value').textContent = data.condition;
                    }
                }
            });
        }
        
        function exportTireCheck() {
            // Mock export function - in real implementation, this would generate a PDF or export data
            alert('Reifenprüfungsbericht wird exportiert...');
        }
        
        // Tire selection functionality
        let selectedTires = [];
        
        function toggleTireCard(position) {
            const checkbox = document.getElementById(`tire-${position.toLowerCase()}`);
            const tireCard = checkbox.closest('.tire-card');
            
            // Toggle checkbox state
            checkbox.checked = !checkbox.checked;
            
            if (checkbox.checked) {
                // Add to selection
                if (!selectedTires.includes(position)) {
                    selectedTires.push(position);
                }
                tireCard.classList.add('selected');
            } else {
                // Remove from selection
                selectedTires = selectedTires.filter(pos => pos !== position);
                tireCard.classList.remove('selected');
            }
            
            // Update UI to show selection count
            updateSelectionInfo();
        }
        
        function toggleTireSelection(position, checkbox) {
            const tireCard = checkbox.closest('.tire-card');
            
            if (checkbox.checked) {
                // Add to selection
                if (!selectedTires.includes(position)) {
                    selectedTires.push(position);
                }
                tireCard.classList.add('selected');
            } else {
                // Remove from selection
                selectedTires = selectedTires.filter(pos => pos !== position);
                tireCard.classList.remove('selected');
            }
            
            // Update UI to show selection count
            updateSelectionInfo();
        }
        
        function updateSelectionInfo() {
            const count = selectedTires.length;
            const positions = selectedTires.join(', ');
            const selectionInfo = document.getElementById('selectionInfo');
            const selectionCount = selectionInfo.querySelector('.selection-count');
            const selectionPositions = selectionInfo.querySelector('.selection-positions');
            const selectedTiresButton = document.getElementById('selectedTiresButton');
            const selectedTiresCount = document.getElementById('selectedTiresCount');
            
            if (count > 0) {
                selectionInfo.style.display = 'flex';
                selectionCount.textContent = `${count} Reifen ausgewählt`;
                selectionPositions.textContent = positions;
                
                // Show offer button
                selectedTiresButton.style.display = 'inline-block';
                selectedTiresCount.textContent = `${count} Reifen ausgewählt`;
            } else {
                selectionInfo.style.display = 'none';
                selectedTiresButton.style.display = 'none';
            }
        }
        
        function selectAllTires() {
            const checkboxes = document.querySelectorAll('.tire-checkbox');
            checkboxes.forEach(checkbox => {
                if (!checkbox.checked) {
                    checkbox.checked = true;
                    toggleTireSelection(checkbox.id.replace('tire-', '').toUpperCase(), checkbox);
                }
            });
        }
        
        function deselectAllTires() {
            const checkboxes = document.querySelectorAll('.tire-checkbox');
            checkboxes.forEach(checkbox => {
                if (checkbox.checked) {
                    checkbox.checked = false;
                    toggleTireSelection(checkbox.id.replace('tire-', '').toUpperCase(), checkbox);
                }
            });
        }
        
        function getSelectedTires() {
            return selectedTires;
        }
        
        // Close modal when clicking outside
        document.addEventListener('click', function(event) {
            const modal = document.getElementById('tireCheckModal');
            if (event.target === modal) {
                closeTireCheckModal();
            }
        });
        
        // Close modal with Escape key
        document.addEventListener('keydown', function(event) {
            if (event.key === 'Escape') {
                const modal = document.getElementById('tireCheckModal');
                if (!modal.classList.contains('hidden')) {
                    closeTireCheckModal();
                }
            }
        });
        
        // RESY Data Extraction Functions
        let resyExtractionStep = 0;
        let resySessionData = {};
        let resyDetailHtml = '';
        
        function startResyDataExtraction() {
            if (!window.currentAppointment) {
                alert('Kein Termin ausgewählt');
                return;
            }
            
            const appointment = window.currentAppointment;
            let lgsId = appointment.lgs_id || appointment.storage_number;
            
            if (!lgsId) {
                alert('Keine Einlagerungsnummer (LGS_ID) gefunden. Bitte fügen Sie eine LGS_ID zum Termin hinzu.');
                return;
            }
            
            // Entferne automatisch Punkte aus der LGS_ID für die RESY-API
            // Frontend behält Punkte für bessere Lesbarkeit
            const lgsIdForApi = lgsId.replace(/\./g, '');
            console.log(`Frontend LGS_ID (mit Punkten): ${lgsId}`);
            console.log(`API LGS_ID (ohne Punkte): ${lgsIdForApi}`);
            
            // Zeige Progress an
            document.getElementById('resyProgress').style.display = 'block';
            document.getElementById('resyFields').style.display = 'block';
            document.getElementById('resyExtractBtn').disabled = true;
            
            // Reset progress
            resyExtractionStep = 0;
            updateProgress(0, 'Initialisierung...');
            
            // Start extraction process mit bereinigter LGS_ID
            extractResyDataStepByStep(lgsIdForApi);
        }
        
        async function extractResyDataStepByStep(lgsId) {
            try {
                // Verwende Breakthrough-API für echte RESY-Integration
                updateProgress(25, 'Breakthrough Login bei RESY...');
                
                const appointmentId = window.currentAppointment ? window.currentAppointment.id : null;
                
                const loginResponse = await fetch('../api/resy_data_extraction_breakthrough.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        action: 'breakthrough',
                        appointment_id: appointmentId,
                        lgsId: lgsId
                    })
                });
                
                const loginResult = await loginResponse.json();
                if (!loginResult.success) {
                    throw new Error('Breakthrough Login & Navigation fehlgeschlagen: ' + loginResult.error);
                }
                
                updateProgress(50, 'Daten aus RESY extrahieren...');
                
                // Speichere HTML-Daten für Feld-Extraktion
                resyDetailHtml = loginResult.detailHtml;
                
                // Prüfe ob HTML-Daten verfügbar sind
                if (!resyDetailHtml || resyDetailHtml.trim() === '') {
                    console.warn('HTML-Daten fehlen, versuche aus Cache zu laden...');
                    // Versuche HTML-Daten aus dem Cache zu laden
                    await loadHtmlFromCache();
                    
                    // Prüfe erneut nach dem Cache-Load
                    if (!resyDetailHtml || resyDetailHtml.trim() === '') {
                        console.error('HTML-Daten konnten nicht aus Cache geladen werden: Keine HTML-Daten im Cache gefunden');
                        throw new Error('HTML-Inhalt fehlt - weder aus API noch aus Cache verfügbar');
                    } else {
                        console.log('✅ HTML-Daten erfolgreich aus Cache geladen (Länge: ' + resyDetailHtml.length + ' Zeichen)');
                    }
                }
                
                // Wenn Cache-Daten vorhanden sind, lade alle Daten gleichzeitig
                if (loginResult.cached && loginResult.vehicle_data && loginResult.tire_data) {
                    console.log('Cache-Daten gefunden, lade alle Daten gleichzeitig...');
                    // Lade Fahrzeugdaten direkt
                    loadVehicleData(loginResult.vehicle_data);
                    // Lade Reifendaten direkt
                    updateTireDataDisplay(loginResult.tire_data);
                    // Extrahiere auch die Felder für Konsistenz
                    await extractDataFields();
                } else {
                    // Extrahiere alle Felder normal
                    await extractDataFields();
                }
                
                updateProgress(100, 'Datenauslese abgeschlossen!');
                document.getElementById('resyExtractBtn').disabled = false;
                
            } catch (error) {
                console.error('RESY Extraction Error:', error);
                updateProgress(0, 'Fehler: ' + error.message);
                document.getElementById('resyExtractBtn').disabled = false;
            }
        }
        
        async function resyLogin() {
            try {
                const response = await fetch('../api/resy_data_extraction_sample.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        action: 'login',
                        appointment_id: window.currentAppointment.id
                    })
                });
                
                const result = await response.json();
                return result;
            } catch (error) {
                return { success: false, error: error.message };
            }
        }
        
        async function resyNavigateToSearch() {
            try {
                const response = await fetch('../api/resy_data_extraction_sample.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        action: 'navigate_to_search',
                        sessionData: resySessionData
                    })
                });
                
                const result = await response.json();
                return result;
            } catch (error) {
                return { success: false, error: error.message };
            }
        }
        
        async function resySearchLgsId(lgsId) {
            try {
                const response = await fetch('../api/resy_data_extraction_sample.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        action: 'search_lgs_id',
                        lgsId: lgsId,
                        sessionData: resySessionData
                    })
                });
                
                const result = await response.json();
                return result;
            } catch (error) {
                return { success: false, error: error.message };
            }
        }
        
        async function resyNavigateToDetail(lgsId) {
            try {
                const response = await fetch('../api/resy_data_extraction_sample.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        action: 'navigate_to_detail',
                        lgsId: lgsId,
                        sessionData: resySessionData
                    })
                });
                
                const result = await response.json();
                
                // Speichere HTML-Daten für Feld-Extraktion
                if (result.success && result.detailHtml) {
                    resyDetailHtml = result.detailHtml;
                }
                
                return result;
            } catch (error) {
                return { success: false, error: error.message };
            }
        }
        
        async function extractDataFields() {
            const fields = [
                'fahrzeughalter',
                'kennzeichen', 
                'fin',
                'eingangsnummer',
                'ladestelle',
                'bemerkung',
                'ruecklieferungsdatum',
                'rueckgabe_bemerkung'
            ];
            
            for (let i = 0; i < fields.length; i++) {
                const field = fields[i];
                const progress = 50 + (i * 6);
                
                updateProgress(progress, `Extrahiere ${field}...`);
                setFieldStatus(field, 'loading', 'Lade...');
                
                try {
                    const result = await extractFieldData(field);
                    if (result.success) {
                        document.getElementById(field).value = result.value;
                        setFieldStatus(field, 'success', '✓ RESY-DATEN erfolgreich');
                    } else {
                        setFieldStatus(field, 'error', '✗ Fehler: ' + result.error);
                    }
                } catch (error) {
                    setFieldStatus(field, 'error', '✗ Fehler: ' + error.message);
                }
            }
            
            // Extrahiere Reifendaten nach den Fahrzeugdaten
            await extractTireData();
        }
        
        async function extractTireData() {
            updateProgress(85, 'Extrahiere Reifendaten...');
            
            try {
                // Prüfe ob HTML-Daten verfügbar sind
                if (!resyDetailHtml || resyDetailHtml.trim() === '') {
                    console.error('HTML-Inhalt fehlt für Reifendaten-Extraktion');
                    updateProgress(85, 'HTML-Inhalt fehlt - kann Reifendaten nicht extrahieren');
                    return;
                }
                
                console.log('Extrahiere Reifendaten aus HTML (Länge: ' + resyDetailHtml.length + ' Zeichen)');
                
                const response = await fetch('../api/resy_data_extraction_breakthrough.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        action: 'extract_tire_data',
                        html: resyDetailHtml,
                        appointment_id: window.currentAppointment ? window.currentAppointment.id : null
                    })
                });
                
                const result = await response.json();
                if (result.success) {
                    // Aktualisiere die Reifendaten-Anzeige
                    updateTireDataDisplay(result.tire_data);
                    updateProgress(90, 'Reifendaten erfolgreich extrahiert');
                    console.log('✅ Reifendaten erfolgreich extrahiert');
                } else {
                    console.error('Reifendaten-Extraktion fehlgeschlagen:', result.error);
                    updateProgress(85, 'Reifendaten-Extraktion fehlgeschlagen: ' + result.error);
                }
            } catch (error) {
                console.error('Reifendaten-Extraktion Fehler:', error);
                updateProgress(85, 'Reifendaten-Extraktion Fehler: ' + error.message);
            }
        }
        
        function determineTireStatus(tire) {
            // Prüfe Empfehlungstext für "Austausch notwendig"
            if (tire.recommendation && tire.recommendation.toLowerCase().includes('austausch notwendig')) {
                return {
                    class: 'tire-bad',
                    text: 'Austausch notwendig',
                    badgeClass: 'status-danger'
                };
            }
            
            // Prüfe Profiltiefe
            const avgDepth = calculateAverageProfileDepth(tire);
            if (avgDepth !== null) {
                if (avgDepth < 2) {
                    return {
                        class: 'tire-bad',
                        text: 'Kritisch (<2mm)',
                        badgeClass: 'status-danger'
                    };
                } else if (avgDepth < 4) {
                    return {
                        class: 'tire-warning',
                        text: 'Befriedigend (2-4mm)',
                        badgeClass: 'status-warning'
                    };
                } else {
                    return {
                        class: 'tire-good',
                        text: 'Sehr gut (4+mm)',
                        badgeClass: 'status-success'
                    };
                }
            }
            
            // Standard: Gut
            return {
                class: 'tire-good',
                text: 'Keine Fehler',
                badgeClass: 'status-success'
            };
        }
        
        function calculateAverageProfileDepth(tire) {
            const inner = parseFloat(tire.profile_depth_inner);
            const middle = parseFloat(tire.profile_depth_middle);
            const outer = parseFloat(tire.profile_depth_outer);
            
            if (!isNaN(inner) && !isNaN(middle) && !isNaN(outer)) {
                return (inner + middle + outer) / 3;
            }
            return null;
        }
        
        function retryImageLoad(lgfotoId, appointmentId) {
            // Erstelle neue Proxy-URL mit Timestamp
            const timestamp = new Date().getTime();
            const proxyUrl = `../api/resy_image_proxy.php?lgfoto_id=${lgfotoId}&appointment_id=${appointmentId}&t=${timestamp}`;
            
            // Erstelle neues Bild-Element
            const imgElement = document.createElement('img');
            imgElement.src = proxyUrl;
            imgElement.className = 'tire-image';
            imgElement.alt = `Reifenbild LGFOTO_ID: ${lgfotoId}`;
            imgElement.title = `Reifenbild - LGFOTO_ID: ${lgfotoId}`;
            imgElement.onclick = () => openImageModal(proxyUrl, `Reifenbild - LGFOTO_ID: ${lgfotoId}`);
            
            // Fehlerbehandlung
            imgElement.onerror = function() {
                console.error('Erneuter Versuch fehlgeschlagen:', proxyUrl);
                this.style.display = 'none';
                
                // Zeige Fehlermeldung
                const errorDiv = document.createElement('div');
                errorDiv.style.cssText = 'padding: 10px; background: #f8d7da; color: #721c24; border: 1px solid #f5c6cb; border-radius: 4px; margin: 5px 0;';
                errorDiv.innerHTML = `
                    <strong>Bild konnte nicht geladen werden</strong><br>
                    LGFOTO_ID: ${lgfotoId}<br>
                    <small>Möglicherweise ist die RESY-Session abgelaufen. Bitte führen Sie "Reifen prüfen" erneut durch.</small>
                `;
                
                this.parentNode.replaceChild(errorDiv, this);
            };
            
            // Ersetze den Platzhalter durch das neue Bild
            const placeholder = document.querySelector(`[onclick*="retryImageLoad('${lgfotoId}'"]`);
            if (placeholder && placeholder.parentNode) {
                placeholder.parentNode.replaceChild(imgElement, placeholder);
            }
        }
        
        function openImageModal(imageUrl, title) {
            // Erstelle Modal für Bildanzeige
            let modal = document.getElementById('imageModal');
            if (!modal) {
                modal = document.createElement('div');
                modal.id = 'imageModal';
                modal.className = 'image-modal';
                modal.innerHTML = `
                    <div class="image-modal-content">
                        <span class="image-modal-close">&times;</span>
                        <img id="modalImage" src="" alt="">
                        <div class="image-modal-title"></div>
                    </div>
                `;
                document.body.appendChild(modal);
                
                // Event Listeners
                modal.querySelector('.image-modal-close').onclick = closeImageModal;
                modal.onclick = function(e) {
                    if (e.target === modal) closeImageModal();
                };
            }
            
            // Setze Bild und Titel
            modal.querySelector('#modalImage').src = imageUrl;
            modal.querySelector('.image-modal-title').textContent = title;
            
            // Zeige Modal
            modal.style.display = 'block';
        }
        
        function closeImageModal() {
            const modal = document.getElementById('imageModal');
            if (modal) {
                modal.style.display = 'none';
            }
        }
        
        function showAllImages(position, images) {
            // Erstelle Modal für alle Bilder einer Position
            let modal = document.getElementById('allImagesModal');
            if (!modal) {
                modal = document.createElement('div');
                modal.id = 'allImagesModal';
                modal.className = 'image-modal';
                modal.innerHTML = `
                    <div class="image-modal-content all-images-modal">
                        <span class="image-modal-close">&times;</span>
                        <div class="image-modal-title">Alle Reifenbilder - ${position}</div>
                        <div class="all-images-grid"></div>
                    </div>
                `;
                document.body.appendChild(modal);
                
                // Event Listeners
                modal.querySelector('.image-modal-close').onclick = closeAllImagesModal;
                modal.onclick = function(e) {
                    if (e.target === modal) closeAllImagesModal();
                };
            }
            
            // Leere und fülle Grid
            const grid = modal.querySelector('.all-images-grid');
            grid.innerHTML = '';
            
            let appointmentId = window.currentAppointment ? window.currentAppointment.id : null;
            
            // Fallback: Verwende die appointment_id aus der URL
            if (!appointmentId) {
                const urlParams = new URLSearchParams(window.location.search);
                appointmentId = urlParams.get('id');
            }
            
            images.forEach((image, index) => {
                const imgContainer = document.createElement('div');
                imgContainer.className = 'all-image-item';
                
                // Erstelle Proxy-URL mit korrekter appointment_id und Timestamp
                const timestamp = new Date().getTime();
                const proxyUrl = `../api/resy_image_proxy.php?lgfoto_id=${image.lgfoto_id}&appointment_id=${appointmentId || ''}&t=${timestamp}`;
                
                imgContainer.innerHTML = `
                    <img src="${proxyUrl}" alt="Reifenbild ${position} ${index + 1}" 
                         onclick="openImageModal('${proxyUrl}', 'Reifenbild ${position} - LGFOTO_ID: ${image.lgfoto_id}')">
                    <div class="image-info">LGFOTO_ID: ${image.lgfoto_id}</div>
                `;
                grid.appendChild(imgContainer);
            });
            
            // Zeige Modal
            modal.style.display = 'block';
        }
        
        function closeAllImagesModal() {
            const modal = document.getElementById('allImagesModal');
            if (modal) {
                modal.style.display = 'none';
            }
        }
        
        function updateTireDataDisplay(tireData) {
            const positions = ['VL', 'VR', 'HL', 'HR'];
            
            positions.forEach(position => {
                if (tireData[position]) {
                    const tire = tireData[position];
                    const tireElement = document.querySelector(`[data-position="${position}"]`);
                    
                    if (tireElement) {
                        // Aktualisiere die Reifendaten-Anzeige
                        const brandElement = tireElement.querySelector('.tire-brand');
                        const modelElement = tireElement.querySelector('.tire-model');
                        const sizeElement = tireElement.querySelector('.tire-size');
                        const dotElement = tireElement.querySelector('.tire-dot');
                        const typeElement = tireElement.querySelector('.tire-type');
                        const profileInnerElement = tireElement.querySelector('.tire-profile-inner');
                        const profileMiddleElement = tireElement.querySelector('.tire-profile-middle');
                        const profileOuterElement = tireElement.querySelector('.tire-profile-outer');
                        const recommendationElement = tireElement.querySelector('.tire-recommendation');
                        
                        if (brandElement) brandElement.textContent = tire.brand || '';
                        if (modelElement) modelElement.textContent = tire.model || '';
                        if (sizeElement) sizeElement.textContent = tire.size || '';
                        if (dotElement) dotElement.textContent = tire.dot || '';
                        if (typeElement) typeElement.textContent = tire.tire_type || '';
                        if (profileInnerElement) profileInnerElement.textContent = tire.profile_depth_inner || '';
                        if (profileMiddleElement) profileMiddleElement.textContent = tire.profile_depth_middle || '';
                        if (profileOuterElement) profileOuterElement.textContent = tire.profile_depth_outer || '';
                        if (recommendationElement) recommendationElement.textContent = tire.recommendation || '';
                        
                        // Aktualisiere auch die DOT-Anzeige im Header
                        const dotHeaderElement = tireElement.querySelector('.tire-dot');
                        if (dotHeaderElement && tire.dot) {
                            dotHeaderElement.textContent = `DOT ${tire.dot}`;
                        }
                        
                        // Markiere als von RESY geladen
                        tireElement.classList.add('resy-loaded');
                        tireElement.setAttribute('data-resy-loaded', 'true');
                        
                        // Bestimme Reifenstatus und füge entsprechende CSS-Klasse hinzu
                        const tireStatus = determineTireStatus(tire);
                        tireElement.classList.remove('tire-good', 'tire-bad', 'tire-warning');
                        tireElement.classList.add(tireStatus.class);
                        
                        // Füge RESY-Badge zur Fußzeile hinzu
                        let footer = tireElement.querySelector('.tire-card-footer');
                        if (footer) {
                            let resyBadge = footer.querySelector('.resy-badge');
                            if (!resyBadge) {
                                resyBadge = document.createElement('div');
                                resyBadge.className = 'resy-badge';
                                resyBadge.textContent = '✓ RESY';
                                footer.appendChild(resyBadge);
                            }
                            
                            // Füge Status-Badge zur Fußzeile hinzu
                            let statusBadge = footer.querySelector('.tire-status-badge');
                            if (!statusBadge) {
                                statusBadge = document.createElement('div');
                                statusBadge.className = 'tire-status-badge';
                                footer.insertBefore(statusBadge, resyBadge);
                            }
                            statusBadge.textContent = tireStatus.text;
                            statusBadge.className = `tire-status-badge ${tireStatus.badgeClass}`;
                        }
                        
                        // Füge Reifenbilder hinzu
                        if (tire.images && tire.images.length > 0) {
                            let imageContainer = tireElement.querySelector('.tire-images');
                            if (!imageContainer) {
                                imageContainer = document.createElement('div');
                                imageContainer.className = 'tire-images';
                                tireElement.appendChild(imageContainer);
                            }
                            
                            // Leere den Container
                            imageContainer.innerHTML = '';
                            
                            // Füge Bilder hinzu (maximal 3 anzeigen)
                            const maxImages = Math.min(3, tire.images.length);
                            const appointmentId = window.currentAppointment ? window.currentAppointment.id : null;
                            
                            console.log('Appointment ID für Bilder:', appointmentId);
                            
                            // Fallback: Verwende die appointment_id aus der URL
                            if (!appointmentId) {
                                const urlParams = new URLSearchParams(window.location.search);
                                appointmentId = urlParams.get('id');
                                console.log('Appointment ID aus URL:', appointmentId);
                            }
                            
                            // Fallback: Verwende die appointment_id aus dem Modal
                            if (!appointmentId) {
                                const modal = document.querySelector('.tire-check-modal');
                                if (modal) {
                                    const appointmentIdInput = modal.querySelector('input[name="appointment_id"]');
                                    if (appointmentIdInput) {
                                        appointmentId = appointmentIdInput.value;
                                        console.log('Appointment ID aus Modal:', appointmentId);
                                    }
                                }
                            }
                            
                            // Fallback: Verwende die appointment_id aus dem globalen Scope
                            if (!appointmentId) {
                                appointmentId = window.currentAppointmentId || null;
                                console.log('Appointment ID aus globalem Scope:', appointmentId);
                            }
                            
                            // Fallback: Verwende die appointment_id aus dem DOM
                            if (!appointmentId) {
                                const appointmentIdElement = document.querySelector('[data-appointment-id]');
                                if (appointmentIdElement) {
                                    appointmentId = appointmentIdElement.getAttribute('data-appointment-id');
                                    console.log('Appointment ID aus DOM:', appointmentId);
                                }
                            }
                            
                            for (let i = 0; i < maxImages; i++) {
                                const image = tire.images[i];
                                const imgElement = document.createElement('img');
                                
                                // Erstelle Proxy-URL mit korrekter appointment_id und Timestamp
                                const timestamp = new Date().getTime();
                                const proxyUrl = `../api/resy_image_proxy.php?lgfoto_id=${image.lgfoto_id}&appointment_id=${appointmentId || ''}&t=${timestamp}`;
                                
                                console.log('Proxy URL:', proxyUrl);
                                
                                imgElement.src = proxyUrl;
                                imgElement.className = 'tire-image';
                                imgElement.alt = `Reifenbild ${position} ${i + 1}`;
                                imgElement.title = `Reifenbild ${position} - LGFOTO_ID: ${image.lgfoto_id}`;
                                imgElement.onclick = () => openImageModal(proxyUrl, `Reifenbild ${position} - LGFOTO_ID: ${image.lgfoto_id}`);
                                
                                // Fehlerbehandlung für Bilder
                                imgElement.onerror = function() {
                                    console.error('Fehler beim Laden des Bildes:', proxyUrl);
                                    
                                    // Erstelle Platzhalter-Element mit Retry-Button
                                    const placeholder = document.createElement('div');
                                    placeholder.className = 'tire-image-placeholder';
                                    placeholder.innerHTML = `
                                        <div class="placeholder-content">
                                            <i class="fas fa-image" style="font-size: 24px; color: #ccc; margin-bottom: 8px;"></i>
                                            <div style="font-size: 12px; color: #666;">Bild nicht verfügbar</div>
                                            <div style="font-size: 10px; color: #999;">LGFOTO_ID: ${image.lgfoto_id}</div>
                                            <button onclick="retryImageLoad('${image.lgfoto_id}', '${appointmentId || ''}')" 
                                                    style="margin-top: 5px; padding: 2px 6px; font-size: 10px; background: #007bff; color: white; border: none; border-radius: 3px; cursor: pointer;">
                                                Erneut versuchen
                                            </button>
                                        </div>
                                    `;
                                    
                                    // Ersetze das Bild durch den Platzhalter
                                    this.parentNode.replaceChild(placeholder, this);
                                };
                                
                                imageContainer.appendChild(imgElement);
                            }
                            
                            // Zeige "Mehr Bilder" Button wenn es mehr als 3 gibt
                            if (tire.images.length > 3) {
                                const moreButton = document.createElement('button');
                                moreButton.className = 'tire-more-images-btn';
                                moreButton.textContent = `+${tire.images.length - 3} weitere`;
                                moreButton.onclick = () => showAllImages(position, tire.images);
                                imageContainer.appendChild(moreButton);
                            }
                        }
                        
                        console.log(`Reifendaten für ${position} aktualisiert:`, tire);
                    }
                }
            });
            
            // Aktualisiere Reifenbilder basierend auf dem Reifentyp
            updateTireTypeImages(tireData);
        }
        
        function loadVehicleData(vehicleData) {
            // Lade Fahrzeugdaten in die entsprechenden Felder
            const fieldMapping = {
                'fahrzeughalter': 'fahrzeughalter',
                'kennzeichen': 'kennzeichen', 
                'fin': 'fin',
                'eingangsnummer': 'eingangsnummer',
                'ladestelle': 'ladestelle',
                'bemerkung': 'bemerkung',
                'ruecklieferungsdatum': 'ruecklieferungsdatum',
                'rueckgabe_bemerkung': 'rueckgabe_bemerkung'
            };
            
            Object.keys(fieldMapping).forEach(field => {
                const element = document.getElementById(field);
                if (element && vehicleData[field]) {
                    element.value = vehicleData[field];
                    setFieldStatus(field, 'success', '✓ RESY-DATEN erfolgreich');
                }
            });
        }
        
        function updateTireTypeImages(tireData) {
            // Aktualisiere Reifenbilder basierend auf dem Reifentyp
            Object.keys(tireData).forEach(position => {
                const tire = tireData[position];
                const tireElement = document.querySelector(`[data-position="${position}"]`);
                if (tireElement && tire.tire_type) {
                    const imageContainer = tireElement.querySelector('.tire-image-container');
                    const tireImage = tireElement.querySelector('.tire-type-image');
                    
                    if (imageContainer && tireImage) {
                        let imagePath = '../assets/images/';
                        
                        // Bestimme den Reifentyp
                        const tireType = tire.tire_type.toLowerCase();
                        if (tireType.includes('winter')) {
                            imagePath += 'winterreifen.png';
                        } else if (tireType.includes('sommer')) {
                            imagePath += 'sommerreifen.png';
                        } else if (tireType.includes('ganzjahres') || tireType.includes('allseason') || tireType.includes('all-season')) {
                            imagePath += 'allseason.png';
                        } else {
                            // Fallback zu Winterreifen
                            imagePath += 'winterreifen.png';
                        }
                        
                        tireImage.src = imagePath;
                        tireImage.alt = tire.tire_type;
                        tireImage.setAttribute('data-tire-type', tireType);
                    }
                }
            });
        }
        
        async function loadHtmlFromCache() {
            try {
                const appointmentId = window.currentAppointment ? window.currentAppointment.id : null;
                if (!appointmentId) {
                    console.error('Keine Appointment ID verfügbar für Cache-Load');
                    return;
                }
                
                const response = await fetch('../api/resy_data_extraction_breakthrough.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        action: 'get_cached_html',
                        appointment_id: appointmentId
                    })
                });
                
                const result = await response.json();
                if (result.success && result.html) {
                    resyDetailHtml = result.html;
                    console.log('HTML-Daten erfolgreich aus Cache geladen');
                } else {
                    console.error('HTML-Daten konnten nicht aus Cache geladen werden:', result.error);
                }
            } catch (error) {
                console.error('Fehler beim Laden der HTML-Daten aus Cache:', error);
            }
        }
        
        async function extractFieldData(field) {
            try {
                // Prüfe ob HTML-Daten verfügbar sind
                if (!resyDetailHtml || resyDetailHtml.trim() === '') {
                    console.error('HTML-Inhalt fehlt für Feld-Extraktion: ' + field);
                    return { success: false, error: 'HTML-Inhalt fehlt' };
                }
                
                const response = await fetch('../api/resy_data_extraction_breakthrough.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        action: 'extract_field',
                        field: field,
                        html: resyDetailHtml
                    })
                });
                
                const result = await response.json();
                return result;
            } catch (error) {
                return { success: false, error: error.message };
            }
        }
        
        
        function setFieldStatus(field, status, message) {
            const statusElement = document.getElementById(field + '-status');
            statusElement.className = 'field-status ' + status;
            statusElement.textContent = message;
        }
        
        function updateProgress(percent, text) {
            document.getElementById('progressFill').style.width = percent + '%';
            document.getElementById('progressText').textContent = text;
        }
        
        function clearResyData() {
            const fields = ['fahrzeughalter', 'kennzeichen', 'fin', 'eingangsnummer', 'ladestelle', 'bemerkung', 'ruecklieferungsdatum', 'rueckgabe_bemerkung'];
            fields.forEach(field => {
                document.getElementById(field).value = '';
                setFieldStatus(field, '', '');
            });
            updateProgress(0, 'Bereit für neue Datenauslese...');
            document.getElementById('resyProgress').style.display = 'none';
        }

        // Tire Offer Modal Functions
        let newTiresData = [];
        let offerData = {};

        // Helper function to get current autohaus ID
        function getCurrentAutohausId() {
            if (window.currentUser && window.currentUser.autohaus_id) {
                return window.currentUser.autohaus_id;
            }
            if (window.currentAppointment && window.currentAppointment.autohaus_id) {
                return window.currentAppointment.autohaus_id;
            }
            // Fallback to 1 if not found
            return 1;
        }

        function openTireOfferModal() {
            const modal = document.getElementById('tireOfferModal');
            modal.classList.remove('hidden');
            document.body.style.overflow = 'hidden';
            
            // Load services
            loadAdditionalServices();
            
            // Add first tire builder
            addTireBuilder();
            
            // Initialize tabs
            switchTab('tires');
            
            // Initialize rich text editor
            initializeRichEditor();
            
            // Populate selected tires from tire cards
            populateSelectedTires();
            
            // Update preview
            updateLivePreview();
        }

        function closeTireOfferModal() {
            const modal = document.getElementById('tireOfferModal');
            modal.classList.add('hidden');
            document.body.style.overflow = 'auto';
        }

        // Initialize Rich Text Editor
        function initializeRichEditor() {
            const editor = document.getElementById('offerEditor');
            if (editor) {
                editor.innerHTML = `
                    <p><strong>B&E Autocentrum GmbH</strong></p>
                    <p>Kiel, ${new Date().toLocaleDateString('de-DE')}</p>
                    <br>
                    <p>Sehr geehrte Damen und Herren,</p>
                    <br>
                    <p>die Vorbereitungen für unseren nächsten Boxenstopp laufen bereits und dabei ist uns leider aufgefallen, dass die bei uns eingelagerten Reifen ersetzt werden müssten.</p>
                    <br>
                    <p>Daher erhalten Sie mit diesem Schreiben das beigefügte Angebot.</p>
                    <br>
                    <p><strong>Auszutauschender Reifen:</strong></p>
                    <p id="selectedTiresPreview">Keine Reifen ausgewählt</p>
                    <br>
                    <p><strong>Neue Reifen:</strong></p>
                    <p id="newTiresPreview">Keine neuen Reifen hinzugefügt</p>
                    <br>
                    <p><strong>Kosten inkl. Reifenmontage:</strong></p>
                    <p>Zzgl.</p>
                    <p>Rädermontage                    49,99€</p>
                    <p>Einlagerung der Sommerreifen     85,00€</p>
                    <p id="servicesPreview">Keine Services ausgewählt</p>
                    <br>
                    <p>Für Rückfragen stehen wir Ihnen gerne unter Tel: 0431/54 63 00 zur Verfügung.</p>
                    <br>
                    <p>Mit freundlichem Gruß<br>Deniz Uludag<br>B&E Autocentrum GmbH</p>
                    <br>
                    <p style="font-size: 0.8em; color: #dc2626;">Dieses Dokument wurde maschinell erstellt und ist ohne Unterschrift gültig</p>
                `;
            }
        }

        function populateSelectedTires() {
            const container = document.getElementById('selectedTiresList');
            if (!container) {
                console.log('selectedTiresList container not found');
                return;
            }
            
            container.innerHTML = '';
            
            // Get selected tire cards
            const selectedTireCards = document.querySelectorAll('.tire-card.selected');
            console.log('Found selected tire cards:', selectedTireCards.length);
            
            selectedTireCards.forEach(card => {
                const tireDiv = document.createElement('div');
                tireDiv.className = 'tire-item';
                
                const brand = card.querySelector('.tire-brand')?.textContent || 'Unbekannt';
                const model = card.querySelector('.tire-model')?.textContent || 'Unbekannt';
                const size = card.querySelector('.tire-size')?.textContent || 'Unbekannt';
                const position = card.querySelector('.tire-position')?.textContent || 'Unbekannt';
                
                tireDiv.innerHTML = `
                    <div class="tire-info">
                        <div class="tire-details">
                            <h4>${brand} ${model}</h4>
                            <p>${size} - Position: ${position}</p>
                        </div>
                        <div class="tire-price">Ausgewählt</div>
                    </div>
                `;
                
                container.appendChild(tireDiv);
            });
            
            // Update count
            const countElement = document.getElementById('selectedTiresCount');
            if (countElement) {
                countElement.textContent = selectedTireCards.length;
            }
            
            // Update live preview
            updateLivePreview();
        }

        function addNewTire() {
            const container = document.getElementById('newTiresList');
            const tireId = 'tire_' + Date.now();
            
            const tireForm = document.createElement('div');
            tireForm.className = 'new-tire-item';
            tireForm.innerHTML = `
                <div class="new-tire-form">
                    <div class="form-group">
                        <label>Hersteller & Modell</label>
                        <div class="suggestion-container">
                            <input type="text" id="${tireId}_brand_model" placeholder="z.B. Continental EcoContact 6 Q" 
                                   onchange="updateTireData('${tireId}')" 
                                   onkeyup="showTireSuggestions('${tireId}', this.value)"
                                   autocomplete="off">
                            <div id="${tireId}_suggestions" class="suggestions-dropdown" style="display: none;"></div>
                        </div>
                    </div>
                    <div class="form-group">
                        <label>EU-Label</label>
                        <input type="text" id="${tireId}_eu_label" placeholder="z.B. A B B 71" onchange="updateTireData('${tireId}')">
                    </div>
                    <div class="form-group">
                        <label>Felgenmaße + Index</label>
                        <input type="text" id="${tireId}_size" placeholder="z.B. 245/45 R19 102 V" onchange="updateTireData('${tireId}')">
                    </div>
                    <div class="form-group">
                        <label>Einzelpreis (€)</label>
                        <input type="number" id="${tireId}_price" step="0.01" placeholder="241.00" onchange="updateTireData('${tireId}')">
                    </div>
                    <div class="form-group">
                        <label>Montage Felge (€)</label>
                        <input type="number" id="${tireId}_mounting" step="0.01" placeholder="24.50" onchange="updateTireData('${tireId}')">
                    </div>
                    <div class="form-group">
                        <label>Anzahl</label>
                        <input type="number" id="${tireId}_quantity" min="1" value="4" onchange="updateTireData('${tireId}')">
                    </div>
                    <div class="form-group">
                        <label>Gesamtpreis (€)</label>
                        <input type="number" id="${tireId}_total" step="0.01" readonly>
                    </div>
                </div>
                <div class="tire-actions">
                    <button class="btn btn-sm btn-danger" onclick="removeNewTire('${tireId}')">
                        <i class="fas fa-trash"></i> Entfernen
                    </button>
                </div>
            `;
            
            container.appendChild(tireForm);
            
            // Auto-set quantity based on selected tires
            const selectedCount = document.querySelectorAll('.tire-card.selected').length;
            if (selectedCount > 0) {
                document.getElementById(tireId + '_quantity').value = selectedCount;
                document.getElementById(tireId + '_quantity').style.backgroundColor = '#e8f5e8';
                document.getElementById(tireId + '_quantity').title = 'Automatisch gesetzt basierend auf ausgewählten Reifen (änderbar)';
                
                // Trigger change event to calculate total
                document.getElementById(tireId + '_quantity').dispatchEvent(new Event('change'));
            }
            updateTireData(tireId);
        }

        function removeNewTire(tireId) {
            const tireItem = document.getElementById(tireId + '_brand_model').closest('.new-tire-item');
            tireItem.remove();
            
            // Remove from both data arrays
            newTires = newTires.filter(tire => tire.id !== tireId);
            newTiresData = newTiresData.filter(tire => tire.id !== tireId);
            
            console.log('Removed tire, newTires:', newTires);
            console.log('Removed tire, newTiresData:', newTiresData);
            
            // Update live preview
            updateLivePreview();
        }

        function updateTireData(tireId) {
            const price = parseFloat(document.getElementById(tireId + '_price').value) || 0;
            const mounting = parseFloat(document.getElementById(tireId + '_mounting').value) || 0;
            const quantity = parseInt(document.getElementById(tireId + '_quantity').value) || 0;
            const total = (price + mounting) * quantity;
            
            document.getElementById(tireId + '_total').value = total.toFixed(2);
            
            // Remove auto-set indicator if user manually changes quantity
            const quantityInput = document.getElementById(tireId + '_quantity');
            if (quantityInput.style.backgroundColor === 'rgb(232, 245, 232)') {
                // User is manually changing the quantity, remove auto-indicator
                quantityInput.style.backgroundColor = '';
                quantityInput.title = '';
            }
            
            // Update both data arrays to keep them in sync
            const tireData = {
                id: tireId,
                brand: document.getElementById(tireId + '_brand_model').value,
                brandModel: document.getElementById(tireId + '_brand_model').value,
                euLabel: document.getElementById(tireId + '_eu_label').value,
                size: document.getElementById(tireId + '_size').value,
                price: price,
                mounting: mounting,
                quantity: quantity,
                total: total
            };
            
            // Update newTires array (used by Smart Offer Studio)
            const existingIndex = newTires.findIndex(tire => tire.id === tireId);
            if (existingIndex >= 0) {
                newTires[existingIndex] = tireData;
            } else {
                newTires.push(tireData);
            }
            
            // Update newTiresData array (used by Offer Letter Modal)
            const existingDataIndex = newTiresData.findIndex(tire => tire.id === tireId);
            if (existingDataIndex >= 0) {
                newTiresData[existingDataIndex] = tireData;
            } else {
                newTiresData.push(tireData);
            }
            
            console.log('Updated newTires:', newTires);
            console.log('Updated newTiresData:', newTiresData);
            
            // Update live preview
            updateLivePreview();
            
            // Update offer letter if it's open
            if (document.getElementById('offerLetterModal') && !document.getElementById('offerLetterModal').classList.contains('hidden')) {
                updateOfferLetterContent();
            }
        }

        // Store services data globally
        let availableServices = [];

        async function loadAdditionalServices() {
            try {
                const response = await fetch('../api/get_autohaus_services.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        autohaus_id: getCurrentAutohausId()
                    })
                });
                
                const result = await response.json();
                if (result.success) {
                    availableServices = result.services;
                    renderServicesSimple(result.services);
                } else {
                    console.error('Fehler beim Laden der Services:', result.error);
                }
            } catch (error) {
                console.error('Fehler beim Laden der Services:', error);
            }
        }

        function populateAdditionalServices(services) {
            const container = document.getElementById('additionalServicesList');
            container.innerHTML = '';
            
            services.forEach(service => {
                const serviceItem = document.createElement('div');
                serviceItem.className = 'service-checkbox';
                serviceItem.innerHTML = `
                    <input type="checkbox" id="service_${service.id}" value="${service.id}" onchange="toggleService(${service.id}, this.checked)">
                    <div class="service-info">
                        <div class="service-name">${service.service_name}</div>
                        <div class="service-description">${service.service_description || ''}</div>
                    </div>
                    <div class="service-price">${service.show_price ? service.price + '€' : 'Preis auf Anfrage'}</div>
                `;
                container.appendChild(serviceItem);
            });
        }

        function renderServicesSimple(services) {
            const container = document.getElementById('servicesGrid');
            if (!container) {
                console.error('servicesGrid container not found');
                return;
            }
            container.innerHTML = '';
            
            services.forEach(service => {
                const serviceDiv = document.createElement('div');
                serviceDiv.className = 'service-item';
                serviceDiv.id = 'service_' + service.id;
                serviceDiv.onclick = () => toggleService(service.id);
                serviceDiv.innerHTML = `
                    <span class="service-name">${service.service_name}</span>
                    <span class="service-price">${service.price.toFixed(2).replace('.', ',')}€</span>
                `;
                container.appendChild(serviceDiv);
            });
        }

        function toggleService(serviceId, isSelected) {
            if (isSelected) {
                if (!selectedServices.includes(serviceId)) {
                    selectedServices.push(serviceId);
                }
            } else {
                selectedServices = selectedServices.filter(id => id !== serviceId);
            }
            
            // Sofortige Vorschau-Aktualisierung
            updateOfferLetterContent();
        }

        // New toggleService for Smart Offer Studio
        function toggleService(serviceId) {
            const service = document.getElementById('service_' + serviceId);
            if (!service) {
                console.log('Service element not found:', serviceId);
                return;
            }
            
            if (service.classList.contains('selected')) {
                service.classList.remove('selected');
                selectedServices = selectedServices.filter(id => id != serviceId);
            } else {
                service.classList.add('selected');
                selectedServices.push(serviceId);
            }
            
            console.log('Selected services:', selectedServices);
            updateOfferSummary();
            updateLivePreview();
        }

        function proceedToOfferLetter() {
            // Get current appointment ID from global scope or modal
            let appointmentId = null;
            if (window.currentAppointment && window.currentAppointment.id) {
                appointmentId = window.currentAppointment.id;
            } else if (window.currentAppointmentId) {
                appointmentId = window.currentAppointmentId;
            } else {
                // Try to get from URL parameter
                const urlParams = new URLSearchParams(window.location.search);
                appointmentId = urlParams.get('appointment_id');
            }
            
            
            // Collect all data
            offerData = {
                selectedTires: selectedTires,
                newTires: newTiresData,
                selectedServices: selectedServices,
                appointmentId: appointmentId
            };
            
            // Close current modal
            closeTireOfferModal();
            
            // Open offer letter modal
            openOfferLetterModal();
        }

        function openOfferLetterModal() {
            const modal = document.getElementById('offerLetterModal');
            modal.classList.remove('hidden');
            document.body.style.overflow = 'hidden';
            
            // Sofortige Aktualisierung mit aktuellen Daten
            updateOfferLetterContent();
            
            // Event listeners für Editor
            const editor = document.getElementById('letterContent');
            editor.addEventListener('input', refreshPreview);
            editor.addEventListener('paste', () => setTimeout(refreshPreview, 100));
            editor.addEventListener('keyup', refreshPreview);
        }

        function closeOfferLetterModal() {
            const modal = document.getElementById('offerLetterModal');
            modal.classList.add('hidden');
            document.body.style.overflow = 'auto';
        }

        function goBackToTireOffer() {
            // Close current modal
            closeOfferLetterModal();
            
            // Open tire offer modal again
            openTireOfferModal();
        }

        // Rich Text Editor Functions
        function formatText(command, value = null) {
            document.execCommand(command, false, value);
            document.getElementById('letterContent').focus();
            refreshPreview();
        }


        function generateInitialLetter() {
            const editor = document.getElementById('letterContent');
            
            // Get appointment data from global scope
            const appointment = window.currentAppointment || {};
            
            // Get selected tires info
            let selectedTiresInfo = '';
            if (selectedTires && selectedTires.length > 0) {
                selectedTiresInfo = 'Beschädigter/Abgenutzter Reifen:\n';
                selectedTires.forEach(position => {
                    const tireCard = document.querySelector(`[data-position="${position}"]`);
                    if (tireCard) {
                        const brand = tireCard.querySelector('.tire-brand')?.textContent || 'Unbekannt';
                        const model = tireCard.querySelector('.tire-model')?.textContent || 'Unbekannt';
                        const size = tireCard.querySelector('.tire-size')?.textContent || 'Unbekannt';
                        const recommendation = tireCard.querySelector('.tire-recommendation')?.textContent || 'Unbekannt';
                        selectedTiresInfo += `- ${position}: ${brand} ${model} (${size}) - ${recommendation}\n`;
                    }
                });
            }
            
            // Get new tires info - under "Beschädigter/Abgenutzter Reifen"
            let newTiresInfo = '';
            if (newTiresData && newTiresData.length > 0) {
                newTiresInfo = '\n\nBeschädigter/Abgenutzter Reifen:\n';
                newTiresData.forEach(tire => {
                    if (tire.brandModel && tire.size) {
                        newTiresInfo += `- ${tire.brandModel} (${tire.size}) - ${tire.quantity}x ${tire.total.toFixed(2).replace('.', ',')}€\n`;
                    }
                });
            }
            
            // Get services info - add to existing Zzgl. section
            let additionalServices = '';
            if (selectedServices && selectedServices.length > 0) {
                selectedServices.forEach(serviceId => {
                    const service = availableServices.find(s => s.id == serviceId);
                    if (service) {
                        const price = service.price.toFixed(2).replace('.', ',');
                        additionalServices += `${service.service_name.padEnd(30)}${price}€\n`;
                    }
                });
            }
            
            // Replace placeholders with actual data
            const haltername = appointment.fahrzeughalter || appointment.customer_name || '[Haltername]';
            const kundenname = appointment.fahrzeughalter || appointment.customer_name || '[Kundenname]';
            const reifenart = 'Winterreifen'; // Could be determined from tire data
            const kennzeichen = appointment.kennzeichen || appointment.license_plate || '[Kennzeichen]';
            const briefanrede = 'Sehr geehrte Damen und Herren';
            
            // Debug: Log the data being used
            console.log('Using appointment data:', {
                haltername,
                kundenname,
                kennzeichen,
                appointment: appointment
            });
            
            const template = `${haltername}

Kiel, ${new Date().toLocaleDateString('de-DE')}
Herr ${kundenname}

eingelagerte ${reifenart}
amtl. Kennzeichen: ${kennzeichen}

${briefanrede},

die Vorbereitungen für unseren nächsten Boxenstopp laufen bereits und dabei ist uns leider aufgefallen, dass die bei uns eingelagerten Reifen ersetzt werden müssten, siehe Prüfbericht.

Daher erhalten Sie mit diesem Schreiben das beigefügte Angebot.

${selectedTiresInfo}${newTiresInfo}

Kosten inkl. Reifenmontage (siehe Angebot im Anhang):
Zzgl.
Rädermontage                    49,99€
Einlagerung der Sommerreifen     85,00€${additionalServices ? additionalServices : ''}

Für Rückfragen stehen wir Ihnen gerne unter Tel: 0431/54 63 00 zur Verfügung.

Mit freundlichem Gruß
Deniz Uludag
B&E Autocentrum GmbH

<span style="font-size: 0.8em; color: #dc2626;">Dieses Dokument wurde maschinell erstellt und ist ohne Unterschrift gültig</span>`;
            
            editor.innerHTML = template.replace(/\n/g, '<br>');
        }

        function updateOfferLetterContent() {
            const editor = document.getElementById('letterContent');
            const appointment = window.currentAppointment || {};
            
            // Einfache Daten sammeln
            let selectedTiresText = '';
            if (selectedTires && selectedTires.length > 0) {
                selectedTiresText = 'Beschädigter/Abgenutzter Reifen:\n';
                selectedTires.forEach(position => {
                    const tireCard = document.querySelector(`[data-position="${position}"]`);
                    if (tireCard) {
                        const brand = tireCard.querySelector('.tire-brand')?.textContent || 'Unbekannt';
                        const model = tireCard.querySelector('.tire-model')?.textContent || 'Unbekannt';
                        const size = tireCard.querySelector('.tire-size')?.textContent || 'Unbekannt';
                        selectedTiresText += `- ${position}: ${brand} ${model} (${size})\n`;
                    }
                });
            }
            
            // Neue Reifen hinzufügen
            let newTiresText = '';
            if (newTiresData && newTiresData.length > 0) {
                if (!selectedTiresText) {
                    newTiresText = 'Beschädigter/Abgenutzter Reifen:\n';
                }
                newTiresData.forEach(tire => {
                    if (tire.brandModel && tire.size) {
                        newTiresText += `- ${tire.brandModel} (${tire.size}) - ${tire.quantity}x ${tire.total.toFixed(2).replace('.', ',')}€\n`;
                    }
                });
            }
            
            // Services hinzufügen
            let servicesText = '';
            if (selectedServices && selectedServices.length > 0) {
                selectedServices.forEach(serviceId => {
                    const service = availableServices.find(s => s.id == serviceId);
                    if (service) {
                        const price = service.price.toFixed(2).replace('.', ',');
                        servicesText += `${service.service_name.padEnd(30)}${price}€\n`;
                    }
                });
            }
            
            // Einfacher Brief
            const brief = `${appointment.fahrzeughalter || appointment.customer_name || '[Haltername]'}

Kiel, ${new Date().toLocaleDateString('de-DE')}
Herr ${appointment.fahrzeughalter || appointment.customer_name || '[Kundenname]'}

eingelagerte Winterreifen
amtl. Kennzeichen: ${appointment.kennzeichen || appointment.license_plate || '[Kennzeichen]'}

Sehr geehrte Damen und Herren,

die Vorbereitungen für unseren nächsten Boxenstopp laufen bereits und dabei ist uns leider aufgefallen, dass die bei uns eingelagerten Reifen ersetzt werden müssten, siehe Prüfbericht.

Daher erhalten Sie mit diesem Schreiben das beigefügte Angebot.

${selectedTiresText}${newTiresText}

Kosten inkl. Reifenmontage (siehe Angebot im Anhang):
Zzgl.
Rädermontage                    49,99€
Einlagerung der Sommerreifen     85,00€${servicesText ? '\n' + servicesText : ''}

Für Rückfragen stehen wir Ihnen gerne unter Tel: 0431/54 63 00 zur Verfügung.

Mit freundlichem Gruß
Deniz Uludag
B&E Autocentrum GmbH

<span style="font-size: 0.8em; color: #dc2626;">Dieses Dokument wurde maschinell erstellt und ist ohne Unterschrift gültig</span>`;
            
            editor.innerHTML = brief.replace(/\n/g, '<br>');
            refreshPreview();
        }

        function resetLetterTemplate() {
            generateInitialLetter();
            refreshPreview();
        }

        // Auto-refresh with cooldown
        let previewTimeout;
        let lastPreviewUpdate = 0;
        const PREVIEW_COOLDOWN = 500; // 500ms cooldown

        function refreshPreview() {
            const now = Date.now();
            if (now - lastPreviewUpdate < PREVIEW_COOLDOWN) {
                // Clear existing timeout and set new one
                if (previewTimeout) {
                    clearTimeout(previewTimeout);
                }
                previewTimeout = setTimeout(refreshPreview, PREVIEW_COOLDOWN - (now - lastPreviewUpdate));
                return;
            }
            
            lastPreviewUpdate = now;
            
            const editor = document.getElementById('letterContent');
            const content = editor.innerHTML || editor.textContent || editor.value || '';
            const preview = document.getElementById('letterPreview');
            
            // Replace placeholders with actual data
            let processedContent = content
                .replace(/\[haltername\]/g, '[Haltername]')
                .replace(/\[kundenname\]/g, '[Kundenname]')
                .replace(/\[reifenart\]/g, '[Reifenart]')
                .replace(/\[kennzeichen\]/g, '[Kennzeichen]')
                .replace(/\[briefanrede\]/g, '[Briefanrede]');
            
            // Convert to HTML for display if needed
            let htmlContent = processedContent;
            if (!processedContent.includes('<')) {
                htmlContent = processedContent
                    .replace(/\n/g, '<br>')
                    .replace(/\[([^\]]+)\]/g, '<span class="placeholder">[$1]</span>');
            } else {
                // Already HTML, just add placeholder styling
                htmlContent = processedContent.replace(/\[([^\]]+)\]/g, '<span class="placeholder">[$1]</span>');
            }
            
            preview.innerHTML = htmlContent;
        }

        function refreshPreviewImmediate() {
            if (previewTimeout) {
                clearTimeout(previewTimeout);
            }
            refreshPreview();
        }

        async function downloadOfferPDF() {
            try {
                const editor = document.getElementById('letterContent');
                const content = editor.innerHTML || editor.textContent || editor.value || '';
                
                const response = await fetch('../api/generate_real_pdf.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        offer_data: offerData,
                        letter_content: content
                    })
                });
                
                const result = await response.json();
                if (result.success) {
                    // Direct download of PDF
                    const link = document.createElement('a');
                    link.href = result.download_url;
                    link.download = result.filename;
                    document.body.appendChild(link);
                    link.click();
                    document.body.removeChild(link);
                } else {
                    alert('Fehler beim Generieren des PDFs: ' + result.error);
                }
            } catch (error) {
                console.error('Fehler beim PDF-Download:', error);
                alert('Fehler beim PDF-Download: ' + error.message);
            }
        }

        async function sendOfferEmail() {
            // Show email modal
            showEmailModal();
        }
        
        // Show email modal
        function showEmailModal() {
            // Remove existing modal if any
            const existingModal = document.querySelector('.email-modal');
            if (existingModal) {
                existingModal.remove();
            }
            
            // Get current appointment email
            const currentAppointment = window.currentAppointment || {};
            const customerEmail = currentAppointment.email || '';
            
            const modal = document.createElement('div');
            modal.className = 'modal email-modal';
            modal.style.display = 'flex';
            modal.innerHTML = `
                <div class="modal-content email-modal-content">
                    <div class="modal-header">
                        <h3><i class="fas fa-envelope"></i> Angebot per E-Mail versenden</h3>
                        <button class="close-btn" onclick="closeEmailModal()">
                            <i class="fas fa-times"></i>
                        </button>
                    </div>
                    <div class="modal-body">
                        <div class="email-form">
                            <div class="form-group">
                                <label for="recipientEmail">E-Mail-Adresse des Kunden:</label>
                                <input type="email" id="recipientEmail" class="form-control" 
                                       placeholder="kunde@beispiel.de" value="${customerEmail}" required>
                            </div>
                            
                            <div class="form-group">
                                <label for="emailSubject">Betreff:</label>
                                <input type="text" id="emailSubject" class="form-control" 
                                       value="Reifenangebot - Boxenstop" required>
                            </div>
                            
                            <div class="form-group">
                                <label for="emailMessage">Nachricht:</label>
                                <textarea id="emailMessage" class="form-control" rows="4" 
                                          placeholder="Ihre zusätzliche Nachricht an den Kunden...">Sehr geehrte Damen und Herren,

anbei erhalten Sie Ihr Reifenangebot für den kommenden Boxenstop.

Bei Fragen stehen wir Ihnen gerne zur Verfügung.

Mit freundlichen Grüßen
Ihr B&E Autocentrum Team</textarea>
                            </div>
                            
                            <div class="smtp-info">
                                <h4><i class="fas fa-server"></i> SMTP-Konfiguration</h4>
                                <div id="smtpStatus" class="smtp-status">
                                    <i class="fas fa-spinner fa-spin"></i> Lade SMTP-Daten...
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button class="btn btn-secondary" onclick="closeEmailModal()">
                            <i class="fas fa-times"></i> Abbrechen
                        </button>
                        <button class="btn btn-primary" onclick="sendEmailWithModal()">
                            <i class="fas fa-paper-plane"></i> E-Mail senden
                        </button>
                    </div>
                </div>
            `;
            
            // Add click outside to close
            modal.onclick = function(e) {
                if (e.target === modal) {
                    closeEmailModal();
                }
            };
            
            document.body.appendChild(modal);
            
            // Load SMTP data
            loadSMTPData();
        }
        
        // Close email modal
        function closeEmailModal() {
            const modal = document.querySelector('.email-modal');
            if (modal) {
                modal.remove();
            }
        }
        
        // Load SMTP data
        async function loadSMTPData() {
            try {
                const appointment = window.currentAppointment || {};
                const appointmentId = appointment.id || window.currentAppointmentId;
                
                if (!appointmentId) {
                    document.getElementById('smtpStatus').innerHTML = 
                        '<i class="fas fa-exclamation-triangle text-warning"></i> Keine Termin-ID gefunden';
                    return;
                }
                
                const response = await fetch(`../api/get_smtp_data.php?appointmentId=${appointmentId}`);
                const data = await response.json();
                
                if (data.success) {
                    const smtpData = data.smtpData;
                    document.getElementById('smtpStatus').innerHTML = `
                        <div class="smtp-details">
                            <p><strong>Server:</strong> ${smtpData.email_smtp_host || 'Nicht konfiguriert'}</p>
                            <p><strong>Port:</strong> ${smtpData.email_smtp_port || 'Nicht konfiguriert'}</p>
                            <p><strong>Verschlüsselung:</strong> ${smtpData.email_smtp_encryption || 'Nicht konfiguriert'}</p>
                            <p><strong>Absender:</strong> ${smtpData.email_from_name || 'Nicht konfiguriert'}</p>
                            <div class="smtp-status-indicator ${smtpData.email_smtp_host ? 'status-ok' : 'status-error'}">
                                <i class="fas ${smtpData.email_smtp_host ? 'fa-check-circle' : 'fa-exclamation-triangle'}"></i>
                                ${smtpData.email_smtp_host ? 'SMTP konfiguriert' : 'SMTP nicht konfiguriert'}
                            </div>
                        </div>
                    `;
                } else {
                    document.getElementById('smtpStatus').innerHTML = 
                        '<i class="fas fa-exclamation-triangle text-warning"></i> Fehler beim Laden der SMTP-Daten';
                }
            } catch (error) {
                console.error('Fehler beim Laden der SMTP-Daten:', error);
                document.getElementById('smtpStatus').innerHTML = 
                    '<i class="fas fa-exclamation-triangle text-warning"></i> Fehler beim Laden der SMTP-Daten';
            }
        }
        
        // Send email with modal data
        async function sendEmailWithModal() {
            const recipientEmail = document.getElementById('recipientEmail').value;
            const emailSubject = document.getElementById('emailSubject').value;
            const emailMessage = document.getElementById('emailMessage').value;
            
            // Validate inputs
            if (!recipientEmail) {
                alert('Bitte geben Sie eine E-Mail-Adresse ein.');
                return;
            }
            
            const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
            if (!emailRegex.test(recipientEmail)) {
                alert('Bitte geben Sie eine gültige E-Mail-Adresse ein.');
                return;
            }
            
            if (!emailSubject) {
                alert('Bitte geben Sie einen Betreff ein.');
                return;
            }
            
            try {
                // Show loading state
                const sendButton = document.querySelector('.email-modal .btn-primary');
                const originalText = sendButton.innerHTML;
                sendButton.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Wird gesendet...';
                sendButton.disabled = true;
                
                // Get current appointment data
                const appointment = window.currentAppointment || {};
                const appointmentId = appointment.id || window.currentAppointmentId;
                
                if (!appointmentId) {
                    throw new Error('Keine Termin-ID gefunden');
                }
                
                // Create offer data for email
                const offerData = {
                    appointmentId: appointmentId,
                    selectedTires: getSelectedTiresData(),
                    newTires: newTires || [],
                    selectedServices: selectedServices || []
                };
                
                const editor = document.getElementById('offerEditor');
                const content = editor ? editor.innerHTML : '';
                
                console.log('Sending email with offer data:', offerData);
                
                const response = await fetch('../api/send_offer_email.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        offer_data: offerData,
                        letter_content: content,
                        recipient_email: recipientEmail,
                        email_subject: emailSubject,
                        email_message: emailMessage
                    })
                });
                
                const result = await response.json();
                if (result.success) {
                    showNotification('E-Mail erfolgreich versendet an: ' + recipientEmail, 'success');
                    
                    // Track offer sending
                    if (appointmentId) {
                        await trackOffer('sent', offerData, null, recipientEmail, emailSubject);
                    }
                    
                    // Close modal
                    closeEmailModal();
                } else {
                    alert('Fehler beim E-Mail-Versand: ' + result.error);
                }
            } catch (error) {
                console.error('Fehler beim E-Mail-Versand:', error);
                alert('Fehler beim E-Mail-Versand: ' + error.message);
            } finally {
                // Reset button state
                const sendButton = document.querySelector('.email-modal .btn-primary');
                if (sendButton) {
                    sendButton.innerHTML = '<i class="fas fa-paper-plane"></i> E-Mail senden';
                    sendButton.disabled = false;
                }
            }
        }

        // Tire Suggestions Functions
        let suggestionTimeout;

        async function showTireSuggestions(tireId, searchTerm) {
            if (suggestionTimeout) {
                clearTimeout(suggestionTimeout);
            }
            
            if (searchTerm.length < 2) {
                hideTireSuggestions(tireId);
                return;
            }
            
            suggestionTimeout = setTimeout(async () => {
                try {
                    const response = await fetch('../api/get_tire_suggestions.php', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                        },
                        body: JSON.stringify({
                            autohaus_id: getCurrentAutohausId(),
                            search: searchTerm,
                            limit: 5
                        })
                    });
                    
                    const result = await response.json();
                    if (result.success) {
                        displayTireSuggestions(tireId, result.suggestions);
                    }
                } catch (error) {
                    console.error('Fehler beim Laden der Reifenvorschläge:', error);
                }
            }, 300);
        }

        function displayTireSuggestions(tireId, suggestions) {
            const dropdown = document.getElementById(tireId + '_suggestions');
            
            if (suggestions.length === 0) {
                dropdown.style.display = 'none';
                return;
            }
            
            dropdown.innerHTML = '';
            
            suggestions.forEach(suggestion => {
                const item = document.createElement('div');
                item.className = 'suggestion-item';
                item.innerHTML = `
                    <div class="suggestion-brand">${suggestion.brand_model}</div>
                    <div class="suggestion-details">
                        ${suggestion.eu_label ? 'EU-Label: ' + suggestion.eu_label : ''}
                        ${suggestion.size_pattern ? ' | Größe: ' + suggestion.size_pattern : ''}
                        <span style="float: right; color: #999;">${suggestion.usage_count}x verwendet</span>
                    </div>
                `;
                
                item.onclick = () => {
                    selectTireSuggestion(tireId, suggestion);
                    hideTireSuggestions(tireId);
                };
                
                dropdown.appendChild(item);
            });
            
            dropdown.style.display = 'block';
        }

        function selectTireSuggestion(tireId, suggestion) {
            document.getElementById(tireId + '_brand_model').value = suggestion.brand_model;
            if (suggestion.eu_label) {
                document.getElementById(tireId + '_eu_label').value = suggestion.eu_label;
            }
            if (suggestion.size_pattern) {
                document.getElementById(tireId + '_size').value = suggestion.size_pattern;
            }
            
            updateTireData(tireId);
            
            // Save suggestion usage
            saveTireSuggestionUsage(suggestion);
        }

        function hideTireSuggestions(tireId) {
            const dropdown = document.getElementById(tireId + '_suggestions');
            dropdown.style.display = 'none';
        }

        async function saveTireSuggestionUsage(suggestion) {
            try {
                await fetch('../api/save_tire_suggestion.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        autohaus_id: getCurrentAutohausId(),
                        brand_model: suggestion.brand_model,
                        eu_label: suggestion.eu_label,
                        size_pattern: suggestion.size_pattern
                    })
                });
            } catch (error) {
                console.error('Fehler beim Speichern der Reifenvorschlag-Nutzung:', error);
            }
        }

        // Hide suggestions when clicking outside
        document.addEventListener('click', function(event) {
            if (!event.target.closest('.suggestion-container')) {
                document.querySelectorAll('.suggestions-dropdown').forEach(dropdown => {
                    dropdown.style.display = 'none';
                });
            }
        });
        
        // Load offer badges on page load
        document.addEventListener('DOMContentLoaded', function() {
            loadAllOfferBadges();
            
        });
        
        // Load all offer badges - DATABASE ONLY
        async function loadAllOfferBadges() {
            try {
                // One-time migration from localStorage to database
                await migrateLocalStorageToDatabase();
                
                // Get all appointment rows
                const appointmentRows = document.querySelectorAll('tr[data-appointment-id]');
                
                for (const row of appointmentRows) {
                    const appointmentId = row.getAttribute('data-appointment-id');
                    if (appointmentId) {
                        await updateOfferBadges(appointmentId);
                    }
                }
            } catch (error) {
                console.error('Fehler beim Laden der Angebot-Badges:', error);
            }
        }
        
        // Send Teams notification when offer is accepted
        async function sendTeamsNotification(appointmentId) {
            const maxRetries = 3;
            let retryCount = 0;
            
            while (retryCount < maxRetries) {
                try {
                    console.log(`📢 Versuche Teams-Nachricht zu senden (Versuch ${retryCount + 1}/${maxRetries}) für Appointment:`, appointmentId);
                    
                    const response = await fetch('../api/send_teams_notification.php', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                        },
                        body: JSON.stringify({
                            appointmentId: appointmentId
                        })
                    });
                    
                    const data = await response.json();
                    
                    if (data.success) {
                        console.log('✅ Teams-Benachrichtigung erfolgreich gesendet:', data.message);
                        
                        // Mark Teams notification as sent in database
                        await markTeamsNotificationSent(appointmentId);
                        return; // Erfolgreich gesendet, beende Funktion
                    } else {
                        console.warn(`⚠️ Teams-Benachrichtigung fehlgeschlagen (Versuch ${retryCount + 1}):`, data.error);
                        
                        if (retryCount < maxRetries - 1) {
                            // Warte vor dem nächsten Versuch (exponential backoff)
                            const waitTime = Math.pow(2, retryCount) * 1000; // 1s, 2s, 4s
                            console.log(`⏳ Warte ${waitTime}ms vor dem nächsten Versuch...`);
                            await new Promise(resolve => setTimeout(resolve, waitTime));
                        }
                    }
                } catch (error) {
                    console.error(`❌ Fehler beim Senden der Teams-Benachrichtigung (Versuch ${retryCount + 1}):`, error);
                    
                    if (retryCount < maxRetries - 1) {
                        // Warte vor dem nächsten Versuch
                        const waitTime = Math.pow(2, retryCount) * 1000;
                        console.log(`⏳ Warte ${waitTime}ms vor dem nächsten Versuch...`);
                        await new Promise(resolve => setTimeout(resolve, waitTime));
                    }
                }
                
                retryCount++;
            }
            
            console.error('❌ Teams-Benachrichtigung nach', maxRetries, 'Versuchen fehlgeschlagen');
        }
        
        // Mark Teams notification as sent
        async function markTeamsNotificationSent(appointmentId) {
            try {
                // Generate unique message ID for tracking
                const teamsMessageId = 'msg_' + appointmentId + '_' + Date.now();
                
                const response = await fetch('../api/mark_teams_notification_sent.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        appointmentId: appointmentId,
                        teamsMessageId: teamsMessageId
                    })
                });
                
                const data = await response.json();
                
                if (data.success) {
                    console.log('✅ Teams-Status aktualisiert mit Message-ID:', teamsMessageId);
                } else {
                    console.warn('⚠️ Teams-Status konnte nicht aktualisiert werden:', data.error);
                }
            } catch (error) {
                console.error('❌ Fehler beim Aktualisieren des Teams-Status:', error);
            }
        }
        
        // One-time migration from localStorage to database
        async function migrateLocalStorageToDatabase() {
            try {
                const localStorageData = JSON.parse(localStorage.getItem('offer_tracking') || '[]');
                
                if (localStorageData.length === 0) {
                    return; // Nothing to migrate
                }
                
                console.log(`🔄 Einmalige Migration: ${localStorageData.length} Angebote von localStorage zur Datenbank...`);
                
                let migratedCount = 0;
                for (const offer of localStorageData) {
                    try {
                        const response = await fetch('../api/track_offer.php', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                            },
                            body: JSON.stringify({
                                appointment_id: offer.appointment_id,
                                user_id: offer.user_id,
                                username: offer.username,
                                offer_type: offer.offer_type,
                                offer_data: offer.offer_data,
                                pdf_filename: offer.pdf_filename,
                                email_recipient: offer.email_recipient,
                                email_subject: offer.email_subject
                            })
                        });
                        
                        const result = await response.json();
                        if (result.success) {
                            migratedCount++;
                            console.log(`✅ Angebot ${offer.offer_type} migriert`);
                        }
                    } catch (migrationError) {
                        console.log(`⚠️ Migration fehlgeschlagen für Angebot ${offer.id}:`, migrationError.message);
                    }
                }
                
                // Clear localStorage after migration
                if (migratedCount > 0) {
                    localStorage.removeItem('offer_tracking');
                    console.log(`🧹 ${migratedCount} Angebote migriert, localStorage geleert`);
                }
                
            } catch (error) {
                console.error('Fehler bei der Migration:', error);
            }
        }
    </script>
    
    <style>
        /* Email Modal Styles */
        .email-modal {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 10000;
        }
        
        .email-modal-content {
            background: white;
            border-radius: 12px;
            max-width: 600px;
            width: 90%;
            max-height: 90%;
            overflow-y: auto;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.3);
        }
        
        .email-form {
            padding: 20px;
        }
        
        .form-group {
            margin-bottom: 20px;
        }
        
        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: #333;
        }
        
        .form-control {
            width: 100%;
            padding: 12px;
            border: 2px solid #e1e5e9;
            border-radius: 8px;
            font-size: 14px;
            transition: border-color 0.3s ease;
            box-sizing: border-box;
        }
        
        .form-control:focus {
            outline: none;
            border-color: #007bff;
            box-shadow: 0 0 0 3px rgba(0, 123, 255, 0.1);
        }
        
        .smtp-info {
            margin-top: 25px;
            padding: 20px;
            background: #f8f9fa;
            border-radius: 8px;
            border: 1px solid #e9ecef;
        }
        
        .smtp-info h4 {
            margin: 0 0 15px 0;
            color: #495057;
            font-size: 16px;
        }
        
        .smtp-status {
            padding: 15px;
            background: white;
            border-radius: 6px;
            border: 1px solid #dee2e6;
        }
        
        .smtp-details p {
            margin: 8px 0;
            font-size: 14px;
            color: #495057;
        }
        
        .smtp-details strong {
            color: #212529;
        }
        
        .smtp-status-indicator {
            margin-top: 15px;
            padding: 10px;
            border-radius: 6px;
            font-weight: 600;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        
        .status-ok {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        
        .status-error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        
        .text-warning {
            color: #856404 !important;
        }
    </style>
</body>
</html>

