const { useState, useEffect } = React;

// Defensive normalization helper
function normalizeToArray(x) {
    console.log('[normalizeToArray] Input:', typeof x, x);
    if (!x) return [];
    if (Array.isArray(x)) return x;
    if (typeof x === 'object') {
        if (Array.isArray(x.data)) return x.data;
        if (Array.isArray(x.assignments)) return x.assignments;
        return [x];
    }
    return [];
}

// STEP 4: Error Boundary Component
class ErrorBoundary extends React.Component {
    constructor(props) {
        super(props);
        this.state = { hasError: false, error: null, errorInfo: null };
    }
    
    static getDerivedStateFromError(error) {
        return { hasError: true };
    }
    
    componentDidCatch(error, errorInfo) {
        console.error('[ErrorBoundary] Caught error:', error, errorInfo);
        this.setState({ error, errorInfo });
    }
    
    render() {
        if (this.state.hasError) {
            return (
                <div style={{ padding: '40px', textAlign: 'center', background: '#fff' }}>
                    <div style={{ fontSize: '48px', marginBottom: '20px' }}>⚠️</div>
                    <h2>Something went wrong</h2>
                    <p style={{ color: '#e74c3c', marginBottom: '20px' }}>
                        The application encountered an unexpected error.
                    </p>
                    <button 
                        className="iwm-btn iwm-btn-primary" 
                        onClick={() => window.location.reload()}
                    >
                        🔄 Reload Page
                    </button>
                    <details style={{ marginTop: '30px', textAlign: 'left', maxWidth: '800px', margin: '30px auto' }}>
                        <summary style={{ cursor: 'pointer', color: '#7f8c8d', marginBottom: '10px' }}>
                            Show Technical Details
                        </summary>
                        <div style={{ background: '#f5f5f5', padding: '20px', borderRadius: '8px', overflow: 'auto' }}>
                            <h4>Error:</h4>
                            <pre style={{ fontSize: '12px', whiteSpace: 'pre-wrap' }}>
                                {this.state.error && this.state.error.toString()}
                            </pre>
                            <h4>Stack Trace:</h4>
                            <pre style={{ fontSize: '11px', whiteSpace: 'pre-wrap', color: '#666' }}>
                                {this.state.errorInfo && this.state.errorInfo.componentStack}
                            </pre>
                        </div>
                    </details>
                </div>
            );
        }
        
        return this.props.children;
    }
}

// Toast Notification Component
function Toast({ message, type = 'success', onClose }) {
    useEffect(() => {
        const timer = setTimeout(onClose, 3000);
        return () => clearTimeout(timer);
    }, [onClose]);
    
    const styles = {
        position: 'fixed',
        top: '20px',
        right: '20px',
        padding: '15px 25px',
        borderRadius: '8px',
        boxShadow: '0 4px 12px rgba(0,0,0,0.15)',
        zIndex: 10000,
        display: 'flex',
        alignItems: 'center',
        gap: '10px',
        animation: 'slideIn 0.3s ease-out',
        background: type === 'success' ? '#27ae60' : type === 'error' ? '#e74c3c' : '#3498db',
        color: 'white',
        fontWeight: '500',
    };
    
    return (
        <div style={styles}>
            <span>{type === 'success' ? '✅' : type === 'error' ? '❌' : 'ℹ️'}</span>
            <span>{message}</span>
            <button 
                onClick={onClose}
                style={{ 
                    background: 'transparent', 
                    border: 'none', 
                    color: 'white', 
                    cursor: 'pointer',
                    fontSize: '18px',
                    padding: '0 0 0 10px'
                }}
            >
                ×
            </button>
        </div>
    );
}

// API Helper with enhanced error handling and logging
const api = {
    baseUrl: IWM_DATA.apiUrl,
    nonce: IWM_DATA.nonce,
    
    async fetch(endpoint, options = {}) {
        const url = `${this.baseUrl}${endpoint}`;
        const headers = {
            'Content-Type': 'application/json',
            'X-WP-Nonce': this.nonce,
            ...options.headers,
        };
        
        console.log(`[IWM API] ${options.method || 'GET'} ${endpoint}`, {
            url,
            headers: { ...headers, 'X-WP-Nonce': '***' },
            body: options.body ? JSON.parse(options.body) : undefined
        });
        
        try {
            const response = await fetch(url, { ...options, headers });
            const data = await response.json();
            
            console.log(`[IWM API] Response ${response.status}:`, data);
            
            // Handle all HTTP status codes properly
            if (response.status >= 200 && response.status < 300) {
                // Success (2xx)
                return { success: true, data, status: response.status };
            } else if (response.status >= 400 && response.status < 500) {
                // Client error (4xx)
                console.error(`[IWM API] Client Error ${response.status}:`, data);
                return { 
                    success: false, 
                    error: data.message || `Client error: ${response.status}`, 
                    status: response.status,
                    data 
                };
            } else if (response.status >= 500) {
                // Server error (5xx)
                console.error(`[IWM API] Server Error ${response.status}:`, data);
                return { 
                    success: false, 
                    error: data.message || `Server error: ${response.status}`, 
                    status: response.status,
                    data 
                };
            }
            
            return { success: true, data, status: response.status };
        } catch (error) {
            console.error('[IWM API] Network Error:', error);
            return { 
                success: false, 
                error: error.message || 'Network error occurred',
                status: 0
            };
        }
    },
    
    async get(endpoint) {
        return this.fetch(endpoint);
    },
    
    async post(endpoint, data) {
        return this.fetch(endpoint, {
            method: 'POST',
            body: JSON.stringify(data),
        });
    },
    
    async put(endpoint, data) {
        return this.fetch(endpoint, {
            method: 'PUT',
            body: JSON.stringify(data),
        });
    },
    
    async delete(endpoint) {
        return this.fetch(endpoint, { method: 'DELETE' });
    },
};

// Modal Component
function Modal({ isOpen, onClose, title, children, footer }) {
    if (!isOpen) return null;
    
    return (
        <div className="iwm-modal-overlay" onClick={onClose}>
            <div className="iwm-modal" onClick={(e) => e.stopPropagation()}>
                <div className="iwm-modal-header">
                    <h2 className="iwm-modal-title">{title}</h2>
                    <button className="iwm-modal-close" onClick={onClose}>×</button>
                </div>
                <div className="iwm-modal-body">
                    {children}
                </div>
                {footer && (
                    <div className="iwm-modal-footer">
                        {footer}
                    </div>
                )}
            </div>
        </div>
    );
}

// Dashboard Component
function Dashboard() {
    const [stats, setStats] = useState(null);
    const [loading, setLoading] = useState(true);
    const [toast, setToast] = useState(null);
    
    useEffect(() => {
        loadStats();
    }, []);
    
    const loadStats = async () => {
        console.log('[Dashboard] Loading stats...');
        try {
            const result = await api.get('/dashboard/stats');
            if (result.success) {
                console.log('[Dashboard] Stats loaded:', result.data);
                setStats(result.data);
            } else {
                console.error('[Dashboard] Failed to load stats:', result.error);
                setToast({ type: 'error', message: result.error || 'Failed to load statistics' });
            }
        } catch (error) {
            console.error('[Dashboard] Error loading stats:', error);
            setToast({ type: 'error', message: 'Network error loading statistics' });
        } finally {
            setLoading(false);
        }
    };
    
    if (loading) {
        return (
            <div className="iwm-loading">
                <div className="iwm-spinner"></div>
                <p>Loading dashboard...</p>
            </div>
        );
    }
    
    return (
        <>
            <div className="iwm-stats-grid">
                <div className="iwm-stat-card">
                    <div className="iwm-stat-icon primary">📋</div>
                    <div className="iwm-stat-content">
                        <h3>{stats?.total_assignments || 0}</h3>
                        <p>Total Assignments</p>
                    </div>
                </div>
                
                <div className="iwm-stat-card">
                    <div className="iwm-stat-icon warning">📋</div>
                    <div className="iwm-stat-content">
                        <h3>{stats?.assigned_tasks || 0}</h3>
                        <p>Assigned Tasks</p>
                    </div>
                </div>
                
                <div className="iwm-stat-card">
                    <div className="iwm-stat-icon danger">⏰</div>
                    <div className="iwm-stat-content">
                        <h3>{stats?.pending_tasks || 0}</h3>
                        <p>Pending Tasks</p>
                    </div>
                </div>
                
                <div className="iwm-stat-card">
                    <div className="iwm-stat-icon success">✅</div>
                    <div className="iwm-stat-content">
                        <h3>{stats?.completed_today || 0}</h3>
                        <p>Completed Today</p>
                    </div>
                </div>
            </div>
            
            {toast && (
                <Toast
                    message={toast.message}
                    type={toast.type}
                    onClose={() => setToast(null)}
                />
            )}
        </>
    );
}

