<script setup>
import { ref, onMounted, computed, shallowRef, onUnmounted, nextTick, watch } from 'vue';
import { useProcessBuilderStore } from '~/stores/processBuilder';
import { useRouter, useRoute } from 'vue-router';
import ProcessFlowCanvas from '~/components/process-flow/ProcessFlowCanvas.vue';
import ProcessBuilderComponents from '~/components/process-flow/ProcessBuilderComponents.vue';
import FormSelector from '~/components/process-flow/FormSelector.vue';
import GatewayConditionManager from '~/components/process-flow/GatewayConditionManager.vue';
import GatewayConditionManagerModal from '~/components/process-flow/GatewayConditionManagerModal.vue';
import ApiNodeConfiguration from '~/components/process-flow/ApiNodeConfiguration.vue';
import ApiNodeConfigurationModal from '~/components/process-flow/ApiNodeConfigurationModal.vue';
import VariableManager from '~/components/process-flow/VariableManager.vue';
import { onBeforeRouteLeave } from 'vue-router';
import FormNodeConfiguration from '~/components/process-flow/FormNodeConfiguration.vue';
import FormNodeConfigurationModal from '~/components/process-flow/FormNodeConfigurationModal.vue';

import BusinessRuleNodeConfiguration from '~/components/process-flow/BusinessRuleNodeConfiguration.vue';
import BusinessRuleNodeConfigurationModal from '~/components/process-flow/BusinessRuleNodeConfigurationModal.vue';
import NotificationNodeConfigurationModal from '~/components/process-flow/NotificationNodeConfigurationModal.vue';
import ScriptNodeConfigurationModal from '~/components/process-flow/ScriptNodeConfigurationModal.vue';
import ProcessTemplatesModal from '~/components/ProcessTemplatesModal.vue';
import ProcessSettingsModal from '~/components/process-flow/ProcessSettingsModal.vue';
import ProcessHistoryModal from '~/components/ProcessHistoryModal.vue';

// Define page meta
definePageMeta({
  title: "Process Builder",
  description: "Create business processes with drag and drop",
  layout: "empty",
  middleware: ["auth"],
  requiresAuth: true,
});

// Initialize the store and router
const processStore = useProcessBuilderStore();
const router = useRouter();
const route = useRoute();

// Initialize toast with fallback
let toast;
try {
  toast = useToast();
} catch (error) {
  // Create a simple toast object if composable is not available
  toast = {
    success: (msg) => console.log('Success:', msg),
    error: (msg) => console.error('Error:', msg),
    info: (msg) => console.info('Info:', msg),
    warning: (msg) => console.warn('Warning:', msg)
  };
}

// Track selected node local state (syncs with store)
// Using shallowRef to avoid making Vue components reactive
const selectedNode = shallowRef(null);

// Track if we're creating a new process
const isCreatingProcess = ref(false);
const newProcessName = ref('');
const newProcessDescription = ref('');

// Track selected node data
const selectedNodeData = ref(null);

// Track drag data
const draggedComponent = ref(null);

// Add a variable to track selected edge
const selectedEdgeData = ref(null);

// Add variables for navigation handling
const showUnsavedChangesModal = ref(false);
const pendingNavigation = ref(null);
const navigationTarget = ref(null);
const navigationConfirmed = ref(false);
const isSaving = ref(false);
const isAddingComponent = ref(false); // Flag to prevent canvas reactivity issues during component addition

// Add a ref for the ProcessFlowCanvas component
const processFlowCanvas = ref(null);

// Add state for node configuration modals
const showFormConfigModal = ref(false);
const showApiConfigModal = ref(false);
const showGatewayConfigModal = ref(false);
const showBusinessRuleConfigModal = ref(false);
const showNotificationConfigModal = ref(false);
const showScriptConfigModal = ref(false);
const showTemplatesModal = ref(false);
const showProcessSettings = ref(false);
const showDropdown = ref(false);
const showProcessHistoryModal = ref(false);

// Add mobile responsive state
const showLeftPanel = ref(true);
const showRightPanel = ref(true);
const isMobile = ref(false);
const isTablet = ref(false);

// Add node highlighting state
const highlightedNodeId = ref(null);
const highlightTimeout = ref(null);

// Mobile breakpoint detection
const checkScreenSize = () => {
  const width = window.innerWidth;
  isMobile.value = width < 768; // Mobile: < 768px
  isTablet.value = width >= 768 && width < 1024; // Tablet: 768px - 1024px
  
  // Auto-hide panels on mobile
  if (isMobile.value) {
    showLeftPanel.value = false;
    showRightPanel.value = false;
  } else if (isTablet.value) {
    // On tablet, show only one panel at a time if both were closed
    if (!showLeftPanel.value && !showRightPanel.value) {
      showRightPanel.value = true;
    }
  } else {
    // Desktop: show both panels by default
    if (!showLeftPanel.value && !showRightPanel.value) {
      showLeftPanel.value = true;
      showRightPanel.value = true;
    }
  }
};

// Toggle panel visibility
const toggleLeftPanel = () => {
  showLeftPanel.value = !showLeftPanel.value;
  
  // On mobile/tablet, close the other panel when opening one
  if ((isMobile.value || isTablet.value) && showLeftPanel.value) {
    showRightPanel.value = false;
  }
};

const toggleRightPanel = () => {
  showRightPanel.value = !showRightPanel.value;
  
  // On mobile/tablet, close the other panel when opening one
  if ((isMobile.value || isTablet.value) && showRightPanel.value) {
    showLeftPanel.value = false;
  }
};

// Close panels when clicking on canvas (mobile only)
const onPaneClickMobile = () => {
  selectedNode.value = null;
  selectedNodeData.value = null;
  selectedEdgeData.value = null;
  processStore.clearSelection();
  
  // Close panels on mobile when clicking canvas
  if (isMobile.value) {
    showLeftPanel.value = false;
    showRightPanel.value = false;
  }
};

// Handle node highlighting from variable usage
const handleNodeHighlight = (event) => {
  console.log('Received highlight event:', event.detail);
  const { nodeId, node } = event.detail;
  
  // Clear any existing highlight timeout
  if (highlightTimeout.value) {
    clearTimeout(highlightTimeout.value);
  }
  
  // Set the highlighted node
  highlightedNodeId.value = nodeId;
  console.log('Set highlighted node ID to:', nodeId);
  
  // Center the view on the highlighted node
  if (processFlowCanvas.value && node) {
    nextTick(() => {
      try {
        console.log('Attempting to center view on node:', node);
        
        // Call the exposed methods from ProcessFlowCanvas
        if (processFlowCanvas.value.centerOnNode) {
          processFlowCanvas.value.centerOnNode(nodeId, node.position);
        } else {
          console.warn('centerOnNode method not available on ProcessFlowCanvas');
        }
      } catch (error) {
        console.error('Error centering view on node:', error);
      }
    });
  }
  
  // Show success toast
  if (toast) {
    toast.success(`Navigated to: ${node.data?.label || node.type} node`);
  }
  
  // Auto-remove highlight after 5 seconds
  highlightTimeout.value = setTimeout(() => {
    highlightedNodeId.value = null;
    highlightTimeout.value = null;
  }, 5000);
};

