import { useState, useEffect } from 'react';
import { Login } from './components/Login';
import { Dashboard } from './components/Dashboard';
import { Settings } from './components/Settings';
import { ForcePasswordResetModal } from './components/ForcePasswordResetModal';
import { User, Ticket, TicketType, Approval, Attachment, UserPermissions, TicketDepartment, Tag, RejectionHistory, DepartmentDefaultApprovers, EmailNotificationSettings, CustomRole, CustomTicketType, CustomDepartment } from './types';
import { projectId, publicAnonKey } from '../../utils/supabase/info';

// Helper function to make fetch requests with better error handling and retries
async function fetchWithRetry(url: string, options: RequestInit = {}, retries = 3, backoff = 1000): Promise<Response> {
  for (let i = 0; i < retries; i++) {
    try {
      console.log(`🌐 Attempting fetch to: ${url} (attempt ${i + 1}/${retries})`);
      const response = await fetch(url, options);
      console.log(`✅ Fetch successful: ${url} - Status: ${response.status}`);
      return response;
    } catch (error: any) {
      console.error(`❌ Fetch attempt ${i + 1} failed for ${url}:`, error);
      
      if (i === retries - 1) {
        // Last attempt failed
        console.error(`🚫 All ${retries} fetch attempts failed for ${url}`);
        throw new Error(`Failed to connect to backend after ${retries} attempts. Please ensure the Supabase Edge Function is deployed. Error: ${error.message}`);
      }
      
      // Wait before retrying with exponential backoff
      const waitTime = backoff * Math.pow(2, i);
      console.log(`⏳ Waiting ${waitTime}ms before retry...`);
      await new Promise(resolve => setTimeout(resolve, waitTime));
    }
  }
  
  throw new Error('Unexpected error in fetchWithRetry');
}

// Helper function to get default permissions based on role
function getDefaultPermissions(role: string): UserPermissions {
  switch (role) {
    case 'super user':
      return {
        createTickets: true,
        editTickets: true,
        resubmitTickets: true,
        approveTickets: true,
        sendReminders: true,
        manageUsers: true,
        accessSettings: true,
        viewAllTickets: true,
        editImplementedDate: true,
        exportTickets: true,
        manageRoles: true, // Only super users can manage roles
      };
    case 'admin':
      return {
        createTickets: true,
        editTickets: true,
        resubmitTickets: true,
        approveTickets: true,
        sendReminders: true,
        manageUsers: true,
        accessSettings: true,
        viewAllTickets: true,
        editImplementedDate: true,
        exportTickets: true,
      };
    case 'approver':
      return {
        createTickets: true,
        editTickets: false,
        resubmitTickets: false,
        approveTickets: true,
        sendReminders: false,
        manageUsers: false,
        accessSettings: false,
        viewAllTickets: true,
        editImplementedDate: true,
        exportTickets: false,
      };
    case 'requester':
      return {
        createTickets: true,
        editTickets: true,
        resubmitTickets: true,
        approveTickets: false,
        sendReminders: true,
        manageUsers: false,
        accessSettings: false,
        viewAllTickets: false,
        editImplementedDate: false,
        exportTickets: false,
      };
    case 'user':
    default:
      return {
        createTickets: true,
        editTickets: false,
        resubmitTickets: false,
        approveTickets: false,
        sendReminders: false,
        manageUsers: false,
        accessSettings: false,
        viewAllTickets: false,
        editImplementedDate: false,
        exportTickets: false,
      };
  }
}

// Mock users
const MOCK_USERS: User[] = [
  { id: '1', name: 'Jevon Wold', email: 'jevon.wold@islandmtn.com', password: 'admin123', role: 'super-user', permissions: getDefaultPermissions('super user') },
];

// Initial mock tickets
const INITIAL_TICKETS: Ticket[] = [];