// Projects Component
function Projects() {
    const [projects, setProjects] = useState([]);
    const [loading, setLoading] = useState(true);
    const [showModal, setShowModal] = useState(false);
    const [selectedProject, setSelectedProject] = useState(null);
    const [toast, setToast] = useState(null);
    
    useEffect(() => {
        loadProjects();
    }, []);
    
    const loadProjects = async () => {
        console.log('[Projects] Loading projects list...');
        try {
            const result = await api.get('/projects');
            if (result.success) {
                console.log('[Projects] Loaded projects:', result.data);
                setProjects(result.data);
            } else {
                console.error('[Projects] Failed to load projects:', result.error);
                setToast({ type: 'error', message: result.error || 'Failed to load projects' });
            }
        } catch (error) {
            console.error('[Projects] Error loading projects:', error);
            setToast({ type: 'error', message: 'Network error loading projects' });
        } finally {
            setLoading(false);
        }
    };
    
    const createProject = () => {
        setSelectedProject(null);
        setShowModal(true);
    };
    
    // Handler for successful project save - OPTION A: Update state directly
    const handleProjectSaved = (savedProject, isNew) => {
        console.log('[Projects] Project saved:', savedProject, 'isNew:', isNew);
        
        if (isNew) {
            // OPTION A (Preferred): Prepend new project to state
            setProjects(prevProjects => [savedProject, ...prevProjects]);
            console.log('[Projects] New project added to state');
            setToast({ type: 'success', message: '✅ Project created successfully!' });
        } else {
            // Update existing project in state
            setProjects(prevProjects => 
                prevProjects.map(p => p.id === savedProject.id ? savedProject : p)
            );
            console.log('[Projects] Project updated in state');
            setToast({ type: 'success', message: '✅ Project updated successfully!' });
        }
        
        setShowModal(false);
    };
    
    // Fallback handler if state update fails
    const handleProjectSaveFallback = async () => {
        console.log('[Projects] Using fallback: re-fetching projects');
        setShowModal(false);
        await loadProjects();
        setToast({ type: 'success', message: '✅ Project saved successfully!' });
    };
    
    if (loading) {
        return (
            <div className="iwm-loading">
                <div className="iwm-spinner"></div>
                <p>Loading projects...</p>
            </div>
        );
    }
    
    return (
        <div>
            <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '20px' }}>
                <h2>My Projects</h2>
                <button className="iwm-btn iwm-btn-primary" onClick={createProject}>
                    + New Project
                </button>
            </div>
            
            {projects.length === 0 ? (
                <div style={{ textAlign: 'center', padding: '60px', color: '#7f8c8d' }}>
                    <div style={{ fontSize: '48px', marginBottom: '20px' }}>📁</div>
                    <h3>No projects yet</h3>
                    <p>Create your first project to get started</p>
                    <button className="iwm-btn iwm-btn-primary" onClick={createProject} style={{ marginTop: '20px' }}>
                        Create Project
                    </button>
                </div>
            ) : (
                <div className="iwm-projects-grid">
                    {projects.map(project => (
                        <ProjectCard 
                            key={project.id} 
                            project={project} 
                            onSelect={setSelectedProject}
                        />
                    ))}
                </div>
            )}
            
            {showModal && (
                <ProjectModal
                    project={selectedProject}
                    onClose={() => setShowModal(false)}
                    onSave={handleProjectSaved}
                    onSaveFallback={handleProjectSaveFallback}
                />
            )}
            
            {toast && (
                <Toast
                    message={toast.message}
                    type={toast.type}
                    onClose={() => setToast(null)}
                />
            )}
        </div>
    );
}

// Project Card Component
function ProjectCard({ project, onSelect }) {
    return (
        <div className="iwm-project-card" onClick={() => onSelect(project)}>
            <div className="iwm-project-header">
                <h3 className="iwm-project-title">{project.title}</h3>
                <span className={`iwm-project-status ${project.status}`}>
                    {project.status}
                </span>
            </div>
            <p className="iwm-project-description">{project.description || 'No description'}</p>
            <div className="iwm-project-footer">
                <div className="iwm-project-meta">
                    {project.start_date && `Started: ${new Date(project.start_date).toLocaleDateString()}`}
                </div>
                <div>
                    {project.budget && `Budget: $${parseFloat(project.budget).toFixed(2)}`}
                </div>
            </div>
        </div>
    );
}

// Project Modal Component
function ProjectModal({ project, onClose, onSave, onSaveFallback }) {
    const [formData, setFormData] = useState({
        title: project?.title || '',
        description: project?.description || '',
        start_date: project?.start_date || '',
        end_date: project?.end_date || '',
        budget: project?.budget || '',
    });
    const [saving, setSaving] = useState(false);
    const [error, setError] = useState(null);
    
    const handleChange = (e) => {
        setFormData({ ...formData, [e.target.name]: e.target.value });
        setError(null); // Clear error on input change
    };
    
    const handleSubmit = async (e) => {
        e.preventDefault();
        
        // Validation
        if (!formData.title.trim()) {
            setError('Project title is required');
            return;
        }
        
        setSaving(true);
        setError(null);
        console.log('[ProjectModal] Submitting project:', formData);
        
        try {
            let result;
            const isNew = !project;
            
            if (project) {
                console.log('[ProjectModal] Updating project ID:', project.id);
                result = await api.put(`/projects/${project.id}`, formData);
            } else {
                console.log('[ProjectModal] Creating new project');
                result = await api.post('/projects', formData);
            }
            
            console.log('[ProjectModal] API Result:', result);
            
            if (result.success) {
                // Extract the created/updated project from response
                const savedProject = result.data;
                
                console.log('[ProjectModal] Success! Saved project:', savedProject);
                
                // OPTION A (Preferred): Call onSave with the saved project data
                if (savedProject && savedProject.id) {
                    onSave(savedProject, isNew);
                } else {
                    // OPTION B (Fallback): If response doesn't include project data, re-fetch
                    console.warn('[ProjectModal] No project data in response, using fallback');
                    onSaveFallback();
                }
            } else {
                // Handle API errors (4xx, 5xx)
                console.error('[ProjectModal] API Error:', result.error);
                setError(result.error || 'Failed to save project. Please try again.');
                
                // Show detailed error for debugging
                if (result.status === 403) {
                    setError('Permission denied. You may not have access to create/edit projects.');
                } else if (result.status === 401) {
                    setError('Authentication failed. Please refresh the page and try again.');
                } else if (result.status >= 500) {
                    setError('Server error occurred. Please try again later.');
                }
            }
        } catch (error) {
            // Handle unexpected errors
            console.error('[ProjectModal] Unexpected error:', error);
            setError('An unexpected error occurred. Please check console for details.');
            
            // Last resort fallback: reload page
            if (window.confirm('An error occurred. Would you like to reload the page?')) {
                window.location.reload();
            }
        } finally {
            setSaving(false);
        }
    };
    
    return (
        <Modal
            isOpen={true}
            onClose={onClose}
            title={project ? 'Edit Project' : 'New Project'}
            footer={
                <>
                    <button className="iwm-btn iwm-btn-outline" onClick={onClose}>
                        Cancel
                    </button>
                    <button 
                        className="iwm-btn iwm-btn-primary" 
                        onClick={handleSubmit}
                        disabled={saving}
                    >
                        {saving ? 'Saving...' : 'Save Project'}
                    </button>
                </>
            }
        >
            <form onSubmit={handleSubmit}>
                {error && (
                    <div style={{
                        padding: '12px',
                        background: '#fee',
                        border: '1px solid #fcc',
                        borderRadius: '6px',
                        color: '#c33',
                        marginBottom: '15px',
                        fontSize: '14px'
                    }}>
                        ❌ {error}
                    </div>
                )}
                
                <div className="iwm-form-group">
                    <label className="iwm-form-label">Project Title *</label>
                    <input
                        type="text"
                        name="title"
                        className="iwm-form-input"
                        value={formData.title}
                        onChange={handleChange}
                        required
                        disabled={saving}
                    />
                </div>
                
                <div className="iwm-form-group">
                    <label className="iwm-form-label">Description</label>
                    <textarea
                        name="description"
                        className="iwm-form-textarea"
                        value={formData.description}
                        onChange={handleChange}
                    />
                </div>
                
                <div className="iwm-form-group">
                    <label className="iwm-form-label">Start Date</label>
                    <input
                        type="date"
                        name="start_date"
                        className="iwm-form-input"
                        value={formData.start_date}
                        onChange={handleChange}
                    />
                </div>
                
                <div className="iwm-form-group">
                    <label className="iwm-form-label">End Date</label>
                    <input
                        type="date"
                        name="end_date"
                        className="iwm-form-input"
                        value={formData.end_date}
                        onChange={handleChange}
                    />
                </div>
                
                <div className="iwm-form-group">
                    <label className="iwm-form-label">Budget</label>
                    <input
                        type="number"
                        name="budget"
                        className="iwm-form-input"
                        value={formData.budget}
                        onChange={handleChange}
                        step="0.01"
                    />
                </div>
            </form>
        </Modal>
    );
}