// Component definitions
const components = [
  {
    type: 'start',
    label: 'Start Point',
    icon: 'play_circle_filled',
    iconColor: 'text-green-500',
    data: { description: 'Process starts here' }
  },
  {
    type: 'form',
    label: 'Form',
    icon: 'description',
    iconColor: 'text-purple-500',
    data: { description: 'Form submission', formName: '' }
  },
  {
    type: 'api',
    label: 'API Call',
    icon: 'api',
    iconColor: 'text-indigo-500',
    data: { 
      description: 'External API call',
      apiMethod: 'GET',
      apiUrl: '',
      requestBody: '',
      headers: '{ "Content-Type": "application/json" }',
      outputVariable: 'apiResponse',
      continueOnError: false,
      errorVariable: 'apiError'
    }
  },
  {
    type: 'gateway',
    label: 'Decision Point',
    icon: 'call_split',
    iconColor: 'text-orange-500',
    data: { description: 'Decision point for branching the workflow', conditions: [] }
  },
  {
    type: 'script',
    label: 'Script',
    icon: 'code',
    iconColor: 'text-gray-500',
    data: { description: 'Script execution', language: 'JavaScript' }
  },
  {
    type: 'end',
    label: 'End Point',
    icon: 'stop_circle',
    iconColor: 'text-red-500',
    data: { description: 'Process completes here' }
  }
];

// Computed to check if we have a current process
const hasCurrentProcess = computed(() => {
  return !!processStore.currentProcess;
});

// Create computed properties for canvas props to control reactivity
const canvasNodes = computed(() => {
  if (!processStore.currentProcess) return [];
  // Return a shallow copy to avoid direct reactivity
  return processStore.currentProcess.nodes.map(node => ({ ...node }));
});

const canvasEdges = computed(() => {
  if (!processStore.currentProcess) return [];
  // Return a shallow copy to avoid direct reactivity  
  return processStore.currentProcess.edges.map(edge => ({ ...edge }));
});

// Computed properties for node data
const nodeLabel = computed({
  get: () => selectedNodeData.value?.label || '',
  set: (value) => {
    if (selectedNodeData.value) {
      selectedNodeData.value.label = value;
      updateNodeInStore();
    }
  }
});

const nodeDescription = computed({
  get: () => selectedNodeData.value?.data?.description || '',
  set: (value) => {
    if (selectedNodeData.value) {
      selectedNodeData.value.data.description = value;
      updateNodeInStore();
    }
  }
});

const nodeAssignee = computed({
  get: () => selectedNodeData.value?.data?.assignee || '',
  set: (value) => {
    if (selectedNodeData.value) {
      selectedNodeData.value.data.assignee = value;
      updateNodeInStore();
    }
  }
});

const nodeFormName = computed({
  get: () => selectedNodeData.value?.data?.formName || '',
  set: (value) => {
    if (selectedNodeData.value) {
      selectedNodeData.value.data.formName = value;
      updateNodeInStore();
    }
  }
});

const nodeLanguage = computed({
  get: () => selectedNodeData.value?.data?.language || 'JavaScript',
  set: (value) => {
    if (selectedNodeData.value) {
      selectedNodeData.value.data.language = value;
      updateNodeInStore();
    }
  }
});

// Add a computed property for gateway conditions
const nodeConditions = computed({
  get: () => selectedNodeData.value?.data?.conditions || [],
  set: (value) => {
    if (selectedNodeData.value) {
      selectedNodeData.value.data.conditions = value;
      updateNodeInStore();
    }
  }
});

// Add a computed property for gateway default path
const nodeDefaultPath = computed({
  get: () => selectedNodeData.value?.data?.defaultPath || 'Default',
  set: (value) => {
    if (selectedNodeData.value) {
      selectedNodeData.value.data.defaultPath = value;
      updateNodeInStore();
    }
  }
});

// Computed for gateway available variables
const gatewayAvailableVariables = computed(() => {
  if (!processStore.currentProcess || !processStore.currentProcess.variables) {
    return [];
  }
  
  // Get variables from the current process instead of variable store
  const processVariables = Object.values(processStore.currentProcess.variables);
  
  const allVars = processVariables.map(v => ({
    name: v.name || 'unnamed',
    label: `${v.name || 'unnamed'} (${v.type || 'string'})`,
    type: v.type || 'string',
    scope: v.scope || 'global',
    description: v.description || ''
  }));
  
  // console.log('Gateway available variables:', allVars);
  return allVars;
});

// Computed key that changes when variables are updated to force re-render of configuration modals
const variablesUpdateKey = computed(() => {
  if (!processStore.currentProcess || !processStore.currentProcess.variables) {
    return 'no-variables';
  }
  
  // Create a hash of variable names to detect changes
  const variableNames = Object.keys(processStore.currentProcess.variables).sort().join(',');
  return `vars-${variableNames.length}-${variableNames.split('').reduce((a, b) => {
    a = ((a << 5) - a) + b.charCodeAt(0);
    return a & a;
  }, 0)}`;
});

// Handle node selection
const onNodeSelected = (node) => {
  // console.log('Node selected:', node);
  
  // Create a deep copy of the node to avoid reactivity issues
  const nodeCopy = JSON.parse(JSON.stringify(node));
  
  // Always ensure label is present in both places for consistency
  if (!nodeCopy.label && nodeCopy.data && nodeCopy.data.label) {
    // If label is missing but exists in data, use it
    nodeCopy.label = nodeCopy.data.label;
  } else if (nodeCopy.label && nodeCopy.data) {
    // If label exists, make sure it's also in data
    nodeCopy.data.label = nodeCopy.label;
  }
  
  // Set the selected node data
  selectedNodeData.value = nodeCopy;
  
  // Keep a reference to the original node
  selectedNode.value = node;
  selectedEdgeData.value = null;
  processStore.selectNode(node.id);
};

// Handle edge selection
const onEdgeSelected = (edge) => {
  selectedEdgeData.value = edge;
  selectedNode.value = null;
  selectedNodeData.value = null;
  processStore.selectEdge(edge.id);
};

// Update edge label
const updateEdgeLabel = (value) => {
  if (selectedEdgeData.value) {
    processStore.updateEdge(selectedEdgeData.value.id, { label: value });
    selectedEdgeData.value.label = value;
  }
};

// Update the pane click handler to clear edge selection too
const onPaneClick = () => {
  onPaneClickMobile();
};

// Update node in store
const updateNodeInStore = () => {
  if (selectedNodeData.value) {
    // console.log('Updating node:', selectedNodeData.value.id, selectedNodeData.value.label);
    
    // Simplify the update to avoid recursive reactivity
    const nodeId = selectedNodeData.value.id;
    const newLabel = selectedNodeData.value.label;
    const newData = { ...selectedNodeData.value.data };
    
    // Update the node canvas separately to avoid reactivity chain
    nextTick(() => {
      if (processFlowCanvas.value) {
        processFlowCanvas.value.updateNode(nodeId, {
          label: newLabel,
          data: {
            ...newData,
            label: newLabel
          }
        });
      }
    });
    
    // Update in store with minimal change
    processStore.updateNode(nodeId, {
      label: newLabel,
      data: newData
    });
  }
};

// Handle condition update
const handleConditionUpdate = (conditions) => {
  if (selectedNodeData.value && selectedNodeData.value.type === 'gateway') {
    // Update conditions in the node data
    selectedNodeData.value.data = {
      ...selectedNodeData.value.data,
      conditions: conditions
    };
    
    // Update edges with new condition outputs
    if (processStore.currentProcess?.edges) {
      const updatedEdges = processStore.currentProcess.edges.map(edge => {
        if (edge.source === selectedNodeData.value.id) {
          // Find matching condition group
          const matchingGroup = conditions.find(group => group.output === edge.label);
          
          // If no matching group found, and this isn't the default path, update edge label
          if (!matchingGroup && edge.label !== selectedNodeData.value.data.defaultPath) {
            return {
              ...edge,
              label: selectedNodeData.value.data.defaultPath || 'Default'
            };
          }
        }
        return edge;
      });
      
      // Update edges in store
      processStore.currentProcess.edges = updatedEdges;
    }
    
    // Update the node in store
    updateNodeInStore();
  }
};