export default function App() {
  console.log('🚀 App component loaded and rendering');
  
  const [currentUser, setCurrentUser] = useState<User | null>(null);
  const [sessionToken, setSessionToken] = useState<string | null>(null);
  const [tickets, setTickets] = useState<Ticket[]>(INITIAL_TICKETS);
  const [users, setUsers] = useState<User[]>(MOCK_USERS);
  const [rfcCounter, setRfcCounter] = useState(1000);
  const [releaseNoteCounter, setReleaseNoteCounter] = useState(1000);
  const [tags, setTags] = useState<Tag[]>([
    { id: '1', name: 'High Priority', color: '#ef4444' },
    { id: '2', name: 'Security', color: '#f59e0b' },
    { id: '3', name: 'Performance', color: '#10b981' },
    { id: '4', name: 'Bug Fix', color: '#3b82f6' },
    { id: '5', name: 'Feature', color: '#8b5cf6' },
  ]);
  const [defaultApprovers, setDefaultApprovers] = useState<DepartmentDefaultApprovers[]>([
    { department: 'Marketing', approver1PrimaryId: undefined, approver1SecondaryId: undefined, approver2PrimaryId: undefined, approver2SecondaryId: undefined },
    { department: 'Risk/Leads', approver1PrimaryId: undefined, approver1SecondaryId: undefined, approver2PrimaryId: undefined, approver2SecondaryId: undefined },
    { department: 'Data', approver1PrimaryId: undefined, approver1SecondaryId: undefined, approver2PrimaryId: undefined, approver2SecondaryId: undefined },
    { department: 'Product', approver1PrimaryId: undefined, approver1SecondaryId: undefined, approver2PrimaryId: undefined, approver2SecondaryId: undefined },
    { department: 'Operations', approver1PrimaryId: undefined, approver1SecondaryId: undefined, approver2PrimaryId: undefined, approver2SecondaryId: undefined },
  ]);
  const [userNeedsPasswordReset, setUserNeedsPasswordReset] = useState<User | null>(null);
  const [emailNotificationSettings, setEmailNotificationSettings] = useState<EmailNotificationSettings>({
    rfcRecipients: [],
    releaseNotesRecipients: [],
    enableNewTicketNotifications: true,
    enableApprovalNotifications: true,
    enableRejectionNotifications: true,
    enableFollowUpEmails: true,
  });
  const [isDataLoaded, setIsDataLoaded] = useState(false);
  const [backendError, setBackendError] = useState<string | null>(null);
  const [isBackendConnected, setIsBackendConnected] = useState(false);
  const [customRoles, setCustomRoles] = useState<CustomRole[]>([
    // Predefined system roles
    {
      id: 'super-user',
      name: 'Super User',
      description: 'Full system access including role management',
      permissions: getDefaultPermissions('super user'),
      isSystem: true,
      createdAt: new Date(),
      createdBy: 'system',
    },
    {
      id: 'admin',
      name: 'Admin',
      description: 'Full system access except role management',
      permissions: getDefaultPermissions('admin'),
      isSystem: true,
      createdAt: new Date(),
      createdBy: 'system',
    },
    {
      id: 'approver',
      name: 'Approver',
      description: 'Can create, edit, and approve tickets',
      permissions: getDefaultPermissions('approver'),
      isSystem: true,
      createdAt: new Date(),
      createdBy: 'system',
    },
    {
      id: 'requester',
      name: 'Requester',
      description: 'Can create and edit their own tickets',
      permissions: getDefaultPermissions('requester'),
      isSystem: true,
      createdAt: new Date(),
      createdBy: 'system',
    },
    {
      id: 'user',
      name: 'User',
      description: 'View-only access to tickets',
      permissions: getDefaultPermissions('user'),
      isSystem: true,
      createdAt: new Date(),
      createdBy: 'system',
    },
  ]);

  const [customTicketTypes, setCustomTicketTypes] = useState<CustomTicketType[]>([
    // Predefined system ticket types
    {
      id: 'rfc',
      name: 'RFC',
      description: 'Request for Change - requires approval from multiple approvers',
      approvalCount: 2,
      color: '#0cb47b',
      prefix: 'RFC',
      isSystem: true,
      createdAt: new Date(),
      createdBy: 'system',
    },
    {
      id: 'release-notes',
      name: 'Release Note',
      description: 'Release documentation - automatically approved',
      approvalCount: 0,
      color: '#3b82f6',
      prefix: 'RN',
      isSystem: true,
      createdAt: new Date(),
      createdBy: 'system',
    },
  ]);

  const [customDepartments, setCustomDepartments] = useState<CustomDepartment[]>([
    // Predefined system departments
    {
      id: 'marketing',
      name: 'Marketing',
      description: 'Marketing-related changes',
      color: '#ec4899', // Pink
      isSystem: true,
      createdAt: new Date(),
      createdBy: 'system',
    },
    {
      id: 'risk-leads',
      name: 'Risk/Leads',
      description: 'Risk management and lead changes',
      color: '#f59e0b', // Amber
      isSystem: true,
      createdAt: new Date(),
      createdBy: 'system',
    },
    {
      id: 'data',
      name: 'Data',
      description: 'Data-related changes',
      color: '#8b5cf6', // Purple
      isSystem: true,
      createdAt: new Date(),
      createdBy: 'system',
    },
    {
      id: 'product',
      name: 'Product',
      description: 'Product-related changes',
      color: '#3b82f6', // Blue
      isSystem: true,
      createdAt: new Date(),
      createdBy: 'system',
    },
    {
      id: 'operations',
      name: 'Operations',
      description: 'Operational changes',
      color: '#10b981', // Green
      isSystem: true,
      createdAt: new Date(),
      createdBy: 'system',
    },
    {
      id: 'training',
      name: 'Training',
      description: 'Training-related changes',
      color: '#06b6d4', // Cyan
      isSystem: true,
      createdAt: new Date(),
      createdBy: 'system',
    },
    {
      id: 'qa',
      name: 'Q&A',
      description: 'Questions and answers',
      color: '#ef4444', // Red
      isSystem: true,
      createdAt: new Date(),
      createdBy: 'system',
    },
  ]);

  // Set page title and favicon
  useEffect(() => {
    document.title = 'CADV Change Control';
    
    // Set favicon
    const link = document.querySelector("link[rel*='icon']") as HTMLLinkElement || document.createElement('link');
    link.type = 'image/svg+xml';
    link.rel = 'icon';
    link.href = '/logo.svg';
    document.head.appendChild(link);
  }, []);

  // Load default approvers from backend
  useEffect(() => {
    const loadDefaultApprovers = async () => {
      try {
        const response = await fetch(`https://${projectId}.supabase.co/functions/v1/make-server-af5db803/default-approvers`, {
          headers: {
            'Authorization': `Bearer ${publicAnonKey}`
          }
        });
        
        if (response.ok) {
          const data = await response.json();
          console.log('Loaded default approvers from backend:', data);
          if (data.defaultApprovers) {
            setDefaultApprovers(data.defaultApprovers);
          }
        }
      } catch (err) {
        console.error('Error loading default approvers:', err);
      }
    };

    loadDefaultApprovers();
  }, []);

  // Load custom ticket types from backend
  useEffect(() => {
    const loadCustomTicketTypes = async () => {
      try {
        const response = await fetch(`https://${projectId}.supabase.co/functions/v1/make-server-af5db803/ticket-types`, {
          headers: {
            'Authorization': `Bearer ${publicAnonKey}`
          }
        });
        
        if (response.ok) {
          const data = await response.json();
          console.log('Loaded custom ticket types from backend:', data);
          if (data.ticketTypes && data.ticketTypes.length > 0) {
            // Merge with system ticket types
            setCustomTicketTypes(prevTypes => {
              const systemTypes = prevTypes.filter(t => t.isSystem);
              return [...systemTypes, ...data.ticketTypes];
            });
          }
        }
      } catch (err) {
        console.error('Error loading custom ticket types:', err);
      }
    };

    loadCustomTicketTypes();
  }, []);

  // Load email notification settings from backend
  useEffect(() => {
    const loadEmailNotifications = async () => {
      try {
        const response = await fetch(`https://${projectId}.supabase.co/functions/v1/make-server-af5db803/email-notifications`, {
          headers: {
            'Authorization': `Bearer ${publicAnonKey}`
          }
        });
        
        if (response.ok) {
          const data = await response.json();
          console.log('Loaded email notification settings from backend:', data);
          if (data.emailNotificationSettings) {
            setEmailNotificationSettings(data.emailNotificationSettings);
          }
        }
      } catch (err) {
        console.error('Error loading email notification settings:', err);
      }
    };

    loadEmailNotifications();
  }, []);

  // Load all data from the backend
  useEffect(() => {
    const loadData = async () => {
      try {
        console.log('📂 Loading data from backend...');
        setBackendError(null);

        // First, ensure admin user exists
        console.log('🔧 Initializing admin user...');
        const initAdminResponse = await fetchWithRetry(`https://${projectId}.supabase.co/functions/v1/make-server-af5db803/init-admin`, {
          method: 'POST',
          headers: {
            'Authorization': `Bearer ${publicAnonKey}`,
            'Content-Type': 'application/json',
          },
        });
        
        if (initAdminResponse.ok) {
          const initResult = await initAdminResponse.json();
          console.log('✅ Admin user initialized:', initResult.message);
        } else {
          console.error('❌ Failed to initialize admin user');
        }

        // Migrate users to new format (individual keys)
        console.log('🔄 Running user migration...');
        const migrateUsersResponse = await fetchWithRetry(`https://${projectId}.supabase.co/functions/v1/make-server-af5db803/migrate-users`, {
          method: 'POST',
          headers: {
            'Authorization': `Bearer ${publicAnonKey}`,
            'Content-Type': 'application/json',
          },
        });
        
        if (migrateUsersResponse.ok) {
          const migrateUsersResult = await migrateUsersResponse.json();
          if (migrateUsersResult.alreadyMigrated) {
            console.log(`✅ Users already in new format: ${migrateUsersResult.userCount} users`);
          } else if (migrateUsersResult.userCount > 0) {
            console.log(`✅ Migrated ${migrateUsersResult.userCount} users to individual keys`);
          } else {
            console.log('ℹ️ No users to migrate');
          }
        } else {
          console.error('❌ Failed to migrate users');
        }

        // Load users from new format
        const usersResponse = await fetch(`https://${projectId}.supabase.co/functions/v1/make-server-af5db803/users`, {
          headers: { 'Authorization': `Bearer ${publicAnonKey}` }
        });
        if (usersResponse.ok) {
          const usersData = await usersResponse.json();
          if (usersData.users && usersData.users.length > 0) {
            setUsers(usersData.users);
            console.log(`✅ Loaded ${usersData.users.length} users`);
            
            // Check if any user has an unhashed password (security fix)
            const hasUnhashedPassword = usersData.users.some((u: any) => 
              u.password && !u.password.startsWith('$2')
            );
            
            if (hasUnhashedPassword) {
              console.log('⚠️ Detected unhashed passwords, re-saving users to hash them...');
              const rehashResponse = await fetch(`https://${projectId}.supabase.co/functions/v1/make-server-af5db803/users`, {
                method: 'POST',
                headers: {
                  'Authorization': `Bearer ${publicAnonKey}`,
                  'Content-Type': 'application/json',
                },
                body: JSON.stringify({ users: usersData.users }),
              });
              
              if (rehashResponse.ok) {
                console.log('✅ Passwords re-hashed successfully');
                // Reload users to get the hashed versions
                const reloadResponse = await fetch(`https://${projectId}.supabase.co/functions/v1/make-server-af5db803/users`, {
                  headers: { 'Authorization': `Bearer ${publicAnonKey}` }
                });
                if (reloadResponse.ok) {
                  const reloadedData = await reloadResponse.json();
                  if (reloadedData.users) {
                    setUsers(reloadedData.users);
                    console.log('✅ Reloaded users with properly hashed passwords');
                  }
                }
              }
            }
          } else {
            console.log('ℹ️ No users found in KV store, initializing with default admin user...');
            // Initialize with default admin user if no users exist
            const initResponse = await fetch(`https://${projectId}.supabase.co/functions/v1/make-server-af5db803/users`, {
              method: 'POST',
              headers: {
                'Authorization': `Bearer ${publicAnonKey}`,
                'Content-Type': 'application/json',
              },
              body: JSON.stringify({ users: MOCK_USERS }),
            });
            
            if (initResponse.ok) {
              console.log('✅ Initialized default admin user');
              // Reload users to get the hashed password version
              const reloadResponse = await fetch(`https://${projectId}.supabase.co/functions/v1/make-server-af5db803/users`, {
                headers: { 'Authorization': `Bearer ${publicAnonKey}` }
              });
              if (reloadResponse.ok) {
                const reloadedData = await reloadResponse.json();
                if (reloadedData.users) {
                  setUsers(reloadedData.users);
                  console.log('✅ Loaded initialized users with hashed passwords');
                }
              }
            } else {
              console.error('❌ Failed to initialize default admin user');
            }
          }
        }

        // Migrate tickets to new format (individual keys)
        console.log('🔄 Running ticket migration...');
        const migrateResponse = await fetch(`https://${projectId}.supabase.co/functions/v1/make-server-af5db803/migrate-tickets`, {
          method: 'POST',
          headers: {
            'Authorization': `Bearer ${publicAnonKey}`,
            'Content-Type': 'application/json',
          },
        });
        
        if (migrateResponse.ok) {
          const migrateResult = await migrateResponse.json();
          if (migrateResult.alreadyMigrated) {
            console.log(`✅ Tickets already in new format: ${migrateResult.ticketCount} tickets`);
          } else if (migrateResult.ticketCount > 0) {
            console.log(`✅ Migrated ${migrateResult.ticketCount} tickets to individual keys`);
          } else {
            console.log('ℹ️ No tickets to migrate');
          }
        } else {
          console.error('❌ Failed to migrate tickets');
        }

        // Load tickets from new format
        const ticketsResponse = await fetch(`https://${projectId}.supabase.co/functions/v1/make-server-af5db803/tickets`, {
          headers: { 'Authorization': `Bearer ${publicAnonKey}` }
        });
        if (ticketsResponse.ok) {
          const ticketsData = await ticketsResponse.json();
          if (ticketsData.tickets && ticketsData.tickets.length > 0) {
            // Convert date strings back to Date objects
            const ticketsWithDates = ticketsData.tickets.map((t: any) => ({
              ...t,
              createdAt: new Date(t.createdAt),
              updatedAt: t.updatedAt ? new Date(t.updatedAt) : undefined,
              plannedImplementationDate: t.plannedImplementationDate ? new Date(t.plannedImplementationDate) : undefined,
              actualImplementationDate: t.actualImplementationDate ? new Date(t.actualImplementationDate) : undefined,
              deprecatedDate: t.deprecatedDate ? new Date(t.deprecatedDate) : undefined,
              archivedAt: t.archivedAt ? new Date(t.archivedAt) : undefined,
              approvals: t.approvals?.map((a: any) => ({
                ...a,
                timestamp: a.timestamp ? new Date(a.timestamp) : undefined,
              })),
              rejectionHistory: t.rejectionHistory?.map((r: any) => ({
                ...r,
                timestamp: new Date(r.timestamp),
              })),
              resubmissionComments: t.resubmissionComments?.map((rc: any) => ({
                ...rc,
                timestamp: new Date(rc.timestamp),
              })),
            }));
            setTickets(ticketsWithDates);
            console.log(`✅ Loaded ${ticketsWithDates.length} tickets`);
          }
        }

        // Load tags
        const tagsResponse = await fetch(`https://${projectId}.supabase.co/functions/v1/make-server-af5db803/tags`, {
          headers: { 'Authorization': `Bearer ${publicAnonKey}` }
        });
        if (tagsResponse.ok) {
          const tagsData = await tagsResponse.json();
          if (tagsData.tags && tagsData.tags.length > 0) {
            setTags(tagsData.tags);
            console.log(`✅ Loaded ${tagsData.tags.length} tags`);
          }
        }

        // Load counters
        const countersResponse = await fetch(`https://${projectId}.supabase.co/functions/v1/make-server-af5db803/counters`, {
          headers: { 'Authorization': `Bearer ${publicAnonKey}` }
        });
        if (countersResponse.ok) {
          const countersData = await countersResponse.json();
          if (countersData.counters) {
            setRfcCounter(countersData.counters.rfc || 1000);
            setReleaseNoteCounter(countersData.counters.releaseNote || 1000);
            console.log(`✅ Loaded counters: RFC=${countersData.counters.rfc}, RN=${countersData.counters.releaseNote}`);
          }
        }

        console.log('✅ All data loaded successfully');
        setIsDataLoaded(true);
        setIsBackendConnected(true);
      } catch (err: any) {
        console.error('❌ Error loading data from backend:', err);
        const errorMessage = err.message || 'Failed to connect to backend. Please ensure the Supabase Edge Function is deployed.';
        setBackendError(errorMessage);
        setIsBackendConnected(false);
        
        // Show user-friendly error
        alert(`⚠️ Backend Connection Error\n\n${errorMessage}\n\nThe application will use local data only. Some features may not work correctly.\n\nTo fix this:\n1. Deploy the Supabase Edge Function: supabase functions deploy make-server-af5db803\n2. Ensure environment variables are set in Supabase\n3. Refresh the page`);
      }
    };

    loadData();
  }, []);

  // Initial batch save after data is loaded (fallback for any sync issues)
  useEffect(() => {
    if (!isDataLoaded) return;
    
    // Only run once after initial data load
    let hasRun = false;
    if (hasRun) return;
    
    const saveTickets = async () => {
      try {
        await fetch(`https://${projectId}.supabase.co/functions/v1/make-server-af5db803/tickets`, {
          method: 'POST',
          headers: {
            'Authorization': `Bearer ${publicAnonKey}`,
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({ tickets }),
        });
        console.log('💾 Initial batch save completed');
        hasRun = true;
      } catch (err) {
        console.error('Error in initial batch save:', err);
      }
    };

    // Delay the initial save to avoid conflicts with individual saves
    const timer = setTimeout(saveTickets, 2000);
    return () => clearTimeout(timer);
  }, [isDataLoaded]);

  // Initial batch save of users after data is loaded (fallback for any sync issues)
  useEffect(() => {
    if (!isDataLoaded) return;
    
    // Only run once after initial data load
    let hasRun = false;
    if (hasRun) return;
    
    const saveUsers = async () => {
      try {
        console.log('💾 Initial user batch save:', users.length, 'users');
        const response = await fetch(`https://${projectId}.supabase.co/functions/v1/make-server-af5db803/users`, {
          method: 'POST',
          headers: {
            'Authorization': `Bearer ${publicAnonKey}`,
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({ users }),
        });
        
        const result = await response.json();
        
        if (!response.ok) {
          console.error('❌ Failed initial user save:', result);
          return;
        }
        
        console.log('✅ Initial user batch save completed');
        hasRun = true;
      } catch (err) {
        console.error('❌ Error in initial user batch save:', err);
      }
    };

    // Delay the initial save to avoid conflicts with individual saves
    const timer = setTimeout(saveUsers, 2000);
    return () => clearTimeout(timer);
  }, [isDataLoaded]);

  // Save tags to backend whenever they change
  useEffect(() => {
    if (!isDataLoaded) return; // Don't save until initial data is loaded
    
    const saveTags = async () => {
      try {
        await fetch(`https://${projectId}.supabase.co/functions/v1/make-server-af5db803/tags`, {
          method: 'POST',
          headers: {
            'Authorization': `Bearer ${publicAnonKey}`,
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({ tags }),
        });
        console.log('💾 Saved tags to Supabase');
      } catch (err) {
        console.error('Error saving tags:', err);
      }
    };

    saveTags();
  }, [tags, isDataLoaded]);

  // Save counters to backend whenever they change
  useEffect(() => {
    if (!isDataLoaded) return; // Don't save until initial data is loaded
    
    const saveCounters = async () => {
      try {
        await fetch(`https://${projectId}.supabase.co/functions/v1/make-server-af5db803/counters`, {
          method: 'POST',
          headers: {
            'Authorization': `Bearer ${publicAnonKey}`,
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({ counters: { rfc: rfcCounter, releaseNote: releaseNoteCounter } }),
        });
        console.log('💾 Saved counters to Supabase');
      } catch (err) {
        console.error('Error saving counters:', err);
      }
    };

    saveCounters();
  }, [rfcCounter, releaseNoteCounter, isDataLoaded]);

  // Helper function to save individual user to backend
  const saveUserToBackend = async (user: User) => {
    try {
      await fetch(`https://${projectId}.supabase.co/functions/v1/make-server-af5db803/user`, {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${publicAnonKey}`,
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(user),
      });
      console.log(`💾 Saved user ${user.email} to backend`);
    } catch (err) {
      console.error(`Error saving user ${user.email}:`, err);
    }
  };

  // Helper function to update individual user in backend
  const updateUserInBackend = async (userId: string, updates: any) => {
    try {
      await fetch(`https://${projectId}.supabase.co/functions/v1/make-server-af5db803/user/${userId}`, {
        method: 'PUT',
        headers: {
          'Authorization': `Bearer ${publicAnonKey}`,
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(updates),
      });
      console.log(`💾 Updated user ${userId} in backend`);
    } catch (err) {
      console.error(`Error updating user ${userId}:`, err);
    }
  };

  // Helper function to delete individual user from backend
  const deleteUserFromBackend = async (userId: string) => {
    try {
      await fetch(`https://${projectId}.supabase.co/functions/v1/make-server-af5db803/user/${userId}`, {
        method: 'DELETE',
        headers: {
          'Authorization': `Bearer ${publicAnonKey}`,
        },
      });
      console.log(`💾 Deleted user ${userId} from backend`);
    } catch (err) {
      console.error(`Error deleting user ${userId}:`, err);
    }
  };

  // Helper function to save individual ticket to backend
  const saveTicketToBackend = async (ticket: Ticket) => {
    try {
      await fetch(`https://${projectId}.supabase.co/functions/v1/make-server-af5db803/ticket`, {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${publicAnonKey}`,
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(ticket),
      });
      console.log(`💾 Saved ticket ${ticket.ticketNumber} to backend`);
    } catch (err) {
      console.error(`Error saving ticket ${ticket.ticketNumber}:`, err);
    }
  };

  // Helper function to update individual ticket in backend
  const updateTicketInBackend = async (ticketId: string, updates: any) => {
    try {
      await fetch(`https://${projectId}.supabase.co/functions/v1/make-server-af5db803/ticket/${ticketId}`, {
        method: 'PUT',
        headers: {
          'Authorization': `Bearer ${publicAnonKey}`,
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(updates),
      });
      console.log(`💾 Updated ticket ${ticketId} in backend`);
    } catch (err) {
      console.error(`Error updating ticket ${ticketId}:`, err);
    }
  };

  // Helper function to delete individual ticket from backend
  const deleteTicketFromBackend = async (ticketId: string) => {
    try {
      await fetch(`https://${projectId}.supabase.co/functions/v1/make-server-af5db803/ticket/${ticketId}`, {
        method: 'DELETE',
        headers: {
          'Authorization': `Bearer ${publicAnonKey}`,
        },
      });
      console.log(`💾 Deleted ticket ${ticketId} from backend`);
    } catch (err) {
      console.error(`Error deleting ticket ${ticketId}:`, err);
    }
  };

  const handleLogin = (user: User, token: string) => {
    setCurrentUser(user);
    setSessionToken(token);
    console.log('✅ User logged in with session token');
  };

  const handleLogout = async () => {
    // Call logout endpoint to destroy session
    if (sessionToken) {
      try {
        await fetch(`https://${projectId}.supabase.co/functions/v1/make-server-af5db803/logout`, {
          method: 'POST',
          headers: {
            'Authorization': `Bearer ${sessionToken}`,
          },
        });
      } catch (err) {
        console.error('Error during logout:', err);
      }
    }
    
    setCurrentUser(null);
    setSessionToken(null);
  };

  const handleCreateTicket = async (data: {
    type: TicketType;
    department: TicketDepartment;
    title: string;
    description: string;
    attachments: Attachment[];
    approvers: Array<{ primary: string; secondary?: string }>;
    plannedImplementationDate?: Date;
    actualImplementationDate?: Date;
    deprecatedDate?: Date;
    tags?: string[];
  }) => {
    if (!currentUser) return;

    const ticketNumber = data.type === 'RFC' ? `RFC-${rfcCounter}` : `RN-${releaseNoteCounter}`;
    if (data.type === 'RFC') {
      setRfcCounter(rfcCounter + 1);
    } else {
      setReleaseNoteCounter(releaseNoteCounter + 1);
    }

    const approvals: Approval[] = data.approvers.map(approverPair => {
      const primaryApprover = MOCK_USERS.find(u => u.id === approverPair.primary);
      const secondaryApprover = approverPair.secondary ? MOCK_USERS.find(u => u.id === approverPair.secondary) : undefined;
      
      return {
        approverId: approverPair.primary,
        approverName: primaryApprover?.name || '',
        secondaryApproverId: secondaryApprover?.id,
        secondaryApproverName: secondaryApprover?.name,
        status: 'pending' as const,
      };
    });

    const newTicket: Ticket = {
      id: Math.random().toString(36).substr(2, 9),
      ticketNumber,
      type: data.type,
      department: data.department,
      title: data.title,
      description: data.description,
      createdBy: currentUser.id,
      createdByName: currentUser.name,
      createdAt: new Date(),
      status: data.type === 'Release Note' ? 'approved' : 'pending',
      approvals,
      attachments: data.attachments,
      plannedImplementationDate: data.plannedImplementationDate,
      actualImplementationDate: data.actualImplementationDate,
      deprecatedDate: data.deprecatedDate,
      tags: data.tags || [],
    };

    setTickets([newTicket, ...tickets]);

    // Save the new ticket to backend immediately
    await saveTicketToBackend(newTicket);

    // Send email notification to cadvchangecontrol
    try {
      const ticketUrl = `${window.location.origin}?ticketId=${newTicket.id}`;
      const response = await fetch(`https://${projectId}.supabase.co/functions/v1/make-server-af5db803/send-ticket-email`, {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${publicAnonKey}`,
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          ticketNumber,
          ticketType: data.type,
          title: data.title,
          createdByName: currentUser.name,
          ticketUrl,
        }),
      });

      const result = await response.json();
      
      if (result.emailSkipped) {
        if (result.message === 'API key not configured') {
          console.log('ℹ️ Email notification skipped: SENDGRID_API_KEY not configured. Add it in Supabase settings to enable email notifications.');
        } else if (result.message === 'API key is invalid') {
          console.log('ℹ️ Email notification skipped: SENDGRID_API_KEY is invalid. Update it in Supabase settings to enable email notifications.');
        } else {
          console.log('ℹ️ Email notification skipped:', result.message);
        }
      } else if (result.success) {
        console.log('✓ Email notification sent successfully');
      } else {
        console.error('Failed to send email notification:', result);
      }
    } catch (error) {
      console.error('Error sending email notification:', error);
    }

    // Approver emails removed - no longer sending automatic emails to approvers
  };

  const handleApprove = (ticketId: string, approverId: string) => {
    let updatedTicket: Ticket | null = null;
    
    setTickets(tickets.map(ticket => {
      if (ticket.id !== ticketId) return ticket;

      const updatedApprovals = ticket.approvals.map(approval => {
        // Check if the approver is either the primary or secondary approver
        const canApprove = approval.approverId === approverId || approval.secondaryApproverId === approverId;
        
        if (canApprove) {
          return {
            ...approval,
            status: 'approved' as const,
            timestamp: new Date(),
            approvedBy: approval.approverId === approverId ? 'primary' as const : 'secondary' as const,
          };
        }
        return approval;
      });

      // Check if all approvals are now approved
      const allApproved = updatedApprovals.every(a => a.status === 'approved');

      // If all approved and this is an RFC, send approval email
      if (allApproved && ticket.type === 'RFC') {
        const creator = users.find(u => u.id === ticket.createdBy);
        sendApprovalEmail(ticket.ticketNumber, ticket.title, ticket.id, creator?.email);
      }

      updatedTicket = {
        ...ticket,
        approvals: updatedApprovals,
        status: allApproved ? 'approved' as const : ticket.status,
        updatedAt: new Date(),
      };
      
      return updatedTicket;
    }));
    
    // Save the updated ticket to backend
    if (updatedTicket) {
      updateTicketInBackend(ticketId, updatedTicket);
    }
  };

  const sendApprovalEmail = async (ticketNumber: string, title: string, ticketId: string, creatorEmail?: string) => {
    try {
      const ticketUrl = `${window.location.origin}?ticketId=${ticketId}`;
      const response = await fetch(`https://${projectId}.supabase.co/functions/v1/make-server-af5db803/send-approval-email`, {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${publicAnonKey}`,
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          ticketNumber,
          title,
          ticketUrl,
          creatorEmail,
        }),
      });

      const result = await response.json();
      
      if (result.emailSkipped) {
        if (result.message === 'API key not configured') {
          console.log('ℹ️ Approval email skipped: RESEND_API_KEY not configured. Add it in Supabase settings to enable email notifications.');
        } else if (result.message === 'API key is invalid') {
          console.log('ℹ️ Approval email skipped: RESEND_API_KEY is invalid. Update it in Supabase settings to enable email notifications.');
        } else {
          console.log('ℹ️ Approval email skipped:', result.message);
        }
      } else if (result.success) {
        console.log('✓ Approval email notification sent successfully');
      } else {
        console.error('Failed to send approval email notification:', result);
      }
    } catch (error) {
      console.error('Error sending approval email notification:', error);
    }
  };

  const handleReject = (ticketId: string, approverId: string, comment: string) => {
    let updatedTicket: Ticket | null = null;
    
    setTickets(tickets.map(ticket => {
      if (ticket.id !== ticketId) return ticket;

      // Find the approver who rejected
      const approver = users.find(u => u.id === approverId);
      const approval = ticket.approvals.find(a => a.approverId === approverId);

      // Create new rejection history entry
      const newRejectionEntry: RejectionHistory = {
        id: Math.random().toString(36).substr(2, 9),
        comment,
        rejectedBy: approverId,
        rejectedByName: approver?.name || 'Unknown',
        approverId: approval?.approverId || approverId,
        timestamp: new Date(),
      };

      const updatedApprovals = ticket.approvals.map(approval => {
        if (approval.approverId === approverId) {
          return {
            ...approval,
            status: 'rejected' as const,
            comment,
            timestamp: new Date(),
          };
        }
        return approval;
      });

      updatedTicket = {
        ...ticket,
        approvals: updatedApprovals,
        status: 'rejected' as const,
        rejectionComment: comment, // Keep for backward compatibility
        rejectionHistory: [...(ticket.rejectionHistory || []), newRejectionEntry],
        updatedAt: new Date(),
      };
      
      return updatedTicket;
    }));
    
    // Save the updated ticket to backend
    if (updatedTicket) {
      updateTicketInBackend(ticketId, updatedTicket);
    }
  };

  const handleUpdateTicket = (ticketId: string, updates: {
    title: string;
    description: string;
    attachments: Attachment[];
    plannedImplementationDate?: Date;
    actualImplementationDate?: Date;
    deprecatedDate?: Date;
    deprecatedReason?: string;
    approvers?: string[];
    tags?: string[];
  }) => {
    let updatedTicket: Ticket | null = null;
    
    setTickets(tickets.map(ticket => {
      if (ticket.id !== ticketId) return ticket;

      // If approvers are being updated, rebuild the approvals array
      let updatedApprovals = ticket.approvals;
      if (updates.approvers && ticket.type === 'RFC') {
        updatedApprovals = updates.approvers.map(approverId => {
          // Keep existing approval if it exists
          const existingApproval = ticket.approvals.find(a => a.approverId === approverId);
          if (existingApproval) {
            return existingApproval;
          }
          // Create new approval for new approvers
          const approver = users.find(u => u.id === approverId);
          return {
            approverId,
            approverName: approver?.name || 'Unknown',
            approverEmail: approver?.email || '',
            status: 'pending' as const,
          };
        });
      }

      updatedTicket = {
        ...ticket,
        title: updates.title,
        description: updates.description,
        attachments: updates.attachments,
        plannedImplementationDate: updates.plannedImplementationDate !== undefined ? updates.plannedImplementationDate : ticket.plannedImplementationDate,
        actualImplementationDate: updates.actualImplementationDate !== undefined ? updates.actualImplementationDate : ticket.actualImplementationDate,
        deprecatedDate: updates.deprecatedDate !== undefined ? updates.deprecatedDate : ticket.deprecatedDate,
        deprecatedReason: updates.deprecatedReason !== undefined ? updates.deprecatedReason : ticket.deprecatedReason,
        approvals: updatedApprovals,
        tags: updates.tags !== undefined ? updates.tags : ticket.tags,
        updatedAt: new Date(),
      };
      
      return updatedTicket;
    }));
    
    // Save the updated ticket to backend
    if (updatedTicket) {
      updateTicketInBackend(ticketId, updatedTicket);
    }
  };

  const handleRequestReapproval = (ticketId: string, resubmissionComment?: string) => {
    let updatedTicket: Ticket | null = null;
    
    setTickets(tickets.map(ticket => {
      if (ticket.id !== ticketId) return ticket;

      // Add resubmission comment to history if provided
      const newResubmissionComment = resubmissionComment?.trim() ? {
        id: Math.random().toString(36).substr(2, 9),
        comment: resubmissionComment,
        submittedBy: currentUser!.id,
        submittedByName: currentUser!.name,
        timestamp: new Date(),
      } : null;

      const updatedResubmissionComments = newResubmissionComment
        ? [...(ticket.resubmissionComments || []), newResubmissionComment]
        : ticket.resubmissionComments;

      // Reset all approvals to pending
      const resetApprovals = ticket.approvals.map(approval => ({
        ...approval,
        status: 'pending' as const,
        comment: undefined,
        timestamp: undefined,
      }));

      updatedTicket = {
        ...ticket,
        status: 'pending' as const,
        approvals: resetApprovals,
        rejectionComment: undefined,
        resubmissionComments: updatedResubmissionComments,
        updatedAt: new Date(),
      };
      
      return updatedTicket;
    }));
    
    // Save the updated ticket to backend
    if (updatedTicket) {
      updateTicketInBackend(ticketId, updatedTicket);
    }
  };

  const handleArchiveTicket = (ticketId: string, archiveReason: string) => {
    let updatedTicket: Ticket | null = null;
    
    setTickets(tickets.map(ticket => {
      if (ticket.id !== ticketId) return ticket;
      
      updatedTicket = {
        ...ticket,
        status: 'archived' as const,
        archivedAt: new Date(),
        archivedBy: currentUser!.id,
        archivedByName: currentUser!.name,
        archiveReason,
        updatedAt: new Date(),
      };
      
      return updatedTicket;
    }));
    
    // Save the updated ticket to backend
    if (updatedTicket) {
      updateTicketInBackend(ticketId, updatedTicket);
    }
  };

  const handleUnarchiveTicket = (ticketId: string) => {
    let updatedTicket: Ticket | null = null;
    
    setTickets(tickets.map(ticket => {
      if (ticket.id !== ticketId) return ticket;
      
      // Determine the status to restore to based on ticket type and approvals
      let restoredStatus: 'pending' | 'approved' = 'pending';
      if (ticket.type === 'Release Note') {
        restoredStatus = 'approved';
      } else if (ticket.approvals.every(a => a.status === 'approved')) {
        restoredStatus = 'approved';
      }
      
      updatedTicket = {
        ...ticket,
        status: restoredStatus,
        archivedAt: undefined,
        archivedBy: undefined,
        archivedByName: undefined,
        archiveReason: undefined,
        updatedAt: new Date(),
      };
      
      return updatedTicket;
    }));
    
    // Save the updated ticket to backend
    if (updatedTicket) {
      updateTicketInBackend(ticketId, updatedTicket);
    }
  };

  const handleCreateUser = (userData: { name: string; email: string; role: string }) => {
    // Generate a random temporary password
    const temporaryPassword = Math.random().toString(36).slice(-10) + Math.random().toString(36).slice(-10).toUpperCase();
    
    const newUser: User = {
      id: Math.random().toString(36).substr(2, 9),
      name: userData.name,
      email: userData.email,
      password: temporaryPassword, // Use temporary password
      role: userData.role,
      permissions: getDefaultPermissions(userData.role),
      requirePasswordReset: true,
      temporaryPassword: temporaryPassword,
    };
    
    console.log('Creating new user:', { name: newUser.name, email: newUser.email, role: newUser.role });
    setUsers([...users, newUser]);

    // Save the new user to backend immediately
    saveUserToBackend(newUser);

    // Send welcome email with temporary password
    const sendWelcomeEmail = async () => {
      try {
        const response = await fetch(`https://${projectId}.supabase.co/functions/v1/make-server-af5db803/send-welcome-email`, {
          method: 'POST',
          headers: {
            'Authorization': `Bearer ${publicAnonKey}`,
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            userName: newUser.name,
            userEmail: newUser.email,
            temporaryPassword: temporaryPassword,
          }),
        });

        const result = await response.json();
        
        if (result.emailSkipped) {
          if (result.message === 'API key not configured') {
            console.log('ℹ️ Welcome email skipped: SENDGRID_API_KEY not configured.');
          } else if (result.message === 'API key is invalid') {
            console.log('ℹ️ Welcome email skipped: SENDGRID_API_KEY is invalid.');
          } else {
            console.log('ℹ️ Welcome email skipped:', result.message);
          }
        } else if (result.success) {
          console.log('✓ Welcome email sent successfully to', newUser.email);
        } else {
          console.error('Failed to send welcome email:', result);
        }
      } catch (error) {
        console.error('Error sending welcome email:', error);
      }
    };

    sendWelcomeEmail();
  };

  const handleUpdateUser = (userId: string, updates: { name?: string; email?: string; password?: string; role?: string; permissions?: UserPermissions }) => {
    let updatedUser: User | null = null;
    
    setUsers(users.map(user => {
      if (user.id !== userId) return user;
      updatedUser = { ...user, ...updates };
      // If role is updated but permissions are not provided, use default permissions for the new role
      if (updates.role && !updates.permissions) {
        updatedUser.permissions = getDefaultPermissions(updates.role);
      }
      return updatedUser;
    }));
    
    // Save the updated user to backend
    if (updatedUser) {
      updateUserInBackend(userId, updatedUser);
    }
  };

  const handleDeleteUser = (userId: string) => {
    setUsers(users.filter(user => user.id !== userId));
    
    // Delete the user from backend
    deleteUserFromBackend(userId);
  };

  const handleCreateTag = (tagData: { name: string; color: string }) => {
    const newTag: Tag = {
      id: Math.random().toString(36).substr(2, 9),
      ...tagData,
    };
    setTags([...tags, newTag]);
  };

  const handleUpdateTag = (tagId: string, updates: { name?: string; color?: string }) => {
    setTags(tags.map(tag => 
      tag.id === tagId ? { ...tag, ...updates } : tag
    ));
  };

  const handleDeleteTag = (tagId: string) => {
    // Remove tag from all tickets
    setTickets(tickets.map(ticket => ({
      ...ticket,
      tags: ticket.tags?.filter(t => t !== tagId)
    })));
    // Remove tag from tags list
    setTags(tags.filter(tag => tag.id !== tagId));
  };

  const handleCreateRole = (roleData: { name: string; description: string; permissions: UserPermissions }) => {
    if (!currentUser) return;
    
    const newRole: CustomRole = {
      id: Math.random().toString(36).substr(2, 9),
      name: roleData.name,
      description: roleData.description,
      permissions: roleData.permissions,
      isSystem: false,
      createdAt: new Date(),
      createdBy: currentUser.id,
    };
    setCustomRoles([...customRoles, newRole]);
  };

  const handleUpdateRole = (roleId: string, updates: { name?: string; description?: string; permissions?: UserPermissions }) => {
    setCustomRoles(customRoles.map(role => {
      if (role.id !== roleId) return role;
      if (role.isSystem) {
        console.warn('Cannot update system role');
        return role;
      }
      return { ...role, ...updates };
    }));
  };

  const handleDeleteRole = (roleId: string) => {
    const role = customRoles.find(r => r.id === roleId);
    if (role?.isSystem) {
      console.warn('Cannot delete system role');
      return;
    }
    
    // Check if any users have this role
    const usersWithRole = users.filter(u => u.role === roleId);
    if (usersWithRole.length > 0) {
      alert(`Cannot delete role "${role?.name}" because ${usersWithRole.length} user(s) are assigned to it. Please reassign these users first.`);
      return;
    }
    
    setCustomRoles(customRoles.filter(r => r.id !== roleId));
  };

  const handleCreateTicketType = async (typeData: { name: string; description: string; approvalCount: 0 | 1 | 2; color: string; prefix: string }) => {
    if (!currentUser) return;
    
    const newType: CustomTicketType = {
      id: Math.random().toString(36).substr(2, 9),
      name: typeData.name,
      description: typeData.description,
      approvalCount: typeData.approvalCount,
      color: typeData.color,
      prefix: typeData.prefix,
      isSystem: false,
      createdAt: new Date(),
      createdBy: currentUser.id,
    };
    
    const updatedTypes = [...customTicketTypes, newType];
    setCustomTicketTypes(updatedTypes);
    
    // Save to backend
    try {
      await fetch(`https://${projectId}.supabase.co/functions/v1/make-server-af5db803/ticket-types`, {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${publicAnonKey}`,
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(newType),
      });
      console.log('✅ Custom ticket type saved to backend:', newType);
    } catch (error) {
      console.error('Error saving custom ticket type:', error);
    }
  };

  const handleUpdateTicketType = async (typeId: string, updates: { name?: string; description?: string; approvalCount?: 0 | 1 | 2; color?: string; prefix?: string }) => {
    const updatedTypes = customTicketTypes.map(type => {
      if (type.id !== typeId) return type;
      if (type.isSystem) {
        console.warn('Cannot update system ticket type');
        return type;
      }
      return { ...type, ...updates };
    });
    
    setCustomTicketTypes(updatedTypes);
    
    // Save to backend
    try {
      const updatedType = updatedTypes.find(t => t.id === typeId);
      if (updatedType) {
        await fetch(`https://${projectId}.supabase.co/functions/v1/make-server-af5db803/ticket-types/${typeId}`, {
          method: 'PUT',
          headers: {
            'Authorization': `Bearer ${publicAnonKey}`,
            'Content-Type': 'application/json',
          },
          body: JSON.stringify(updatedType),
        });
        console.log('✅ Custom ticket type updated in backend:', updatedType);
      }
    } catch (error) {
      console.error('Error updating custom ticket type:', error);
    }
  };

  const handleDeleteTicketType = (typeId: string) => {
    const type = customTicketTypes.find(t => t.id === typeId);
    if (type?.isSystem) {
      console.warn('Cannot delete system ticket type');
      return;
    }
    
    // Check if any tickets use this type
    const ticketsWithType = tickets.filter(t => t.type === type?.name);
    if (ticketsWithType.length > 0) {
      alert(`Cannot delete ticket type "${type?.name}" because ${ticketsWithType.length} ticket(s) are using it.`);
      return;
    }
    
    setCustomTicketTypes(customTicketTypes.filter(t => t.id !== typeId));
    
    // Delete from backend
    fetch(`https://${projectId}.supabase.co/functions/v1/make-server-af5db803/ticket-types/${typeId}`, {
      method: 'DELETE',
      headers: {
        'Authorization': `Bearer ${publicAnonKey}`,
      },
    }).then(() => {
      console.log('✅ Custom ticket type deleted from backend');
    }).catch((error) => {
      console.error('Error deleting custom ticket type:', error);
    });
  };

  const handleCreateDepartment = (departmentData: { name: string; description?: string; color?: string }) => {
    if (!currentUser) return;
    
    const newDepartment: CustomDepartment = {
      id: Math.random().toString(36).substr(2, 9),
      name: departmentData.name,
      description: departmentData.description,
      color: departmentData.color,
      isSystem: false,
      createdAt: new Date(),
      createdBy: currentUser.id,
    };
    setCustomDepartments([...customDepartments, newDepartment]);
    
    // Add default approver configuration for the new department
    setDefaultApprovers([
      ...defaultApprovers,
      {
        department: departmentData.name,
        approver1PrimaryId: undefined,
        approver1SecondaryId: undefined,
        approver2PrimaryId: undefined,
        approver2SecondaryId: undefined,
      },
    ]);
  };

  const handleUpdateDepartment = (departmentId: string, updates: { name?: string; description?: string; color?: string }) => {
    setCustomDepartments(customDepartments.map(department => {
      if (department.id !== departmentId) return department;
      if (department.isSystem) {
        console.warn('Cannot update system department');
        return department;
      }
      
      // If name is being updated, also update the defaultApprovers
      if (updates.name && department.name !== updates.name) {
        setDefaultApprovers(defaultApprovers.map(da =>
          da.department === department.name
            ? { ...da, department: updates.name }
            : da
        ));
      }
      
      return { ...department, ...updates };
    }));
  };

  const handleDeleteDepartment = (departmentId: string) => {
    const department = customDepartments.find(c => c.id === departmentId);
    if (department?.isSystem) {
      console.warn('Cannot delete system department');
      return;
    }
    
    // Check if any tickets use this department
    const ticketsWithDepartment = tickets.filter(t => t.department === department?.name);
    if (ticketsWithDepartment.length > 0) {
      alert(`Cannot delete department \"${department?.name}\" because ${ticketsWithDepartment.length} ticket(s) are using it. Please reassign these tickets first.`);
      return;
    }
    
    setCustomDepartments(customDepartments.filter(c => c.id !== departmentId));
    
    // Remove default approver configuration for the deleted department
    setDefaultApprovers(defaultApprovers.filter(da => da.department !== department?.name));
  };

  const handleUpdateDefaultApprovers = async (
    department: TicketDepartment, 
    approver1PrimaryId?: string, 
    approver1SecondaryId?: string,
    approver2PrimaryId?: string,
    approver2SecondaryId?: string
  ) => {
    console.log('handleUpdateDefaultApprovers called:', { 
      department, 
      approver1PrimaryId, 
      approver1SecondaryId, 
      approver2PrimaryId, 
      approver2SecondaryId,
      currentDefaultApprovers: defaultApprovers
    });

    // Ensure all departments exist
    const departments: TicketDepartment[] = ['Marketing', 'Risk/Leads', 'Data', 'Product', 'Operations', 'Training', 'Q&A'];
    const ensureAllDepartments = departments.map(dept => {
      const existing = defaultApprovers.find(d => d.department === dept);
      return existing || { 
        department: dept, 
        approver1PrimaryId: undefined, 
        approver1SecondaryId: undefined, 
        approver2PrimaryId: undefined, 
        approver2SecondaryId: undefined 
      };
    });

    const updatedApprovers = ensureAllDepartments.map(config =>
      config.department === department
        ? { ...config, approver1PrimaryId, approver1SecondaryId, approver2PrimaryId, approver2SecondaryId }
        : config
    );
    
    console.log('Updated approvers:', updatedApprovers);
    setDefaultApprovers(updatedApprovers);

    // Save to backend
    try {
      const response = await fetch(`https://${projectId}.supabase.co/functions/v1/make-server-af5db803/default-approvers`, {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${publicAnonKey}`,
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ defaultApprovers: updatedApprovers }),
      });
      const result = await response.json();
      console.log('Backend save response:', result);
    } catch (err) {
      console.error('Failed to save default approvers to backend:', err);
    }
  };

  // New handler to update all default approvers at once
  const handleUpdateAllDefaultApprovers = async (allApprovers: DepartmentDefaultApprovers[]) => {
    console.log('handleUpdateAllDefaultApprovers called with:', allApprovers);
    
    setDefaultApprovers(allApprovers);

    // Save to backend
    try {
      const response = await fetch(`https://${projectId}.supabase.co/functions/v1/make-server-af5db803/default-approvers`, {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${publicAnonKey}`,
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ defaultApprovers: allApprovers }),
      });
      const result = await response.json();
      console.log('Backend save response for all approvers:', result);
    } catch (err) {
      console.error('Failed to save all default approvers to backend:', err);
      throw err;
    }
  };

  const handleUpdateEmailNotifications = async (settings: EmailNotificationSettings) => {
    console.log('handleUpdateEmailNotifications called with:', settings);
    
    setEmailNotificationSettings(settings);

    // Save to backend
    try {
      const response = await fetch(`https://${projectId}.supabase.co/functions/v1/make-server-af5db803/email-notifications`, {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${publicAnonKey}`,
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ emailNotificationSettings: settings }),
      });
      const result = await response.json();
      console.log('Backend save response for email notifications:', result);
    } catch (err) {
      console.error('Failed to save email notifications to backend:', err);
      throw err;
    }
  };

  const handleSendFollowUpEmails = async () => {
    try {
      const response = await fetch(`https://${projectId}.supabase.co/functions/v1/make-server-af5db803/send-follow-up-emails`, {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${publicAnonKey}`,
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          tickets: tickets.map(t => ({
            ...t,
            createdAt: t.createdAt.toISOString(),
          })),
          users: users,
        }),
      });

      const result = await response.json();
      
      if (!response.ok) {
        console.error('Error checking follow-up emails:', result);
        return;
      }

      // Handle API key issues silently
      if (result.message === 'API key not configured') {
        console.log('ℹ️ Follow-up check: RESEND_API_KEY not configured. Add it in Supabase to enable automatic emails.');
        return;
      }
      
      if (result.message === 'API key is invalid') {
        console.log('ℹ️ Follow-up check: RESEND_API_KEY is invalid. Update it in Supabase to enable automatic emails.');
        return;
      }

      // Update tickets with the follow-up flags for emails that were sent
      if (result.updatedTickets && result.updatedTickets.length > 0) {
        setTickets(tickets.map(ticket => {
          const update = result.updatedTickets.find((u: any) => u.id === ticket.id);
          if (update) {
            return { ...ticket, ...update };
          }
          return ticket;
        }));
      }

      // Log successful sends
      if (result.emailsSent > 0) {
        console.log(`✓ Automatically sent ${result.emailsSent} follow-up email(s)`);
      }
    } catch (error) {
      console.error('Error in automatic follow-up email check:', error);
    }
  };

  // Automatically check and send follow-up emails
  useEffect(() => {
    if (!currentUser) return;

    // Run immediately on mount
    handleSendFollowUpEmails();

    // Then check every 24 hours
    const interval = setInterval(() => {
      handleSendFollowUpEmails();
    }, 24 * 60 * 60 * 1000); // 24 hours

    return () => clearInterval(interval);
  }, [currentUser, tickets, users]);

  if (!currentUser) {
    if (userNeedsPasswordReset) {
      return (
        <ForcePasswordResetModal
          userId={userNeedsPasswordReset.id}
          userEmail={userNeedsPasswordReset.email}
          onComplete={(newPassword) => {
            // Update user with new password and clear reset flag
            const updatedUser = { 
              ...userNeedsPasswordReset, 
              password: newPassword,
              requirePasswordReset: false, 
              temporaryPassword: undefined 
            };
            setUserNeedsPasswordReset(null);
            setCurrentUser(updatedUser);
            // Update the users list
            setUsers(users.map(u => u.id === updatedUser.id ? updatedUser : u));
          }}
        />
      );
    }
    return (
      <div>
        {backendError && (
          <div style={{ 
            background: '#fee2e2', 
            border: '1px solid #ef4444', 
            padding: '12px 16px', 
            margin: '0',
            color: '#991b1b',
            fontSize: '14px',
            fontWeight: '500',
            display: 'flex',
            alignItems: 'center',
            gap: '8px'
          }}>
            <span style={{ fontSize: '18px' }}>⚠️</span>
            <div>
              <strong>Backend Connection Error:</strong> {backendError}
              <div style={{ fontSize: '12px', marginTop: '4px', opacity: 0.8 }}>
                The app is running in offline mode. Please deploy the Supabase Edge Function.
              </div>
            </div>
          </div>
        )}
        <Login onLogin={handleLogin} onPasswordResetRequired={(user) => setUserNeedsPasswordReset(user)} users={users} />
      </div>
    );
  }

  return (
    <div>
      {backendError && (
        <div style={{ 
          background: '#fee2e2', 
          border: '1px solid #ef4444', 
          padding: '12px 16px', 
          margin: '0',
          color: '#991b1b',
          fontSize: '14px',
          fontWeight: '500',
          display: 'flex',
          alignItems: 'center',
          gap: '8px'
        }}>
          <span style={{ fontSize: '18px' }}>⚠️</span>
          <div>
            <strong>Backend Connection Error:</strong> {backendError}
            <div style={{ fontSize: '12px', marginTop: '4px', opacity: 0.8 }}>
              The app is running in offline mode. Some features may not work correctly.
            </div>
          </div>
        </div>
      )}
      <Dashboard
        currentUser={currentUser}
        tickets={tickets}
        users={users}
        tags={tags}
        defaultApprovers={defaultApprovers}
        emailNotificationSettings={emailNotificationSettings}
        onLogout={handleLogout}
        onCreateTicket={handleCreateTicket}
        onApprove={handleApprove}
        onReject={handleReject}
        onUpdateTicket={handleUpdateTicket}
        onRequestReapproval={handleRequestReapproval}
        onCreateUser={handleCreateUser}
        onUpdateUser={handleUpdateUser}
        onDeleteUser={handleDeleteUser}
        onCreateTag={handleCreateTag}
        onUpdateTag={handleUpdateTag}
        onDeleteTag={handleDeleteTag}
        onUpdateDefaultApprovers={handleUpdateDefaultApprovers}
        onUpdateAllDefaultApprovers={handleUpdateAllDefaultApprovers}
        onUpdateEmailNotifications={handleUpdateEmailNotifications}
        onArchiveTicket={handleArchiveTicket}
        onUnarchiveTicket={handleUnarchiveTicket}
        onCreateRole={handleCreateRole}
        onUpdateRole={handleUpdateRole}
        onDeleteRole={handleDeleteRole}
        customRoles={customRoles}
        customTicketTypes={customTicketTypes}
        onCreateTicketType={handleCreateTicketType}
        onUpdateTicketType={handleUpdateTicketType}
        onDeleteTicketType={handleDeleteTicketType}
        customDepartments={customDepartments}
        onCreateDepartment={handleCreateDepartment}
        onUpdateDepartment={handleUpdateDepartment}
        onDeleteDepartment={handleDeleteDepartment}
      />
    </div>
  );
}