import React, { useState, useEffect, useRef } from 'react'; import { Calendar, Search, Plus, Trash2, Settings, X, Save, AlertCircle, Edit, Eye, EyeOff, ChevronDown, ChevronUp, Tag, PlusCircle, ThumbsUp, ThumbsDown, Lightbulb, CheckSquare, List, AlertTriangle, Tool, DollarSign, Clock, Share2, Printer, ArrowUp, ArrowDown, Star, StarHalf, Clipboard, FileText } from 'lucide-react'; // Import TensorFlow.js for NLP processing // Note: In a real implementation, you would need to include this in your package.json // and properly import the specific models needed const tf = window.tf; const C130EngineProblemTracker = () => { // State for form inputs const [problem, setProblem] = useState(''); const [solution, setSolution] = useState(''); const [date, setDate] = useState(''); const [jobCardNumber, setJobCardNumber] = useState(''); const [selectedComponent, setSelectedComponent] = useState(''); // State for entries and search const [entries, setEntries] = useState([]); const [searchTerm, setSearchTerm] = useState(''); const [isFormValid, setIsFormValid] = useState(false); // State for engine map and components const [showEngineMap, setShowEngineMap] = useState(false); const [selectedMapComponent, setSelectedMapComponent] = useState(null); const [componentProblems, setComponentProblems] = useState([]); const [showAdminPanel, setShowAdminPanel] = useState(false); const [isAdmin, setIsAdmin] = useState(false); const [adminPassword, setAdminPassword] = useState(''); const [showPasswordPrompt, setShowPasswordPrompt] = useState(false); const [passwordError, setPasswordError] = useState(''); const [engineComponents, setEngineComponents] = useState([]); const [newComponentName, setNewComponentName] = useState(''); const [newComponentKeywords, setNewComponentKeywords] = useState(''); const [editingComponent, setEditingComponent] = useState(null); const [showBlueprintView, setShowBlueprintView] = useState(true); const [uncategorizedProblems, setUncategorizedProblems] = useState([]); const [showUncategorized, setShowUncategorized] = useState(false); // State for NLP solution recommendations const [solutionSuggestions, setSolutionSuggestions] = useState([]); const [isProcessingNLP, setIsProcessingNLP] = useState(false); const [nlpModelLoaded, setNlpModelLoaded] = useState(false); const [solutionFeedback, setSolutionFeedback] = useState({}); const [selectedSuggestion, setSelectedSuggestion] = useState(null); // New state for checklists const [checklists, setChecklists] = useState([]); const [showChecklistModal, setShowChecklistModal] = useState(false); const [currentChecklist, setCurrentChecklist] = useState(null); const [isGeneratingChecklist, setIsGeneratingChecklist] = useState(false); const [checklistLibrary, setChecklistLibrary] = useState([]); const [showChecklistLibrary, setShowChecklistLibrary] = useState(false); const [checklistSearchTerm, setChecklistSearchTerm] = useState(''); const [checklistSortBy, setChecklistSortBy] = useState('rating'); const [commonTools, setCommonTools] = useState([ 'Wrench', 'Screwdriver', 'Pliers', 'Socket set', 'Torque wrench', 'Multimeter', 'Pressure gauge', 'Borescope', 'Fuel tester', 'Oil analyzer', 'Hydraulic jack', 'Safety wire pliers', 'Inspection mirror', 'Flashlight', 'Calibration tools', 'Compression tester', 'Timing light', 'Feeler gauge' ]); // Refs const mapRef = useRef(null); const modalRef = useRef(null); const problemInputRef = useRef(null); const nlpModelRef = useRef(null); const problemInputTimeoutRef = useRef(null); const checklistModalRef = useRef(null); // Default engine components with zones and keywords const defaultEngineComponents = [ { id: 1, name: 'Propeller Assembly', keywords: ['propeller', 'prop', 'blade', 'spinner', 'hub'], coordinates: { x1: 10, y1: 40, x2: 80, y2: 160 }, color: 'rgba(255, 0, 0, 0.3)' }, { id: 2, name: 'Reduction Gearbox', keywords: ['gearbox', 'reduction', 'gear', 'transmission'], coordinates: { x1: 90, y1: 50, x2: 150, y2: 150 }, color: 'rgba(0, 255, 0, 0.3)' }, { id: 3, name: 'Compressor Section', keywords: ['compressor', 'inlet', 'compression', 'air intake', 'stator'], coordinates: { x1: 160, y1: 60, x2: 240, y2: 140 }, color: 'rgba(0, 0, 255, 0.3)' }, { id: 4, name: 'Combustion Chamber', keywords: ['combustion', 'chamber', 'burner', 'fuel nozzle', 'igniter'], coordinates: { x1: 250, y1: 70, x2: 310, y2: 130 }, color: 'rgba(255, 255, 0, 0.3)' }, { id: 5, name: 'Turbine Section', keywords: ['turbine', 'power turbine', 'gas generator', 'hot section', 'nozzle'], coordinates: { x1: 320, y1: 60, x2: 400, y2: 140 }, color: 'rgba(255, 0, 255, 0.3)' }, { id: 6, name: 'Exhaust System', keywords: ['exhaust', 'tailpipe', 'outlet', 'duct'], coordinates: { x1: 410, y1: 70, x2: 480, y2: 130 }, color: 'rgba(0, 255, 255, 0.3)' }, { id: 7, name: 'Fuel System', keywords: ['fuel', 'pump', 'injector', 'filter', 'line', 'tank'], coordinates: { x1: 250, y1: 150, x2: 350, y2: 190 }, color: 'rgba(255, 165, 0, 0.3)' }, { id: 8, name: 'Oil System', keywords: ['oil', 'lubrication', 'cooler', 'filter', 'pump', 'pressure'], coordinates: { x1: 180, y1: 150, x2: 240, y2: 190 }, color: 'rgba(128, 0, 128, 0.3)' } ]; // Sample NLP model data (in a real implementation, this would be loaded from a pre-trained model) const sampleWordEmbeddings = { 'propeller': [0.2, 0.3, 0.1], 'blade': [0.25, 0.35, 0.15], 'broken': [0.5, 0.1, 0.2], 'damaged': [0.55, 0.15, 0.25], 'leak': [0.7, 0.4, 0.1], 'oil': [0.75, 0.45, 0.15], 'fuel': [0.8, 0.5, 0.2], 'pressure': [0.4, 0.6, 0.3], 'low': [0.45, 0.65, 0.35], 'high': [0.5, 0.7, 0.4], 'temperature': [0.55, 0.75, 0.45], 'vibration': [0.6, 0.8, 0.5], 'noise': [0.65, 0.85, 0.55], 'crack': [0.7, 0.9, 0.6], 'worn': [0.75, 0.95, 0.65], 'replace': [0.8, 0.1, 0.7], 'repair': [0.85, 0.15, 0.75], 'adjust': [0.9, 0.2, 0.8], 'clean': [0.95, 0.25, 0.85], 'inspect': [0.1, 0.3, 0.9], 'test': [0.15, 0.35, 0.95], 'check': [0.2, 0.4, 0.1], 'monitor': [0.25, 0.45, 0.15], 'overhaul': [0.3, 0.5, 0.2], 'rebuild': [0.35, 0.55, 0.25], 'compressor': [0.4, 0.6, 0.3], 'turbine': [0.45, 0.65, 0.35], 'combustion': [0.5, 0.7, 0.4], 'exhaust': [0.55, 0.75, 0.45], 'gearbox': [0.6, 0.8, 0.5], 'warning': [0.65, 0.85, 0.55], 'caution': [0.7, 0.9, 0.6], 'danger': [0.75, 0.95, 0.65], 'careful': [0.8, 0.1, 0.7], 'ensure': [0.85, 0.15, 0.75], 'must': [0.9, 0.2, 0.8], 'never': [0.95, 0.25, 0.85], 'always': [0.1, 0.3, 0.9], 'first': [0.15, 0.35, 0.95], 'then': [0.2, 0.4, 0.1], 'finally': [0.25, 0.45, 0.15], 'before': [0.3, 0.5, 0.2], 'after': [0.35, 0.55, 0.25], 'remove': [0.4, 0.6, 0.3], 'install': [0.45, 0.65, 0.35], 'disconnect': [0.5, 0.7, 0.4], 'connect': [0.55, 0.75, 0.45], 'tighten': [0.6, 0.8, 0.5], 'loosen': [0.65, 0.85, 0.55], }; // Safety keywords for checklist generation const safetyKeywords = { warnings: [ 'warning', 'caution', 'danger', 'hazard', 'careful', 'attention', 'hot', 'explosive', 'flammable', 'toxic', 'poisonous', 'corrosive', 'high voltage', 'high pressure', 'safety', 'injury', 'death' ], prohibitions: [ 'never', 'do not', 'avoid', 'prevent', 'refrain', 'prohibited', 'forbidden', 'stop', 'no', 'don\'t' ], requirements: [ 'must', 'required', 'necessary', 'essential', 'critical', 'important', 'ensure', 'verify', 'confirm', 'check', 'always', 'mandatory' ] }; // Load data from localStorage on component mount useEffect(() => { const savedEntries = localStorage.getItem('c130EngineEntries'); if (savedEntries) { setEntries(JSON.parse(savedEntries)); } const savedComponents = localStorage.getItem('c130EngineComponents'); if (savedComponents) { setEngineComponents(JSON.parse(savedComponents)); } else { setEngineComponents(defaultEngineComponents); } const savedFeedback = localStorage.getItem('c130SolutionFeedback'); if (savedFeedback) { setSolutionFeedback(JSON.parse(savedFeedback)); } const savedChecklists = localStorage.getItem('c130Checklists'); if (savedChecklists) { setChecklistLibrary(JSON.parse(savedChecklists)); } // Set admin password - in a real app, this would be securely stored and verified const ADMIN_PASSWORD = 'admin123'; localStorage.setItem('adminPassword', ADMIN_PASSWORD); // Initialize NLP model initializeNLPModel(); }, []); // Save entries to localStorage whenever they change useEffect(() => { localStorage.setItem('c130EngineEntries', JSON.stringify(entries)); // Process entries to find uncategorized problems const uncategorized = entries.filter(entry => !findComponentForProblem(entry.problem)); setUncategorizedProblems(uncategorized); }, [entries]); // Save components to localStorage whenever they change useEffect(() => { localStorage.setItem('c130EngineComponents', JSON.stringify(engineComponents)); }, [engineComponents]); // Save solution feedback to localStorage whenever it changes useEffect(() => { localStorage.setItem('c130SolutionFeedback', JSON.stringify(solutionFeedback)); }, [solutionFeedback]); // Save checklists to localStorage whenever they change useEffect(() => { localStorage.setItem('c130Checklists', JSON.stringify(checklistLibrary)); }, [checklistLibrary]); // Process problem input for NLP analysis with debounce useEffect(() => { if (problemInputTimeoutRef.current) { clearTimeout(problemInputTimeoutRef.current); } if (problem.trim().length > 10 && nlpModelLoaded) { setIsProcessingNLP(true); problemInputTimeoutRef.current = setTimeout(() => { findSimilarProblems(problem); }, 500); // 500ms debounce } else { setSolutionSuggestions([]); } return () => { if (problemInputTimeoutRef.current) { clearTimeout(problemInputTimeoutRef.current); } }; }, [problem, nlpModelLoaded]); // Validate form useEffect(() => { setIsFormValid(problem.trim() !== '' && date !== '' && jobCardNumber.trim() !== ''); }, [problem, solution, date, jobCardNumber]); // Close modal when clicking outside useEffect(() => { const handleClickOutside = (event) => { if (modalRef.current && !modalRef.current.contains(event.target)) { setSelectedMapComponent(null); } if (checklistModalRef.current && !checklistModalRef.current.contains(event.target)) { setShowChecklistModal(false); } }; document.addEventListener('mousedown', handleClickOutside); return () => { document.removeEventListener('mousedown', handleClickOutside); }; }, []); // Initialize NLP model const initializeNLPModel = async () => { try { // In a real implementation, you would load a pre-trained model here // For this example, we'll simulate model loading with a timeout setTimeout(() => { nlpModelRef.current = { // Simulated model with word embeddings wordEmbeddings: sampleWordEmbeddings, // Simulated text embedding function embedText: (text) => { const words = text.toLowerCase().split(/\W+/).filter(word => word.length > 0); const embeddings = words.map(word => sampleWordEmbeddings[word] || [0, 0, 0]); // Average the embeddings if (embeddings.length === 0) return [0, 0, 0]; const sum = embeddings.reduce((acc, curr) => { return acc.map((val, idx) => val + (curr[idx] || 0)); }, [0, 0, 0]); return sum.map(val => val / embeddings.length); }, // Simulated similarity function calculateSimilarity: (embedding1, embedding2) => { // Cosine similarity const dotProduct = embedding1.reduce((sum, val, idx) => sum + val * embedding2[idx], 0); const magnitude1 = Math.sqrt(embedding1.reduce((sum, val) => sum + val * val, 0)); const magnitude2 = Math.sqrt(embedding2.reduce((sum, val) => sum + val * val, 0)); if (magnitude1 === 0 || magnitude2 === 0) return 0; return dotProduct / (magnitude1 * magnitude2); } }; setNlpModelLoaded(true); console.log("NLP model loaded successfully"); }, 1000); } catch (error) { console.error("Error loading NLP model:", error); } }; // Find similar problems using NLP const findSimilarProblems = (problemText) => { if (!nlpModelRef.current || !problemText.trim()) { setIsProcessingNLP(false); return; } try { // Get embedding for current problem const currentEmbedding = nlpModelRef.current.embedText(problemText); // Filter entries with solutions const entriesWithSolutions = entries.filter(entry => entry.solution && entry.solution.trim() !== ''); if (entriesWithSolutions.length === 0) { // If no entries with solutions, try to find component-related entries findComponentRelatedSolutions(problemText); return; } // Calculate similarity scores const similarityScores = entriesWithSolutions.map(entry => { const entryEmbedding = nlpModelRef.current.embedText(entry.problem); const similarity = nlpModelRef.current.calculateSimilarity(currentEmbedding, entryEmbedding); return { entry, similarity, // Adjust score based on feedback adjustedScore: adjustScoreBasedOnFeedback(similarity, entry.id) }; }); // Sort by adjusted similarity score similarityScores.sort((a, b) => b.adjustedScore - a.adjustedScore); // Take top 5 suggestions const topSuggestions = similarityScores .slice(0, 5) .filter(item => item.similarity > 0.3) // Only include reasonably similar items .map(item => ({ id: item.entry.id, problem: item.entry.problem, solution: item.entry.solution, similarity: item.similarity, adjustedScore: item.adjustedScore, componentName: item.entry.componentName })); setSolutionSuggestions(topSuggestions); setIsProcessingNLP(false); // If no good matches found, try component-related solutions if (topSuggestions.length === 0) { findComponentRelatedSolutions(problemText); } } catch (error) { console.error("Error finding similar problems:", error); setIsProcessingNLP(false); } }; // Find component-related solutions when no direct matches are found const findComponentRelatedSolutions = (problemText) => { // Detect component from problem text const detectedComponent = findComponentForProblem(problemText); if (!detectedComponent) { setIsProcessingNLP(false); return; } // Find entries with solutions for the same component const componentSolutions = entries.filter( entry => entry.componentId === detectedComponent.id && entry.solution && entry.solution.trim() !== '' ); if (componentSolutions.length === 0) { setIsProcessingNLP(false); return; } // Map to suggestion format const suggestions = componentSolutions.slice(0, 5).map(entry => ({ id: entry.id, problem: entry.problem, solution: entry.solution, similarity: 0.5, // Default similarity for component-based matches adjustedScore: 0.5, componentName: entry.componentName, isComponentMatch: true })); setSolutionSuggestions(suggestions); setIsProcessingNLP(false); }; // Adjust similarity score based on feedback const adjustScoreBasedOnFeedback = (similarity, entryId) => { const feedback = solutionFeedback[entryId]; if (!feedback) return similarity; // Adjust score based on thumbs up/down if (feedback.thumbsUp > 0) { // Boost score for positive feedback return similarity * (1 + (feedback.thumbsUp * 0.1)); } else if (feedback.thumbsDown > 0) { // Reduce score for negative feedback return similarity * (1 - (feedback.thumbsDown * 0.1)); } return similarity; }; // Handle solution suggestion selection const handleSelectSuggestion = (suggestion) => { setSolution(suggestion.solution); setSelectedSuggestion(suggestion); }; // Handle solution feedback const handleSolutionFeedback = (suggestionId, isPositive) => { setSolutionFeedback(prevFeedback => { const currentFeedback = prevFeedback[suggestionId] || { thumbsUp: 0, thumbsDown: 0 }; if (isPositive) { return { ...prevFeedback, [suggestionId]: { ...currentFeedback, thumbsUp: currentFeedback.thumbsUp + 1 } }; } else { return { ...prevFeedback, [suggestionId]: { ...currentFeedback, thumbsDown: currentFeedback.thumbsDown + 1 } }; } }); }; // Generate checklist from solution text const generateChecklist = () => { if (!solution.trim()) { alert('Please enter a solution before generating a checklist.'); return; } setIsGeneratingChecklist(true); // In a real implementation, this would use a more sophisticated NLP model // For this example, we'll use a simple rule-based approach setTimeout(() => { try { // Extract steps from solution text const steps = extractStepsFromSolution(solution, problem); // Extract tools from solution and problem const tools = extractToolsFromText(solution + ' ' + problem); // Estimate difficulty based on number of steps, tools, and complexity const difficulty = estimateDifficulty(steps, tools, solution); // Estimate cost based on tools and solution text const cost = estimateCost(tools, solution); // Create new checklist const newChecklist = { id: Date.now(), title: `Fix for: ${problem.substring(0, 50)}${problem.length > 50 ? '...' : ''}`, problemId: null, // Will be set when saved with a problem componentId: findComponentForProblem(problem)?.id || null, componentName: findComponentForProblem(problem)?.name || null, steps, tools, difficulty, cost, timeEstimate: estimateTime(steps, difficulty), createdAt: new Date().toISOString(), updatedAt: new Date().toISOString(), votes: { upvotes: 0, downvotes: 0 }, rating: 0, usageCount: 0, isTemplate: false }; setCurrentChecklist(newChecklist); setShowChecklistModal(true); setIsGeneratingChecklist(false); } catch (error) { console.error("Error generating checklist:", error); setIsGeneratingChecklist(false); alert('An error occurred while generating the checklist. Please try again.'); } }, 1500); // Simulate processing time }; // Extract steps from solution text const extractStepsFromSolution = (solutionText, problemText) => { // Split text into sentences const sentences = solutionText.split(/(?<=[.!?])\s+/); // Initialize steps array let steps = []; // Process each sentence sentences.forEach((sentence, index) => { // Skip very short sentences if (sentence.trim().length < 5) return; // Check if sentence contains step indicators const hasStepIndicator = /^(\d+\.|\-|\*|first|then|next|finally|lastly|after|before)/i.test(sentence.trim()); // Check if sentence contains action verbs const hasActionVerb = /(check|inspect|remove|install|replace|clean|adjust|tighten|loosen|connect|disconnect|test|verify|ensure|measure)/i.test(sentence); // Determine if this is a step const isStep = hasStepIndicator || hasActionVerb; if (isStep) { // Check for safety warnings const isSafetyWarning = safetyKeywords.warnings.some(keyword => sentence.toLowerCase().includes(keyword.toLowerCase()) ); // Check for prohibitions const isProhibition = safetyKeywords.prohibitions.some(keyword => sentence.toLowerCase().includes(keyword.toLowerCase()) ); // Check for requirements const isRequirement = safetyKeywords.requirements.some(keyword => sentence.toLowerCase().includes(keyword.toLowerCase()) ); // Create step object const step = { id: Date.now() + index, text: sentence.trim(), isCompleted: false, isSafetyWarning, isProhibition, isRequirement, notes: '' }; steps.push(step); } else if (steps.length > 0) { // If not a step but we have previous steps, append to the last step const lastStep = steps[steps.length - 1]; lastStep.text += ' ' + sentence.trim(); } else { // If not a step and no previous steps, create a new step const step = { id: Date.now() + index, text: sentence.trim(), isCompleted: false, isSafetyWarning: false, isProhibition: false, isRequirement: false, notes: '' }; steps.push(step); } }); // If we couldn't extract steps properly, create a single step with the entire solution if (steps.length === 0) { steps = [{ id: Date.now(), text: solutionText.trim(), isCompleted: false, isSafetyWarning: false, isProhibition: false, isRequirement: false, notes: '' }]; } // Add a preparation step if not already present if (!steps.some(step => step.text.toLowerCase().includes('prepare') || step.text.toLowerCase().includes('gather') || step.text.toLowerCase().includes('ensure') )) { steps.unshift({ id: Date.now() - 1, text: 'Prepare all necessary tools and ensure the aircraft is in a safe state for maintenance.', isCompleted: false, isSafetyWarning: true, isProhibition: false, isRequirement: true, notes: '' }); } // Add a verification step if not already present if (!steps.some(step => step.text.toLowerCase().includes('verify') || step.text.toLowerCase().includes('test') || step.text.toLowerCase().includes('check') )) { steps.push({ id: Date.now() + 1000, text: 'Verify the repair by testing the component and ensuring proper operation.', isCompleted: false, isSafetyWarning: false, isProhibition: false, isRequirement: true, notes: '' }); } return steps; }; // Extract tools from text const extractToolsFromText = (text) => { const extractedTools = []; // Check for common tools in the text commonTools.forEach(tool => { if (text.toLowerCase().includes(tool.toLowerCase())) { extractedTools.push({ name: tool, isRequired: true }); } }); // Add some default tools based on the component const component = findComponentForProblem(text); if (component) { if (component.name === 'Propeller Assembly') { if (!extractedTools.some(t => t.name === 'Torque wrench')) { extractedTools.push({ name: 'Torque wrench', isRequired: true }); } } else if (component.name === 'Fuel System') { if (!extractedTools.some(t => t.name === 'Fuel tester')) { extractedTools.push({ name: 'Fuel tester', isRequired: true }); } } else if (component.name === 'Oil System') { if (!extractedTools.some(t => t.name === 'Oil analyzer')) { extractedTools.push({ name: 'Oil analyzer', isRequired: false }); } } } // Always include basic tools if none found if (extractedTools.length === 0) { extractedTools.push({ name: 'Basic tool kit', isRequired: true }); extractedTools.push({ name: 'Inspection tools', isRequired: true }); } return extractedTools; }; // Estimate difficulty based on steps, tools, and text const estimateDifficulty = (steps, tools, text) => { let score = 0; // More steps = higher difficulty score += steps.length * 0.5; // More tools = higher difficulty score += tools.length * 0.7; // Check for complex terms const complexTerms = ['calibrate', 'overhaul', 'rebuild', 'reprogram', 'troubleshoot', 'diagnose']; complexTerms.forEach(term => { if (text.toLowerCase().includes(term)) { score += 2; } }); // Check for safety warnings const safetyCount = steps.filter(step => step.isSafetyWarning).length; score += safetyCount * 1.5; // Map score to difficulty level if (score < 5) return 1; // Easy if (score < 10) return 2; // Moderate if (score < 15) return 3; // Challenging if (score < 20) return 4; // Difficult return 5; // Expert }; // Estimate cost based on tools and text const estimateCost = (tools, text) => { let cost = 0; // Base cost on tools tools.forEach(tool => { if (tool.name.includes('analyzer') || tool.name.includes('tester')) { cost += 2; } else if (tool.name.includes('wrench') || tool.name.includes('gauge')) { cost += 1; } else { cost += 0.5; } }); // Check for terms indicating parts replacement const replacementTerms = ['replace', 'new', 'install', 'part', 'component']; replacementTerms.forEach(term => { if (text.toLowerCase().includes(term)) { cost += 2; } }); // Map cost to cost level if (cost < 3) return 1; // Low if (cost < 6) return 2; // Moderate if (cost < 10) return 3; // High if (cost < 15) return 4; // Very High return 5; // Extremely High }; // Estimate time based on steps and difficulty const estimateTime = (steps, difficulty) => { // Base time on number of steps and difficulty const baseTime = steps.length * 10; // 10 minutes per step const difficultyMultiplier = 1 + (difficulty * 0.2); // Higher difficulty = more time const totalMinutes = baseTime * difficultyMultiplier; // Convert to hours and minutes const hours = Math.floor(totalMinutes / 60); const minutes = Math.round(totalMinutes % 60); return { hours, minutes }; }; // Save checklist to library const saveChecklistToLibrary = (checklist, problemId = null) => { const updatedChecklist = { ...checklist, problemId, updatedAt: new Date().toISOString() }; setChecklistLibrary(prevLibrary => { // Check if checklist already exists const existingIndex = prevLibrary.findIndex(c => c.id === checklist.id); if (existingIndex >= 0) { // Update existing checklist const updatedLibrary = [...prevLibrary]; updatedLibrary[existingIndex] = updatedChecklist; return updatedLibrary; } else { // Add new checklist return [...prevLibrary, updatedChecklist]; } }); setShowChecklistModal(false); alert('Checklist saved to library successfully!'); }; // Handle checklist vote const handleChecklistVote = (checklistId, isUpvote) => { setChecklistLibrary(prevLibrary => { return prevLibrary.map(checklist => { if (checklist.id === checklistId) { const votes = { ...checklist.votes }; if (isUpvote) { votes.upvotes += 1; } else { votes.downvotes += 1; } // Calculate rating (0-5 scale) const totalVotes = votes.upvotes + votes.downvotes; const rating = totalVotes > 0 ? Math.round((votes.upvotes / totalVotes) * 5 * 10) / 10 : 0; return { ...checklist, votes, rating }; } return checklist; }); }); }; // Handle checklist step toggle const handleStepToggle = (stepId) => { if (!currentChecklist) return; setCurrentChecklist(prevChecklist => { const updatedSteps = prevChecklist.steps.map(step => { if (step.id === stepId) { return { ...step, isCompleted: !step.isCompleted }; } return step; }); return { ...prevChecklist, steps: updatedSteps }; }); }; // Handle step reordering const handleStepReorder = (stepId, direction) => { if (!currentChecklist) return; setCurrentChecklist(prevChecklist => { const stepIndex = prevChecklist.steps.findIndex(step => step.id === stepId); if (stepIndex === -1) return prevChecklist; const newSteps = [...prevChecklist.steps]; if (direction === 'up' && stepIndex > 0) { // Move step up [newSteps[stepIndex], newSteps[stepIndex - 1]] = [newSteps[stepIndex - 1], newSteps[stepIndex]]; } else if (direction === 'down' && stepIndex < newSteps.length - 1) { // Move step down [newSteps[stepIndex], newSteps[stepIndex + 1]] = [newSteps[stepIndex + 1], newSteps[stepIndex]]; } return { ...prevChecklist, steps: newSteps }; }); }; // Handle step edit const handleStepEdit = (stepId, newText) => { if (!currentChecklist) return; setCurrentChecklist(prevChecklist => { const updatedSteps = prevChecklist.steps.map(step => { if (step.id === stepId) { return { ...step, text: newText }; } return step; }); return { ...prevChecklist, steps: updatedSteps }; }); }; // Handle step note edit const handleStepNoteEdit = (stepId, newNote) => { if (!currentChecklist) return; setCurrentChecklist(prevChecklist => { const updatedSteps = prevChecklist.steps.map(step => { if (step.id === stepId) { return { ...step, notes: newNote }; } return step; }); return { ...prevChecklist, steps: updatedSteps }; }); }; // Handle add new step const handleAddStep = () => { if (!currentChecklist) return; setCurrentChecklist(prevChecklist => { const newStep = { id: Date.now(), text: '', isCompleted: false, isSafetyWarning: false, isProhibition: false, isRequirement: false, notes: '' }; return { ...prevChecklist, steps: [...prevChecklist.steps, newStep] }; }); }; // Handle delete step const handleDeleteStep = (stepId) => { if (!currentChecklist || !window.confirm('Are you sure you want to delete this step?')) return; setCurrentChecklist(prevChecklist => { const updatedSteps = prevChecklist.steps.filter(step => step.id !== stepId); return { ...prevChecklist, steps: updatedSteps }; }); }; // Handle add tool const handleAddTool = (toolName) => { if (!currentChecklist) return; setCurrentChecklist(prevChecklist => { // Check if tool already exists if (prevChecklist.tools.some(tool => tool.name === toolName)) { return prevChecklist; } const newTool = { name: toolName, isRequired: true }; return { ...prevChecklist, tools: [...prevChecklist.tools, newTool] }; }); }; // Handle remove tool const handleRemoveTool = (toolName) => { if (!currentChecklist) return; setCurrentChecklist(prevChecklist => { const updatedTools = prevChecklist.tools.filter(tool => tool.name !== toolName); return { ...prevChecklist, tools: updatedTools }; }); }; // Handle toggle tool requirement const handleToggleToolRequirement = (toolName) => { if (!currentChecklist) return; setCurrentChecklist(prevChecklist => { const updatedTools = prevChecklist.tools.map(tool => { if (tool.name === toolName) { return { ...tool, isRequired: !tool.isRequired }; } return tool; }); return { ...prevChecklist, tools: updatedTools }; }); }; // Handle checklist title edit const handleChecklistTitleEdit = (newTitle) => { if (!currentChecklist) return; setCurrentChecklist(prevChecklist => { return { ...prevChecklist, title: newTitle }; }); }; // Handle difficulty change const handleDifficultyChange = (newDifficulty) => { if (!currentChecklist) return; setCurrentChecklist(prevChecklist => { return { ...prevChecklist, difficulty: newDifficulty }; }); }; // Handle cost change const handleCostChange = (newCost) => { if (!currentChecklist) return; setCurrentChecklist(prevChecklist => { return { ...prevChecklist, cost: newCost }; }); }; // Handle time estimate change const handleTimeEstimateChange = (hours, minutes) => { if (!currentChecklist) return; setCurrentChecklist(prevChecklist => { return { ...prevChecklist, timeEstimate: { hours, minutes } }; }); }; // Print checklist const printChecklist = () => { if (!currentChecklist) return; // Create a printable version of the checklist const printWindow = window.open('', '_blank'); if (!printWindow) { alert('Please allow pop-ups to print the checklist.'); return; } const componentText = currentChecklist.componentName ? `