// Tasks Component
function Tasks() {
    const [projects, setProjects] = useState([]);
    const [selectedProject, setSelectedProject] = useState(null);
    const [tasks, setTasks] = useState([]);
    const [loading, setLoading] = useState(true);
    const [loadingTasks, setLoadingTasks] = useState(false);
    const [showTaskModal, setShowTaskModal] = useState(false);
    const [selectedTask, setSelectedTask] = useState(null);
    const [toast, setToast] = useState(null);
    const [error, setError] = useState(null);
    
    useEffect(() => {
        console.log('[Tasks] Component mounted, loading projects...');
        loadProjects();
    }, []);
    
    useEffect(() => {
        if (selectedProject) {
            console.log('[Tasks] Selected project changed to:', selectedProject);
            loadTasks();
        } else {
            console.log('[Tasks] No project selected, clearing tasks');
            setTasks([]);
        }
    }, [selectedProject]);
    
    const loadProjects = async () => {
        console.log('[Tasks] Loading projects list...');
        setLoading(true);
        setError(null);
        
        try {
            const result = await api.get('/projects');
            console.log('[Tasks] Projects API result:', result);
            
            if (result.success) {
                const projectsData = result.data;
                console.log('[Tasks] Loaded projects:', projectsData, 'Type:', Array.isArray(projectsData) ? 'Array' : typeof projectsData);
                
                // Handle both array and {data: []} response formats
                let projectsList = [];
                if (Array.isArray(projectsData)) {
                    projectsList = projectsData;
                } else if (projectsData && Array.isArray(projectsData.data)) {
                    console.log('[Tasks] Response wrapped in data object, unwrapping...');
                    projectsList = projectsData.data;
                } else if (projectsData && typeof projectsData === 'object') {
                    console.warn('[Tasks] Unexpected response format:', projectsData);
                    projectsList = [];
                }
                
                console.log('[Tasks] Final projects list:', projectsList, 'Length:', projectsList.length);
                setProjects(projectsList);
                
                if (projectsList.length > 0) {
                    console.log('[Tasks] Auto-selecting first project:', projectsList[0]);
                    setSelectedProject(projectsList[0]);
                } else {
                    console.log('[Tasks] No projects available');
                    setSelectedProject(null);
                }
            } else {
                console.error('[Tasks] Failed to load projects:', result.error);
                setError(result.error || 'Failed to load projects');
                setProjects([]);
                setSelectedProject(null);
            }
        } catch (error) {
            console.error('[Tasks] Error loading projects:', error);
            setError('Network error loading projects');
            setProjects([]);
            setSelectedProject(null);
        } finally {
            setLoading(false);
        }
    };
    
    const loadTasks = async () => {
        if (!selectedProject || !selectedProject.id) {
            console.warn('[Tasks] Cannot load tasks: No project selected or invalid project ID');
            setTasks([]);
            return;
        }
        
        console.log('[Tasks] >>> Loading tasks for project ID:', selectedProject.id); // Enhanced logging
        setLoadingTasks(true);
        setError(null);
        
        try {
            // STEP 2: Construct proper API endpoint with project_id parameter
            const endpoint = `/projects/${selectedProject.id}/tasks`;
            const fullUrl = `${api.baseUrl}${endpoint}`;
            console.log('[Tasks] >>> FETCH URL:', fullUrl); // STEP 2: Confirm fetch URL
            console.log('[Tasks] Fetching tasks from:', endpoint);
            
            const result = await api.get(endpoint);
            console.log('[Tasks] >>> RAW API RESPONSE:', result); // STEP 3: Log raw response
            
            if (result.success) {
                const tasksData = result.data;
                console.log('[Tasks] >>> Response data type:', typeof tasksData, 'isArray:', Array.isArray(tasksData));
                console.log('[Tasks] >>> Response data:', tasksData);
                
                // STEP 3 & 4: Handle multiple response formats with validation
                let tasksList = [];
                
                if (Array.isArray(tasksData)) {
                    // Direct array response
                    tasksList = tasksData;
                    console.log('[Tasks] >>> Direct array response, length:', tasksList.length);
                } else if (tasksData && typeof tasksData === 'object' && tasksData.data) {
                    // Wrapped in data property
                    if (Array.isArray(tasksData.data)) {
                        tasksList = tasksData.data;
                        console.log('[Tasks] >>> Unwrapped from data property, length:', tasksList.length);
                    } else {
                        console.warn('[Tasks] >>> tasksData.data is not an array:', tasksData.data);
                    }
                } else if (tasksData && typeof tasksData === 'object') {
                    // Object but not wrapped - might be single object, convert to array
                    console.warn('[Tasks] >>> Unexpected object format, attempting conversion:', tasksData);
                    // Check if it's a single task object with id
                    if (tasksData.id) {
                        tasksList = [tasksData];
                    } else {
                        tasksList = [];
                    }
                } else {
                    console.warn('[Tasks] >>> Invalid tasks data type:', typeof tasksData, tasksData);
                    tasksList = [];
                }
                
                // STEP 4: Validate it's an array before setState
                if (!Array.isArray(tasksList)) {
                    console.error('[Tasks] >>> tasksList is not an array after parsing! Type:', typeof tasksList);
                    tasksList = [];
                }
                
                console.log('[Tasks] >>> Final tasks list (validated array):', tasksList, 'Length:', tasksList.length);
                console.log('[Tasks] >>> Calling setTasks with:', tasksList);
                
                // STEP 4: Force state update
                setTasks(tasksList);
                
                // Verify state update in next tick
                setTimeout(() => {
                    console.log('[Tasks] >>> State verification - tasks should be updated now');
                }, 0);
                
                if (tasksList.length === 0) {
                    console.log('[Tasks] >>> ⚠️ No tasks found for project:', selectedProject.title);
                    console.log('[Tasks] >>> This could be legitimate (no tasks) or a filtering issue');
                }
            } else {
                // STEP 5: Error handling
                console.error('[Tasks] >>> API returned success=false:', result.error);
                setError(result.error || 'Failed to load tasks');
                setTasks([]);
            }
        } catch (error) {
            // STEP 5: Error handling
            console.error('[Tasks] >>> Exception while loading tasks:', error);
            console.error('[Tasks] >>> Error stack:', error.stack);
            setError('Network error loading tasks');
            setTasks([]);
        } finally {
            setLoadingTasks(false);
            console.log('[Tasks] >>> loadTasks complete, loadingTasks set to false');
        }
    };
    
    // Handler for task save with state update
    const handleTaskSaved = (savedTask, isNew) => {
        console.log('[Tasks] Task saved:', savedTask, 'isNew:', isNew);
        
        if (isNew) {
            // Prepend new task
            setTasks(prevTasks => [savedTask, ...prevTasks]);
            console.log('[Tasks] New task added to state');
            setToast({ type: 'success', message: '✅ Task created successfully!' });
        } else {
            // Update existing task
            setTasks(prevTasks => 
                prevTasks.map(t => t.id === savedTask.id ? savedTask : t)
            );
            console.log('[Tasks] Task updated in state');
            setToast({ type: 'success', message: '✅ Task updated successfully!' });
        }
        
        setShowTaskModal(false);
    };
    
    // Fallback handler
    const handleTaskSaveFallback = async () => {
        console.log('[Tasks] Using fallback: re-fetching tasks');
        setShowTaskModal(false);
        await loadTasks();
        setToast({ type: 'success', message: '✅ Task saved successfully!' });
    };
    
    // Handle project selection change
    const handleProjectChange = (e) => {
        const projectId = parseInt(e.target.value);
        console.log('[Tasks] >>> projectClick', projectId); // STEP 1: Log project click
        console.log('[Tasks] Project dropdown changed to ID:', projectId);
        
        const project = projects.find(p => p.id === projectId);
        console.log('[Tasks] Found project:', project);
        
        if (project) {
            setSelectedProject(project);
            // Clear tasks immediately while loading
            setTasks([]);
        } else {
            console.warn('[Tasks] Project not found for ID:', projectId);
        }
    };
    
    if (loading) {
        return (
            <div className="iwm-loading">
                <div className="iwm-spinner"></div>
                <p>Loading tasks...</p>
            </div>
        );
    }
    
    if (error && projects.length === 0) {
        return (
            <div style={{ textAlign: 'center', padding: '60px', color: '#e74c3c' }}>
                <div style={{ fontSize: '48px', marginBottom: '20px' }}>⚠️</div>
                <h3>Error Loading Projects</h3>
                <p>{error}</p>
                <button 
                    className="iwm-btn iwm-btn-primary" 
                    onClick={loadProjects}
                    style={{ marginTop: '20px' }}
                >
                    Retry
                </button>
            </div>
        );
    }
    
    if (projects.length === 0) {
        return (
            <div style={{ textAlign: 'center', padding: '60px', color: '#7f8c8d' }}>
                <div style={{ fontSize: '48px', marginBottom: '20px' }}>📋</div>
                <h3>No projects available</h3>
                <p>Create a project first to manage tasks</p>
            </div>
        );
    }
    
    console.log('[Tasks] >>> RENDER - Projects:', projects.length, 'Selected:', selectedProject?.title, 'Tasks:', tasks, 'Tasks.length:', tasks?.length, 'Array.isArray(tasks):', Array.isArray(tasks));
    
    return (
        <div>
            <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '20px', alignItems: 'center' }}>
                <div style={{ display: 'flex', gap: '15px', alignItems: 'center' }}>
                    <h2>Tasks</h2>
                    <select 
                        className="iwm-form-select" 
                        style={{ width: 'auto' }}
                        value={selectedProject?.id || ''}
                        onChange={handleProjectChange}
                        disabled={loadingTasks}
                    >
                        {projects.map(project => (
                            <option key={project.id} value={project.id}>
                                {project.title}
                            </option>
                        ))}
                    </select>
                    {loadingTasks && (
                        <span style={{ color: '#7f8c8d', fontSize: '14px' }}>⏳ Loading tasks...</span>
                    )}
                </div>
                <button 
                    className="iwm-btn iwm-btn-primary" 
                    onClick={() => {
                        setSelectedTask(null);
                        setShowTaskModal(true);
                    }}
                    disabled={!selectedProject || loadingTasks}
                >
                    + New Task
                </button>
            </div>
            
            {error && (
                <div style={{
                    padding: '12px',
                    background: '#fee',
                    border: '1px solid #fcc',
                    borderRadius: '6px',
                    color: '#c33',
                    marginBottom: '15px',
                    fontSize: '14px'
                }}>
                    ⚠️ {error}
                </div>
            )}
            
            {/* STEP 5: Loading state */}
            <div className="iwm-task-list">
                {loadingTasks ? (
                    <div className="iwm-loading" style={{ padding: '40px' }}>
                        <div className="iwm-spinner" style={{ margin: '0 auto' }}></div>
                        <p style={{ textAlign: 'center', color: '#7f8c8d' }}>Loading tasks...</p>
                    </div>
                ) : Array.isArray(tasks) && tasks.length > 0 ? (
                    <>
                        {console.log('[Tasks] >>> Rendering', tasks.length, 'task items')}
                        {tasks.map((task, index) => {
                            console.log('[Tasks] >>> Rendering task', index, ':', task.id, task.title);
                            return (
                                <TaskItem 
                                    key={task.id} 
                                    task={task} 
                                    onSelect={() => setSelectedTask(task)}
                                    onUpdate={loadTasks}
                                />
                            );
                        })}
                    </>
                ) : (
                    /* STEP 5: Empty state */
                    <div style={{ textAlign: 'center', padding: '40px', color: '#7f8c8d' }}>
                        <div style={{ fontSize: '36px', marginBottom: '10px' }}>📝</div>
                        <p>No tasks yet for "{selectedProject?.title}"</p>
                        <p style={{ fontSize: '14px', marginTop: '10px', color: '#95a5a6' }}>
                            Tasks in database: {Array.isArray(tasks) ? tasks.length : 'N/A (not an array)'}
                        </p>
                        <p style={{ fontSize: '12px', marginTop: '5px', color: '#95a5a6' }}>
                            Check console for detailed debugging info
                        </p>
                        <button 
                            className="iwm-btn iwm-btn-primary" 
                            onClick={() => {
                                setSelectedTask(null);
                                setShowTaskModal(true);
                            }}
                            style={{ marginTop: '15px' }}
                        >
                            Create First Task
                        </button>
                    </div>
                )}
            </div>
            
            {showTaskModal && (
                <TaskModal
                    task={selectedTask}
                    projectId={selectedProject?.id}
                    onClose={() => setShowTaskModal(false)}
                    onSave={handleTaskSaved}
                    onSaveFallback={handleTaskSaveFallback}
                />
            )}
            
            {toast && (
                <Toast
                    message={toast.message}
                    type={toast.type}
                    onClose={() => setToast(null)}
                />
            )}
        </div>
    );
}