// Handle updates from the canvas when nodes change
const onNodesChange = (changes, currentNodes) => {
  if (!changes || !currentNodes) return;
  
  // Skip processing during component addition to avoid conflicts
  if (isAddingComponent.value) {
    console.log('🔄 Skipping node changes during component addition');
    return;
  }
  
  // Handle position changes (only when dragging is complete)
  const positionChanges = {};
  const hasPositionChanges = changes
    .filter(change => change.type === 'position' && change.position && !change.dragging)
    .forEach(change => {
      positionChanges[change.id] = change.position;
    });
    
  if (Object.keys(positionChanges).length > 0) {
    console.log('📍 Updating node positions:', Object.keys(positionChanges));
    processStore.updateNodePositions(positionChanges);
  }
  
  // Handle node removals (from delete key or other removal actions)
  const removedNodes = changes
    .filter(change => change.type === 'remove')
    .map(change => change.id);
    
  if (removedNodes.length > 0) {
    console.log('🗑️ Removing nodes:', removedNodes);
    removedNodes.forEach(nodeId => {
      processStore.deleteNode(nodeId);
    });
    
    // Clear selection if the selected node was deleted
    if (selectedNodeData.value && removedNodes.includes(selectedNodeData.value.id)) {
      selectedNodeData.value = null;
    }
  }
  
  // Update node selection if needed
  if (selectedNodeData.value) {
    const updatedNode = currentNodes.find(node => node.id === selectedNodeData.value.id);
    if (updatedNode) {
      selectedNodeData.value = { ...updatedNode };
    }
  }
};

// Handle updates from the canvas when edges change
const onEdgesChange = (changes, currentEdges) => {
  if (!changes || !currentEdges) return;
  
  // Handle edge removals
  const removedEdges = changes
    .filter(change => change.type === 'remove')
    .map(change => change.id);
    
  if (removedEdges.length > 0) {
    removedEdges.forEach(edgeId => {
      processStore.deleteEdge(edgeId);
    });
    
    // Clear selection if the selected edge was deleted
    if (selectedEdgeData.value && removedEdges.includes(selectedEdgeData.value.id)) {
      selectedEdgeData.value = null;
    }
  }
  
  // Handle edge additions (new connections)
  const addedEdges = changes.filter(change => change.type === 'add');
  
  if (addedEdges.length > 0) {
    addedEdges.forEach(change => {
      const edge = currentEdges.find(e => e.id === change.id);
      if (edge) {
        processStore.addEdge({
          id: edge.id,
          source: edge.source,
          target: edge.target,
          label: edge.label || '',
          type: edge.type || 'smoothstep',
          animated: edge.animated !== undefined ? edge.animated : true,
          data: edge.data || {}
        });
      }
    });
  }
};

// Handle creating a new process
const createNewProcess = async () => {
  if (!newProcessName.value.trim()) {
    toast.error('Please enter a process name');
    return;
  }
  
  try {
    const newProcess = await processStore.createProcess(
      newProcessName.value.trim(),
      newProcessDescription.value.trim()
    );
    
    if (newProcess && newProcess.id) {
      // Update the URL to include the new process ID
      router.replace(`/process-builder?id=${newProcess.id}`);
      
      // Show success message
      toast.success(`Process "${newProcess.name}" created successfully`);
      
      // Reset form
      isCreatingProcess.value = false;
      newProcessName.value = '';
      newProcessDescription.value = '';
      
      // Reset navigation confirmation
      navigationConfirmed.value = false;
    } else {
      toast.error('Failed to create process. Please try again.');
    }
  } catch (error) {
    console.error('Error creating process:', error);
    toast.error(`Failed to create process: ${error.message || 'Unknown error'}`);
  }
};

// Add navigation guard
onBeforeRouteLeave((to, from, next) => {
  // If navigation was already confirmed or there are no unsaved changes, proceed
  if (navigationConfirmed.value || !processStore.hasUnsavedChanges) {
    next();
    return;
  }
  
  // Otherwise show the confirmation modal
  showUnsavedChangesModal.value = true;
  pendingNavigation.value = () => {
    navigationConfirmed.value = true;
    next();
  };
  next(false);
});

// Navigation handlers
const cancelNavigation = () => {
  showUnsavedChangesModal.value = false;
  pendingNavigation.value = null;
  navigationTarget.value = null;
  navigationConfirmed.value = false;
};

// Update the confirmNavigation function to handle targets
const confirmNavigation = (target) => {
  // Force check unsaved changes by calling the getter
  const hasChanges = processStore.hasUnsavedChanges;
  
  // If already confirmed or no unsaved changes, navigate directly
  if (navigationConfirmed.value || !hasChanges) {
    // Clear the current process when navigating away
    if (target !== '/process-builder') {
      processStore.clearCurrentProcess();
    }
    // Reset navigation confirmation
    navigationConfirmed.value = false;
    router.push(target);
    return;
  }
  
  // Otherwise show confirmation modal
  showUnsavedChangesModal.value = true;
  navigationTarget.value = target;
};

// Add proceeding with navigation
const proceedWithNavigation = () => {
  showUnsavedChangesModal.value = false;
  
  if (pendingNavigation.value) {
    pendingNavigation.value();
  } else if (navigationTarget.value) {
    // Clear the current process when navigating away
    if (navigationTarget.value !== '/process-builder') {
      processStore.clearCurrentProcess();
    }
    navigationConfirmed.value = true; // Mark as confirmed before navigating
    router.push(navigationTarget.value);
  }
};

// Update the goToManage function to use the navigation system
const goToManage = () => {
  // If already confirmed or no unsaved changes, navigate directly
  if (navigationConfirmed.value || !processStore.hasUnsavedChanges) {
    router.push('/process-builder/manage');
    return;
  }
  
  // Otherwise show confirmation modal
  showUnsavedChangesModal.value = true;
  navigationTarget.value = "/process-builder/manage";
};

// Add events for beforeunload
onMounted(() => {
  // Check if there's a process ID in the URL query parameters
  const processId = route.query.id;
  
  if (processId) {
    // Load the specific process
    processStore.loadProcess(processId).then((result) => {
      if (!result.success) {
        console.error('Failed to load process:', processId, result.error);
        // Could show an error notification here
        // For now, just redirect back to manage page
        router.push('/process-builder/manage');
      }
    }).catch((error) => {
      console.error('Error loading process:', error);
      router.push('/process-builder/manage');
    });
  }
  
  // Add the beforeunload event listener
  window.addEventListener('beforeunload', handleBeforeUnload);
  
  // Add click outside listener for dropdown
  document.addEventListener('click', handleClickOutside);
  
  // Add resize listener for responsive behavior
  window.addEventListener('resize', checkScreenSize);
  
  // Add node highlight listener for variable navigation
  window.addEventListener('highlightNode', handleNodeHighlight);
  
  // Initial screen size check
  checkScreenSize();
});

// Handle click outside dropdown
const handleClickOutside = (event) => {
  if (!event.target.closest('.dropdown')) {
    showDropdown.value = false;
  }
};

onUnmounted(() => {
  // Remove event listeners
  window.removeEventListener('beforeunload', handleBeforeUnload);
  document.removeEventListener('click', handleClickOutside);
  window.removeEventListener('resize', checkScreenSize);
  window.removeEventListener('highlightNode', handleNodeHighlight);
  
  // Clear highlight timeout if it exists
  if (highlightTimeout.value) {
    clearTimeout(highlightTimeout.value);
  }
});