Component: ${currentChecklist.componentName}

` : ''; const difficultyText = getDifficultyText(currentChecklist.difficulty); const costText = getCostText(currentChecklist.cost); const timeText = `${currentChecklist.timeEstimate.hours}h ${currentChecklist.timeEstimate.minutes}m`; const toolsHtml = currentChecklist.tools.map(tool => `
  • ${tool.name}${tool.isRequired ? ' (Required)' : ' (Optional)'}
  • ` ).join(''); const stepsHtml = currentChecklist.steps.map(step => { let stepClass = ''; let prefix = ''; if (step.isSafetyWarning) { stepClass = 'safety-warning'; prefix = '⚠️ SAFETY WARNING: '; } else if (step.isProhibition) { stepClass = 'prohibition'; prefix = '🚫 DO NOT: '; } else if (step.isRequirement) { stepClass = 'requirement'; prefix = '✓ REQUIRED: '; } const noteHtml = step.notes ? `

    Note: ${step.notes}

    ` : ''; return `
  • ${prefix}${step.text}
    ${noteHtml}
  • `; }).join(''); printWindow.document.write(` ${currentChecklist.title} - Checklist

    ${currentChecklist.title}

    ${componentText}
    Difficulty: ${difficultyText}
    Cost: ${costText}
    Est. Time: ${timeText}

    Required Tools

    Procedure Steps

      ${stepsHtml}
    `); printWindow.document.close(); }; // Share checklist const shareChecklist = () => { if (!currentChecklist) return; // In a real implementation, this would generate a shareable link or export the checklist // For this example, we'll just copy a JSON representation to the clipboard const shareableData = JSON.stringify(currentChecklist, null, 2); try { navigator.clipboard.writeText(shareableData).then(() => { alert('Checklist data copied to clipboard! You can share this with other users.'); }); } catch (err) { console.error('Failed to copy checklist data:', err); alert('Failed to copy checklist data. Please try again.'); } }; // Get difficulty text const getDifficultyText = (difficulty) => { switch (difficulty) { case 1: return 'Easy'; case 2: return 'Moderate'; case 3: return 'Challenging'; case 4: return 'Difficult'; case 5: return 'Expert'; default: return 'Unknown'; } }; // Get cost text const getCostText = (cost) => { switch (cost) { case 1: return 'Low'; case 2: return 'Moderate'; case 3: return 'High'; case 4: return 'Very High'; case 5: return 'Extremely High'; default: return 'Unknown'; } }; // Simple NLP function to find component based on problem description const findComponentForProblem = (problemText) => { if (!problemText) return null; const text = problemText.toLowerCase(); for (const component of engineComponents) { for (const keyword of component.keywords) { if (text.includes(keyword.toLowerCase())) { return component; } } } return null; }; // Handle form submission const handleSubmit = (e) => { e.preventDefault(); if (!isFormValid) return; // Find component based on problem description or use selected component const detectedComponent = findComponentForProblem(problem) || (selectedComponent ? engineComponents.find(c => c.name === selectedComponent) : null); const newEntry = { id: Date.now(), problem: problem.trim(), solution: solution.trim(), date, jobCardNumber: jobCardNumber.trim(), timestamp: new Date().toISOString(), componentId: detectedComponent ? detectedComponent.id : null, componentName: detectedComponent ? detectedComponent.name : null, // If a suggestion was selected, record which one suggestedSolutionId: selectedSuggestion ? selectedSuggestion.id : null, // If a checklist was created, record its ID checklistId: currentChecklist ? currentChecklist.id : null }; setEntries([newEntry, ...entries]); // If we have a current checklist, save it with this problem if (currentChecklist) { saveChecklistToLibrary(currentChecklist, newEntry.id); } // Reset form setProblem(''); setSolution(''); setDate(''); setJobCardNumber(''); setSelectedComponent(''); setSelectedSuggestion(null); setSolutionSuggestions([]); setCurrentChecklist(null); }; // Delete an entry const deleteEntry = (id) => { if (window.confirm('Are you sure you want to delete this entry?')) { setEntries(entries.filter(entry => entry.id !== id)); } }; // Filter entries based on search term const filteredEntries = entries.filter(entry => entry.problem.toLowerCase().includes(searchTerm.toLowerCase()) || entry.solution.toLowerCase().includes(searchTerm.toLowerCase()) || entry.jobCardNumber.toLowerCase().includes(searchTerm.toLowerCase()) || (entry.componentName && entry.componentName.toLowerCase().includes(searchTerm.toLowerCase())) ); // Filter checklists based on search term const filteredChecklists = checklistLibrary.filter(checklist => checklist.title.toLowerCase().includes(checklistSearchTerm.toLowerCase()) || (checklist.componentName && checklist.componentName.toLowerCase().includes(checklistSearchTerm.toLowerCase())) ); // Sort checklists based on sort criteria const sortedChecklists = [...filteredChecklists].sort((a, b) => { switch (checklistSortBy) { case 'rating': return b.rating - a.rating; case 'newest': return new Date(b.updatedAt) - new Date(a.updatedAt); case 'oldest': return new Date(a.updatedAt) - new Date(b.updatedAt); case 'difficulty-asc': return a.difficulty - b.difficulty; case 'difficulty-desc': return b.difficulty - a.difficulty; case 'usage': return b.usageCount - a.usageCount; default: return b.rating - a.rating; } }); // Format date for display const formatDate = (dateString) => { const options = { year: 'numeric', month: 'short', day: 'numeric' }; return new Date(dateString).toLocaleDateString(undefined, options); }; // Handle engine component click const handleComponentClick = (component) => { setSelectedMapComponent(component); // Filter problems related to this component const relatedProblems = entries.filter(entry => entry.componentId === component.id); setComponentProblems(relatedProblems); }; // Handle admin login const handleAdminLogin = () => { const storedPassword = localStorage.getItem('adminPassword'); if (adminPassword === storedPassword) { setIsAdmin(true); setShowPasswordPrompt(false); setShowAdminPanel(true); setPasswordError(''); } else { setPasswordError('Incorrect password'); } }; // Add or update component const handleSaveComponent = () => { if (!newComponentName.trim() || !newComponentKeywords.trim()) return; const keywordsArray = newComponentKeywords.split(',').map(k => k.trim()); if (editingComponent) { // Update existing component const updatedComponents = engineComponents.map(comp => comp.id === editingComponent.id ? { ...comp, name: newComponentName, keywords: keywordsArray, } : comp ); setEngineComponents(updatedComponents); } else { // Add new component const newComponent = { id: Date.now(), name: newComponentName, keywords: keywordsArray, coordinates: { x1: 100, y1: 100, x2: 150, y2: 150 }, // Default coordinates color: `rgba(${Math.floor(Math.random() * 255)}, ${Math.floor(Math.random() * 255)}, ${Math.floor(Math.random() * 255)}, 0.3)` }; setEngineComponents([...engineComponents, newComponent]); } // Reset form setNewComponentName(''); setNewComponentKeywords(''); setEditingComponent(null); }; // Edit component const handleEditComponent = (component) => { setEditingComponent(component); setNewComponentName(component.name); setNewComponentKeywords(component.keywords.join(', ')); }; // Delete component const handleDeleteComponent = (componentId) => { if (window.confirm('Are you sure you want to delete this component?')) { setEngineComponents(engineComponents.filter(comp => comp.id !== componentId)); // Update entries that were associated with this component const updatedEntries = entries.map(entry => entry.componentId === componentId ? { ...entry, componentId: null, componentName: null } : entry ); setEntries(updatedEntries); } }; // Categorize an uncategorized problem const handleCategorizeProblem = (entry, componentId) => { const component = engineComponents.find(c => c.id === componentId); if (!component) return; const updatedEntries = entries.map(e => e.id === entry.id ? { ...e, componentId: component.id, componentName: component.name } : e ); setEntries(updatedEntries); }; // Add keyword from uncategorized problem const handleAddKeywordFromProblem = (problem, componentId) => { const component = engineComponents.find(c => c.id === componentId); if (!component) return; // Extract potential keywords (words with 4+ characters) const words = problem.toLowerCase().split(/\s+/); const potentialKeywords = words.filter(word => word.length >= 4 && !component.keywords.includes(word)); if (potentialKeywords.length === 0) { alert('No new potential keywords found in this problem description.'); return; } const keyword = window.prompt('Select or enter a keyword to add:', potentialKeywords[0]); if (!keyword || component.keywords.includes(keyword)) return; const updatedComponents = engineComponents.map(c => c.id === componentId ? { ...c, keywords: [...c.keywords, keyword] } : c ); setEngineComponents(updatedComponents); }; // Assign component to problem const handleAssignComponent = (problemId, componentId) => { const component = engineComponents.find(c => c.id === componentId); if (!component) return; const updatedEntries = entries.map(entry => entry.id === problemId ? { ...entry, componentId: component.id, componentName: component.name } : entry ); setEntries(updatedEntries); }; // Get confidence level class based on similarity score const getConfidenceClass = (score) => { if (score >= 0.8) return 'bg-green-100 border-green-500 text-green-800'; if (score >= 0.6) return 'bg-blue-100 border-blue-500 text-blue-800'; if (score >= 0.4) return 'bg-yellow-100 border-yellow-500 text-yellow-800'; return 'bg-gray-100 border-gray-500 text-gray-800'; }; // Get confidence text based on similarity score const getConfidenceText = (score) => { if (score >= 0.8) return 'High Match'; if (score >= 0.6) return 'Good Match'; if (score >= 0.4) return 'Possible Match'; return 'Low Confidence'; }; // View checklist for an entry const viewChecklistForEntry = (entry) => { if (!entry.checklistId) { alert('No checklist associated with this entry.'); return; } const checklist = checklistLibrary.find(c => c.id === entry.checklistId); if (!checklist) { alert('Checklist not found.'); return; } setCurrentChecklist(checklist); setShowChecklistModal(true); }; // Load checklist from library const loadChecklistFromLibrary = (checklistId) => { const checklist = checklistLibrary.find(c => c.id === checklistId); if (!checklist) { alert('Checklist not found.'); return; } // Increment usage count setChecklistLibrary(prevLibrary => { return prevLibrary.map(c => { if (c.id === checklistId) { return { ...c, usageCount: c.usageCount + 1 }; } return c; }); }); setCurrentChecklist({ ...checklist }); setShowChecklistModal(true); setShowChecklistLibrary(false); }; // Render star rating const renderStarRating = (rating) => { const fullStars = Math.floor(rating); const hasHalfStar = rating % 1 >= 0.5; const emptyStars = 5 - fullStars - (hasHalfStar ? 1 : 0); return (
    {[...Array(fullStars)].map((_, i) => ( ))} {hasHalfStar && } {[...Array(emptyStars)].map((_, i) => ( ))} {rating.toFixed(1)}
    ); }; return (
    {/* Header */}
    C130 Aircraft

    C130 Engine Problem Tracker

    Record and track maintenance issues and solutions

    {/* Admin Password Prompt */} {showPasswordPrompt && (

    Admin Login

    setAdminPassword(e.target.value)} className="w-full p-2 border rounded focus:outline-none focus:ring-2 focus:ring-[#205295]" placeholder="Enter admin password" /> {passwordError &&

    {passwordError}

    }
    )} {/* Checklist Library Modal */} {showChecklistLibrary && (

    Checklist Library

    setChecklistSearchTerm(e.target.value)} placeholder="Search checklists..." className="w-full p-2 pl-10 border rounded focus:outline-none focus:ring-2 focus:ring-[#205295]" />
    {sortedChecklists.length === 0 ? (
    {checklistSearchTerm ? 'No matching checklists found' : 'No checklists in the library yet.'}
    ) : (
    {sortedChecklists.map((checklist) => (
    loadChecklistFromLibrary(checklist.id)} >

    {checklist.title}

    {renderStarRating(checklist.rating)}
    {checklist.componentName && (
    {checklist.componentName}
    )}
    {checklist.timeEstimate.hours}h {checklist.timeEstimate.minutes}m
    {getDifficultyText(checklist.difficulty)}
    {getCostText(checklist.cost)}
    {checklist.tools.length} tools
    {checklist.steps.length} steps
    {checklist.votes.upvotes}
    Updated {new Date(checklist.updatedAt).toLocaleDateString()}
    ))}
    )}
    )} {/* Checklist Modal */} {showChecklistModal && currentChecklist && (
    handleChecklistTitleEdit(e.target.value)} className="w-full text-xl font-semibold text-[#144272] border-b border-transparent hover:border-gray-300 focus:border-[#205295] focus:outline-none px-1 py-1" />
    {currentChecklist.componentName && (
    {currentChecklist.componentName}
    )}

    Difficulty

    {getDifficultyText(currentChecklist.difficulty)}

    Cost

    {getCostText(currentChecklist.cost)}

    Time Estimate

    handleTimeEstimateChange(parseInt(e.target.value), currentChecklist.timeEstimate.minutes)} className="w-16 p-1 border rounded focus:outline-none focus:ring-2 focus:ring-[#205295] mr-1" /> h handleTimeEstimateChange(currentChecklist.timeEstimate.hours, parseInt(e.target.value))} className="w-16 p-1 border rounded focus:outline-none focus:ring-2 focus:ring-[#205295] mr-1" /> m

    Required Tools

    {commonTools.map((tool) => ( ))}
    {currentChecklist.tools.map((tool) => (
    {tool.name}
    ))} {currentChecklist.tools.length === 0 && (
    No tools specified. Click "Add Tool" to add tools.
    )}

    Procedure Steps

    {currentChecklist.steps.map((step, index) => (
    handleStepToggle(step.id)} className="h-5 w-5 text-[#205295] rounded focus:ring-[#205295]" />
    Step {index + 1} {step.isSafetyWarning && ( Safety Warning )} {step.isProhibition && ( Do Not Do )} {step.isRequirement && ( Required )}