// Task Item Component
function TaskItem({ task, onSelect, onUpdate }) {
    const [quickReplies, setQuickReplies] = useState([]);
    const [showUpdates, setShowUpdates] = useState(false);
    
    useEffect(() => {
        loadQuickReplies();
    }, []);
    
    const loadQuickReplies = async () => {
        console.log('[TaskItem] Loading quick replies...');
        try {
            const result = await api.get('/quick-replies');
            if (result.success) {
                const repliesData = Array.isArray(result.data) ? result.data : [];
                console.log('[TaskItem] Loaded quick replies:', repliesData);
                setQuickReplies(repliesData);
            } else {
                console.error('[TaskItem] Failed to load quick replies:', result.error);
            }
        } catch (error) {
            console.error('[TaskItem] Error loading quick replies:', error);
        }
    };
    
    const handleQuickReply = async (reply) => {
        console.log('[TaskItem] Sending quick reply:', reply, 'for task:', task.id);
        try {
            const result = await api.post(`/tasks/${task.id}/updates`, {
                update_type: 'quick_reply',
                quick_reply_id: reply.id,
                message: reply.label,
                new_status: reply.status,
            });
            
            if (result.success) {
                console.log('[TaskItem] Quick reply sent successfully');
                onUpdate();
                alert(`✅ ${reply.emoji} ${reply.label} - Update sent!`);
            } else {
                console.error('[TaskItem] Quick reply failed:', result.error);
                alert('Error sending update: ' + (result.error || 'Unknown error'));
            }
        } catch (error) {
            console.error('[TaskItem] Error sending quick reply:', error);
            alert('Error sending update');
        }
    };
    
    const statusColors = {
        pending: '#95a5a6',
        in_progress: '#3498db',
        review: '#9b59b6',
        delayed: '#e74c3c',
        blocked: '#e67e22',
        completed: '#27ae60',
    };
    
    return (
        <div className="iwm-task-item">
            <div className="iwm-task-header">
                <h3 className="iwm-task-title">{task.title}</h3>
                <span className={`iwm-task-priority ${task.priority}`}>
                    {task.priority}
                </span>
            </div>
            
            <p style={{ color: '#7f8c8d', fontSize: '14px', margin: '10px 0' }}>
                {task.description}
            </p>
            
            <div className="iwm-task-meta">
                <span style={{ 
                    background: statusColors[task.status] + '20',
                    color: statusColors[task.status],
                    padding: '4px 10px',
                    borderRadius: '10px',
                    fontSize: '12px',
                    fontWeight: '600'
                }}>
                    {task.status.replace('_', ' ').toUpperCase()}
                </span>
                {task.due_date && (
                    <span>📅 Due: {new Date(task.due_date).toLocaleDateString()}</span>
                )}
                {task.estimated_hours && (
                    <span>⏱️ Est: {task.estimated_hours}h</span>
                )}
            </div>
            
            {task.status !== 'completed' && (
                <div className="iwm-quick-replies">
                    {quickReplies.map(reply => (
                        <button
                            key={reply.id}
                            className="iwm-quick-reply-btn"
                            onClick={() => handleQuickReply(reply)}
                        >
                            <span>{reply.emoji}</span>
                            <span>{reply.label}</span>
                        </button>
                    ))}
                </div>
            )}
            
            <div className="iwm-task-actions">
                <button 
                    className="iwm-btn iwm-btn-outline" 
                    onClick={() => setShowUpdates(!showUpdates)}
                    style={{ fontSize: '13px', padding: '6px 14px' }}
                >
                    {showUpdates ? 'Hide Updates' : 'View Updates'}
                </button>
            </div>
            
            {showUpdates && <TaskUpdates taskId={task.id} />}
        </div>
    );
}