// Show warning if there are unsaved changes
const handleBeforeUnload = (event) => {
  if (processStore.hasUnsavedChanges) {
    event.preventDefault();
    event.returnValue = '';
    return '';
  }
};

// Handle drag start
const onDragStart = (event, component) => {
  try {
    const dragData = {
      type: component.type,
      label: component.label,
      data: {
        ...component.data,
        label: component.label
      }
    };
    
    draggedComponent.value = dragData;
    event.dataTransfer.effectAllowed = 'move';
    event.dataTransfer.setData('application/json', JSON.stringify(dragData));
    
    // Add visual feedback
    event.target.classList.add('dragging');
  } catch (error) {
    console.error('Error starting drag:', error);
  }
};

// Handle drag end
const onDragEnd = (event) => {
  event.target.classList.remove('dragging');
  draggedComponent.value = null;
};

// Add these functions to handle form selection
const handleFormSelection = (form) => {
  if (selectedNodeData.value) {
    // Update all form-related data
    selectedNodeData.value.data = {
      ...selectedNodeData.value.data,
      formId: form.formID,
      formName: form.formName,
      formUuid: form.formUUID,
      label: form.formName,
      description: `Form: ${form.formName}`
    };
    
    // Also update the node's root label
    selectedNodeData.value.label = form.formName;
    
    // Update the node in store to trigger reactivity
    updateNodeInStore();
  }
};

const clearFormSelection = () => {
  if (selectedNodeData.value) {
    selectedNodeData.value.data = {
      ...selectedNodeData.value.data,
      formId: null,
      formName: '',
      formUuid: null,
      label: 'Form Task',
      description: 'Form submission task'
    };
    
    // Reset the node's root label
    selectedNodeData.value.label = 'Form Task';
    
    // Update the node in store
    updateNodeInStore();
  }
};

// Delete current node
const deleteNode = () => {
  if (selectedNodeData.value) {
    // Store the node ID before clearing the selection
    const nodeId = selectedNodeData.value.id;
    
    // Clear selection first to avoid references to deleted node
    selectedNodeData.value = null;
    selectedNode.value = null;
    
    // Delete the node
    processStore.deleteNode(nodeId);
  }
};

// Delete current edge
const deleteEdge = () => {
  if (selectedEdgeData.value) {
    processStore.deleteEdge(selectedEdgeData.value.id);
    selectedEdgeData.value = null;
  }
};

// Save current process
const saveProcess = async () => {
  if (!processStore.currentProcess) {
    toast.error('No process to save');
    return;
  }
  
  if (!processStore.currentProcess.name.trim()) {
    toast.error('Please enter a process name before saving');
    return;
  }
  
  if (isSaving.value) {
    return; // Prevent multiple simultaneous save operations
  }
  
  try {
    isSaving.value = true;
    
    // Capture complete Vue Flow state before saving
    if (processFlowCanvas.value && processFlowCanvas.value.toObject) {
      console.log('💾 Capturing Vue Flow state before save...');
      
      try {
        const flowState = processFlowCanvas.value.toObject();
        
        if (flowState && flowState.nodes) {
          // Set the captured flow state in the store for saving
          processStore.setFlowStateForSave(flowState);
          console.log('✅ Vue Flow state captured successfully');
        } else {
          console.warn('⚠️ Vue Flow state capture returned invalid data, proceeding with store data');
        }
      } catch (captureError) {
        console.error('❌ Error capturing Vue Flow state:', captureError);
        console.warn('⚠️ Proceeding with store data as fallback');
      }
    } else {
      console.warn('⚠️ Vue Flow canvas not available for state capture');
    }
    
    const success = await processStore.saveProcess();
    
    if (success) {
      toast.success(`Process "${processStore.currentProcess.name}" saved successfully`);
      
      // Reset navigation confirmation since changes are now saved
      navigationConfirmed.value = false;
      
      // Force a reactivity update to ensure unsavedChanges is properly reflected
      await nextTick();
    } else {
      toast.error('Failed to save process. Please try again.');
    }
  } catch (error) {
    console.error('Error saving process:', error);
    toast.error(`Failed to save process: ${error.message || 'Unknown error'}`);
  } finally {
    isSaving.value = false;
  }
};

// Add a component handler to add components from the component panel
const onAddComponent = async (component) => {
  if (isAddingComponent.value) return; // Prevent concurrent additions
  
  try {
    isAddingComponent.value = true;
    
    // Create a new node from the component definition
    const newNode = {
      id: `${component.type}_${Date.now()}`,
      type: component.type,
      position: { x: 100, y: 100 }, // Default position
      label: component.label,
      data: component.data
    };
    
    // Add the node to the process store
    processStore.addNode(newNode);
    
    // Wait for the next tick to ensure the store update is complete
    await nextTick();
    
    // Explicitly sync the canvas with current store state
    if (processFlowCanvas.value && processFlowCanvas.value.syncCanvas) {
      processFlowCanvas.value.syncCanvas(
        processStore.currentProcess.nodes,
        processStore.currentProcess.edges
      );
    }
    
    // Select the newly added node
    onNodeSelected(newNode);
    
    console.log('Component added successfully:', component.type);
  } catch (error) {
    console.error('Error adding component:', error);
  } finally {
    // Reset the flag after a short delay to allow canvas to stabilize
    setTimeout(() => {
      isAddingComponent.value = false;
    }, 100);
  }
};

// Handle template application
const applyProcessTemplate = async (template) => {
  try {
    console.log('Applying process template:', template.name);
    console.log('Template nodes:', template.nodes ? template.nodes.length : 0);
    console.log('Template edges:', template.edges ? template.edges.length : 0);
    
    // Create a new process if one doesn't exist
    if (!processStore.currentProcess) {
      console.log('No current process, creating new one...');
      processStore.createProcess(template.name, template.description || 'Process created from template');
    } else {
      // Confirm if there's already content in the existing process
      if (processStore.currentProcess.nodes.length > 0 || processStore.currentProcess.edges.length > 0) {
        if (!confirm("This will replace your current process content. Continue?")) {
          return;
        }
      }
      
      // Update process name if user allows
      if (processStore.currentProcess.name === 'New Process' || confirm("Update the process name to match the template?")) {
        processStore.currentProcess.name = template.name;
        processStore.currentProcess.description = template.description;
      }
    }

    // Clear current process nodes and edges
    if (processStore.currentProcess) {
      console.log('Clearing existing nodes and edges...');
      processStore.currentProcess.nodes = [];
      processStore.currentProcess.edges = [];
    }

    // Prepare template data
    const templateNodes = template.nodes || [];
    const templateEdges = template.edges || [];
    
    console.log('Adding template nodes:', templateNodes.length);
    console.log('Adding template edges:', templateEdges.length);
    
    // Process nodes first and wait for them to be fully added
    for (const node of templateNodes) {
      const newNode = {
        ...node,
        id: node.id, // Keep original ID for edge references
        label: node.data?.label || node.label || `${node.type} node`, // Set label at root level
        position: node.position || { x: 100, y: 100 },
        data: {
          ...node.data,
          label: node.data?.label || node.label || `${node.type} node`
        }
      };
      
      processStore.addNode(newNode);
    }
    
    // Wait for nodes to be processed by the canvas
    await nextTick();
    await new Promise(resolve => setTimeout(resolve, 100));
    
    // Process edges after nodes are fully loaded
    for (const edge of templateEdges) {
      const newEdge = {
        ...edge,
        id: edge.id, // Keep original ID
        type: edge.type || 'smoothstep',
        animated: edge.animated !== undefined ? edge.animated : true
      };
      
      processStore.addEdge(newEdge);
    }
    
    // Wait for edges to be added to store
    await nextTick();
    
    // Explicitly sync the canvas to ensure everything is displayed
    if (processFlowCanvas.value && processFlowCanvas.value.syncCanvas) {
      console.log('Forcing canvas sync after template application...');
      processFlowCanvas.value.syncCanvas(
        processStore.currentProcess.nodes,
        processStore.currentProcess.edges
      );
    }
    
    // Add template variables to the variable store
    if (template.variables && template.variables.length > 0) {
      console.log('Adding template variables:', template.variables.length);
      
      // Clear existing process variables first (they'll be loaded from the process)
      // Process variables are now managed directly in the process store
      
      template.variables.forEach((variable) => {
        console.log(`Adding variable: ${variable.name} (${variable.type}) with scope: ${variable.scope}`);
        processStore.addProcessVariable({
          ...variable,
          id: crypto.randomUUID() // Generate unique ID for the variable
        });
      });
    }

    console.log('Template application completed - nodes:', processStore.currentProcess.nodes.length, 'edges:', processStore.currentProcess.edges.length);

    // Mark the process as having unsaved changes
    processStore.unsavedChanges = true;
    
    // Fit the view to show all nodes after a short delay
    await nextTick();
    setTimeout(() => {
      if (processFlowCanvas.value && processFlowCanvas.value.fitView) {
        processFlowCanvas.value.fitView();
      }
    }, 200);
    
    // Show success message
    toast.success(`Template "${template.name}" applied successfully`);
    
  } catch (error) {
    console.error('Error applying process template:', error);
    toast.error('Failed to apply template: ' + error.message);
  }
};

