<?php if (isset($component)) { $__componentOriginal9ac128a9029c0e4701924bd2d73d7f54 = $component; } ?>
<?php if (isset($attributes)) { $__attributesOriginal9ac128a9029c0e4701924bd2d73d7f54 = $attributes; } ?>
<?php $component = App\View\Components\AppLayout::resolve([] + (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag ? (array) $attributes->getIterator() : [])); ?>
<?php $component->withName('app-layout'); ?>
<?php if ($component->shouldRender()): ?>
<?php $__env->startComponent($component->resolveView(), $component->data()); ?>
<?php if (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag && $constructor = (new ReflectionClass(App\View\Components\AppLayout::class))->getConstructor()): ?>
<?php $attributes = $attributes->except(collect($constructor->getParameters())->map->getName()->all()); ?>
<?php endif; ?>
<?php $component->withAttributes([]); ?>
     <?php $__env->slot('title', null, []); ?> 
        <?php echo e($flow ? 'تعديل: ' . $flow->name : 'Flow Builder جديد'); ?>

     <?php $__env->endSlot(); ?>

<style>
        /* Base & Structure Reset */
        body, html {
            overflow: hidden;
            height: 100vh;
        }
        
        /* Override unnecessary max-width */
        .max-w-\[1200px\] {
            max-width: none !important;
        }

        /* -------------------------------------- */
        /* Canvas Grid Background */
        #flowCanvas {
            background-image: 
                linear-gradient(rgba(0, 0, 0, 0.05) 1px, transparent 1px),
                linear-gradient(90deg, rgba(0, 0, 0, 0.05) 1px, transparent 1px);
            background-size: 20px 20px;
        }
        
        /* Node Styles (Same as before) */
        .node {
            cursor: grab;
            transition: all 0.2s;
            user-select: none;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
        }
        .node:hover {
            transform: scale(1.02);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        }
        .node:active { cursor: grabbing; }
        .node.selected {
            border: 2px solid #4f46e5 !important;
            box-shadow: 0 0 0 4px rgba(79, 70, 229, 0.1);
        }

        /* Node Type Colors (Same as before) */
        .node-start { border-left: 4px solid #10b981; }
        .node-text { border-left: 4px solid #3b82f6; }
        .node-buttons { border-left: 4px solid #8b5cf6; }
        .node-quick_replies { border-left: 4px solid #f59e0b; }
        .node-carousel { border-left: 4px solid #ec4899; }
        .node-image { border-left: 4px solid #06b6d4; }
        .node-video { border-left: 4px solid #ef4444; }
        .node-delay { border-left: 4px solid #6366f1; }
        .node-condition { border-left: 4px solid #eab308; }
        .node-end { border-left: 4px solid #dc2626; }
        .node-ai { border-left: 4px solid #14b8a6; }

        /* Connection Lines (Same as before) */
        .connection-line {
            stroke: #94a3b8;
            stroke-width: 2;
            fill: none;
            pointer-events: stroke;
            cursor: pointer;
        }
        .connection-line:hover { stroke: #4f46e5; stroke-width: 3; }
        .connection-arrow { fill: #94a3b8; }
        #nodesContainer { transform-origin: 0 0; }

        /* Sidebar Scrollbar (Same as before) */
        .sidebar-scroll {
            max-height: calc(100vh - 64px);
            overflow-y: auto;
        }
        .sidebar-scroll::-webkit-scrollbar { width: 6px; }
        .sidebar-scroll::-webkit-scrollbar-thumb { background: rgba(0, 0, 0, 0.2); border-radius: 3px; }

        /* Palette Item (Same as before) */
        .node-palette-item { user-select: none; cursor: grab; }
        .node-palette-item:active { cursor: grabbing; }

        /* Loading Spinner (Same as before) */
        .spinner {
            border: 3px solid #f3f4f6;
            border-top: 3px solid #4f46e5;
            border-radius: 50%;
            width: 24px;
            height: 24px;
            animation: spin 0.8s linear infinite;
        }
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        /* -------------------------------------- */
        /* 📱 MOBILE RESPONSIVENESS HACKS (Override for small screens) */
        
        /* إخفاء الأشرطة الجانبية افتراضياً على الشاشات الصغيرة */
        .left-sidebar, .right-sidebar {
            transition: transform 0.3s ease;
            position: absolute;
            height: 100%;
            z-index: 20;
            top: 0;
        }
        
        /* إعدادات الشريط الأيسر (Palette) */
        .left-sidebar {
            width: 80%; /* يشغل 80% من العرض على الموبايل */
            transform: translateX(-100%); /* مخفي يساراً */
        }
        .left-sidebar.is-open {
            transform: translateX(0);
        }
        
        /* إعدادات الشريط الأيمن (Properties) */
        .right-sidebar {
            width: 80%; /* يشغل 80% من العرض على الموبايل */
            right: 0;
            transform: translateX(100%); /* مخفي يميناً */
        }
        .right-sidebar.is-open {
            transform: translateX(0);
        }
        
        /* إخفاء زر التبديل على الشاشات الكبيرة */
        .mobile-toggle {
            display: flex;
        }

        /* 💻 DESKTOP/TABLET VIEW (≥ 1024px) */
        @media (min-width: 1024px) {
            .left-sidebar {
                position: relative;
                width: 256px; /* w-64 */
                transform: translateX(0);
            }
            .right-sidebar {
                position: relative;
                width: 320px; /* w-80 */
                transform: translateX(0);
            }
            .mobile-toggle {
                display: none;
            }
        }
    </style>
   
<script src="https://kit.fontawesome.com/6130ba508c.js" crossorigin="anonymous"></script>    <div class="h-screen flex flex-col">
        <!-- Top Bar -->
        <div class="bg-white border-b px-4 py-3 flex items-center justify-between flex-shrink-0">
            <div class="flex items-center gap-4">
                <a href="<?php echo e(route('messenger-flows.index')); ?>" class="text-gray-500 hover:text-gray-700">
                    <i class="fas fa-arrow-left"></i>
                </a>
                <div>
                    <input type="text" id="flowName" 
                           value="<?php echo e($flow->name ?? 'Flow جديد'); ?>" 
                           class="text-lg font-semibold bg-transparent border-none focus:outline-none focus:ring-0 p-0"
                           placeholder="اسم الـFlow">
                    <div class="text-xs text-gray-500">Flow Builder</div>
                </div>
            </div>

            <div class="flex items-center gap-2">
                <!-- Undo/Redo -->
                <button onclick="undoAction()" class="p-2 hover:bg-gray-100 rounded-lg transition-colors" title="تراجع (Ctrl+Z)">
                    <i class="fas fa-undo"></i>
                </button>
                <button onclick="redoAction()" class="p-2 hover:bg-gray-100 rounded-lg transition-colors" title="إعادة (Ctrl+Y)">
                    <i class="fas fa-redo"></i>
                </button>

                <div class="w-px h-6 bg-gray-300 mx-2"></div>

                <!-- Zoom Controls -->
                <button onclick="zoomIn()" class="p-2 hover:bg-gray-100 rounded-lg transition-colors" title="تكبير">
                    <i class="fas fa-search-plus"></i>
                </button>
                <button onclick="zoomOut()" class="p-2 hover:bg-gray-100 rounded-lg transition-colors" title="تصغير">
                    <i class="fas fa-search-minus"></i>
                </button>
                <button onclick="resetZoom()" class="p-2 hover:bg-gray-100 rounded-lg transition-colors" title="إعادة تعيين">
                    <i class="fas fa-expand"></i>
                </button>

                <div class="w-px h-6 bg-gray-300 mx-2"></div>

                <!-- Settings & Save -->
                <button onclick="openSettings()" class="px-4 py-2 border rounded-lg hover:bg-gray-50 transition-colors text-sm">
                    <i class="fas fa-cog mr-2"></i>الإعدادات
                </button>
                <button onclick="saveFlow()" class="px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary/90 transition-colors text-sm">
                    <i class="fas fa-save mr-2"></i>حفظ
                </button>
            </div>
        </div>

        <div class="flex flex-1 overflow-hidden">
            <!-- Left Sidebar - Node Palette -->
            <div class="w-64 bg-gray-50 border-r flex-shrink-0 sidebar-scroll">
                <div class="p-4">
                    <h3 class="text-xs font-semibold mb-3 text-gray-600 border-b pb-2">
                        <i class="fas fa-puzzle-piece mr-1"></i>
                        عناصر الـFlow
                    </h3>
                    
                    <div class="space-y-2" id="nodePalette">
                        <!-- Start Node -->
                        <div class="node-palette-item p-3 bg-white border border-green-200 rounded-lg shadow-sm hover:shadow-md transition-shadow" 
                             draggable="true" data-node-type="start">
                            <div class="flex items-center gap-2">
                                <div class="w-8 h-8 bg-green-100 rounded-lg flex items-center justify-center flex-shrink-0">
                                    <i class="fas fa-play text-green-600"></i>
                                </div>
                                <div>
                                    <div class="text-sm font-medium">بداية</div>
                                    <div class="text-xs text-gray-400">نقطة البداية</div>
                                </div>
                            </div>
                        </div>

                        <!-- Text Node -->
                        <div class="node-palette-item p-3 bg-white border border-blue-200 rounded-lg shadow-sm hover:shadow-md transition-shadow" 
                             draggable="true" data-node-type="text">
                            <div class="flex items-center gap-2">
                                <div class="w-8 h-8 bg-blue-100 rounded-lg flex items-center justify-center flex-shrink-0">
                                    <i class="fas fa-comment text-blue-600"></i>
                                </div>
                                <div>
                                    <div class="text-sm font-medium">رسالة نصية</div>
                                    <div class="text-xs text-gray-400">إرسال نص</div>
                                </div>
                            </div>
                        </div>


<!-- AI Node   -->
<div class="node-palette-item p-3 bg-white border border-teal-200 rounded-lg shadow-sm hover:shadow-md transition-shadow" 
     draggable="true" data-node-type="ai">
    <div class="flex items-center gap-2">
        <div class="w-8 h-8 bg-teal-100 rounded-lg flex items-center justify-center flex-shrink-0">
            <i class="fas fa-brain text-teal-600"></i>
        </div>
        <div>
            <div class="text-sm font-medium">ذكاء اصطناعي</div>
            <div class="text-xs text-gray-400">AI Response</div>
        </div>
    </div>
</div>

                        <!-- Buttons Node -->
                        <div class="node-palette-item p-3 bg-white border border-purple-200 rounded-lg shadow-sm hover:shadow-md transition-shadow" 
                             draggable="true" data-node-type="buttons">
                            <div class="flex items-center gap-2">
                                <div class="w-8 h-8 bg-purple-100 rounded-lg flex items-center justify-center flex-shrink-0">
                                    <i class="fas fa-th text-purple-600"></i>
                                </div>
                                <div>
                                    <div class="text-sm font-medium">أزرار</div>
                                    <div class="text-xs text-gray-400">خيارات بأزرار</div>
                                </div>
                            </div>
                        </div>

                        <!-- Quick Replies Node -->
                        <div class="node-palette-item p-3 bg-white border border-orange-200 rounded-lg shadow-sm hover:shadow-md transition-shadow" 
                             draggable="true" data-node-type="quick_replies">
                            <div class="flex items-center gap-2">
                                <div class="w-8 h-8 bg-orange-100 rounded-lg flex items-center justify-center flex-shrink-0">
                                    <i class="fas fa-bolt text-orange-600"></i>
                                </div>
                                <div>
                                    <div class="text-sm font-medium">ردود سريعة</div>
                                    <div class="text-xs text-gray-400">Quick Replies</div>
                                </div>
                            </div>
                        </div>

                        <!-- Carousel Node -->
                        <div class="node-palette-item p-3 bg-white border border-pink-200 rounded-lg shadow-sm hover:shadow-md transition-shadow" 
                             draggable="true" data-node-type="carousel">
                            <div class="flex items-center gap-2">
                                <div class="w-8 h-8 bg-pink-100 rounded-lg flex items-center justify-center flex-shrink-0">
                                    <i class="fas fa-images text-pink-600"></i>
                                </div>
                                <div>
                                    <div class="text-sm font-medium">Carousel</div>
                                    <div class="text-xs text-gray-400">معرض صور</div>
                                </div>
                            </div>
                        </div>

                        <!-- Image Node -->
                        <div class="node-palette-item p-3 bg-white border border-cyan-200 rounded-lg shadow-sm hover:shadow-md transition-shadow" 
                             draggable="true" data-node-type="image">
                            <div class="flex items-center gap-2">
                                <div class="w-8 h-8 bg-cyan-100 rounded-lg flex items-center justify-center flex-shrink-0">
                                    <i class="fas fa-image text-cyan-600"></i>
                                </div>
                                <div>
                                    <div class="text-sm font-medium">صورة</div>
                                    <div class="text-xs text-gray-400">إرسال صورة</div>
                                </div>
                            </div>
                        </div>

                        <!-- Video Node -->
                        <div class="node-palette-item p-3 bg-white border border-red-200 rounded-lg shadow-sm hover:shadow-md transition-shadow" 
                             draggable="true" data-node-type="video">
                            <div class="flex items-center gap-2">
                                <div class="w-8 h-8 bg-red-100 rounded-lg flex items-center justify-center flex-shrink-0">
                                    <i class="fas fa-video text-red-600"></i>
                                </div>
                                <div>
                                    <div class="text-sm font-medium">فيديو</div>
                                    <div class="text-xs text-gray-400">إرسال فيديو</div>
                                </div>
                            </div>
                        </div>

                        <!-- Delay Node -->
                        <div class="node-palette-item p-3 bg-white border border-indigo-200 rounded-lg shadow-sm hover:shadow-md transition-shadow" 
                             draggable="true" data-node-type="delay">
                            <div class="flex items-center gap-2">
                                <div class="w-8 h-8 bg-indigo-100 rounded-lg flex items-center justify-center flex-shrink-0">
                                    <i class="fas fa-clock text-indigo-600"></i>
                                </div>
                                <div>
                                    <div class="text-sm font-medium">تأخير</div>
                                    <div class="text-xs text-gray-400">انتظار</div>
                                </div>
                            </div>
                        </div>

                        <!-- Condition Node -->
                        <div class="node-palette-item p-3 bg-white border border-yellow-200 rounded-lg shadow-sm hover:shadow-md transition-shadow" 
                             draggable="true" data-node-type="condition">
                            <div class="flex items-center gap-2">
                                <div class="w-8 h-8 bg-yellow-100 rounded-lg flex items-center justify-center flex-shrink-0">
                                    <i class="fas fa-code-branch text-yellow-600"></i>
                                </div>
                                <div>
                                    <div class="text-sm font-medium">شرط</div>
                                    <div class="text-xs text-gray-400">تفرّع منطقي</div>
                                </div>
                            </div>
                        </div>

                        <!-- End Node -->
                        <div class="node-palette-item p-3 bg-white border border-red-200 rounded-lg shadow-sm hover:shadow-md transition-shadow" 
                             draggable="true" data-node-type="end">
                            <div class="flex items-center gap-2">
                                <div class="w-8 h-8 bg-red-100 rounded-lg flex items-center justify-center flex-shrink-0">
                                    <i class="fas fa-stop text-red-600"></i>
                                </div>
                                <div>
                                    <div class="text-sm font-medium">نهاية</div>
                                    <div class="text-xs text-gray-400">إنهاء الـFlow</div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Canvas -->
            <div class="flex-1 relative overflow-hidden bg-gray-100" id="canvasContainer">
                <svg id="flowCanvas" class="absolute inset-0 w-full h-full" style="pointer-events: none;">
                    <defs>
                        <marker id="arrowhead" markerWidth="10" markerHeight="10" refX="9" refY="3" orient="auto">
                            <polygon points="0 0, 10 3, 0 6" class="connection-arrow fill-gray-500" />
                        </marker>
                    </defs>
                    <g id="connectionsGroup"></g>
                </svg>
                <div id="nodesContainer" class="absolute inset-0" style="pointer-events: auto;"></div>
            </div>

            <!-- Right Sidebar - Properties -->
            <div class="w-80 bg-white border-l flex-shrink-0 sidebar-scroll" id="propertiesPanel">
                <div class="p-4">
                    <h3 class="text-sm font-semibold mb-4 text-gray-600 border-b pb-2">
                        <i class="fas fa-sliders-h mr-1"></i>
                        خصائص العقدة
                    </h3>
                    <div id="propertiesContent" class="text-sm text-gray-500 text-center py-12">
                        <i class="fas fa-mouse-pointer text-4xl mb-3 opacity-50"></i>
                        <p>اختر عقدة لتعديل خصائصها</p>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Settings Modal -->
    <div id="settingsModal" class="hidden fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
        <div class="bg-white rounded-xl max-w-2xl w-full shadow-2xl max-h-[90vh] overflow-y-auto">
            <div class="p-6 border-b flex items-center justify-between">
                <h3 class="text-lg font-semibold">
                    <i class="fas fa-cog text-indigo-600 mr-2"></i>
                    إعدادات الـFlow
                </h3>
                <button onclick="closeSettings()" class="text-gray-400 hover:text-gray-600">
                    <i class="fas fa-times"></i>
                </button>
            </div>

            <div class="p-6 space-y-4">
                <!-- Facebook Page -->
                <div>
                    <label class="block text-sm font-medium mb-2">
                        <i class="fas fa-facebook text-blue-600 mr-1"></i>
                        صفحة الفيسبوك
                        <span class="text-red-500">*</span>
                    </label>
                    <select id="facebookPageId" class="w-full border rounded-lg px-3 py-2 text-sm" required>
                        <option value="">-- اختر صفحة --</option>
                        <?php $__currentLoopData = $pages; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $page): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                            <option value="<?php echo e($page->id); ?>" <?php echo e(($flow->facebook_page_id ?? null) == $page->id ? 'selected' : ''); ?>>
                                <?php echo e($page->name); ?>

                                <?php if($page->page_id): ?>
                                    <span class="text-muted-foreground">(<?php echo e($page->page_id); ?>)</span>
                                <?php endif; ?>
                            </option>
                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                    </select>
                    <?php if($pages->isEmpty()): ?>
                        <p class="text-xs text-red-600 mt-1">
                            <i class="fas fa-exclamation-triangle mr-1"></i>
                            لا توجد صفحات متصلة. 
                            <a href="<?php echo e(route('facebook-pages.index')); ?>" class="underline">أضف صفحة</a>
                        </p>
                    <?php else: ?>
                        <p class="text-xs text-muted-foreground mt-1">
                            الصفحة التي سيعمل عليها هذا الـFlow
                        </p>
                    <?php endif; ?>
                </div>

                <!-- Description -->
                <div>
                    <label class="block text-sm font-medium mb-2">الوصف</label>
                    <textarea id="flowDescription" 
                              class="w-full border rounded-lg px-3 py-2 text-sm" 
                              rows="3" 
                              placeholder="وصف مختصر للـFlow..."><?php echo e($flow->description ?? ''); ?></textarea>
                </div>

                <!-- Trigger Type -->
                <div>
                    <label class="block text-sm font-medium mb-2">نوع التشغيل</label>
                    <select id="triggerType" class="w-full border rounded-lg px-3 py-2 text-sm" onchange="toggleTriggerFields()">
                        <option value="keyword" <?php echo e(($flow->trigger_type ?? 'keyword') == 'keyword' ? 'selected' : ''); ?>>كلمة مفتاحية</option>
                        <option value="greeting" <?php echo e(($flow->trigger_type ?? '') == 'greeting' ? 'selected' : ''); ?>>رسالة ترحيب</option>
                    </select>
                </div>

                <!-- Keywords Field -->
                <div id="keywordsField">
                    <label class="block text-sm font-medium mb-2">الكلمات المفتاحية</label>
                    <input type="text" 
                           id="triggerKeywords" 
                           class="w-full border rounded-lg px-3 py-2 text-sm" 
                           placeholder="hello, مرحبا, start" 
                           value="<?php echo e(is_array($flow->trigger_keywords ?? null) ? implode(', ', $flow->trigger_keywords) : ''); ?>">
                    <p class="text-xs text-muted-foreground mt-1">
                        افصل الكلمات بفاصلة (,)
                    </p>
                </div>


<div class="space-y-2">
    <label class="flex items-center justify-between p-3 bg-purple-50 dark:bg-purple-900/20 rounded-lg cursor-pointer">
        <div class="flex-1">
            <div class="font-semibold text-purple-800 dark:text-purple-200">
                <i class="fas fa-brain me-2"></i>
                وضع المحادثة المستمرة بالذكاء الاصطناعي
            </div>
            <p class="text-sm text-purple-600 dark:text-purple-300 mt-1">
                عند التفعيل، سيستمر البوت في الرد باستخدام AI على جميع الرسائل دون الحاجة للكلمات المفتاحية
            </p>
        </div>
        <div>
            <input type="hidden" name="continuous_ai_mode" value="0">
            <input type="checkbox" 
                   name="continuous_ai_mode" 
                   value="1"
                   <?php echo e(old('continuous_ai_mode', $flow->continuous_ai_mode ?? false) ? 'checked' : ''); ?>

                   class="w-5 h-5 text-purple-600 bg-gray-100 border-gray-300 rounded focus:ring-purple-500 dark:bg-gray-700 dark:border-gray-600">
        </div>
    </label>
    
    <div class="bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-700 text-yellow-800 dark:text-yellow-200 px-3 py-2 rounded text-xs">
        <i class="fas fa-exclamation-triangle me-1"></i>
        <strong>ملاحظة:</strong> يعمل فقط إذا كان Flow يحتوي على عقدة AI
    </div>
</div>

                <!-- Priority -->
                <div>
                    <label class="block text-sm font-medium mb-2">الأولوية</label>
                    <input type="number" 
                           id="flowPriority" 
                           class="w-full border rounded-lg px-3 py-2 text-sm" 
                           min="0" 
                           value="<?php echo e($flow->priority ?? 0); ?>">
                    <p class="text-xs text-muted-foreground mt-1">
                        الـFlows ذات الأولوية الأعلى يتم فحصها أولاً
                    </p>
                </div>

                <!-- Is Active -->
                <div class="flex items-center gap-2">
                    <input type="checkbox" 
                           id="isActive" 
                           class="w-4 h-4" 
                           <?php echo e(($flow->is_active ?? true) ? 'checked' : ''); ?>>
                    <label for="isActive" class="text-sm font-medium">تفعيل الـFlow</label>
                </div>
            </div>

            <div class="p-6 border-t flex justify-end gap-2">
                <button onclick="closeSettings()" 
                        class="px-4 py-2 border rounded-lg hover:bg-gray-50">
                    إلغاء
                </button>
                <button onclick="applySettings()" 
                        class="px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary/90 transition-colors">
                    تطبيق
                </button>
            </div>
        </div>
    </div>

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        // Global Variables
        const FLOW_ID = <?php echo e($flow->id ?? 'null'); ?>;
        const CSRF_TOKEN = '<?php echo e(csrf_token()); ?>';
        const SAVE_URL = FLOW_ID ? `/messenger-flows/${FLOW_ID}` : '/messenger-flows';
        const HTTP_METHOD = FLOW_ID ? 'PUT' : 'POST';

        let flowData = {
            nodes: [],
            connections: []
        };
        
        let selectedNode = null;
        let isDraggingNode = false;
        let isConnecting = false;
        let connectionStart = null;
        let nodeIdCounter = 1;
        let zoom = 1;
        let panX = 0;
        let panY = 0;
        let history = [];
        let historyIndex = -1;

        let flowSettings = {
            description: document.getElementById('flowDescription')?.value.trim() || '',
            triggerType: document.getElementById('triggerType')?.value || 'keyword',
            triggerKeywords: document.getElementById('triggerKeywords')?.value.split(',').map(k => k.trim()).filter(k => k) || [],
            priority: parseInt(document.getElementById('flowPriority')?.value || 0),
            isActive: document.getElementById('isActive')?.checked || false,
                continuousAIMode: false  
        };

        // Initialize
       // Initialize flow settings on page load
document.addEventListener('DOMContentLoaded', function() {
    console.log('🚀 Flow Builder Initialized');
    
    // تحديث إعدادات الـFlow من العناصر
    updateFlowSettingsFromDOM();
    
    // Load existing flow data
    <?php if($flow && $flow->flow_data): ?>
        const existingFlowJson = <?php echo json_encode($flow->flow_data, 15, 512) ?>;
        if (existingFlowJson && existingFlowJson.nodes) {
            flowData = existingFlowJson;
            nodeIdCounter = Math.max(...flowData.nodes.map(n => parseInt(n.id.replace('node-', ''))), 0) + 1;
            renderFlow();
        }
    <?php endif; ?>

    // Load template from sessionStorage if exists
    const templateData = sessionStorage.getItem('flowTemplate');
    if (templateData && !FLOW_ID) {
        try {
            const template = JSON.parse(templateData);
            flowData = template;
            nodeIdCounter = Math.max(...flowData.nodes.map(n => parseInt(n.id.replace('node-', ''))), 0) + 1;
            renderFlow();
            sessionStorage.removeItem('flowTemplate');
        } catch(e) {
            console.error('Failed to load template', e);
        }
    }

    // Add start node if empty
    if (flowData.nodes.length === 0) {
        addNode('start', 150, 100);
    }

    setupEventListeners();
    toggleTriggerFields();
    saveToHistory();
});

// دالة لتحديث إعدادات الـFlow من الـDOM
function updateFlowSettingsFromDOM() {
    const descElement = document.getElementById('flowDescription');
    const triggerElement = document.getElementById('triggerType');
    const keywordsElement = document.getElementById('triggerKeywords');
    const priorityElement = document.getElementById('flowPriority');
    const activeElement = document.getElementById('isActive');
    
    flowSettings = {
        description: descElement ? descElement.value.trim() : '',
        triggerType: triggerElement ? triggerElement.value : 'keyword',
        triggerKeywords: keywordsElement ? keywordsElement.value.split(',').map(k => k.trim()).filter(k => k) : [],
        priority: priorityElement ? parseInt(priorityElement.value || 0) : 0,
        isActive: activeElement ? activeElement.checked : false
    };
}


        // Event Listeners Setup
        function setupEventListeners() {
            // Drag & Drop from Palette
            document.querySelectorAll('.node-palette-item').forEach(item => {
                item.addEventListener('dragstart', function(e) {
                    const nodeType = this.getAttribute('data-node-type');
                    e.dataTransfer.setData('nodeType', nodeType);
                    e.dataTransfer.effectAllowed = 'copy';
                });
            });

            const canvasContainer = document.getElementById('canvasContainer');
            
            canvasContainer.addEventListener('dragover', function(e) {
                e.preventDefault();
                e.dataTransfer.dropEffect = 'copy';
            });

            canvasContainer.addEventListener('drop', function(e) {
                e.preventDefault();
                const nodeType = e.dataTransfer.getData('nodeType');
                if (!nodeType) return;

                const rect = this.getBoundingClientRect();
                const x = (e.clientX - rect.left - panX) / zoom;
                const y = (e.clientY - rect.top - panY) / zoom;

                addNode(nodeType, x, y);
            });

            // Canvas Panning
            let isPanning = false;
            let startX, startY;

            canvasContainer.addEventListener('mousedown', function(e) {
                if (e.target.closest('.node') || isConnecting) return;
                
                if (e.target === this || e.target.id === 'flowCanvas' || e.target.id === 'nodesContainer') {
                    isPanning = true;
                    startX = e.clientX - panX;
                    startY = e.clientY - panY;
                    this.style.cursor = 'grabbing';
                }
            });

            document.addEventListener('mousemove', function(e) {
                if (isPanning) {
                    panX = e.clientX - startX;
                    panY = e.clientY - startY;
                    updateTransform();
                }
            });

            document.addEventListener('mouseup', function() {
                if (isPanning) {
                    isPanning = false;
                    canvasContainer.style.cursor = 'default';
                }
            });

            // Keyboard Shortcuts
            document.addEventListener('keydown', function(e) {
                if (e.key === 'Delete' && selectedNode) {
                    e.preventDefault();
                    deleteNode(selectedNode);
                }

                if ((e.ctrlKey || e.metaKey) && e.key === 'z') {
                    e.preventDefault();
                    undoAction();
                }

                if ((e.ctrlKey || e.metaKey) && e.key === 'y') {
                    e.preventDefault();
                    redoAction();
                }

                if ((e.ctrlKey || e.metaKey) && e.key === 's') {
                    e.preventDefault();
                    saveFlow();
                }
            });

            // Canvas Click (deselect)
            canvasContainer.addEventListener('click', function(e) {
                if (e.target.closest('.node') || e.target.closest('.connection-line') || e.target.closest('.connection-point')) {
                    return;
                }
                
                if (e.target === this || e.target.id === 'flowCanvas' || e.target.id === 'nodesContainer') {
                    selectedNode = null;
                    document.querySelectorAll('.node').forEach(n => n.classList.remove('selected'));
                    document.getElementById('propertiesContent').innerHTML = `
                        <div class="text-sm text-gray-500 text-center py-12">
                            <i class="fas fa-mouse-pointer text-4xl mb-3 opacity-50"></i>
                            <p>اختر عقدة لتعديل خصائصها</p>
                        </div>
                    `;
                }
            });
        }

        // Add Node
        function addNode(type, x, y) {
            // Check if start node already exists
            if (type === 'start' && flowData.nodes.some(n => n.type === 'start')) {
                alert('يمكن وجود عقدة بداية واحدة فقط');
                return;
            }

            const nodeId = `node-${nodeIdCounter++}`;
            const node = {
                id: nodeId,
                type: type,
                position: { x, y },
                data: getDefaultNodeData(type)
            };

            flowData.nodes.push(node);
            renderNode(node);
            selectNode(nodeId);
            saveToHistory();
        }

        // Get Default Node Data
      function getDefaultNodeData(type) {
    const defaults = {
        'start': {},
        'text': { text: 'مرحباً! 👋' },
        'buttons': { 
            text: 'اختر أحد الخيارات:', 
            buttons: [
                { title: 'خيار 1', payload: 'option1', type: 'postback' }
            ] 
        },
        'quick_replies': { 
            text: 'اختر:', 
            quick_replies: [
                { title: 'استفسار', payload: 'inquiry' }
            ] 
        },
        'carousel': { 
            elements: [
                { 
                    title: 'عنصر 1', 
                    subtitle: 'وصف العنصر', 
                    image_url: 'https://placehold.co/300x200/F0F4FF/1E40AF?text=صورة',
                    buttons: [
                        { title: 'تفاصيل', payload: 'details1', type: 'postback' }
                    ]
                }
            ] 
        },
        'image': { image_url: 'https://placehold.co/400x300/F0F4FF/1E40AF?text=صورة' },
        'video': { video_url: '' },
        'delay': { seconds: 2 },
        'condition': { variable: 'user_input', operator: '==', value: '' },
        'ai': {
            ai_provider: 'openai',
            model: 'gpt-4o-mini',
            instructions: 'أنت مساعد خدمة عملاء محترف ومهذب. أجب على أسئلة العملاء بشكل واضح ومفيد.\n\nمعلومات الشركة:\n- اسم الشركة: [اسم شركتك]\n- المنتجات/الخدمات: [اذكر منتجاتك]\n- ساعات العمل: [ساعات العمل]',
            context: '',
            temperature: 0.7,
            max_tokens: 500,
            use_conversation_history: true,
            fallback_message: 'عذراً، لم أتمكن من معالجة طلبك في الوقت الحالي. يرجى المحاولة مرة أخرى أو التواصل مع فريق الدعم.'
        },
        'end': {}
    };
    return defaults[type] || {};
}

function renderNode(node) {
    const icons = {
        'start': 'fa-play',
        'text': 'fa-comment',
        'buttons': 'fa-th',
        'quick_replies': 'fa-bolt',
        'carousel': 'fa-images',
        'image': 'fa-image',
        'video': 'fa-video',
        'delay': 'fa-clock',
        'condition': 'fa-code-branch',
        'ai': 'fa-brain',
        'end': 'fa-stop'
    };

    const colors = {
        'start': 'green',
        'text': 'blue',
        'buttons': 'purple',
        'quick_replies': 'orange',
        'carousel': 'pink',
        'image': 'cyan',
        'video': 'red',
        'delay': 'indigo',
        'condition': 'yellow',
        'ai': 'teal',
        'end': 'red'
    };

    const labels = {
        'start': 'بداية',
        'text': 'رسالة نصية',
        'buttons': 'أزرار',
        'quick_replies': 'ردود سريعة',
        'carousel': 'Carousel',
        'image': 'صورة',
        'video': 'فيديو',
        'delay': 'تأخير',
        'condition': 'شرط',
        'ai': 'ذكاء اصطناعي',
        'end': 'نهاية'
    };

            // Remove existing node if exists
            const existingNodeEl = document.querySelector(`[data-node-id="${node.id}"]`);
            if (existingNodeEl) existingNodeEl.remove();

            const nodeDiv = document.createElement('div');
            nodeDiv.className = `node node-${node.type} absolute bg-white border rounded-lg shadow-md p-3`;
            nodeDiv.setAttribute('data-node-id', node.id);
            nodeDiv.style.left = `${node.position.x}px`;
            nodeDiv.style.top = `${node.position.y}px`;
            nodeDiv.style.width = '200px';
            nodeDiv.style.zIndex = '10';

            const hasInput = node.type !== 'start';
            const hasOutput = node.type !== 'end';

            let connectionPointsHtml = '';
            if (hasInput && hasOutput) {
                connectionPointsHtml = `
                    <div class="connection-point connection-input absolute -top-1 left-1/2 -translate-x-1/2 w-3 h-3 bg-gray-300 rounded-full cursor-pointer hover:bg-primary transition-colors" 
                         data-node-id="${node.id}" data-type="input"></div>
                    <div class="connection-point connection-output absolute -bottom-1 left-1/2 -translate-x-1/2 w-3 h-3 bg-gray-300 rounded-full cursor-pointer hover:bg-primary transition-colors" 
                         data-node-id="${node.id}" data-type="output"></div>
                `;
            } else if (hasInput) {
                connectionPointsHtml = `
                    <div class="connection-point connection-input absolute -top-1 left-1/2 -translate-x-1/2 w-3 h-3 bg-gray-300 rounded-full cursor-pointer hover:bg-primary transition-colors" 
                         data-node-id="${node.id}" data-type="input"></div>
                    <div></div>
                `;
            } else if (hasOutput) {
                connectionPointsHtml = `
                    <div></div>
                    <div class="connection-point connection-output absolute -bottom-1 left-1/2 -translate-x-1/2 w-3 h-3 bg-gray-300 rounded-full cursor-pointer hover:bg-primary transition-colors" 
                         data-node-id="${node.id}" data-type="output"></div>
                `;
            }

            nodeDiv.innerHTML = `
                <div class="flex items-start gap-2 mb-2">
                    <div class="w-8 h-8 bg-${colors[node.type]}-100 rounded-lg flex items-center justify-center flex-shrink-0">
                        <i class="fas ${icons[node.type]} text-${colors[node.type]}-600 text-sm"></i>
                    </div>
                    <div class="flex-1 min-w-0">
                        <div class="font-semibold text-sm">${labels[node.type]}</div>
                        <div class="text-xs text-gray-500 truncate node-preview">${getNodePreview(node)}</div>
                    </div>
                    ${node.type !== 'start' ? `
                        <button class="delete-node-btn text-gray-400 hover:text-red-600 transition-colors flex-shrink-0" title="حذف">
                            <i class="fas fa-times text-xs"></i>
                        </button>
                    ` : ''}
                </div>
                <div class="flex items-center justify-between pt-2 border-t">
                    ${connectionPointsHtml}
                </div>
            `;

            // Event Listeners
            nodeDiv.addEventListener('click', function(e) {
                if (!e.target.closest('.delete-node-btn, .connection-point')) {
                    selectNode(node.id);
                }
            });

            // Delete button
            const deleteButton = nodeDiv.querySelector('.delete-node-btn');
            if (deleteButton) {
                deleteButton.addEventListener('click', function(e) {
                    e.stopPropagation();
                    deleteNode(node.id);
                });
            }

            // Dragging
            nodeDiv.addEventListener('mousedown', function(e) {
                if (e.target.closest('.connection-point, .delete-node-btn')) return;

                isDraggingNode = true;
                const startMouseX = e.clientX;
                const startMouseY = e.clientY;
                const startPosX = node.position.x;
                const startPosY = node.position.y;

                function onMouseMove(e) {
                    if (!isDraggingNode) return;
                    const dx = (e.clientX - startMouseX) / zoom;
                    const dy = (e.clientY - startMouseY) / zoom;
                    node.position.x = startPosX + dx;
                    node.position.y = startPosY + dy;
                    nodeDiv.style.left = `${node.position.x}px`;
                    nodeDiv.style.top = `${node.position.y}px`;
                    renderConnections();
                }

                function onMouseUp() {
                    isDraggingNode = false;
                    document.removeEventListener('mousemove', onMouseMove);
                    document.removeEventListener('mouseup', onMouseUp);
                    saveToHistory();
                }

                document.addEventListener('mousemove', onMouseMove);
                document.addEventListener('mouseup', onMouseUp);
            });

            // Connection Points - Output
            const outputPoint = nodeDiv.querySelector('.connection-output');
            if (outputPoint) {
                outputPoint.addEventListener('mousedown', function(e) {
                    e.stopPropagation();
                    isConnecting = true;
                    connectionStart = { nodeId: node.id, element: this };
                    document.addEventListener('mousemove', onConnectingMove);
                    document.addEventListener('mouseup', onConnectingEnd);
                });
            }

            // Connection Points - Input
            const inputPoint = nodeDiv.querySelector('.connection-input');
            if (inputPoint) {
                inputPoint.addEventListener('mouseup', function(e) {
                    if (isConnecting && connectionStart && connectionStart.nodeId !== node.id) {
                        e.stopPropagation();
                        
                        // Check if connection already exists
                        if (!flowData.connections.some(c => c.source === connectionStart.nodeId && c.target === node.id)) {
                            addConnection(connectionStart.nodeId, node.id);
                        }
                        stopConnecting();
                    }
                });
            }

            document.getElementById('nodesContainer').appendChild(nodeDiv);
        }

        // Connecting Functions
        function onConnectingMove(e) {
            if (!isConnecting || !connectionStart) return;

            const rect = document.getElementById('canvasContainer').getBoundingClientRect();
            const startEl = connectionStart.element;
            const startPos = startEl.getBoundingClientRect();
            
            const startX = (startPos.left + startPos.width/2 - rect.left) / zoom;
            const startY = (startPos.top + startPos.height/2 - rect.top) / zoom;
            const endX = (e.clientX - rect.left) / zoom;
            const endY = (e.clientY - rect.top) / zoom;

            drawTempLine(startX, startY, endX, endY);
        }

        function onConnectingEnd(e) {
            stopConnecting();
        }

        function stopConnecting() {
            isConnecting = false;
            connectionStart = null;
            const tempLine = document.getElementById('tempLine');
            if (tempLine) tempLine.remove();
            document.removeEventListener('mousemove', onConnectingMove);
            document.removeEventListener('mouseup', onConnectingEnd);
        }

        function drawTempLine(x1, y1, x2, y2) {
            let tempLine = document.getElementById('tempLine');
            if (!tempLine) {
                tempLine = document.createElementNS('http://www.w3.org/2000/svg', 'path');
                tempLine.setAttribute('id', 'tempLine');
                tempLine.setAttribute('stroke', '#4f46e5');
                tempLine.setAttribute('stroke-width', '2');
                tempLine.setAttribute('stroke-dasharray', '5,5');
                tempLine.setAttribute('fill', 'none');
                document.getElementById('connectionsGroup').appendChild(tempLine);
            }

            const path = `M ${x1} ${y1} C ${x1} ${y1 + 50}, ${x2} ${y2 - 50}, ${x2} ${y2}`;
            tempLine.setAttribute('d', path);
        }

        // Add Connection
        function addConnection(sourceId, targetId) {
            if (flowData.connections.some(c => c.source === sourceId && c.target === targetId)) {
                return;
            }

            const connection = {
                id: `conn-${Date.now()}`,
                source: sourceId,
                target: targetId,
                label: ''
            };

            flowData.connections.push(connection);
            renderConnections();
            saveToHistory();
        }

        // Render Connections
        function renderConnections() {
            const group = document.getElementById('connectionsGroup');
            group.innerHTML = '';

            flowData.connections.forEach(conn => {
                const sourceNode = flowData.nodes.find(n => n.id === conn.source);
                const targetNode = flowData.nodes.find(n => n.id === conn.target);

                if (!sourceNode || !targetNode) return;

                const sourceEl = document.querySelector(`[data-node-id="${conn.source}"] .connection-output`);
                const targetEl = document.querySelector(`[data-node-id="${conn.target}"] .connection-input`);

                if (!sourceEl || !targetEl) return;

                const rect = document.getElementById('canvasContainer').getBoundingClientRect();
                const sourceRect = sourceEl.getBoundingClientRect();
                const targetRect = targetEl.getBoundingClientRect();

                const x1 = (sourceRect.left + sourceRect.width/2 - rect.left) / zoom;
                const y1 = (sourceRect.top + sourceRect.height/2 - rect.top) / zoom;
                const x2 = (targetRect.left + targetRect.width/2 - rect.left) / zoom;
                const y2 = (targetRect.top + targetRect.height/2 - rect.top) / zoom;

                drawConnection(x1, y1, x2, y2, conn.id);
            });
        }

        function drawConnection(x1, y1, x2, y2, connId) {
            const path = `M ${x1} ${y1} C ${x1} ${y1 + 50}, ${x2} ${y2 - 50}, ${x2} ${y2}`;
            
            const line = document.createElementNS('http://www.w3.org/2000/svg', 'path');
            line.setAttribute('d', path);
            line.setAttribute('class', 'connection-line');
            line.setAttribute('marker-end', 'url(#arrowhead)');
            line.setAttribute('data-conn-id', connId);

            line.addEventListener('click', function(e) {
                e.stopPropagation();
                if (confirm('هل تريد حذف هذا الاتصال؟')) {
                    deleteConnection(connId);
                }
            });

            document.getElementById('connectionsGroup').appendChild(line);
        }

        // Delete Connection
        function deleteConnection(connId) {
            flowData.connections = flowData.connections.filter(c => c.id !== connId);
            renderConnections();
            saveToHistory();
        }

        // Select Node
        function selectNode(nodeId) {
            selectedNode = nodeId;
            document.querySelectorAll('.node').forEach(n => n.classList.remove('selected'));
            
            const nodeEl = document.querySelector(`[data-node-id="${nodeId}"]`);
            if (nodeEl) nodeEl.classList.add('selected');

            const node = flowData.nodes.find(n => n.id === nodeId);
            if (node) showNodeProperties(node);
        }

        // Delete Node
        function deleteNode(nodeId) {
            if (!confirm('هل تريد حذف هذه العقدة؟')) return;

            flowData.nodes = flowData.nodes.filter(n => n.id !== nodeId);
            flowData.connections = flowData.connections.filter(c => c.source !== nodeId && c.target !== nodeId);

            const nodeEl = document.querySelector(`[data-node-id="${nodeId}"]`);
            if (nodeEl) nodeEl.remove();

            if (selectedNode === nodeId) {
                selectedNode = null;
                document.getElementById('propertiesContent').innerHTML = `
                    <div class="text-sm text-gray-500 text-center py-12">
                        <i class="fas fa-mouse-pointer text-4xl mb-3 opacity-50"></i>
                        <p>اختر عقدة لتعديل خصائصها</p>
                    </div>
                `;
            }

            renderConnections();
            saveToHistory();
        }

        // Show Node Properties
function showNodeProperties(node) {
    let html = '<div class="space-y-4">';

    // Node Type Label
    html += `<div class="text-sm font-semibold mb-3 text-indigo-600">${getNodeTypeName(node.type)}</div>`;

    // Text nodes
    if (['text', 'buttons', 'quick_replies'].includes(node.type)) {
        html += `
            <div>
                <label class="block text-sm font-medium mb-2">النص</label>
                <textarea class="w-full border rounded-lg px-3 py-2 text-sm" rows="3" 
                          onchange="updateNodeData('${node.id}', 'text', this.value)">${node.data.text || ''}</textarea>
                <p class="text-xs text-gray-500 mt-1">يمكنك استخدام {name} للإشارة لاسم المستخدم</p>
            </div>
        `;
    }

    // Delay node
    if (node.type === 'delay') {
        html += `
            <div>
                <label class="block text-sm font-medium mb-2">التأخير (بالثواني)</label>
                <input type="number" min="1" max="60" 
                       class="w-full border rounded-lg px-3 py-2 text-sm" 
                       value="${node.data.seconds || 2}" 
                       onchange="updateNodeData('${node.id}', 'seconds', parseInt(this.value))">
            </div>
        `;
    }

    // Buttons
    if (node.type === 'buttons') {
        html += renderButtonsList(node);
    }

    // Quick Replies
    if (node.type === 'quick_replies') {
        html += renderQuickRepliesList(node);
    }

    // Carousel
    if (node.type === 'carousel') {
        html += renderCarouselElements(node);
    }

    // Image
    if (node.type === 'image') {
        html += `
            <div>
                <label class="block text-sm font-medium mb-2">رابط الصورة</label>
                <input type="url" placeholder="https://example.com/image.jpg" 
                       class="w-full border rounded-lg px-3 py-2 text-sm" 
                       value="${node.data.image_url || ''}" 
                       onchange="updateNodeData('${node.id}', 'image_url', this.value)">
            </div>
        `;
    }

    // Video
    if (node.type === 'video') {
        html += `
            <div>
                <label class="block text-sm font-medium mb-2">رابط الفيديو</label>
                <input type="url" placeholder="https://example.com/video.mp4" 
                       class="w-full border rounded-lg px-3 py-2 text-sm" 
                       value="${node.data.video_url || ''}" 
                       onchange="updateNodeData('${node.id}', 'video_url', this.value)">
            </div>
        `;
    }

    // Condition
    if (node.type === 'condition') {
        html += renderConditionFields(node);
    }

    // AI Node
    if (node.type === 'ai') {
        html += renderAIFields(node);
    }

    // Delete button
    if (node.type !== 'start') {
        html += `
            <div class="pt-4 border-t">
                <button onclick="deleteNode('${node.id}')" 
                        class="w-full px-4 py-2 bg-red-50 text-red-600 rounded-lg hover:bg-red-100 transition-colors text-sm">
                    <i class="fas fa-trash mr-2"></i>حذف العقدة
                </button>
            </div>
        `;
    }

    html += '</div>';
    document.getElementById('propertiesContent').innerHTML = html;
}


       
        // Render Buttons List
        function renderButtonsList(node) {
            const buttons = node.data.buttons || [];
            let html = `
                <div class="border-t pt-4">
                    <label class="block text-sm font-medium mb-2">الأزرار (حد أقصى 3)</label>
                    <div id="${node.id}-buttons-list" class="space-y-2">
            `;

            buttons.forEach((btn, index) => {
                html += `
                    <div class="p-3 border rounded-lg bg-gray-50">
                        <div class="flex items-center justify-between mb-2">
                            <div class="text-xs font-semibold text-gray-700">زر ${index + 1}</div>
                            <button onclick="removeListItem('${node.id}', 'buttons', ${index})" 
                                    class="text-red-500 hover:text-red-700 text-xs">
                                <i class="fas fa-trash"></i>
                            </button>
                        </div>
                        <input type="text" placeholder="نص الزر" 
                               class="w-full border rounded px-2 py-1 text-xs mb-1" 
                               value="${btn.title || ''}" 
                               onchange="updateListItem('${node.id}', 'buttons', ${index}, 'title', this.value)">
                        <select class="w-full border rounded px-2 py-1 text-xs mb-1"
                                onchange="updateListItem('${node.id}', 'buttons', ${index}, 'type', this.value)">
                            <option value="postback" ${btn.type === 'postback' ? 'selected' : ''}>عادي</option>
                            <option value="web_url" ${btn.type === 'web_url' ? 'selected' : ''}>رابط</option>
                        </select>
                        ${btn.type === 'web_url' ? `
                            <input type="url" placeholder="https://example.com" 
                                   class="w-full border rounded px-2 py-1 text-xs" 
                                   value="${btn.url || ''}" 
                                   onchange="updateListItem('${node.id}', 'buttons', ${index}, 'url', this.value)">
                        ` : `
                            <input type="text" placeholder="Payload" 
                                   class="w-full border rounded px-2 py-1 text-xs" 
                                   value="${btn.payload || ''}" 
                                   onchange="updateListItem('${node.id}', 'buttons', ${index}, 'payload', this.value)">
                        `}
                    </div>
                `;
            });

            html += `
                    </div>
                    ${buttons.length < 3 ? `
                        <button onclick="addListItem('${node.id}', 'buttons')" 
                                class="w-full mt-2 px-3 py-2 text-sm border border-dashed border-gray-400 rounded-lg text-gray-500 hover:text-indigo-600 hover:border-indigo-600">
                            <i class="fas fa-plus mr-1"></i>إضافة زر
                        </button>
                    ` : ''}
                </div>
            `;

            return html;
        }

// Render AI Node Fields
function renderAIFields(node) {
    return `
        <div class="border-t pt-4 space-y-4">
            <!-- AI Provider -->
            <div>
                <label class="block text-sm font-medium mb-2">
                    <i class="fas fa-server text-teal-600 mr-1"></i>
                    مزود الذكاء الاصطناعي
                </label>
                <select class="w-full border rounded-lg px-3 py-2 text-sm" 
                        onchange="updateNodeData('${node.id}', 'ai_provider', this.value); updateAIModel('${node.id}', this.value)">
                    <option value="openai" ${node.data.ai_provider === 'openai' ? 'selected' : ''}>OpenAI (GPT)</option>
                    <option value="claude" ${node.data.ai_provider === 'claude' ? 'selected' : ''}>Anthropic (Claude)</option>
                    <option value="gemini" ${node.data.ai_provider === 'gemini' ? 'selected' : ''}>Google (Gemini)</option>
                </select>
            </div>

            <!-- AI Model -->
            <div>
                <label class="block text-sm font-medium mb-2">
                    <i class="fas fa-microchip text-teal-600 mr-1"></i>
                    النموذج
                </label>
                <select id="model-${node.id}" class="w-full border rounded-lg px-3 py-2 text-sm" 
                        onchange="updateNodeData('${node.id}', 'model', this.value)">
                    ${getModelOptions(node.data.ai_provider, node.data.model)}
                </select>
                <p class="text-xs text-gray-500 mt-1">
                    <i class="fas fa-info-circle mr-1"></i>
                    النماذج الأحدث أذكى لكن أغلى
                </p>
            </div>

            <!-- Instructions -->
            <div>
                <label class="block text-sm font-medium mb-2">
                    <i class="fas fa-file-alt text-teal-600 mr-1"></i>
                    تعليمات الذكاء الاصطناعي
                    <span class="text-red-500">*</span>
                </label>
                <textarea class="w-full border rounded-lg px-3 py-2 text-sm font-mono" 
                          rows="8" 
                          placeholder="أنت مساعد خدمة عملاء محترف. أجب على الأسئلة بشكل مفيد وواضح..."
                          onchange="updateNodeData('${node.id}', 'instructions', this.value)">${node.data.instructions || ''}</textarea>
                <div class="flex items-start gap-2 mt-2 text-xs text-gray-600 bg-blue-50 p-2 rounded">
                    <i class="fas fa-lightbulb text-blue-600 mt-0.5"></i>
                    <div>
                        <div class="font-semibold mb-1">نصائح لكتابة التعليمات:</div>
                        <ul class="list-disc list-inside space-y-1">
                            <li>حدد دور الذكاء الاصطناعي بوضوح</li>
                            <li>أعط معلومات عن الشركة/المنتج</li>
                            <li>حدد أسلوب الرد (رسمي/ودي)</li>
                            <li>اذكر القواعد والمحظورات</li>
                        </ul>
                    </div>
                </div>
            </div>

            <!-- Context -->
            <div>
                <label class="block text-sm font-medium mb-2">
                    <i class="fas fa-book text-teal-600 mr-1"></i>
                    سياق إضافي (اختياري)
                </label>
                <textarea class="w-full border rounded-lg px-3 py-2 text-sm font-mono" 
                          rows="4" 
                          placeholder="معلومات إضافية يحتاجها الذكاء الاصطناعي (مثل: كتالوج المنتجات، أسعار، عروض خاصة...)"
                          onchange="updateNodeData('${node.id}', 'context', this.value)">${node.data.context || ''}</textarea>
            </div>

            <!-- Temperature -->
            <div>
                <label class="block text-sm font-medium mb-2">
                    <i class="fas fa-temperature-high text-teal-600 mr-1"></i>
                    الإبداعية (Temperature)
                    <span class="text-gray-500 text-xs font-normal">${node.data.temperature || 0.7}</span>
                </label>
                <input type="range" 
                       min="0" 
                       max="1" 
                       step="0.1" 
                       value="${node.data.temperature || 0.7}"
                       class="w-full"
                       oninput="this.nextElementSibling.textContent = this.value; updateNodeData('${node.id}', 'temperature', parseFloat(this.value))">
                <div class="flex justify-between text-xs text-gray-500 mt-1">
                    <span>0.0 (دقيق ومباشر)</span>
                    <span>1.0 (إبداعي ومتنوع)</span>
                </div>
            </div>

            <!-- Max Tokens -->
            <div>
                <label class="block text-sm font-medium mb-2">
                    <i class="fas fa-text-width text-teal-600 mr-1"></i>
                    أقصى طول للرد
                </label>
                <select class="w-full border rounded-lg px-3 py-2 text-sm" 
                        onchange="updateNodeData('${node.id}', 'max_tokens', parseInt(this.value))">
                    <option value="150" ${node.data.max_tokens == 150 ? 'selected' : ''}>قصير (150 كلمة)</option>
                    <option value="300" ${node.data.max_tokens == 300 ? 'selected' : ''}>متوسط (300 كلمة)</option>
                    <option value="500" ${node.data.max_tokens == 500 ? 'selected' : ''}>طويل (500 كلمة)</option>
                    <option value="1000" ${node.data.max_tokens == 1000 ? 'selected' : ''}>طويل جداً (1000 كلمة)</option>
                </select>
                <p class="text-xs text-gray-500 mt-1">
                    <i class="fas fa-coins mr-1"></i>
                    الردود الأطول تكلف أكثر
                </p>
            </div>

            <!-- Use Conversation History -->
            <div class="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
                <div class="flex-1">
                    <div class="text-sm font-medium">
                        <i class="fas fa-history text-teal-600 mr-1"></i>
                        استخدام تاريخ المحادثة
                    </div>
                    <p class="text-xs text-gray-500 mt-1">
                        يسمح للذكاء الاصطناعي برؤية الرسائل السابقة
                    </p>
                </div>
                <label class="relative inline-flex items-center cursor-pointer">
                    <input type="checkbox" 
                           class="sr-only peer" 
                           ${node.data.use_conversation_history !== false ? 'checked' : ''}
                           onchange="updateNodeData('${node.id}', 'use_conversation_history', this.checked)">
                    <div class="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-teal-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-teal-600"></div>
                </label>
            </div>

            <!-- Fallback Message -->
            <div>
                <label class="block text-sm font-medium mb-2">
                    <i class="fas fa-exclamation-triangle text-orange-600 mr-1"></i>
                    رسالة بديلة (عند الفشل)
                </label>
                <textarea class="w-full border rounded-lg px-3 py-2 text-sm" 
                          rows="2" 
                          placeholder="عذراً، لم أتمكن من معالجة طلبك..."
                          onchange="updateNodeData('${node.id}', 'fallback_message', this.value)">${node.data.fallback_message || ''}</textarea>
            </div>

            <!-- Variables Guide -->
            <div class="bg-purple-50 border border-purple-200 rounded-lg p-3">
                <div class="text-sm font-semibold text-purple-800 mb-2">
                    <i class="fas fa-code mr-1"></i>
                    المتغيرات المتاحة
                </div>
                <div class="text-xs text-purple-700 space-y-1">
                    <div class="bg-white px-1 py-0.5 rounded">{name}</code> - اسم المستخدم</div>
                    <div class="bg-white px-1 py-0.5 rounded">{user_input}</code> - آخر رسالة من المستخدم</div>
                    <div class="bg-white px-1 py-0.5 rounded">{page_name}</code> - اسم الصفحة</div>
                </div>
            </div>

            <!-- Cost Estimate -->
            <div class="bg-yellow-50 border border-yellow-200 rounded-lg p-3">
                <div class="flex items-start gap-2">
                    <i class="fas fa-dollar-sign text-yellow-600 mt-1"></i>
                    <div class="text-xs text-yellow-800">
                        <div class="font-semibold mb-1">تقدير التكلفة</div>
                        <div>التكلفة التقريبية لكل استخدام: <span id="cost-estimate-${node.id}" class="font-bold">${estimateAICost(node.data)}</span></div>
                        <div class="text-yellow-600 mt-1">💡 استخدم النماذج الأرخص للمهام البسيطة</div>
                    </div>
                </div>
            </div>
        </div>
    `;
}

// Get Model Options based on Provider
function getModelOptions(provider, currentModel) {
    const models = {
        openai: [
            { value: 'gpt-4o', label: 'GPT-4o (الأحدث والأذكى) 💎', cost: '$$$$' },
            { value: 'gpt-4o-mini', label: 'GPT-4o Mini (موصى به) ⭐', cost: '$' },
            { value: 'gpt-4-turbo', label: 'GPT-4 Turbo', cost: '$$$' },
            { value: 'gpt-4', label: 'GPT-4 (قديم)', cost: '$$$' },
            { value: 'gpt-3.5-turbo', label: 'GPT-3.5 Turbo (اقتصادي)', cost: '$' }
        ],
        claude: [
            { value: 'claude-3-5-sonnet-20241022', label: 'Claude 3.5 Sonnet (الأفضل) 💎', cost: '$$$' },
            { value: 'claude-3-opus-20240229', label: 'Claude 3 Opus', cost: '$$$$' },
            { value: 'claude-3-sonnet-20240229', label: 'Claude 3 Sonnet', cost: '$$' },
            { value: 'claude-3-haiku-20240307', label: 'Claude 3 Haiku (سريع ورخيص) ⭐', cost: '$' }
        ],
        gemini: [
            { value: 'gemini-2.5-pro', label: 'Gemini 2.5 Pro (الأفضل) 💎', cost: '$$' },
            { value: 'gemini-2.5-flash', label: 'Gemini 2.5 Flash (موصى به) ⭐', cost: '$' },
            { value: 'gemini-2.5-flash-lite', label: 'Gemini flash lite', cost: '$' }
        ]
    };

    const providerModels = models[provider] || models.openai;
    
    return providerModels.map(model => 
        `<option value="${model.value}" ${currentModel === model.value ? 'selected' : ''}>
            ${model.label} ${model.cost}
        </option>`
    ).join('');
}

// Update AI Model when Provider Changes
function updateAIModel(nodeId, provider) {
    const node = flowData.nodes.find(n => n.id === nodeId);
    if (!node) return;

    const defaultModels = {
        openai: 'gpt-4o-mini',
        claude: 'claude-3-haiku-20240307',
        gemini: 'gemini-2.5-flash'
    };

    node.data.model = defaultModels[provider] || 'gpt-4o-mini';
    
    const modelSelect = document.getElementById(`model-${nodeId}`);
    if (modelSelect) {
        modelSelect.innerHTML = getModelOptions(provider, node.data.model);
    }
    
    updateCostEstimate(nodeId);
    saveToHistory();
}

// Estimate AI Cost
function estimateAICost(data) {
    const provider = data.ai_provider || 'openai';
    const model = data.model || 'gpt-4o-mini';
    const maxTokens = data.max_tokens || 500;

    const costs = {
        'gpt-4o': 0.005,
        'gpt-4o-mini': 0.00015,
        'gpt-4-turbo': 0.01,
        'gpt-4': 0.03,
        'gpt-3.5-turbo': 0.0015,
        'claude-3-5-sonnet-20241022': 0.003,
        'claude-3-opus-20240229': 0.015,
        'claude-3-sonnet-20240229': 0.003,
        'claude-3-haiku-20240307': 0.00025,
        'gemini-2.5-pro': 0.001,
        'gemini-2.5-flash': 0.0001,
        'gemini-pro': 0.0005
    };

    const rate = costs[model] || 0.001;
    const estimatedCost = ((maxTokens * 2) / 1000) * rate; // x2 for input+output

    if (estimatedCost < 0.001) return '< $0.001';
    return `~$${estimatedCost.toFixed(4)}`;
}

function updateCostEstimate(nodeId) {
    const node = flowData.nodes.find(n => n.id === nodeId);
    if (!node) return;
    
    const costElement = document.getElementById(`cost-estimate-${nodeId}`);
    if (costElement) {
        costElement.textContent = estimateAICost(node.data);
    }
}


        // Render Quick Replies List
        function renderQuickRepliesList(node) {
            const quickReplies = node.data.quick_replies || [];
            let html = `
                <div class="border-t pt-4">
                    <label class="block text-sm font-medium mb-2">الردود السريعة (حد أقصى 13)</label>
                    <div id="${node.id}-quickreplies-list" class="space-y-2">
            `;

            quickReplies.forEach((qr, index) => {
                html += `
                    <div class="p-3 border rounded-lg bg-gray-50">
                        <div class="flex items-center justify-between mb-2">
                            <div class="text-xs font-semibold text-gray-700">رد ${index + 1}</div>
                            <button onclick="removeListItem('${node.id}', 'quick_replies', ${index})" 
                                    class="text-red-500 hover:text-red-700 text-xs">
                                <i class="fas fa-trash"></i>
                            </button>
                        </div>
                        <input type="text" placeholder="النص" 
                               class="w-full border rounded px-2 py-1 text-xs mb-1" 
                               value="${qr.title || ''}" 
                               onchange="updateListItem('${node.id}', 'quick_replies', ${index}, 'title', this.value)">
                        <input type="text" placeholder="Payload" 
                               class="w-full border rounded px-2 py-1 text-xs" 
                               value="${qr.payload || ''}" 
                               onchange="updateListItem('${node.id}', 'quick_replies', ${index}, 'payload', this.value)">
                    </div>
                `;
            });

            html += `
                    </div>
                    ${quickReplies.length < 13 ? `
                        <button onclick="addListItem('${node.id}', 'quick_replies')" 
                                class="w-full mt-2 px-3 py-2 text-sm border border-dashed border-gray-400 rounded-lg text-gray-500 hover:text-indigo-600 hover:border-indigo-600">
                            <i class="fas fa-plus mr-1"></i>إضافة رد سريع
                        </button>
                    ` : ''}
                </div>
            `;

            return html;
        }

        // Render Carousel Elements
        function renderCarouselElements(node) {
            const elements = node.data.elements || [];
            let html = `
                <div class="border-t pt-4">
                    <label class="block text-sm font-medium mb-2">عناصر Carousel (حد أقصى 10)</label>
                    <div id="${node.id}-elements-list" class="space-y-3">
            `;

            elements.forEach((element, index) => {
                html += `
                    <div class="p-3 border rounded-lg bg-gray-50">
                        <div class="flex items-center justify-between mb-2">
                            <div class="text-xs font-semibold text-gray-700">عنصر ${index + 1}</div>
                            <button onclick="removeListItem('${node.id}', 'elements', ${index})" 
                                    class="text-red-500 hover:text-red-700 text-xs">
                                <i class="fas fa-trash"></i>
                            </button>
                        </div>
                        <input type="text" placeholder="العنوان" 
                               class="w-full border rounded px-2 py-1 text-xs mb-1" 
                               value="${element.title || ''}" 
                               onchange="updateListItem('${node.id}', 'elements', ${index}, 'title', this.value)">
                        <input type="text" placeholder="الوصف" 
                               class="w-full border rounded px-2 py-1 text-xs mb-1" 
                               value="${element.subtitle || ''}" 
                               onchange="updateListItem('${node.id}', 'elements', ${index}, 'subtitle', this.value)">
                        <input type="url" placeholder="رابط الصورة" 
                               class="w-full border rounded px-2 py-1 text-xs mb-2" 
                               value="${element.image_url || ''}" 
                               onchange="updateListItem('${node.id}', 'elements', ${index}, 'image_url', this.value)">
                        <div class="text-xs text-gray-600 mb-1">أزرار العنصر:</div>
                        ${renderCarouselElementButtons(node.id, index, element.buttons || [])}
                    </div>
                `;
            });

            html += `
                    </div>
                    ${elements.length < 10 ? `
                        <button onclick="addListItem('${node.id}', 'elements')" 
                                class="w-full mt-2 px-3 py-2 text-sm border border-dashed border-gray-400 rounded-lg text-gray-500 hover:text-indigo-600 hover:border-indigo-600">
                            <i class="fas fa-plus mr-1"></i>إضافة عنصر
                        </button>
                    ` : ''}
                </div>
            `;

            return html;
        }

        // Render Carousel Element Buttons
        function renderCarouselElementButtons(nodeId, elementIndex, buttons) {
            let html = '<div class="space-y-1">';
            
            buttons.forEach((btn, btnIndex) => {
                html += `
                    <div class="flex gap-1">
                        <input type="text" placeholder="نص الزر" 
                               class="flex-1 border rounded px-2 py-1 text-xs" 
                               value="${btn.title || ''}" 
                               onchange="updateCarouselButton('${nodeId}', ${elementIndex}, ${btnIndex}, 'title', this.value)">
                        <button onclick="removeCarouselButton('${nodeId}', ${elementIndex}, ${btnIndex})" 
                                class="px-2 text-red-500 hover:text-red-700">
                            <i class="fas fa-times text-xs"></i>
                        </button>
                    </div>
                `;
            });

            if (buttons.length < 3) {
                html += `
                    <button onclick="addCarouselButton('${nodeId}', ${elementIndex})" 
                            class="w-full px-2 py-1 text-xs border border-dashed rounded text-gray-500 hover:text-indigo-600">
                        <i class="fas fa-plus"></i> زر
                    </button>
                `;
            }

            html += '</div>';
            return html;
        }

        // Render Condition Fields
        function renderConditionFields(node) {
            return `
                <div class="border-t pt-4 space-y-3">
                    <div>
                        <label class="block text-sm font-medium mb-2">المتغير</label>
                        <input type="text" placeholder="user_input" 
                               class="w-full border rounded-lg px-3 py-2 text-sm" 
                               value="${node.data.variable || ''}" 
                               onchange="updateNodeData('${node.id}', 'variable', this.value)">
                    </div>
                    <div>
                        <label class="block text-sm font-medium mb-2">المعامل</label>
                        <select class="w-full border rounded-lg px-3 py-2 text-sm" 
                                onchange="updateNodeData('${node.id}', 'operator', this.value)">
                            <option value="==" ${node.data.operator === '==' ? 'selected' : ''}>يساوي (==)</option>
                            <option value="!=" ${node.data.operator === '!=' ? 'selected' : ''}>لا يساوي (!=)</option>
                            <option value=">" ${node.data.operator === '>' ? 'selected' : ''}>أكبر من (>)</option>
                            <option value="<" ${node.data.operator === '<' ? 'selected' : ''}>أصغر من (<)</option>
                            <option value="contains" ${node.data.operator === 'contains' ? 'selected' : ''}>يحتوي على</option>
                        </select>
                    </div>
                    <div>
                        <label class="block text-sm font-medium mb-2">القيمة</label>
                        <input type="text" placeholder="القيمة المراد مقارنتها" 
                               class="w-full border rounded-lg px-3 py-2 text-sm" 
                               value="${node.data.value || ''}" 
                               onchange="updateNodeData('${node.id}', 'value', this.value)">
                    </div>
                    <div class="text-xs text-gray-500 bg-blue-50 p-2 rounded">
                        <i class="fas fa-info-circle mr-1"></i>
                        قم بتوصيل مخرج "true" و "false" للعقد التالية
                    </div>
                </div>
            `;
        }

        // Update Node Data
        function updateNodeData(nodeId, key, value) {
            const node = flowData.nodes.find(n => n.id === nodeId);
            if (node) {
                node.data[key] = value;
                const preview = document.querySelector(`[data-node-id="${nodeId}"] .node-preview`);
                if (preview) preview.textContent = getNodePreview(node);
                saveToHistory();
            }
        }

        // Update List Item
        function updateListItem(nodeId, listKey, index, key, value) {
            const node = flowData.nodes.find(n => n.id === nodeId);
            if (node && node.data[listKey]) {
                if (!node.data[listKey][index]) node.data[listKey][index] = {};
                node.data[listKey][index][key] = value;
                
                const preview = document.querySelector(`[data-node-id="${nodeId}"] .node-preview`);
                if (preview) preview.textContent = getNodePreview(node);
                saveToHistory();
            }
        }

        // Add List Item
        function addListItem(nodeId, listKey) {
            const node = flowData.nodes.find(n => n.id === nodeId);
            if (node) {
                if (!node.data[listKey]) node.data[listKey] = [];
                
                let newItem;
                if (listKey === 'buttons' || listKey === 'quick_replies') {
                    newItem = { 
                        title: `${listKey === 'buttons' ? 'زر' : 'رد'} ${node.data[listKey].length + 1}`, 
                        payload: `option${node.data[listKey].length + 1}`,
                        type: 'postback'
                    };
                } else if (listKey === 'elements') {
                    newItem = { 
                        title: `عنصر ${node.data[listKey].length + 1}`, 
                        subtitle: '', 
                        image_url: 'https://placehold.co/300x200/F0F4FF/1E40AF?text=صورة',
                        buttons: []
                    };
                }
                
                node.data[listKey].push(newItem);
                showNodeProperties(node);
                saveToHistory();
            }
        }

        // Remove List Item
        function removeListItem(nodeId, listKey, index) {
            const node = flowData.nodes.find(n => n.id === nodeId);
            if (node && node.data[listKey]) {
                node.data[listKey].splice(index, 1);
                showNodeProperties(node);
                saveToHistory();
            }
        }

        // Carousel Button Functions
        function updateCarouselButton(nodeId, elementIndex, btnIndex, key, value) {
            const node = flowData.nodes.find(n => n.id === nodeId);
            if (node && node.data.elements && node.data.elements[elementIndex]) {
                if (!node.data.elements[elementIndex].buttons[btnIndex]) {
                    node.data.elements[elementIndex].buttons[btnIndex] = {};
                }
                node.data.elements[elementIndex].buttons[btnIndex][key] = value;
                saveToHistory();
            }
        }

        function addCarouselButton(nodeId, elementIndex) {
            const node = flowData.nodes.find(n => n.id === nodeId);
            if (node && node.data.elements && node.data.elements[elementIndex]) {
                if (!node.data.elements[elementIndex].buttons) {
                    node.data.elements[elementIndex].buttons = [];
                }
                node.data.elements[elementIndex].buttons.push({
                    title: 'زر',
                    payload: 'action',
                    type: 'postback'
                });
                showNodeProperties(node);
                saveToHistory();
            }
        }

        function removeCarouselButton(nodeId, elementIndex, btnIndex) {
            const node = flowData.nodes.find(n => n.id === nodeId);
            if (node && node.data.elements && node.data.elements[elementIndex]) {
                node.data.elements[elementIndex].buttons.splice(btnIndex, 1);
                showNodeProperties(node);
                saveToHistory();
            }
        }

        // Get Node Preview
    function getNodePreview(node) {
    switch(node.type) {
        case 'start':
            return 'نقطة البداية';
        case 'text':
            return node.data.text ? (node.data.text.substring(0, 30) + (node.data.text.length > 30 ? '...' : '')) : 'رسالة فارغة';
        case 'buttons':
            return `${node.data.buttons?.length || 0} أزرار`;
        case 'quick_replies':
            return `${node.data.quick_replies?.length || 0} ردود`;
        case 'carousel':
            return `${node.data.elements?.length || 0} عناصر`;
        case 'image':
            return node.data.image_url ? (node.data.image_url.substring(0, 15) + '...') : 'لا يوجد';
        case 'video':
            return node.data.video_url ? (node.data.video_url.substring(0, 15) + '...') : 'لا يوجد';
        case 'delay':
            return `${node.data.seconds || 0} ثانية`;
        case 'condition':
            return 'شرط منطقي';
        case 'ai':
            const provider = node.data.ai_provider || 'openai';
            const model = node.data.model || 'gpt-4o-mini';
            return `${provider.toUpperCase()} - ${model}`;
        case 'end':
            return 'نهاية الـFlow';
        default:
            return '';
    }
}

        function getNodeTypeName(type) {
            const names = {
                'start': 'بداية',
                'text': 'رسالة نصية',
                'buttons': 'أزرار',
                'quick_replies': 'ردود سريعة',
                'carousel': 'Carousel',
                'image': 'صورة',
                'video': 'فيديو',
                'delay': 'تأخير',
                'condition': 'شرط',
                'end': 'نهاية'
            };
            return names[type] || type;
        }

        // Render Flow
        function renderFlow() {
            document.getElementById('nodesContainer').innerHTML = '';
            flowData.nodes.forEach(node => renderNode(node));
            setTimeout(() => renderConnections(), 100);
        }

        // Transform Functions
        function updateTransform() {
            const container = document.getElementById('nodesContainer');
            container.style.transform = `translate(${panX}px, ${panY}px) scale(${zoom})`;
            renderConnections();
        }

        function zoomIn() {
            zoom = Math.min(zoom + 0.1, 2);
            updateTransform();
        }

        function zoomOut() {
            zoom = Math.max(zoom - 0.1, 0.5);
            updateTransform();
        }

        function resetZoom() {
            zoom = 1;
            panX = 0;
            panY = 0;
            updateTransform();
        }

        // History Functions
        function saveToHistory() {
            const state = JSON.parse(JSON.stringify(flowData));
            history = history.slice(0, historyIndex + 1);
            history.push(state);
            historyIndex++;
            
            if (history.length > 50) {
                history.shift();
                historyIndex--;
            }
        }

        function undoAction() {
            if (historyIndex > 0) {
                historyIndex--;
                flowData = JSON.parse(JSON.stringify(history[historyIndex]));
                renderFlow();
            }
        }

        function redoAction() {
            if (historyIndex < history.length - 1) {
                historyIndex++;
                flowData = JSON.parse(JSON.stringify(history[historyIndex]));
                renderFlow();
            }
        }

        // Settings Functions
        function openSettings() {
            document.getElementById('flowDescription').value = flowSettings.description;
            document.getElementById('triggerType').value = flowSettings.triggerType;
            document.getElementById('triggerKeywords').value = flowSettings.triggerKeywords.join(', ');
            document.getElementById('flowPriority').value = flowSettings.priority;
            document.getElementById('isActive').checked = flowSettings.isActive;
            toggleTriggerFields();
            document.getElementById('settingsModal').classList.remove('hidden');
        }

        function closeSettings() {
            document.getElementById('settingsModal').classList.add('hidden');
        }

      function applySettings() {
    flowSettings.description = document.getElementById('flowDescription').value.trim();
    flowSettings.triggerType = document.getElementById('triggerType').value;
    flowSettings.triggerKeywords = document.getElementById('triggerKeywords').value.split(',').map(k => k.trim()).filter(k => k);
    flowSettings.priority = parseInt(document.getElementById('flowPriority').value || 0);
    flowSettings.isActive = document.getElementById('isActive').checked;
    
    flowSettings.continuousAIMode = document.querySelector('input[name="continuous_ai_mode"]:checked')?.value === '1';
    
    console.log('Settings applied:', flowSettings); // للتحقق
    
    closeSettings();
}

        function toggleTriggerFields() {
            const type = document.getElementById('triggerType').value;
            const field = document.getElementById('keywordsField');
            field.style.display = type === 'keyword' ? 'block' : 'none';
        }

        // Save Flow (AJAX)
      // Save Flow (AJAX) - Fixed Version
function saveFlow() {
    const name = document.getElementById('flowName').value.trim();
    const description = document.getElementById('flowDescription')?.value.trim() || '';
    const facebookPageId = document.getElementById('facebookPageId')?.value;
    const triggerType = document.getElementById('triggerType')?.value || 'keyword';
    const keywordsInput = document.getElementById('triggerKeywords')?.value || '';
    const keywords = keywordsInput.split(',').map(k => k.trim()).filter(k => k);
    const priority = parseInt(document.getElementById('flowPriority')?.value || 0);
    const isActive = document.getElementById('isActive')?.checked || false;
    const continuousAIMode = document.querySelector('input[name="continuous_ai_mode"]:checked')?.value === '1';

    // Validation
    if (!name) {
        alert('⚠️ الرجاء إدخال اسم الـFlow');
        document.getElementById('flowName').focus();
        return;
    }

    if (!facebookPageId) {
        alert('⚠️ الرجاء اختيار صفحة الفيسبوك من الإعدادات');
        openSettings();
        return;
    }

    if (!flowData.nodes.some(n => n.type === 'start')) {
        alert('⚠️ يجب أن يحتوي الـFlow على عقدة بداية (Start)');
        return;
    }

    // Prepare data
    const data = {
        name: name,
        description: description,
        facebook_page_id: parseInt(facebookPageId),
        flow_data: JSON.stringify(flowData),
        trigger_type: triggerType,
        trigger_keywords: triggerType === 'keyword' ? keywords : null,
        priority: priority,
        is_active: isActive ? 1 : 0,
                continuous_ai_mode: continuousAIMode ? 1 : 0  
    };

    console.log('Sending data:', data); // للتحقق

    const url = FLOW_ID ? `/messenger-flows/${FLOW_ID}` : '/messenger-flows';
    const method = FLOW_ID ? 'PUT' : 'POST';

    // Show loading
    const saveBtn = event?.target;
    let originalHtml = '';
    if (saveBtn) {
        originalHtml = saveBtn.innerHTML;
        saveBtn.innerHTML = '<div class="spinner inline-block mr-2"></div>جاري الحفظ...';
        saveBtn.disabled = true;
    }

    $.ajax({
        url: url,
        method: method,
        data: data,
        headers: {
            'X-CSRF-TOKEN': CSRF_TOKEN,
            'Accept': 'application/json'
        },
        success: function(response) {
            console.log('Save response:', response);
            if (response.success) {
                alert('✅ تم حفظ الـFlow بنجاح!');
                if (!FLOW_ID && response.flow && response.flow.id) {
                    window.location.href = `/messenger-flows/builder/${response.flow.id}`;
                } else {
                    location.reload();
                }
            }
        },
        error: function(xhr) {
            console.error('Save error:', xhr.responseJSON);
            
            let errorMessage = 'حدث خطأ أثناء الحفظ';
            
            if (xhr.responseJSON) {
                if (xhr.responseJSON.message) {
                    errorMessage = xhr.responseJSON.message;
                }
                
                if (xhr.responseJSON.errors) {
                    const errors = xhr.responseJSON.errors;
                    const errorList = Object.keys(errors).map(key => {
                        return `• ${errors[key][0]}`;
                    }).join('\n');
                    
                    errorMessage += '\n\n' + errorList;
                }
            }
            
            alert('❌ ' + errorMessage);
        },
        complete: function() {
            if (saveBtn) {
                saveBtn.innerHTML = originalHtml;
                saveBtn.disabled = false;
            }
        }
    });
}

        // Load template from sessionStorage if exists
document.addEventListener('DOMContentLoaded', function() {
    const templateData = sessionStorage.getItem('flowTemplate');
    if (templateData && !FLOW_ID) {
        try {
            const template = JSON.parse(templateData);
            flowData = template;
            nodeIdCounter = Math.max(...flowData.nodes.map(n => parseInt(n.id.replace('node-', ''))), 0) + 1;
            renderFlow();
            sessionStorage.removeItem('flowTemplate');
        } catch(e) {
            console.error('Failed to load template', e);
        }
    }
});

    </script>
 <?php echo $__env->renderComponent(); ?>
<?php endif; ?>
<?php if (isset($__attributesOriginal9ac128a9029c0e4701924bd2d73d7f54)): ?>
<?php $attributes = $__attributesOriginal9ac128a9029c0e4701924bd2d73d7f54; ?>
<?php unset($__attributesOriginal9ac128a9029c0e4701924bd2d73d7f54); ?>
<?php endif; ?>
<?php if (isset($__componentOriginal9ac128a9029c0e4701924bd2d73d7f54)): ?>
<?php $component = $__componentOriginal9ac128a9029c0e4701924bd2d73d7f54; ?>
<?php unset($__componentOriginal9ac128a9029c0e4701924bd2d73d7f54); ?>
<?php endif; ?>
<?php /**PATH /www/wwwroot/fast.rompure.com/fast.rompure.com/resources/views/messenger-flows/builder.blade.php ENDPATH**/ ?>