// Task Updates Component
function TaskUpdates({ taskId }) {
    const [updates, setUpdates] = useState([]);
    const [loading, setLoading] = useState(true);
    const [newComment, setNewComment] = useState('');
    
    useEffect(() => {
        loadUpdates();
    }, [taskId]);
    
    const loadUpdates = async () => {
        try {
            const data = await api.get(`/tasks/${taskId}/updates`);
            setUpdates(data);
        } catch (error) {
            console.error('Error loading updates:', error);
        } finally {
            setLoading(false);
        }
    };
    
    const handleAddComment = async (e) => {
        e.preventDefault();
        if (!newComment.trim()) return;
        
        try {
            await api.post(`/tasks/${taskId}/updates`, {
                update_type: 'comment',
                message: newComment,
            });
            setNewComment('');
            loadUpdates();
        } catch (error) {
            console.error('Error adding comment:', error);
        }
    };
    
    if (loading) {
        return <div className="iwm-loading"><div className="iwm-spinner"></div></div>;
    }
    
    return (
        <div style={{ marginTop: '20px', padding: '20px', background: '#f8f9fa', borderRadius: '8px' }}>
            <h4 style={{ marginTop: 0 }}>Activity Timeline</h4>
            
            <form onSubmit={handleAddComment} style={{ marginBottom: '20px' }}>
                <textarea
                    className="iwm-form-textarea"
                    placeholder="Add a comment..."
                    value={newComment}
                    onChange={(e) => setNewComment(e.target.value)}
                    style={{ minHeight: '60px' }}
                />
                <button 
                    type="submit" 
                    className="iwm-btn iwm-btn-primary" 
                    style={{ marginTop: '10px', fontSize: '13px', padding: '8px 16px' }}
                >
                    Post Comment
                </button>
            </form>
            
            {updates.length === 0 ? (
                <p style={{ color: '#7f8c8d', textAlign: 'center' }}>No updates yet</p>
            ) : (
                <div className="iwm-timeline">
                    {updates.map(update => (
                        <div key={update.id} className="iwm-timeline-item">
                            <div className="iwm-timeline-content">
                                <div className="iwm-timeline-header">
                                    <span className="iwm-timeline-user">{update.user_name}</span>
                                    <span className="iwm-timeline-time">
                                        {new Date(update.created_at).toLocaleString()}
                                    </span>
                                </div>
                                <div>{update.message}</div>
                                {update.new_status && (
                                    <div style={{ marginTop: '8px' }}>
                                        <span style={{ 
                                            background: '#3498db', 
                                            color: 'white', 
                                            padding: '3px 8px', 
                                            borderRadius: '3px', 
                                            fontSize: '11px' 
                                        }}>
                                            {update.new_status.replace('_', ' ').toUpperCase()}
                                        </span>
                                    </div>
                                )}
                            </div>
                        </div>
                    ))}
                </div>
            )}
        </div>
    );
}

// Task Modal Component
function TaskModal({ task, projectId, onClose, onSave, onSaveFallback }) {
    const [formData, setFormData] = useState({
        title: task?.title || '',
        description: task?.description || '',
        priority: task?.priority || 'medium',
        due_date: task?.due_date || '',
        estimated_hours: task?.estimated_hours || '',
    });
    const [saving, setSaving] = useState(false);
    const [error, setError] = useState(null);
    
    const handleChange = (e) => {
        setFormData({ ...formData, [e.target.name]: e.target.value });
        setError(null);
    };
    
    const handleSubmit = async (e) => {
        e.preventDefault();
        
        // Validation
        if (!formData.title.trim()) {
            setError('Task title is required');
            return;
        }
        
        if (!projectId) {
            setError('No project selected');
            return;
        }
        
        setSaving(true);
        setError(null);
        console.log('[TaskModal] Submitting task:', formData, 'Project ID:', projectId);
        
        try {
            let result;
            const isNew = !task;
            
            if (task) {
                console.log('[TaskModal] Updating task ID:', task.id);
                result = await api.put(`/tasks/${task.id}`, formData);
            } else {
                console.log('[TaskModal] Creating new task for project:', projectId);
                result = await api.post(`/projects/${projectId}/tasks`, formData);
            }
            
            console.log('[TaskModal] API Result:', result);
            
            if (result.success) {
                const savedTask = result.data;
                console.log('[TaskModal] Success! Saved task:', savedTask);
                
                // OPTION A (Preferred): Call onSave with the saved task data
                if (savedTask && savedTask.id) {
                    onSave(savedTask, isNew);
                } else {
                    // OPTION B (Fallback): If response doesn't include task data, re-fetch
                    console.warn('[TaskModal] No task data in response, using fallback');
                    onSaveFallback();
                }
            } else {
                // Handle API errors
                console.error('[TaskModal] API Error:', result.error);
                setError(result.error || 'Failed to save task. Please try again.');
                
                if (result.status === 403) {
                    setError('Permission denied. You may not have access to create/edit tasks.');
                } else if (result.status === 401) {
                    setError('Authentication failed. Please refresh the page and try again.');
                } else if (result.status >= 500) {
                    setError('Server error occurred. Please try again later.');
                }
            }
        } catch (error) {
            console.error('[TaskModal] Unexpected error:', error);
            setError('An unexpected error occurred. Please check console for details.');
        } finally {
            setSaving(false);
        }
    };
    
    return (
        <Modal
            isOpen={true}
            onClose={onClose}
            title={task ? 'Edit Task' : 'New Task'}
            footer={
                <>
                    <button className="iwm-btn iwm-btn-outline" onClick={onClose}>
                        Cancel
                    </button>
                    <button 
                        className="iwm-btn iwm-btn-primary" 
                        onClick={handleSubmit}
                        disabled={saving}
                    >
                        {saving ? 'Saving...' : 'Save Task'}
                    </button>
                </>
            }
        >
            <form onSubmit={handleSubmit}>
                {error && (
                    <div style={{
                        padding: '12px',
                        background: '#fee',
                        border: '1px solid #fcc',
                        borderRadius: '6px',
                        color: '#c33',
                        marginBottom: '15px',
                        fontSize: '14px'
                    }}>
                        ❌ {error}
                    </div>
                )}
                
                <div className="iwm-form-group">
                    <label className="iwm-form-label">Task Title *</label>
                    <input
                        type="text"
                        name="title"
                        className="iwm-form-input"
                        value={formData.title}
                        onChange={handleChange}
                        required
                        disabled={saving}
                    />
                </div>
                
                <div className="iwm-form-group">
                    <label className="iwm-form-label">Description</label>
                    <textarea
                        name="description"
                        className="iwm-form-textarea"
                        value={formData.description}
                        onChange={handleChange}
                    />
                </div>
                
                <div className="iwm-form-group">
                    <label className="iwm-form-label">Priority</label>
                    <select
                        name="priority"
                        className="iwm-form-select"
                        value={formData.priority}
                        onChange={handleChange}
                    >
                        <option value="low">Low</option>
                        <option value="medium">Medium</option>
                        <option value="high">High</option>
                    </select>
                </div>
                
                <div className="iwm-form-group">
                    <label className="iwm-form-label">Due Date</label>
                    <input
                        type="date"
                        name="due_date"
                        className="iwm-form-input"
                        value={formData.due_date}
                        onChange={handleChange}
                    />
                </div>
                
                <div className="iwm-form-group">
                    <label className="iwm-form-label">Estimated Hours</label>
                    <input
                        type="number"
                        name="estimated_hours"
                        className="iwm-form-input"
                        value={formData.estimated_hours}
                        onChange={handleChange}
                        step="0.5"
                    />
                </div>
            </form>
        </Modal>
    );
}