// Fix references to functions
const onFormSelected = (formData) => {
  if (selectedNodeData.value && selectedNodeData.value.type === 'form') {
    selectedNodeData.value.data.formId = formData.id;
    selectedNodeData.value.data.formName = formData.name;
    updateNodeInStore();
  }
};

const onConditionsUpdated = (conditions) => {
  if (selectedNodeData.value && selectedNodeData.value.type === 'gateway') {
    selectedNodeData.value.data.conditions = conditions;
    updateNodeInStore();
  }
};

// Handle API node update
const handleApiNodeUpdate = (updatedData) => {
  if (selectedNodeData.value && selectedNodeData.value.type === 'api') {
    // Make sure to update the label both in data and at the root level
    const newLabel = updatedData.label || 'API Call';
    
    // Update the data
    selectedNodeData.value.data = {
      ...updatedData,
      label: newLabel // Ensure label is in data
    };
    
    // Also update the root label
    selectedNodeData.value.label = newLabel;
    
    // Update the node in store
    updateNodeInStore();
  }
};

// Add this function to handle form node updates
const handleFormNodeUpdate = (updatedData) => {
  if (selectedNodeData.value && selectedNodeData.value.type === 'form') {
    // Make sure to update the label both in data and at the root level
    const newLabel = updatedData.label || 'Form Task';
    
    // Update the data
    selectedNodeData.value.data = {
      ...updatedData,
      label: newLabel // Ensure label is in data
    };
    
    // Also update the root label
    selectedNodeData.value.label = newLabel;
    
    // Update the node in store
    updateNodeInStore();
  }
};

// Update handler for business rule node
const handleBusinessRuleUpdate = (data) => {
  if (selectedNodeData.value) {
    selectedNodeData.value.data = {
      ...selectedNodeData.value.data,
      ...data
    };
    updateNodeInStore();
  }
};

// Add a method to handle default path updates
const handleDefaultPathUpdate = (path) => {
  if (selectedNodeData.value && selectedNodeData.value.type === 'gateway') {
    selectedNodeData.value.data.defaultPath = path;
    updateNodeInStore();
  }
};

// Handle notification node update
const handleNotificationNodeUpdate = (updatedData) => {
  if (selectedNodeData.value) {
    selectedNodeData.value.data = { ...updatedData };
    updateNodeInStore();
  }
};

// Handle script node update
const handleScriptNodeUpdate = (updatedData) => {
  if (selectedNodeData.value && selectedNodeData.value.type === 'script') {
    // Make sure to update the label both in data and at the root level
    const newLabel = updatedData.label || 'Script Task';
    
    // Update the data
    selectedNodeData.value.data = {
      ...updatedData,
      label: newLabel // Ensure label is in data
    };
    
    // Also update the root label
    selectedNodeData.value.label = newLabel;
    
    // Add output variables to the process
    if (updatedData.outputVariables && Array.isArray(updatedData.outputVariables)) {
      updatedData.outputVariables.forEach(output => {
        if (output.name && output.name.trim()) {
          processStore.addProcessVariable({
            name: output.name,
            type: output.type || 'string',
            scope: 'global',
            value: null,
            description: output.description || `Output from ${newLabel}`
          });
        }
      });
    }
    
    // Update the node in store
    updateNodeInStore();
  }
};

// Handle process restoration from history
const handleProcessRestored = (restoredProcess) => {
  // The process has been restored in the backend, so we need to reload it
  console.log('Process restored:', restoredProcess);
  // The current process will be automatically updated by the store
  toast.success('Process has been restored successfully');
};

// Navigate to variables page
const navigateToVariables = () => {
  confirmNavigation('/variables');
};

// Watch for route changes to handle process ID changes
watch(() => route.query.id, (newProcessId, oldProcessId) => {
  // Only react if the process ID actually changed and it's not empty
  if (newProcessId && newProcessId !== oldProcessId) {
    processStore.loadProcess(newProcessId).then((result) => {
      if (!result.success) {
        console.error('Failed to load process:', newProcessId, result.error);
        router.push('/process-builder/manage');
      }
    }).catch((error) => {
      console.error('Error loading process:', error);
      router.push('/process-builder/manage');
    });
  } else if (!newProcessId && oldProcessId) {
    // If the ID was removed from the URL, clear the current process
    processStore.clearCurrentProcess();
  }
});

// Watch for unsaved changes to reset navigation confirmation
watch(() => processStore.hasUnsavedChanges, (hasChanges) => {
  // If there are no more unsaved changes, reset navigation confirmation
  if (!hasChanges) {
    navigationConfirmed.value = false;
  }
});

// Watch for process changes to restore Vue Flow state
watch(() => processStore.currentProcess, async (newProcess, oldProcess) => {
  if (!newProcess) return;
  
  // Only restore when a different process is loaded (not on updates)
  if (oldProcess && newProcess.id === oldProcess.id) return;
  
  console.log('🔄 Process changed, preparing Vue Flow restoration for:', newProcess.name);
  
  // Wait for the canvas to be ready
  await nextTick();
  
  // Give the canvas component a moment to initialize
  setTimeout(async () => {
    if (processFlowCanvas.value && processFlowCanvas.value.fromObject) {
      try {
        // Prepare the flow object for restoration
        const rawFlowObject = {
          nodes: newProcess.nodes || [],
          edges: newProcess.edges || [],
          viewport: newProcess.viewport || { x: 0, y: 0, zoom: 1 }
        };
        
        // Clean the data to remove any Vue Flow internal properties
        const flowObject = processStore.cleanFlowData(rawFlowObject);
        
        console.log('🔄 Restoring Vue Flow state:', {
          nodes: flowObject.nodes.length,
          edges: flowObject.edges.length,
          viewport: flowObject.viewport,
          nodeTypes: flowObject.nodes.map(n => ({ id: n.id, type: n.type, position: n.position })),
          edgeConnections: flowObject.edges.map(e => `${e.source} -> ${e.target}`)
        });
        
        // Use Vue Flow's proper restoration method (now returns a Promise)
        await processFlowCanvas.value.fromObject(flowObject);
        
        console.log('✅ Vue Flow state restoration completed');
        
        // Fit view after restoration with a small delay to ensure everything is rendered
        setTimeout(() => {
          if (processFlowCanvas.value && processFlowCanvas.value.fitView) {
            processFlowCanvas.value.fitView();
          }
        }, 300);
        
      } catch (error) {
        console.error('❌ Error restoring Vue Flow state:', error);
        
        // Fallback to manual sync if Vue Flow restoration fails
        if (processFlowCanvas.value && processFlowCanvas.value.syncCanvas) {
          console.log('🔄 Falling back to manual canvas sync...');
          processFlowCanvas.value.syncCanvas(newProcess.nodes, newProcess.edges);
        }
      }
    } else {
      console.warn('⚠️ Vue Flow canvas not available for restoration, using sync fallback');
      
      // Fallback sync method
      if (processFlowCanvas.value && processFlowCanvas.value.syncCanvas) {
        processFlowCanvas.value.syncCanvas(newProcess.nodes, newProcess.edges);
      }
    }
  }, 200); // Allow time for canvas to initialize
}, { immediate: false });
</script>