// Assignments Component - Replaces Projects
function Assignments() {
    const [assignments, setAssignments] = useState([]);
    const [binItems, setBinItems] = useState([]);
    const [fieldConfig, setFieldConfig] = useState([]);
    const [loading, setLoading] = useState(true);
    const [showModal, setShowModal] = useState(false);
    const [selectedAssignment, setSelectedAssignment] = useState(null);
    const [showDetailView, setShowDetailView] = useState(false);
    const [toast, setToast] = useState(null);
    const [showBin, setShowBin] = useState(false);
    
    useEffect(() => {
        loadFieldConfig();
        loadAssignments();
        loadBinItems();
    }, []);
    
    const loadFieldConfig = async () => {
        console.log('[Assignments] Loading field configuration...');
        try {
            const result = await api.get('/assignments/fields');
            if (result.success) {
                console.log('[Assignments] Field config loaded:', result.data);
                setFieldConfig(result.data);
            } else {
                console.error('[Assignments] Failed to load field config:', result.error);
            }
        } catch (error) {
            console.error('[Assignments] Error loading field config:', error);
        }
    };
    
    const loadAssignments = async () => {
        console.log('[Assignments] Loading assignments list...');
        try {
            const result = await api.get('/assignments');
            console.log('[Assignments] payload', result);
            
            if (result.success) {
                const rawData = result.data;
                console.log('[Assignments] Raw response data:', rawData, 'Type:', Array.isArray(rawData) ? 'Array' : typeof rawData);
                
                // STEP 2: Normalize result using helper before setState
                const normalizedAssignments = normalizeToArray(rawData);
                console.log('[Assignments] Normalized to array, length:', normalizedAssignments.length);
                
                setAssignments(normalizedAssignments);
            } else {
                console.error('[Assignments] Failed to load assignments:', result.error);
                setToast({ type: 'error', message: result.error || 'Failed to load assignments' });
                setAssignments([]);
            }
        } catch (error) {
            console.error('[Assignments] Error loading assignments:', error);
            setToast({ type: 'error', message: 'Network error loading assignments' });
            setAssignments([]);
        } finally {
            setLoading(false);
        }
    };
    
    const loadBinItems = async () => {
        console.log('[Assignments] Loading bin items...');
        try {
            const result = await api.get('/assignments/bin');
            console.log('[Assignments] Bin payload', result);
            
            if (result.success) {
                const normalizedBin = normalizeToArray(result.data);
                console.log('[Assignments] Normalized bin items, length:', normalizedBin.length);
                setBinItems(normalizedBin);
            } else {
                console.error('[Assignments] Failed to load bin items:', result.error);
                setBinItems([]);
            }
        } catch (error) {
            console.error('[Assignments] Error loading bin items:', error);
            setBinItems([]);
        }
    };
    
    const createAssignment = () => {
        setSelectedAssignment(null);
        setShowModal(true);
    };
    
    const handleAssignmentSaved = (savedAssignment, isNew) => {
        console.log('[Assignments] Assignment saved:', savedAssignment, 'isNew:', isNew);
        if (isNew) {
            setAssignments(prevAssignments => [savedAssignment, ...prevAssignments]);
            setToast({ type: 'success', message: '✅ Assignment created successfully!' });
        } else {
            setAssignments(prevAssignments => 
                prevAssignments.map(a => a.id === savedAssignment.id ? savedAssignment : a)
            );
            setToast({ type: 'success', message: '✅ Assignment updated successfully!' });
        }
        setShowModal(false);
    };
    
    const handleMoveToBin = async (assignmentId) => {
        if (!confirm('Move this assignment to bin? It will be auto-deleted after 30 days.')) return;
        try {
            const result = await api.post(`/assignments/${assignmentId}/bin`);
            if (result.success) {
                setAssignments(prev => prev.filter(a => a.id !== assignmentId));
                await loadBinItems();
                setToast({ type: 'success', message: '✅ Assignment moved to bin' });
            } else {
                setToast({ type: 'error', message: result.error || 'Failed to move to bin' });
            }
        } catch (error) {
            setToast({ type: 'error', message: 'Network error' });
        }
    };
    
    const handleRestore = async (assignmentId) => {
        try {
            const result = await api.post(`/assignments/${assignmentId}/restore`);
            if (result.success) {
                setAssignments(prev => [result.data, ...prev]);
                setBinItems(prev => prev.filter(item => item.id !== assignmentId));
                setToast({ type: 'success', message: '✅ Assignment restored' });
            } else {
                setToast({ type: 'error', message: result.error || 'Failed to restore' });
            }
        } catch (error) {
            setToast({ type: 'error', message: 'Network error' });
        }
    };
    
    const handleDeletePermanent = async (assignmentId) => {
        if (!confirm('Permanently delete this assignment? This action cannot be undone!')) return;
        try {
            const result = await api.delete(`/assignments/${assignmentId}/delete-permanent`);
            if (result.success) {
                setBinItems(prev => prev.filter(item => item.id !== assignmentId));
                setToast({ type: 'success', message: '✅ Assignment permanently deleted' });
            } else {
                setToast({ type: 'error', message: result.error || 'Failed to delete' });
            }
        } catch (error) {
            setToast({ type: 'error', message: 'Network error' });
        }
    };
    
    // Handle assignment selection for detail view
    const handleSelectAssignment = (assignment) => {
        console.log('[Assignments] Assignment selected:', assignment);
        setSelectedAssignment(assignment);
        setShowDetailView(true);
    };
    
    // Handle edit from detail view
    const handleEditAssignment = () => {
        setShowDetailView(false);
        setShowModal(true);
    };
    
    // Handle back from detail view
    const handleBackToList = () => {
        setShowDetailView(false);
        setSelectedAssignment(null);
    };
    
    if (loading) {
        return <div className="iwm-loading"><div className="iwm-spinner"></div><p>Loading assignments...</p></div>;
    }
    
    // Show detail view if assignment selected
    if (showDetailView && selectedAssignment) {
        return (
            <AssignmentDetailView 
                assignment={selectedAssignment}
                onBack={handleBackToList}
                onEdit={handleEditAssignment}
                onMoveToBin={handleMoveToBin}
                toast={toast}
                setToast={setToast}
            />
        );
    }
    
    // STEP 1 & 4: Normalize and guard assignments before rendering
    const assignmentsRaw = assignments;
    const assignmentsList = normalizeToArray(assignmentsRaw);
    console.log('[Assignments] render', assignmentsList);
    
    return (
        <div>
            <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '20px', alignItems: 'center' }}>
                <h2>My Assignments</h2>
                <div style={{ display: 'flex', gap: '10px' }}>
                    <button className={`iwm-btn ${showBin ? 'iwm-btn-secondary' : 'iwm-btn-outline'}`} onClick={() => setShowBin(!showBin)}>
                        🗑️ Bin {binItems.length > 0 && `(${binItems.length})`}
                    </button>
                    <button className="iwm-btn iwm-btn-primary" onClick={createAssignment}>+ New Assignment</button>
                </div>
            </div>
            {showBin && (
                <div className="iwm-bin-panel">
                    <h3>🗑️ Bin - Items Auto-Delete After 30 Days</h3>
                    {!Array.isArray(binItems) ? (
                        <div style={{ textAlign: 'center', padding: '40px', color: '#e74c3c' }}>
                            <p>⚠️ Bin data error (not an array)</p>
                        </div>
                    ) : binItems.length === 0 ? (
                        <div style={{ textAlign: 'center', padding: '40px', color: '#7f8c8d' }}><p>Bin is empty</p></div>
                    ) : (
                        <div className="iwm-bin-items">
                            {binItems.map(item => <BinItemCard key={item.id} item={item} onRestore={handleRestore} onDeletePermanent={handleDeletePermanent} />)}
                        </div>
                    )}
                </div>
            )}
            {assignmentsList.length === 0 ? (
                <div style={{ textAlign: 'center', padding: '60px', color: '#7f8c8d' }}>
                    <div style={{ fontSize: '48px', marginBottom: '20px' }}>📋</div>
                    <h3>No assignments yet</h3>
                    <p>Create your first assignment to get started</p>
                    <button className="iwm-btn iwm-btn-primary" onClick={createAssignment} style={{ marginTop: '20px' }}>Create Assignment</button>
                </div>
            ) : (
                <div className="iwm-projects-grid">
                    {assignmentsList.map(assignment => (
                        <AssignmentCard 
                            key={assignment.id} 
                            assignment={assignment} 
                            onSelect={handleSelectAssignment} 
                            onMoveToBin={handleMoveToBin} 
                        />
                    ))}
                </div>
            )}
            {showModal && <AssignmentModal assignment={selectedAssignment} fieldConfig={fieldConfig} onClose={() => setShowModal(false)} onSave={handleAssignmentSaved} />}
            {toast && <Toast message={toast.message} type={toast.type} onClose={() => setToast(null)} />}
        </div>
    );
}

// Assignment Detail View Component
function AssignmentDetailView({ assignment, onBack, onEdit, onMoveToBin, toast, setToast }) {
    const [loading, setLoading] = useState(false);
    const [assignmentData, setAssignmentData] = useState(assignment);
    const [error, setError] = useState(null);
    const [deletedNotice, setDeletedNotice] = useState(false);
    
    console.log('[AssignmentDetailView] Rendering assignment:', assignmentData);
    
    // STEP 2: Defensive fetch with error handling and deleted_at check
    const loadAssignment = async (id) => {
        console.log('[AssignmentDetailView] >>> load', id);
        setLoading(true);
        setError(null);
        setDeletedNotice(false);
        
        try {
            const result = await api.get(`/assignments/${id}`);
            console.log('[AssignmentDetailView] >>> response', result);
            
            if (!result || !result.success) {
                console.error('[AssignmentDetailView] >>> Invalid data:', result);
                setError(result?.error || 'Invalid data received from server');
                return;
            }
            
            const data = result.data;
            
            // Check if assignment was deleted (soft-delete)
            if (data.deleted_at && data.deleted_at !== '0000-00-00 00:00:00') {
                console.warn('[AssignmentDetailView] >>> Assignment is in bin (deleted_at:', data.deleted_at, ')');
                setDeletedNotice(true);
                return;
            }
            
            // Check status
            if (data.status === 'in_bin' || data.status === 'deleted') {
                console.warn('[AssignmentDetailView] >>> Assignment status indicates deletion:', data.status);
                setDeletedNotice(true);
                return;
            }
            
            console.log('[AssignmentDetailView] >>> Setting assignment data:', data);
            setAssignmentData(data);
        } catch (error) {
            console.error('[AssignmentDetailView] >>> load error', error);
            setError('Unable to fetch assignment: ' + error.message);
        } finally {
            setLoading(false);
        }
    };
    
    // Reload assignment data on mount
    useEffect(() => {
        if (assignment && assignment.id) {
            loadAssignment(assignment.id);
        }
    }, [assignment?.id]);
    
    const getCategoryIcon = (category) => ({
        'Carpenter': '🔨', 'Electrician': '⚡', 'Plumber': '🔧', 'Painter': '🎨', 'Supervisor': '👷', 'Other': '📋'
    }[category] || '📋');
    
    // STEP 4: Error boundary / fallback UI
    if (error) {
        return (
            <div style={{ padding: '40px', textAlign: 'center' }}>
                <div style={{ fontSize: '48px', marginBottom: '20px' }}>⚠️</div>
                <h2>Something went wrong</h2>
                <p style={{ color: '#e74c3c', marginBottom: '20px' }}>{error}</p>
                <div style={{ display: 'flex', gap: '10px', justifyContent: 'center' }}>
                    <button className="iwm-btn iwm-btn-primary" onClick={onBack}>
                        ← Back to Assignments
                    </button>
                    <button className="iwm-btn iwm-btn-outline" onClick={() => loadAssignment(assignment.id)}>
                        🔄 Retry
                    </button>
                </div>
                <details style={{ marginTop: '20px', textAlign: 'left', maxWidth: '600px', margin: '20px auto' }}>
                    <summary style={{ cursor: 'pointer', color: '#7f8c8d' }}>Technical Details</summary>
                    <pre style={{ background: '#f5f5f5', padding: '15px', borderRadius: '5px', overflow: 'auto', fontSize: '12px' }}>
                        {JSON.stringify({ assignment, error }, null, 2)}
                    </pre>
                </details>
            </div>
        );
    }
    
    // Show deleted notice if assignment is in bin
    if (deletedNotice) {
        return (
            <div style={{ padding: '40px', textAlign: 'center' }}>
                <div style={{ fontSize: '48px', marginBottom: '20px' }}>🗑️</div>
                <h2>Assignment Moved to Bin</h2>
                <p style={{ color: '#7f8c8d', marginBottom: '20px' }}>
                    This assignment has been moved to the bin and will be auto-deleted after 30 days.
                </p>
                <button className="iwm-btn iwm-btn-primary" onClick={onBack}>
                    ← Back to Assignments
                </button>
            </div>
        );
    }
    
    if (loading) {
        return (
            <div className="iwm-loading">
                <div className="iwm-spinner"></div>
                <p>Loading assignment details...</p>
            </div>
        );
    }
    
    return (
        <div>
            {/* Header with back button */}
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '20px' }}>
                <button 
                    className="iwm-btn iwm-btn-outline"
                    onClick={onBack}
                    style={{ display: 'flex', alignItems: 'center', gap: '8px' }}
                >
                    ← Back to Assignments
                </button>
                <div style={{ display: 'flex', gap: '10px' }}>
                    <button className="iwm-btn iwm-btn-primary" onClick={onEdit}>
                        ✏️ Edit
                    </button>
                    <button 
                        className="iwm-btn iwm-btn-danger" 
                        onClick={() => {
                            onMoveToBin(assignmentData.id);
                            onBack();
                        }}
                    >
                        🗑️ Move to Bin
                    </button>
                </div>
            </div>
            
            {/* Assignment Details Card */}
            <div className="iwm-detail-view">
                <div className="iwm-detail-header">
                    <h1 style={{ margin: 0, display: 'flex', alignItems: 'center', gap: '12px' }}>
                        <span style={{ fontSize: '36px' }}>{getCategoryIcon(assignmentData.category)}</span>
                        {assignmentData.title}
                    </h1>
                    <span className={`iwm-project-status ${assignmentData.status}`} style={{ fontSize: '14px', padding: '8px 16px' }}>
                        {assignmentData.status}
                    </span>
                </div>
                
                <div className="iwm-detail-body">
                    {/* Info Grid */}
                    <div className="iwm-detail-grid">
                        <div className="iwm-detail-item">
                            <label>Category</label>
                            <div>{assignmentData.category}</div>
                        </div>
                        
                        {assignmentData.assignee_name && (
                            <div className="iwm-detail-item">
                                <label>Assigned To</label>
                                <div>{assignmentData.assignee_name}</div>
                            </div>
                        )}
                        
                        <div className="iwm-detail-item">
                            <label>Created</label>
                            <div>{new Date(assignmentData.created_at).toLocaleDateString()}</div>
                        </div>
                        
                        <div className="iwm-detail-item">
                            <label>Last Updated</label>
                            <div>{new Date(assignmentData.updated_at).toLocaleDateString()}</div>
                        </div>
                    </div>
                    
                    {/* Description */}
                    {assignmentData.description && (
                        <div className="iwm-detail-section">
                            <h3>Description</h3>
                            <p style={{ whiteSpace: 'pre-wrap', color: '#555', lineHeight: '1.6' }}>
                                {assignmentData.description}
                            </p>
                        </div>
                    )}
                    
                    {/* Custom Fields */}
                    {assignmentData.custom_fields && Object.keys(assignmentData.custom_fields).length > 0 && (
                        <div className="iwm-detail-section">
                            <h3>Additional Information</h3>
                            <div className="iwm-detail-grid">
                                {Object.entries(assignmentData.custom_fields).map(([key, value]) => (
                                    <div key={key} className="iwm-detail-item">
                                        <label>{key.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase())}</label>
                                        <div>{value}</div>
                                    </div>
                                ))}
                            </div>
                        </div>
                    )}
                </div>
            </div>
            
            {toast && <Toast message={toast.message} type={toast.type} onClose={() => setToast(null)} />}
        </div>
    );
}