<template>
  <div class="process-builder flex flex-col h-screen bg-white">
    <!-- Header Bar -->
    <header
      class="bg-gray-800 px-2 md:px-4 py-2 md:py-4 flex items-center justify-between text-white shadow-md"
    >
      <!-- Left section - Logo and navigation -->
      <div class="flex items-center gap-2 md:gap-3">
        <Icon
          @click="confirmNavigation('/process-builder/manage')"
          name="ph:arrow-circle-left-duotone"
          class="cursor-pointer w-5 h-5 md:w-6 md:h-6"
        />
        <img
          src="@/assets/img/logo/logo-word-white.svg"
          alt="Corrad Logo"
          class="h-5 md:h-7 hidden sm:block"
        />
        <!-- Mobile panel toggles -->
        <div v-if="hasCurrentProcess && (isMobile || isTablet)" class="flex items-center gap-1 ml-2">
          <RsButton 
            @click="toggleLeftPanel" 
            variant="tertiary" 
            size="sm"
            :class="{ 'bg-gray-700': showLeftPanel }"
            class="p-1"
          >
            <Icon name="material-symbols:widgets" class="w-4 h-4" />
          </RsButton>
          <RsButton 
            @click="toggleRightPanel" 
            variant="tertiary" 
            size="sm"
            :class="{ 'bg-gray-700': showRightPanel }"
            class="p-1"
          >
            <Icon name="material-symbols:tune" class="w-4 h-4" />
          </RsButton>
        </div>
      </div>

      <!-- Middle section - Process name -->
      <div class="flex-1 flex justify-center items-center mx-2 md:mx-4">
        <FormKit
          v-if="hasCurrentProcess"
          v-model="processStore.currentProcess.name"
          type="text"
          placeholder="Process Name"
          validation="required"
          validation-visibility="live"
          :validation-messages="{ required: 'Please enter a process name' }"
          class="process-name-input max-w-xs md:max-w-md"
          :classes="{
            outer: 'mb-0 w-full',
          }"
        />
        <div v-else class="text-sm md:text-lg font-medium text-gray-400 hidden sm:block">No Process Selected</div>
      </div>

      <!-- Right section - Actions -->
      <div class="flex items-center">
        <!-- Primary actions -->
        <div class="flex items-center mr-1 md:mr-2 border-r border-gray-600 pr-1 md:pr-2">
          <RsButton @click="saveProcess" variant="primary" size="sm" class="mr-1 md:mr-2" :disabled="!hasCurrentProcess || isSaving">
            <Icon v-if="isSaving" name="material-symbols:progress-activity" class="mr-0 md:mr-1 animate-spin" />
            <Icon v-else name="material-symbols:save" class="mr-0 md:mr-1" />
            <span class="hidden md:inline">{{ isSaving ? 'Saving...' : 'Save' }}</span>
          </RsButton>
        </div>
        
        <!-- Templates button - Hidden on mobile -->
        <div class="mr-1 md:mr-2 border-r border-gray-600 pr-1 md:pr-2 hidden md:block">
          <RsButton @click="showTemplatesModal = true" variant="secondary" size="sm" :disabled="!hasCurrentProcess">
            <Icon name="material-symbols:description-outline" class="mr-0 md:mr-1" />
            <span class="hidden lg:inline">Templates</span>
          </RsButton>
        </div>

        <!-- Process History button - Hidden on mobile, only show if process is saved -->
        <div v-if="processStore.currentProcess && processStore.currentProcess.id" class="mr-1 md:mr-2 border-r border-gray-600 pr-1 md:pr-2 hidden md:block">
          <RsButton @click="showProcessHistoryModal = true" variant="secondary" size="sm">
            <Icon name="material-symbols:history" class="mr-0 md:mr-1" />
            <span class="hidden lg:inline">History</span>
          </RsButton>
        </div>
        
        <!-- Secondary actions -->
        <div class="flex items-center">
          <div class="dropdown relative">
            <RsButton @click="showDropdown = !showDropdown" variant="tertiary" size="sm" class="flex items-center">
              <Icon name="material-symbols:more-vert" class="w-4 h-4 md:w-5 md:h-5" />
            </RsButton>
            
            <div v-if="showDropdown" class="dropdown-menu absolute right-0 mt-2 bg-white rounded shadow-lg py-1 z-10 w-48 text-gray-800">
              <!-- Mobile-only actions -->
              <div v-if="isMobile" class="md:hidden border-b border-gray-200 pb-1 mb-1">
                <button @click="showTemplatesModal = true; showDropdown = false" :disabled="!hasCurrentProcess" class="w-full text-left px-4 py-2 hover:bg-gray-100 flex items-center disabled:opacity-50">
                  <Icon name="material-symbols:description-outline" class="mr-2 w-4 h-4" />
                  <span>Templates</span>
                </button>
                <button v-if="processStore.currentProcess && processStore.currentProcess.id" @click="showProcessHistoryModal = true; showDropdown = false" class="w-full text-left px-4 py-2 hover:bg-gray-100 flex items-center">
                  <Icon name="material-symbols:history" class="mr-2 w-4 h-4" />
                  <span>History</span>
                </button>
              </div>
              <button @click="showProcessSettings = true; showDropdown = false" class="w-full text-left px-4 py-2 hover:bg-gray-100 flex items-center">
                <Icon name="material-symbols:tune" class="mr-2 w-4 h-4" />
                <span>Process Settings</span>
              </button>
              <button @click="confirmNavigation('/process-builder/manage'); showDropdown = false" class="w-full text-left px-4 py-2 hover:bg-gray-100 flex items-center">
                <Icon name="material-symbols:settings" class="mr-2 w-4 h-4" />
                <span>Manage Processes</span>
              </button>
            </div>
          </div>
        </div>
      </div>
    </header>

    <!-- Main Content Area -->
    <div class="flex-1 flex overflow-hidden relative" v-if="hasCurrentProcess">
      <!-- Left Panel - Components -->
      <div 
        v-show="showLeftPanel"
        :class="{
          'absolute inset-y-0 left-0 z-20 bg-white shadow-lg': isMobile,
          'absolute inset-y-0 left-0 z-10 bg-white shadow-md': isTablet,
          'relative w-64': !isMobile && !isTablet,
          'w-72': isMobile,
          'w-80': isTablet
        }"
        class="border-r border-gray-200 flex flex-col overflow-hidden transition-transform duration-300 ease-in-out"
      >
        <div class="bg-gray-100 p-3 flex items-center justify-between border-b border-gray-200">
          <h2 class="text-sm font-medium text-gray-700">Process Components</h2>
          <!-- Close button for mobile/tablet -->
          <button 
            v-if="isMobile || isTablet"
            @click="showLeftPanel = false"
            class="p-1 hover:bg-gray-200 rounded"
          >
            <Icon name="material-symbols:close" class="w-4 h-4 text-gray-500" />
          </button>
        </div>
        <div class="flex-1 overflow-y-auto">
          <ProcessBuilderComponents @add-component="onAddComponent" />
        </div>
      </div>

      <!-- Center Panel - Process Canvas -->
      <div class="flex-1 relative">
        <ProcessFlowCanvas 
          ref="processFlowCanvas"
          :initial-nodes="canvasNodes"
          :initial-edges="canvasEdges"
          :highlighted-node-id="highlightedNodeId"
          @node-selected="onNodeSelected"
          @edge-selected="onEdgeSelected"
          @pane-click="onPaneClick" 
          @nodes-change="onNodesChange"
          @edges-change="onEdgesChange"
        />
        
        <!-- Mobile floating action buttons -->
        <div v-if="isMobile" class="absolute bottom-4 right-4 flex flex-col gap-2">
          <RsButton 
            @click="toggleLeftPanel"
            variant="primary"
            class="rounded-full w-12 h-12 p-0 shadow-lg"
            :class="{ 'bg-blue-600': showLeftPanel }"
          >
            <Icon name="material-symbols:widgets" class="w-6 h-6" />
          </RsButton>
          <RsButton 
            @click="toggleRightPanel"
            variant="primary"
            class="rounded-full w-12 h-12 p-0 shadow-lg"
            :class="{ 'bg-blue-600': showRightPanel }"
          >
            <Icon name="material-symbols:tune" class="w-6 h-6" />
          </RsButton>
        </div>
      </div>

      <!-- Right Panel - Properties -->
      <div 
        v-show="showRightPanel"
        :class="{
          'absolute inset-y-0 right-0 z-20 bg-white shadow-lg': isMobile,
          'absolute inset-y-0 right-0 z-10 bg-white shadow-md': isTablet,
          'relative w-72': !isMobile && !isTablet,
          'w-72': isMobile,
          'w-80': isTablet
        }"
        class="border-l border-gray-200 flex flex-col overflow-hidden transition-transform duration-300 ease-in-out"
      >
        <div class="bg-gray-100 p-3 flex items-center justify-between border-b border-gray-200">
          <h2 class="text-sm font-medium text-gray-700">Properties</h2>
          <!-- Close button for mobile/tablet -->
          <button 
            v-if="isMobile || isTablet"
            @click="showRightPanel = false"
            class="p-1 hover:bg-gray-200 rounded"
          >
            <Icon name="material-symbols:close" class="w-4 h-4 text-gray-500" />
          </button>
        </div>
        <div class="flex-1 overflow-y-auto">
          <!-- Show variable manager when no node is selected -->
          <VariableManager v-if="!selectedNodeData" :key="`variables-${variablesUpdateKey}`" />
          
          <!-- Show node properties when a node is selected -->
          <div v-else class="p-4 space-y-4">
            <!-- Node Label -->
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">Label</label>
              <input
                v-model="nodeLabel"
                type="text"
                class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
              />
            </div>

            <!-- Node Description -->
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">Description</label>
              <textarea
                v-model="nodeDescription"
                rows="2"
                class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
              />
            </div>

            <!-- Node Type Specific Properties -->

            <!-- Form Selection for Form Nodes -->
            <div v-if="selectedNodeData.type === 'form'">
              <RsButton @click="showFormConfigModal = true" variant="primary" class="w-full">
                Configure Form Task
              </RsButton>
            </div>

            <!-- API Configuration for API Nodes -->
            <div v-if="selectedNodeData.type === 'api'">
              <RsButton @click="showApiConfigModal = true" variant="primary" class="w-full">
                Configure API Call
              </RsButton>
            </div>

            <!-- Gateway Conditions -->
            <div v-if="selectedNodeData.type === 'gateway'">
              <RsButton @click="showGatewayConfigModal = true" variant="primary" class="w-full">
                Configure Decision Paths
              </RsButton>
            </div>
            
            <!-- Business Rule Configuration -->
            <div v-if="selectedNodeData.type === 'business-rule'">
              <RsButton @click="showBusinessRuleConfigModal = true" variant="primary" class="w-full">
                Configure Business Rule
              </RsButton>
            </div>
            
            <!-- Notification Configuration -->
            <div v-if="selectedNodeData.type === 'notification'">
              <RsButton @click="showNotificationConfigModal = true" variant="primary" class="w-full">
                Configure Notification
              </RsButton>
            </div>
            
            <!-- Script Configuration -->
            <div v-if="selectedNodeData.type === 'script'">
              <RsButton @click="showScriptConfigModal = true" variant="primary" class="w-full">
                Configure Script Task
              </RsButton>
            </div>
          </div>
        </div>
      </div>

      <!-- Backdrop for mobile panels -->
      <div 
        v-if="(isMobile || isTablet) && (showLeftPanel || showRightPanel)"
        @click="showLeftPanel = false; showRightPanel = false"
        class="absolute inset-0 bg-black bg-opacity-50 z-5"
      ></div>
    </div>

    <!-- Empty state - No process selected -->
    <div v-else class="flex-1 flex items-center justify-center bg-gray-50">
      <div class="text-center p-8 max-w-md">
        <Icon name="material-symbols:flowchart" class="w-16 h-16 mx-auto mb-4 text-gray-400" />
        <h2 class="text-xl font-semibold text-gray-800 mb-2">Create a New Process</h2>
        <p class="text-gray-600 mb-6">Get started by creating a new process or navigate back to manage your existing processes.</p>
        
        <div class="space-y-3">
          <div class="mb-4">
            <FormKit
              v-model="newProcessName"
              type="text"
              label="Process Name"
              placeholder="Enter a name for your new process"
              validation="required"
            />
            
            <FormKit
              v-model="newProcessDescription"
              type="textarea"
              label="Description (Optional)"
              placeholder="Enter a description"
              :rows="3"
            />
          </div>
          
          <div class="flex justify-center gap-4">
            <RsButton @click="createNewProcess" variant="primary" :disabled="!newProcessName.trim()">
              <Icon name="material-symbols:add" class="mr-1" />
              Create Process
            </RsButton>
            
            <RsButton @click="confirmNavigation('/process-builder/manage')" variant="tertiary">
              <Icon name="material-symbols:arrow-back" class="mr-1" />
              Back to Processes
            </RsButton>
          </div>
        </div>
      </div>
    </div>
    
    <!-- Unsaved changes dialog -->
    <RsModal v-model="showUnsavedChangesModal" title="Unsaved Changes" size="md" position="center">
      <div class="p-4">
        <div class="flex items-center mb-4">
          <Icon name="material-symbols:warning-outline" class="text-yellow-500 w-8 h-8 mr-3" />
          <div>
            <p class="text-gray-600">You have unsaved changes that will be lost if you leave the page.</p>
          </div>
        </div>
      </div>
      <template #footer>
        <div class="flex justify-end gap-2">
          <RsButton @click="cancelNavigation" variant="tertiary">
            Stay on this Page
          </RsButton>
          <RsButton @click="proceedWithNavigation" variant="danger">
            Discard Changes
          </RsButton>
        </div>
      </template>
    </RsModal>
    
    <!-- Form Task Configuration Modal -->
    <FormNodeConfigurationModal
      v-if="selectedNodeData && selectedNodeData.type === 'form'"
      v-model="showFormConfigModal"
      :key="`form-${selectedNodeData.id}-${variablesUpdateKey}`"
      :nodeData="selectedNodeData.data"
      :availableVariables="gatewayAvailableVariables"
      @update="handleFormNodeUpdate"
    />
    
    <!-- API Call Configuration Modal -->
    <ApiNodeConfigurationModal
      v-if="selectedNodeData && selectedNodeData.type === 'api'"
      v-model="showApiConfigModal"
      :key="`api-${selectedNodeData.id}-${variablesUpdateKey}`"
      :nodeData="selectedNodeData.data"
      :availableVariables="gatewayAvailableVariables"
      @update="handleApiNodeUpdate"
    />
    
    <!-- Gateway/Decision Point Configuration Modal -->
    <GatewayConditionManagerModal
      v-if="selectedNodeData && selectedNodeData.type === 'gateway'"
      v-model="showGatewayConfigModal"
      :key="`gateway-${selectedNodeData.id}-${variablesUpdateKey}`"
      :conditions="selectedNodeData.data.conditions || []"
      :availableVariables="gatewayAvailableVariables"
      :defaultPath="selectedNodeData.data.defaultPath || 'Default'"
      @update:conditions="handleConditionUpdate"
      @update:defaultPath="handleDefaultPathUpdate"
    />
    
    <!-- Business Rule Configuration Modal -->
    <BusinessRuleNodeConfigurationModal
      v-if="selectedNodeData && selectedNodeData.type === 'business-rule'"
      v-model="showBusinessRuleConfigModal"
      :key="`business-rule-${selectedNodeData.id}-${variablesUpdateKey}`"
      :nodeId="selectedNodeData.id"
      :nodeData="selectedNodeData.data"
      :availableVariables="gatewayAvailableVariables"
      @update="handleBusinessRuleUpdate"
    />
    
    <!-- Notification Configuration Modal -->
    <NotificationNodeConfigurationModal
      v-if="selectedNodeData && selectedNodeData.type === 'notification'"
      v-model="showNotificationConfigModal"
      :key="`notification-${selectedNodeData.id}-${variablesUpdateKey}`"
      :nodeData="selectedNodeData.data"
      :availableVariables="gatewayAvailableVariables"
      @update="handleNotificationNodeUpdate"
    />
    
    <!-- Script Configuration Modal -->
    <ScriptNodeConfigurationModal
      v-if="selectedNodeData && selectedNodeData.type === 'script'"
      v-model="showScriptConfigModal"
      :key="`script-${selectedNodeData.id}-${variablesUpdateKey}`"
      :nodeData="selectedNodeData.data"
      :availableVariables="gatewayAvailableVariables"
      @update="handleScriptNodeUpdate"
    />
    
    <!-- Process Templates Modal -->
    <ProcessTemplatesModal
      v-model="showTemplatesModal"
      @select-template="applyProcessTemplate"
    />
    
    <!-- Process Settings Modal -->
    <ProcessSettingsModal
      v-model="showProcessSettings"
    />

    <!-- Process History Modal -->
    <ProcessHistoryModal
      :is-open="showProcessHistoryModal"
      :process-id="processStore.currentProcess?.id"
      @close="showProcessHistoryModal = false"
      @restored="handleProcessRestored"
    />
  </div>