function AssignmentCard({ assignment, onSelect, onMoveToBin }) {
    const getCategoryIcon = (category) => ({
        'Carpenter': '🔨', 'Electrician': '⚡', 'Plumber': '🔧', 'Painter': '🎨', 'Supervisor': '👷', 'Other': '📋'
    }[category] || '📋');
    
    // STEP 3: Prevent accidental move-to-bin on card click - card opens detail view ONLY
    const handleCardClick = (e) => {
        // Ignore clicks on buttons or interactive elements
        if (e.target.tagName === 'BUTTON' || e.target.closest('button')) {
            return; // Let button handle its own click
        }
        console.log('[AssignmentCard] Clicked card ID:', assignment.id, '- Opening detail view');
        onSelect(assignment); // Only open detail view
    };
    
    // STEP 3: Explicit move-to-bin handler with event stop propagation
    const handleMoveToBin = (e) => {
        e.stopPropagation(); // CRITICAL: Prevent card click event from firing
        console.log('[AssignmentCard] Move to Bin clicked for ID:', assignment.id);
        onMoveToBin(assignment.id);
    };
    
    return (
        <div className="iwm-project-card" onClick={handleCardClick} style={{ cursor: 'pointer' }}>
            <div className="iwm-project-header">
                <h3 className="iwm-project-title">{getCategoryIcon(assignment.category)} {assignment.title}</h3>
                <span className={`iwm-project-status ${assignment.status}`}>{assignment.status}</span>
            </div>
            <div style={{ marginBottom: '10px' }}><strong>Category:</strong> {assignment.category}</div>
            {assignment.assignee_name && <div style={{ marginBottom: '10px' }}><strong>Assigned to:</strong> {assignment.assignee_name}</div>}
            <p className="iwm-project-description">{assignment.description || 'No description'}</p>
            {assignment.custom_fields && Object.keys(assignment.custom_fields).length > 0 && (
                <div style={{ marginTop: '10px', fontSize: '13px', color: '#7f8c8d' }}>
                    {Object.entries(assignment.custom_fields).map(([key, value]) => <div key={key}><strong>{key}:</strong> {value}</div>)}
                </div>
            )}
            <div className="iwm-project-footer" style={{ marginTop: '15px', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <button 
                    className="iwm-btn iwm-btn-sm iwm-btn-danger" 
                    onClick={handleMoveToBin}
                >
                    🗑️ Move to Bin
                </button>
                <div style={{ fontSize: '12px', color: '#95a5a6' }}>Created: {new Date(assignment.created_at).toLocaleDateString()}</div>
            </div>
        </div>
    );
}

function BinItemCard({ item, onRestore, onDeletePermanent }) {
    const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
    return (
        <div className="iwm-bin-item">
            <div className="iwm-bin-item-header">
                <h4>{item.title}</h4>
                <span className="iwm-bin-days-remaining">{item.days_remaining > 0 ? `${item.days_remaining} days left` : 'Expires today!'}</span>
            </div>
            <div style={{ fontSize: '13px', marginBottom: '10px' }}><strong>Category:</strong> {item.category}</div>
            {item.assignee_name && <div style={{ fontSize: '13px', marginBottom: '10px' }}><strong>Assigned to:</strong> {item.assignee_name}</div>}
            <div style={{ fontSize: '12px', color: '#95a5a6', marginBottom: '10px' }}>Deleted: {new Date(item.deleted_at).toLocaleDateString()}</div>
            <div className="iwm-bin-actions">
                <button className="iwm-btn iwm-btn-sm iwm-btn-success" onClick={() => onRestore(item.id)}>↩️ Restore</button>
                {!showDeleteConfirm ? (
                    <button className="iwm-btn iwm-btn-sm iwm-btn-danger" onClick={() => setShowDeleteConfirm(true)}>🗑️ Delete Permanently</button>
                ) : (
                    <div style={{ display: 'flex', gap: '5px' }}>
                        <button className="iwm-btn iwm-btn-sm iwm-btn-danger" onClick={() => onDeletePermanent(item.id)}>✓ Confirm Delete</button>
                        <button className="iwm-btn iwm-btn-sm iwm-btn-outline" onClick={() => setShowDeleteConfirm(false)}>Cancel</button>
                    </div>
                )}
            </div>
        </div>
    );
}

function AssignmentModal({ assignment, fieldConfig, onClose, onSave }) {
    const [formData, setFormData] = useState({});
    const [saving, setSaving] = useState(false);
    const [error, setError] = useState(null);
    
    // Validate fieldConfig is an array
    if (!Array.isArray(fieldConfig)) {
        console.error('[AssignmentModal] ❌ Invalid fieldConfig - expected array, got:', typeof fieldConfig, fieldConfig);
        return (
            <div className="iwm-modal-overlay" onClick={onClose}>
                <div className="iwm-modal" onClick={e => e.stopPropagation()}>
                    <div className="iwm-modal-header">
                        <h2>⚠️ Configuration Error</h2>
                        <button className="iwm-modal-close" onClick={onClose}>×</button>
                    </div>
                    <div className="iwm-modal-body">
                        <div className="iwm-alert iwm-alert-danger">
                            <strong>Field configuration error:</strong>
                            <p>The assignment form configuration is invalid (not an array).</p>
                            <p>Type received: {typeof fieldConfig}</p>
                            <p style={{ marginTop: '10px' }}>Please reload the page or contact the administrator.</p>
                        </div>
                        <div style={{ marginTop: '20px', textAlign: 'center' }}>
                            <button className="iwm-btn iwm-btn-outline" onClick={onClose}>Close</button>
                            <button className="iwm-btn iwm-btn-primary" onClick={() => window.location.reload()} style={{ marginLeft: '10px' }}>
                                Reload Page
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        );
    }
    
    // Check for empty field config
    if (fieldConfig.length === 0) {
        console.warn('[AssignmentModal] ⚠️ Empty fieldConfig array');
        return (
            <div className="iwm-modal-overlay" onClick={onClose}>
                <div className="iwm-modal" onClick={e => e.stopPropagation()}>
                    <div className="iwm-modal-header">
                        <h2>Loading Configuration...</h2>
                        <button className="iwm-modal-close" onClick={onClose}>×</button>
                    </div>
                    <div className="iwm-modal-body">
                        <div className="iwm-alert iwm-alert-warning">
                            <strong>Configuration loading...</strong>
                            <p>The assignment form fields are still loading.</p>
                            <p>Please wait a moment and try again.</p>
                        </div>
                        <div style={{ marginTop: '20px', textAlign: 'center' }}>
                            <button className="iwm-btn iwm-btn-outline" onClick={onClose}>Close</button>
                            <button className="iwm-btn iwm-btn-primary" onClick={() => window.location.reload()} style={{ marginLeft: '10px' }}>
                                Reload Page
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        );
    }
    
    useEffect(() => {
        const initialData = {};
        
        // Safety check: ensure fieldConfig is an array
        if (Array.isArray(fieldConfig)) {
            fieldConfig.forEach(field => {
                if (assignment) {
                    if (field.is_system) {
                        initialData[field.key] = assignment[field.key] || field.default_value || '';
                    } else if (assignment.custom_fields && assignment.custom_fields[field.key]) {
                        initialData[field.key] = assignment.custom_fields[field.key];
                    } else {
                        initialData[field.key] = field.default_value || '';
                    }
                } else {
                    initialData[field.key] = field.default_value || '';
                }
            });
        }
        
        setFormData(initialData);
    }, [assignment, fieldConfig]);
    
    const handleChange = (e) => {
        setFormData({ ...formData, [e.target.name]: e.target.value });
        setError(null);
    };
    
    const handleSubmit = async (e) => {
        e.preventDefault();
        const errors = [];
        
        // Safety check: ensure fieldConfig is an array before validation
        if (Array.isArray(fieldConfig)) {
            fieldConfig.forEach(field => {
                if (field.required && field.visible && (!formData[field.key] || formData[field.key].trim() === '')) {
                    errors.push(`${field.label} is required`);
                }
            });
        }
        
        if (errors.length > 0) { setError(errors.join(', ')); return; }
        setSaving(true); setError(null);
        try {
            const isNew = !assignment;
            const result = isNew ? await api.post('/assignments', formData) : await api.put(`/assignments/${assignment.id}`, formData);
            if (result.success) { onSave(result.data, isNew); } else { setError(result.error || 'Failed to save assignment'); setSaving(false); }
        } catch (error) {
            setError('Network error. Please try again.'); setSaving(false);
        }
    };
    
    const renderField = (field) => {
        if (!field.visible) return null;
        const value = formData[field.key] || '';
        switch (field.type) {
            case 'text': return <input type="text" name={field.key} value={value} onChange={handleChange} className="iwm-form-control" required={field.required} />;
            case 'textarea': return <textarea name={field.key} value={value} onChange={handleChange} className="iwm-form-control" rows="4" required={field.required} />;
            case 'select': return (
                <select name={field.key} value={value} onChange={handleChange} className="iwm-form-control" required={field.required}>
                    <option value="">Select {field.label}</option>
                    {field.options && Object.entries(field.options).map(([key, label]) => <option key={key} value={key}>{label}</option>)}
                </select>
            );
            case 'number': return <input type="number" name={field.key} value={value} onChange={handleChange} className="iwm-form-control" required={field.required} />;
            case 'date': return <input type="date" name={field.key} value={value} onChange={handleChange} className="iwm-form-control" required={field.required} />;
            default: return <input type="text" name={field.key} value={value} onChange={handleChange} className="iwm-form-control" required={field.required} />;
        }
    };
    
    return (
        <div className="iwm-modal-overlay" onClick={onClose}>
            <div className="iwm-modal" onClick={e => e.stopPropagation()}>
                <div className="iwm-modal-header">
                    <h2>{assignment ? 'Edit Assignment' : 'New Assignment'}</h2>
                    <button className="iwm-modal-close" onClick={onClose}>×</button>
                </div>
                <div className="iwm-modal-body">
                    {error && <div className="iwm-alert iwm-alert-danger">{error}</div>}
                    <form onSubmit={handleSubmit}>
                        {Array.isArray(fieldConfig) && fieldConfig.map((field) => field.visible && (
                            <div key={field.key} className="iwm-form-group">
                                <label>{field.label}{field.required && <span style={{ color: 'red' }}> *</span>}</label>
                                {renderField(field)}
                            </div>
                        ))}
                        <div className="iwm-modal-footer">
                            <button type="button" className="iwm-btn iwm-btn-outline" onClick={onClose} disabled={saving}>Cancel</button>
                            <button type="submit" className="iwm-btn iwm-btn-primary" disabled={saving}>{saving ? 'Saving...' : 'Save Assignment'}</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    );
}

// Main App Component
function App() {
    const [activeTab, setActiveTab] = useState('dashboard');
    const [useV2, setUseV2] = useState(true); // Toggle between V1 and V2
    const currentUser = IWM_DATA.currentUser;
    
    const renderContent = () => {
        switch(activeTab) {
            case 'dashboard':
                return <Dashboard />;
            case 'assignments':
                // Use V2 by default, fallback to V1 if needed
                return useV2 && window.WorkAssignmentsV2 ? <WorkAssignmentsV2 /> : <Assignments />;
            case 'tasks':
                return <Tasks />;
            default:
                return <Dashboard />;
        }
    };
    
    return (
        <div className="iwm-app-container">
            <nav className="iwm-nav">
                <div className="iwm-nav-tabs">
                    <button 
                        className={`iwm-nav-tab ${activeTab === 'dashboard' ? 'active' : ''}`}
                        onClick={() => setActiveTab('dashboard')}
                    >
                        📊 Dashboard
                    </button>
                    <button 
                        className={`iwm-nav-tab ${activeTab === 'assignments' ? 'active' : ''}`}
                        onClick={() => setActiveTab('assignments')}
                    >
                        📋 Assignments
                    </button>
                    <button 
                        className={`iwm-nav-tab ${activeTab === 'tasks' ? 'active' : ''}`}
                        onClick={() => setActiveTab('tasks')}
                    >
                        ✓ Tasks
                    </button>
                </div>
                
                <div className="iwm-user-info">
                    <div className="iwm-user-avatar">
                        {currentUser.name.charAt(0).toUpperCase()}
                    </div>
                    <span>{currentUser.name}</span>
                </div>
            </nav>
            
            <div>
                {renderContent()}
            </div>
        </div>
    );
}

// Render App
const root = ReactDOM.createRoot(document.getElementById('iwm-app'));
root.render(
    <ErrorBoundary>
        <App />
    </ErrorBoundary>
);