</template>

<style scoped>
.process-builder {
  --flow-node-selected-color: theme('colors.blue.500');
  --flow-background-color: theme('colors.gray.100');
  --flow-connection-path-color: theme('colors.gray.400');
  --flow-connection-path-hover-color: theme('colors.blue.400');
}

:deep(.custom-node) {
  border-radius: 4px;
  padding: 10px;
}

:deep(.custom-node.selected) {
  border-color: var(--flow-node-selected-color);
  box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.3);
}

:deep(.custom-node-content) {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

:deep(.custom-node-title) {
  margin-top: 4px;
  text-align: center;
  font-weight: 500;
}

:deep(.node-gateway) {
  transform: rotate(45deg);
  background: white;
  border: 2px solid #FF9800;
}

:deep(.node-gateway .custom-node-content) {
  transform: rotate(-45deg);
}

:deep(.node-start), :deep(.node-end) {
  border-radius: 50%;
  width: 60px;
  height: 60px;
}

:deep(.node-task), :deep(.node-form), :deep(.node-script) {
  min-width: 160px;
  background: white;
  border: 1px solid #ddd;
}

:deep(.node-business-rule) {
  min-width: 160px;
  background: white;
  border: 1px solid #ddd;
  border-left: 4px solid #9333ea;  /* Purple border to match our icon color */
}

:deep(.node-notification) {
  min-width: 160px;
  background: white;
  border: 1px solid #ddd;
  border-left: 4px solid #3b82f6;  /* Blue border to match our icon color */
}

:deep(.node-details) {
  margin-top: 8px;
  font-size: 0.75rem;
  width: 100%;
}

:deep(.node-description) {
  color: #666;
  margin-bottom: 4px;
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.process-builder-container {
  background-color: #f8fafc;
}

.process-name-input {
  width: 100%;
  max-width: 400px;
}

.process-name-input :deep(.formkit-inner) {
  background-color: rgba(255, 255, 255, 0.1);
  border-color: rgba(255, 255, 255, 0.2);
  color: white;
}

.process-name-input :deep(.formkit-inner:focus-within) {
  border-color: rgba(255, 255, 255, 0.5);
  box-shadow: 0 0 0 1px rgba(255, 255, 255, 0.1);
}

.process-name-input :deep(input::placeholder) {
  color: rgba(255, 255, 255, 0.6);
}

.process-name-input :deep(.formkit-message) {
  color: rgba(255, 200, 200, 0.9);
  font-size: 0.7rem;
  position: absolute;
}

.process-builder-palette,
.process-builder-properties {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.process-component-item.dragging {
  opacity: 0.5;
  transform: scale(0.95);
}

.process-component-item {
  transition: all 0.2s ease;
  user-select: none;
}

.process-component-item:active {
  cursor: grabbing;
}

/* Mobile responsive adjustments */
@media (max-width: 768px) {
  .process-name-input {
    max-width: 200px;
  }
  
  .process-name-input :deep(.formkit-inner) {
    font-size: 0.875rem;
    padding: 0.5rem 0.75rem;
  }
}

/* Touch-friendly adjustments */
@media (hover: none) and (pointer: coarse) {
  .component-item {
    min-height: 44px; /* iOS touch target minimum */
  }
  
  .dropdown-menu button {
    min-height: 44px;
    padding: 0.75rem 1rem;
  }
  
  /* Larger tap targets for mobile */
  .process-builder :deep(.vue-flow__node) {
    min-width: 120px;
    min-height: 40px;
  }
  
  .process-builder :deep(.vue-flow__handle) {
    width: 12px;
    height: 12px;
  }
}

/* Panel transitions and animations */
.panel-enter-active,
.panel-leave-active {
  transition: transform 0.3s ease-in-out;
}

.panel-enter-from {
  transform: translateX(-100%);
}

.panel-leave-to {
  transform: translateX(-100%);
}

.panel-right-enter-from {
  transform: translateX(100%);
}

.panel-right-leave-to {
  transform: translateX(100%);
}

/* Improved mobile canvas interactions */
@media (max-width: 768px) {
  .process-builder :deep(.vue-flow__pane) {
    touch-action: pan-x pan-y;
  }
  
  .process-builder :deep(.vue-flow__node) {
    cursor: pointer;
  }
  
  .process-builder :deep(.vue-flow__edge) {
    pointer-events: stroke;
    stroke-width: 3px; /* Thicker edges for easier mobile selection */
  }
}
</style> 