import React, { useState, useMemo, useEffect, useRef, useCallback, Component, ErrorInfo, ReactNode } from 'react';
import { createRoot } from 'react-dom/client';
import { 
  Settings, Plus, Trash2, Zap, User, Cpu, BarChart3, AlertCircle, Bot, RefreshCcw,
  ChevronRight, ChevronLeft, Gauge, Activity, CheckCircle2, Layers, Flame, Clock,
  Upload, ZoomIn, ZoomOut, Eye, ImageIcon, Search, Filter, FileDown, Copy,
  MoreHorizontal, Folder, Palette, LayoutGrid, Timer, Info, Link as LinkIcon,
  AlertTriangle, Printer, Camera, Share2, Save, Download, Undo, Redo, Edit3,
  Link2, Keyboard, Bell, Moon, X, Layout, Pin, Wrench, Sun, Split, Table as TableIcon,
  GitMerge, ArrowRightLeft, Sparkles, FileSpreadsheet, Unlock, Coins, TrendingUp,
  Scale, ZapOff, Move, Play, Pause, RotateCcw, FastForward, DollarSign, Calculator,
  Target, Circle, Calendar, Siren, FileText, MousePointer2, Hand, Users, PieChart as PieChartIcon, Package,
  Trophy, TrendingDown, Wallet, Radar as RadarIcon, Loader2, MapPin, Home, TimerReset,
  Briefcase
} from 'lucide-react';
import { 
  BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, 
  ReferenceLine, Legend, Cell, LineChart, Line, PieChart, Pie,
  Radar, RadarChart, PolarGrid, PolarAngleAxis, PolarRadiusAxis
} from 'recharts';
import { GoogleGenAI, Type, GenerateContentResponse } from "@google/genai";

// --- Types & Interfaces ---

type WeldingMode = 'MANUAL' | 'ROBOT';
type MaterialType = 'STEEL' | 'STAINLESS' | 'ALUMINUM';
type WeldPosition = string; 
type WeldSide = 'LEFT' | 'RIGHT';

interface WeldGroup {
  id: string;
  name: string;
  color: string;
}

interface WeldSegment {
  id: string;
  name: string;
  length: number; 
  travelSpeed: number; 
  approachTime: number; 
  liftTime: number; 
  position: WeldPosition;
  side: WeldSide;
  groupId: string;
  x?: number; 
  y?: number; 
}

interface WeldConstraint {
  id: string;
  firstWeldId: string;
  secondWeldId: string;
  description: string;
}

interface ScheduleItem {
  type: 'WELD' | 'MOVE' | 'IDLE' | 'SETUP';
  targetId?: string;
  fromId?: string;
  toId?: string;
  startTime: number;
  endTime: number;
  duration: number;
  inConflict?: boolean;
}

interface ProcessResult {
  id: number;
  weldIds: string[];
  cycleTime: number;
  side: WeldSide | 'MIXED'; 
  distanceTravelled?: number;
  timeline: ScheduleItem[];
}

interface ModelData {
  id: string;
  name: string;
  segments: WeldSegment[];
  weldGroups: WeldGroup[];
  constraints: WeldConstraint[];
  manualOverrides?: Record<string, number>;
  // Frame View Data (Per Model)
  frameImage?: string | null;
  frameWidthMM?: number;
  robotBases?: { left: { x: number; y: number }; right: { x: number; y: number } };
}

interface RobotSettings {
  moveSpeed: number; // m/s (Air cut speed)
  toolChangeTime: number;
  fixtureRotationTime: number;
  includeMovementTime: boolean;
  optimizePath: boolean;
  includeReturnHome: boolean;
  useFixedHomeTimes: boolean; // New: Toggle for fixed times
  fixedApproachTime: number;  // New: Home -> First Weld
  fixedReturnTime: number;    // New: Last Weld -> Home
  maxReach: number;
  interferenceZoneMinX: number;
  interferenceZoneMaxX: number;
  arcDelay: number;        
  avgMoveDist: number;     
  cleaningInterval: number;
  cleaningTime: number;    
}

interface ManualSettings {
  handlingTime: number;      // General handling (Pick torch, mask) per cycle
  jigRotationTime: number;   // Time to rotate Jig once
  jigRotationsPerCycle: number; // How many times jig is rotated
  efficiencyFactor: number;  // 1.0 = 100%, 0.9 = 90% performance
}

interface CostSettings {
  wirePricePerKg: number;
  gasPricePerLiter: number;
  electricPricePerKw: number;
  wireDiameter: number; 
  gasFlowRate: number; 
  powerSourceKw: number; 
  wireFeedSpeed: number; 
}

interface ROISettings {
  manualHourlyWage: number;
  operatorsPerShift: number;
  shiftsPerDay: number;
  daysPerMonth: number;
  robotSystemCost: number;
  robotMaintenanceYearly: number;
}

interface WeldPositionDefinition {
  id: string;
  label: string;
  factor: number; 
}

interface ModelStats {
  modelId: string;
  modelName: string;
  totalSegments: number;
  totalTime: number;
  processes: ProcessResult[];
  maxCycleTime: number;
  efficiency: number;
  isBalanced: boolean;
  totalCost?: number; 
  collisionDetected?: boolean;
}

// --- Constants ---

const MATERIAL_PRESETS = {
  STEEL: { manual: 6, robot: 15 },
  STAINLESS: { manual: 5, robot: 12 },
  ALUMINUM: { manual: 8, robot: 20 },
};

const DEFAULT_GROUPS: WeldGroup[] = [
  { id: 'G1', name: 'Main Rails (คานหลัก)', color: '#3b82f6' },
  { id: 'G2', name: 'Cross Members (คานขวาง)', color: '#10b981' },
  { id: 'G3', name: 'Brackets (ขายึด)', color: '#f59e0b' },
];

const PRESET_COLORS = [
  '#3b82f6', '#10b981', '#f59e0b', '#ef4444', '#8b5cf6', '#ec4899', '#06b6d4', '#6366f1'
];

const DEFAULT_POSITIONS: WeldPositionDefinition[] = [
  { id: 'FLAT', label: 'ท่าราบ (Flat 1F)', factor: 0.06 },
  { id: 'HORIZONTAL', label: 'ท่าขนานนอน (Horz 2F)', factor: 0.07 },
  { id: 'VERTICAL', label: 'ท่าตั้ง (Vert 3F)', factor: 0.08 },
  { id: 'OVERHEAD', label: 'ท่าเหนือศีรษะ (Over 4F)', factor: 0.10 }
];

const DEFAULT_ROBOT_BASES = { left: { x: 5, y: 50 }, right: { x: 95, y: 50 } };
const DEFAULT_FRAME_WIDTH = 2000;

// --- Sub-Components ---

// Simulation Visualizer Component
interface SimulationVisualizerProps {
  showPathFlow: boolean;
  currentStats: ModelStats;
  segments: WeldSegment[];
  robotBases: { left: { x: number; y: number }; right: { x: number; y: number } };
  simTime: number;
  frameWidthMM: number;
  robotSettings: RobotSettings;
  showReachZones: boolean;
  showInterferenceZone: boolean;
  isCollisionNow: boolean;
}

const SimulationVisualizer: React.FC<SimulationVisualizerProps> = ({
  showPathFlow,
  currentStats,
  segments,
  robotBases,
  simTime,
  frameWidthMM,
  robotSettings,
  showReachZones,
  showInterferenceZone,
  isCollisionNow
}) => {
  return (
    <svg className="absolute inset-0 w-full h-full pointer-events-none z-0">
      <defs>
        {PRESET_COLORS.map((color, i) => (
          <marker key={i} id={`arrow-${i}`} markerWidth="6" markerHeight="6" refX="5" refY="3" orient="auto" markerUnits="strokeWidth"><path d="M0,0 L0,6 L6,3 z" fill={color} /></marker>
        ))}
        <pattern id="hazardPattern" width="10" height="10" patternUnits="userSpaceOnUse" patternTransform="rotate(45)">
          <rect width="5" height="10" fill="#f59e0b" opacity="0.3"/>
        </pattern>
      </defs>
      
      {/* Robot Reach Zones */}
      {showReachZones && (
        <>
          <circle 
            cx={`${robotBases.left.x}%`} cy={`${robotBases.left.y}%`} 
            r={(robotSettings.maxReach / frameWidthMM) * 100 + "%"} 
            fill="rgba(59, 130, 246, 0.1)" stroke="rgba(59, 130, 246, 0.4)" strokeWidth="1" strokeDasharray="4 4"
          />
          <circle 
            cx={`${robotBases.right.x}%`} cy={`${robotBases.right.y}%`} 
            r={(robotSettings.maxReach / frameWidthMM) * 100 + "%"} 
            fill="rgba(244, 63, 94, 0.1)" stroke="rgba(244, 63, 94, 0.4)" strokeWidth="1" strokeDasharray="4 4"
          />
        </>
      )}

      {/* Interference Zone */}
      {showInterferenceZone && (
          <rect 
            x={`${robotSettings.interferenceZoneMinX}%`} 
            y="0" 
            width={`${robotSettings.interferenceZoneMaxX - robotSettings.interferenceZoneMinX}%`} 
            height="100%"
            fill="url(#hazardPattern)"
            stroke="none"
            className={isCollisionNow ? "flash-collision" : ""}
          />
      )}

      {/* Simulation Move Lines */}
      {showPathFlow && currentStats.processes.map((proc, pIdx) => {
          const pathColor = PRESET_COLORS[pIdx % PRESET_COLORS.length];
          return proc.timeline.map((item, idx) => {
              if (item.type === 'MOVE' && item.toId) {
                  const sideKey = proc.side === 'RIGHT' ? 'right' : 'left';
                  const baseCoords = robotBases[sideKey];
                  
                  let x1: number | undefined, y1: number | undefined;
                  let x2: number | undefined, y2: number | undefined;

                  // Determine Start Point
                  if (item.fromId === 'START') {
                      x1 = baseCoords.x;
                      y1 = baseCoords.y;
                  } else {
                      const fromSeg = segments.find(s => s.id === item.fromId);
                      x1 = fromSeg?.x;
                      y1 = fromSeg?.y;
                  }

                  // Determine End Point
                  if (item.toId === 'HOME') {
                      x2 = baseCoords.x;
                      y2 = baseCoords.y;
                  } else {
                      const toSeg = segments.find(s => s.id === item.toId);
                      x2 = toSeg?.x;
                      y2 = toSeg?.y;
                  }

                  const isMovingNow = simTime >= item.startTime && simTime <= item.endTime;
                  
                  if (x1 !== undefined && y1 !== undefined && x2 !== undefined && y2 !== undefined) {
                      return (
                          <line 
                              key={`move-${pIdx}-${idx}`}
                              x1={`${x1}%`} y1={`${y1}%`}
                              x2={`${x2}%`} y2={`${y2}%`}
                              stroke={isMovingNow ? '#f59e0b' : pathColor}
                              strokeWidth={isMovingNow ? "4" : "2"}
                              strokeDasharray={isMovingNow ? "4 4" : "6 4"}
                              className={isMovingNow ? "path-flow-line" : ""}
                              opacity={isMovingNow ? "1" : "0.3"}
                              markerEnd={`url(#arrow-${pIdx % PRESET_COLORS.length})`}
                          />
                      );
                  }
              }
              return null;
          });
      })}
    </svg>
  );
};


// Error Boundary
interface ErrorBoundaryProps {
  children?: ReactNode;
}

interface ErrorBoundaryState {
  hasError: boolean;
  error: Error | null;
}

class ErrorBoundary extends Component<ErrorBoundaryProps, ErrorBoundaryState> {
  state: ErrorBoundaryState = {
    hasError: false,
    error: null
  };

  static getDerivedStateFromError(error: Error): ErrorBoundaryState {
    return { hasError: true, error };
  }

  componentDidCatch(error: Error, errorInfo: ErrorInfo) {
    console.error("ErrorBoundary caught an error", error, errorInfo);
  }

  render() {
    if (this.state.hasError) {
      return (
        <div className="p-8 bg-red-50 text-red-900 h-screen flex flex-col items-center justify-center">
          <div className="bg-white p-6 rounded-xl shadow-xl max-w-2xl w-full border border-red-100">
             <h2 className="text-2xl font-bold mb-4 flex items-center gap-2 text-red-600"><AlertTriangle /> Application Error</h2>
             <p className="mb-4 text-slate-700">โปรแกรมพบข้อผิดพลาดที่ไม่คาดคิด (An unexpected error occurred).</p>
             <div className="bg-slate-900 text-slate-100 p-4 rounded-lg overflow-auto text-xs font-mono mb-4">
                {this.state.error?.message}
             </div>
             <button onClick={() => window.location.reload()} className="px-4 py-2 bg-red-600 text-white rounded-lg font-bold hover:bg-red-700">
                Reload Page
             </button>
          </div>
        </div>
      );
    }
    return this.props.children;
  }
}

// --- Main App Component ---

const App = () => {
  // Global State
  const [projectName, setProjectName] = useState("Chassis Project 1");
  const [mode, setMode] = useState<WeldingMode>('MANUAL');
  const [material, setMaterial] = useState<MaterialType>('STEEL');
  const [taktTime, setTaktTime] = useState(180);
  const [targetProcessMode, setTargetProcessMode] = useState("AUTO");
  
  // Fixed Robot Counts
  const [fixedRobotsLeft, setFixedRobotsLeft] = useState(1);
  const [fixedRobotsRight, setFixedRobotsRight] = useState(1);
  
  // Balancing Strategy State
  const [separateSides, setSeparateSides] = useState(true);
  const [balancingAlgo, setBalancingAlgo] = useState<'SEQUENTIAL' | 'LPT'>('SEQUENTIAL'); 

  // World Class Features State
  const [costSettings, setCostSettings] = useState<CostSettings>({
    wirePricePerKg: 45,
    gasPricePerLiter: 0.5,
    electricPricePerKw: 4.5,
    wireDiameter: 1.2,
    gasFlowRate: 15,
    powerSourceKw: 6,
    wireFeedSpeed: 8
  });
  
  // ROI & Financials
  const [roiSettings, setRoiSettings] = useState<ROISettings>({
    manualHourlyWage: 350,
    operatorsPerShift: 2,
    shiftsPerDay: 2,
    daysPerMonth: 24,
    robotSystemCost: 3500000,
    robotMaintenanceYearly: 50000
  });

  const [showReachZones, setShowReachZones] = useState(true);
  const [showInterferenceZone, setShowInterferenceZone] = useState(true);

  // Dynamic Positions State
  const [weldPositions, setWeldPositions] = useState<WeldPositionDefinition[]>(DEFAULT_POSITIONS);

  // Robot Settings State
  const [robotSettings, setRobotSettings] = useState<RobotSettings>({
    moveSpeed: 2,        
    toolChangeTime: 5,   
    fixtureRotationTime: 8, 
    includeMovementTime: true,
    optimizePath: true,
    includeReturnHome: true, // Default to true
    useFixedHomeTimes: false, // Default to false (calculate)
    fixedApproachTime: 3.0,
    fixedReturnTime: 3.0,
    maxReach: 1800, // mm
    interferenceZoneMinX: 40, // %
    interferenceZoneMaxX: 60, // %
    arcDelay: 0.8,       
    avgMoveDist: 200,    
    cleaningInterval: 20,
    cleaningTime: 6      
  });

  // Manual Settings State
  const [manualSettings, setManualSettings] = useState<ManualSettings>({
    handlingTime: 5, // Pickup torch, mask, start
    jigRotationTime: 10, 
    jigRotationsPerCycle: 0,
    efficiencyFactor: 1.0 // 100%
  });

  // Models State
  const [models, setModels] = useState<ModelData[]>([{
    id: 'm1',
    name: 'Base Model',
    segments: [
      { id: 'W001', name: 'Main Frame L', length: 150, travelSpeed: 6, approachTime: 3, liftTime: 0.5, position: 'FLAT', side: 'LEFT', groupId: 'G1', x: 20, y: 30 },
      { id: 'W002', name: 'Main Frame R', length: 150, travelSpeed: 6, approachTime: 3, liftTime: 0.5, position: 'FLAT', side: 'RIGHT', groupId: 'G1', x: 60, y: 30 },
      { id: 'W003', name: 'Cross Bar A', length: 80, travelSpeed: 6, approachTime: 3, liftTime: 0.5, position: 'HORIZONTAL', side: 'LEFT', groupId: 'G2', x: 40, y: 30 },
      { id: 'W004', name: 'Cross Bar B', length: 80, travelSpeed: 6, approachTime: 3, liftTime: 0.5, position: 'HORIZONTAL', side: 'RIGHT', groupId: 'G2', x: 40, y: 60 },
    ],
    weldGroups: DEFAULT_GROUPS,
    constraints: [],
    manualOverrides: {},
    frameWidthMM: 2000,
    robotBases: DEFAULT_ROBOT_BASES,
    frameImage: null
  }]);
  
  // History State
  const [history, setHistory] = useState<{past: ModelData[][], future: ModelData[][]}>({ past: [], future: [] });

  const [activeModelId, setActiveModelId] = useState<string>('m1');

  // Modals
  const [showAddModal, setShowAddModal] = useState(false);
  const [newModelName, setNewModelName] = useState('');
  const [copyFromId, setCopyFromId] = useState('EMPTY');
  const [showOverview, setShowOverview] = useState(false);
  const [showAIModal, setShowAIModal] = useState(false);
  const [showRobotSettingsModal, setShowRobotSettingsModal] = useState(false);
  const [showManualSettingsModal, setShowManualSettingsModal] = useState(false);
  const [aiPrompt, setAiPrompt] = useState('');
  const [isAiLoading, setIsAiLoading] = useState(false);
  
  // UI State
  const [activeTab, setActiveTab] = useState<'FRAME_VIEW' | 'WELD_LIST' | 'GROUPS' | 'STANDARD_TIMES' | 'CONSTRAINTS' | 'RESULTS'>('WELD_LIST');
  const [isDarkMode, setIsDarkMode] = useState(false);
  const [showPathFlow, setShowPathFlow] = useState(true);

  // Manual Balance UI State
  const [isManualBalanceMode, setIsManualBalanceMode] = useState(false);
  const [selectedManualProcess, setSelectedManualProcess] = useState(0); // 0-based index
  const [isDragMode, setIsDragMode] = useState(false); // For Yamazumi Drag & Drop

  // Simulation State
  const [simTime, setSimTime] = useState(0);
  const [isPlaying, setIsPlaying] = useState(false);
  const [simSpeed, setSimSpeed] = useState(1);
  const animationFrameRef = useRef<number>();

  // Balancing Results State
  const [processes, setProcesses] = useState<ProcessResult[]>([]);
  const [isBalanced, setIsBalanced] = useState(true);
  const [totalCost, setTotalCost] = useState(0);
  const [hasCollision, setHasCollision] = useState(false);

  // Visual Reference State (Now derived from Active Model)
  const [zoomLevel, setZoomLevel] = useState(100);
  const [draggingId, setDraggingId] = useState<string | null>(null);
  const [draggingBase, setDraggingBase] = useState<'left'|'right'|null>(null); 

  const fileInputRef = useRef<HTMLInputElement>(null);
  const loadFileInputRef = useRef<HTMLInputElement>(null);
  const imageContainerRef = useRef<HTMLDivElement>(null);
  const projectNameInputRef = useRef<HTMLInputElement>(null);
  const balAlgoRef = useRef(balancingAlgo);
  
  // List Filters
  const [selectedSegmentId, setSelectedSegmentId] = useState<string | null>(null);

  // --- Computed Properties ---
  const activeModel = useMemo(() => models.find(m => m.id === activeModelId) || models[0], [models, activeModelId]);
  const segments = activeModel.segments;
  const weldGroups = activeModel.weldGroups;
  const constraints = activeModel.constraints;
  
  // Derive visual properties from activeModel with fallbacks
  const frameImage = activeModel.frameImage || null;
  const frameWidthMM = activeModel.frameWidthMM || DEFAULT_FRAME_WIDTH;
  const robotBases = activeModel.robotBases || DEFAULT_ROBOT_BASES;

  const calculateSegmentTime = useCallback((s: WeldSegment) => {
    // FIX: Safer calculation to prevent NaN
    const speed = s.travelSpeed > 0 ? s.travelSpeed : 1; 
    const weldTime = s.length / speed;
    const lift = s.liftTime || 0;
    if (mode === 'MANUAL') {
      return Number((weldTime + s.approachTime + lift).toFixed(1));
    } else {
      const moveSpeedMM = robotSettings.moveSpeed * 1000;
      const safeMoveSpeed = moveSpeedMM > 0 ? moveSpeedMM : 2000;
      const moveTime = robotSettings.includeMovementTime 
         ? (robotSettings.avgMoveDist / safeMoveSpeed) * (robotSettings.optimizePath ? 0.8 : 1.0)
         : 0;
      const techTime = robotSettings.arcDelay;
      const cleaningFactor = robotSettings.cleaningTime / (robotSettings.cleaningInterval || 1);
      return Number((weldTime + moveTime + techTime + cleaningFactor + lift).toFixed(1));
    }
  }, [mode, robotSettings]);

  // --- UNDO / REDO ---
  const pushHistory = (currentModels: ModelData[]) => {
    setHistory(prev => {
       const newPast = [...prev.past, currentModels];
       const trimmedPast = newPast.length > 20 ? newPast.slice(newPast.length - 20) : newPast;
       return {
         past: trimmedPast,
         future: []
       };
    });
  };

  const undo = useCallback(() => {
    if (history.past.length === 0) return;
    const previous = history.past[history.past.length - 1];
    const newPast = history.past.slice(0, -1);
    setHistory({ past: newPast, future: [models, ...history.future] });
    setModels(previous);
  }, [history, models]);

  const redo = useCallback(() => {
    if (history.future.length === 0) return;
    const next = history.future[0];
    const newFuture = history.future.slice(1);
    setHistory({ past: [...history.past, models], future: newFuture });
    setModels(next);
  }, [history, models]);

  const handleModelUpdate = (newModels: ModelData[]) => {
     pushHistory(models); 
     setModels(newModels);
  };

  // --- SAVE / LOAD ---
  const handleSaveProject = async () => {
    const projectData = {
      version: "2.0", // Bump for new structure
      timestamp: new Date().toISOString(),
      projectName, mode, material, taktTime, targetProcessMode,
      fixedRobotsLeft, fixedRobotsRight, separateSides, weldPositions,
      robotSettings, manualSettings, costSettings, roiSettings, models
    };
    const suggestedName = `${projectName.replace(/[^a-z0-9]/gi, '_').toLowerCase()}_${new Date().toISOString().slice(0,10)}.json`;
    if ('showSaveFilePicker' in window) {
       try {
          const handle = await (window as any).showSaveFilePicker({
             suggestedName: suggestedName,
             types: [{ description: 'JSON Project File', accept: { 'application/json': ['.json'] } }],
          });
          // Ensure we pass arguments if required by user's setup, though {} is correct for File System Access API
          const writable = await handle.createWritable({});
          await writable.write(JSON.stringify(projectData, null, 2));
          await (writable as any).close();
          alert("บันทึกโปรเจคสำเร็จ (Project Saved Successfully - Images Included)");
          return;
       } catch (err: any) {
          if (err.name === 'AbortError') return; 
          console.error("FS API failed", err);
       }
    }
    const blob = new Blob([JSON.stringify(projectData, null, 2)], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url; a.download = suggestedName; document.body.appendChild(a); a.click(); document.body.removeChild(a);
    URL.revokeObjectURL(url);
    alert("บันทึกโปรเจคลงในโฟลเดอร์ Downloads สำเร็จ (พร้อมรูปภาพ)");
  };

  const handleExportCSV = () => {
     const headers = "ID,Name,Side,Length(mm),Position,Est.Time(s),Group,LiftTime(s)\n";
     const rows = segments.map(s => 
        `${s.id},"${s.name}",${s.side},${s.length},${s.position},${calculateSegmentTime(s)},${s.groupId},${s.liftTime||0}`
     ).join("\n");
     const csvContent = "data:text/csv;charset=utf-8," + headers + rows;
     const encodedUri = encodeURI(csvContent);
     const link = document.createElement("a");
     link.setAttribute("href", encodedUri);
     link.setAttribute("download", `${projectName}_weld_data.csv`);
     document.body.appendChild(link);
     link.click();
     document.body.removeChild(link);
  };

  const handleLoadClick = () => loadFileInputRef.current?.click();

  const handleFileLoad = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;
    const reader = new FileReader();
    reader.onload = (event: ProgressEvent<FileReader>) => {
        try {
            const json = JSON.parse(event.target?.result as string);
            if (!json.models || !Array.isArray(json.models)) throw new Error("Invalid project file");
            if (json.projectName) setProjectName(json.projectName);
            if (json.mode) setMode(json.mode);
            if (json.material) setMaterial(json.material);
            if (json.taktTime) setTaktTime(json.taktTime);
            if (json.targetProcessMode) setTargetProcessMode(json.targetProcessMode);
            if (json.fixedRobotsLeft !== undefined) setFixedRobotsLeft(json.fixedRobotsLeft);
            if (json.fixedRobotsRight !== undefined) setFixedRobotsRight(json.fixedRobotsRight);
            if (json.separateSides !== undefined) setSeparateSides(json.separateSides);
            if (json.weldPositions) setWeldPositions(json.weldPositions);
            if (json.robotSettings) setRobotSettings(json.robotSettings);
            if (json.manualSettings) setManualSettings(json.manualSettings);
            if (json.costSettings) setCostSettings(json.costSettings);
            if (json.roiSettings) setRoiSettings(json.roiSettings);
            
            // Backward compatibility for old saves where frameWidth/bases were global
            const loadedModels = json.models.map((m: any) => ({
                ...m,
                frameWidthMM: m.frameWidthMM || json.frameWidthMM || DEFAULT_FRAME_WIDTH,
                robotBases: m.robotBases || json.robotBases || DEFAULT_ROBOT_BASES,
                frameImage: m.frameImage || null // Images are now model specific
            }));

            pushHistory(models); 
            setModels(loadedModels);
            setActiveModelId(loadedModels[0]?.id || '');
            alert(`โหลดโปรเจค "${json.projectName || 'Unknown'}" สำเร็จ`);
        } catch (err) { console.error(err); alert("Error loading file."); }
    };
    reader.readAsText(file);
    e.target.value = '';
  };

  const toggleDarkMode = () => setIsDarkMode(!isDarkMode);
  
  const getDefaultSpeed = useCallback(() => {
    return mode === 'MANUAL' ? MATERIAL_PRESETS[material].manual : MATERIAL_PRESETS[material].robot;
  }, [mode, material]);

  // --- AI ---
  const handleAIGenerate = async (e?: any) => {
     if (!aiPrompt || !aiPrompt.trim()) return;
     
     setIsAiLoading(true);
     try {
        const ai = new GoogleGenAI({ apiKey: process.env.API_KEY });
        const response = await ai.models.generateContent({
            model: 'gemini-3-flash-preview',
            contents: {
              parts: [{ text: `Extract welding data from text: "${aiPrompt}"` }]
            },
            config: {
                responseMimeType: "application/json",
                responseSchema: {
                    type: Type.ARRAY,
                    items: {
                        type: Type.OBJECT,
                        properties: {
                            name: { type: Type.STRING },
                            length: { type: Type.NUMBER },
                            side: { type: Type.STRING },
                            position: { type: Type.STRING },
                        },
                        propertyOrdering: ["name", "length", "side", "position"],
                    }
                }
            }
        });
        const responseText = response.text;
        if (!responseText) throw new Error("No response text received");
        
        const parsedData = JSON.parse(responseText);
        const currentDefaultSpeed = mode === 'MANUAL' ? MATERIAL_PRESETS[material].manual : MATERIAL_PRESETS[material].robot;

        const newSegments = parsedData.map((item: any, idx: number) => {
           // Calculate max ID to prevent duplicates from AI generation too
           const maxIdNum = segments.reduce((max, s) => {
               const match = s.id.match(/^W(\d+)$/);
               return match ? Math.max(max, parseInt(match[1], 10)) : max;
           }, 0);
           const idNum = maxIdNum + 1 + idx;
           
           const posDef = weldPositions.find(p => p.id === item.position) || weldPositions[0];
           const stdTime = posDef.factor;
           const speed = stdTime > 0 ? 1 / stdTime : currentDefaultSpeed;
           return {
              id: `W${idNum.toString().padStart(3, '0')}`,
              name: item.name || `Weld ${idNum}`,
              length: Number(item.length) || 100,
              travelSpeed: speed,
              approachTime: mode === 'MANUAL' ? 5 : 2,
              liftTime: 0.5,
              position: posDef.id,
              side: ['LEFT', 'RIGHT'].includes(item.side) ? item.side : 'LEFT',
              groupId: '',
           };
        });
        setSegments([...segments, ...newSegments]);
        setShowAIModal(false); setAiPrompt('');
     } catch (error: any) { alert("AI Generation failed: " + error.message); } finally { setIsAiLoading(false); }
  };

  // --- Wrapper Setters ---
  const setSegments = (newVal: WeldSegment[] | ((prev: WeldSegment[]) => WeldSegment[])) => {
    const updatedModels = models.map(m => {
      if (m.id === activeModelId) {
        const updatedSegments = typeof newVal === 'function' ? newVal(m.segments) : newVal;
        return { ...m, segments: updatedSegments };
      }
      return m;
    });
    handleModelUpdate(updatedModels);
  };
  const setWeldGroups = (newVal: WeldGroup[] | ((prev: WeldGroup[]) => WeldGroup[])) => {
    const updatedModels = models.map(m => { if (m.id === activeModelId) { const updated = typeof newVal === 'function' ? newVal(m.weldGroups) : newVal; return { ...m, weldGroups: updated }; } return m; }); handleModelUpdate(updatedModels);
  };
  const setConstraints = (newVal: WeldConstraint[] | ((prev: WeldConstraint[]) => WeldConstraint[])) => {
    const updatedModels = models.map(m => { if (m.id === activeModelId) { const updated = typeof newVal === 'function' ? newVal(m.constraints) : newVal; return { ...m, constraints: updated }; } return m; }); handleModelUpdate(updatedModels);
  };
  const setManualOverrides = (newOverrides: Record<string, number>) => {
    const updatedModels = models.map(m => { if (m.id === activeModelId) { return { ...m, manualOverrides: newOverrides }; } return m; }); handleModelUpdate(updatedModels);
  };
  const setFrameWidthMM = (val: number) => {
    const updatedModels = models.map(m => m.id === activeModelId ? { ...m, frameWidthMM: val } : m);
    setModels(updatedModels); // No history push for typing? Or maybe push. Let's not push on every keystroke, handle elsewhere or use blur. For now simple set.
  };
  const setRobotBases = (val: {left: {x:number, y:number}, right: {x:number, y:number}} | ((prev: {left: {x:number, y:number}, right: {x:number, y:number}}) => {left: {x:number, y:number}, right: {x:number, y:number}})) => {
      const updatedModels = models.map(m => {
          if (m.id === activeModelId) {
              const currentBases = m.robotBases || DEFAULT_ROBOT_BASES;
              const newBases = typeof val === 'function' ? val(currentBases) : val;
              return { ...m, robotBases: newBases };
          }
          return m;
      });
      setModels(updatedModels);
  };

  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 'z') { e.preventDefault(); e.shiftKey ? redo() : undo(); }
      else if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 'y') { e.preventDefault(); redo(); }
      else if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 's') { e.preventDefault(); handleSaveProject(); }
    };
    window.addEventListener('keydown', handleKeyDown);
    return () => window.removeEventListener('keydown', handleKeyDown);
  }, [undo, redo, projectName, models, weldPositions, robotSettings, costSettings, frameWidthMM]); 

  // --- Core Logic: Balancing Calculator with Timeline ---
  const calculateBalancingForModel = useCallback((model: ModelData): ModelStats => {
    const modelWidthMM = model.frameWidthMM || DEFAULT_FRAME_WIDTH;
    const modelBases = model.robotBases || DEFAULT_ROBOT_BASES;
    
    const adj = new Map<string, string[]>();
    const inDegree = new Map<string, number>();
    const predecessors = new Map<string, string[]>();
    model.segments.forEach(s => { adj.set(s.id, []); inDegree.set(s.id, 0); predecessors.set(s.id, []); });
    model.constraints.forEach(c => {
      if (model.segments.some(s => s.id === c.firstWeldId) && model.segments.some(s => s.id === c.secondWeldId)) {
        adj.get(c.firstWeldId)?.push(c.secondWeldId);
        inDegree.set(c.secondWeldId, (inDegree.get(c.secondWeldId) || 0) + 1);
        predecessors.get(c.secondWeldId)?.push(c.firstWeldId);
      }
    });
    const queue: string[] = [];
    inDegree.forEach((val, key) => { if (val === 0) queue.push(key); });
    
    const sortQueue = (q: string[]) => {
       if (balAlgoRef.current === 'LPT') {
          q.sort((a, b) => {
             const segA = model.segments.find(s => s.id === a); const segB = model.segments.find(s => s.id === b);
             const timeA = segA ? segA.length/segA.travelSpeed : 0; const timeB = segB ? segB.length/segB.travelSpeed : 0;
             return timeB - timeA; 
          });
       } else { q.sort(); }
    };
    if (balancingAlgo === 'LPT') sortQueue(queue); else queue.sort();

    const sortedIds: string[] = [];
    const tempInDegree = new Map(inDegree); const tempAdj = adj; 
    while (queue.length > 0) {
      const u = queue.shift()!; sortedIds.push(u);
      tempAdj.get(u)?.forEach(v => { tempInDegree.set(v, (tempInDegree.get(v) || 0) - 1); if (tempInDegree.get(v) === 0) queue.push(v); });
      if (balancingAlgo === 'LPT') sortQueue(queue); else queue.sort();
    }
    model.segments.forEach(s => { if (!sortedIds.includes(s.id)) sortedIds.push(s.id); });

    const newProcesses: ProcessResult[] = [];
    const taskProcessMap = new Map<string, number>(); 
    const processLastPos = new Map<number, {x: number, y: number}>();
    
    let totalTime = 0;
    let totalCost = 0;
    const manualOverrides = model.manualOverrides || {};
    let limitLeft = taktTime; let limitRight = taktTime; let limitGlobal = taktTime;

    if (targetProcessMode === 'FIXED') {
        const segsLeft = model.segments.filter(s => s.side === 'LEFT'); const segsRight = model.segments.filter(s => s.side === 'RIGHT');
        const sumLeft = segsLeft.reduce((acc, s) => acc + calculateSegmentTime(s), 0);
        const sumRight = segsRight.reduce((acc, s) => acc + calculateSegmentTime(s), 0);
        
        if (separateSides) {
            limitLeft = fixedRobotsLeft > 0 ? Math.max(taktTime, (sumLeft / fixedRobotsLeft) * 1.1) : taktTime; 
            limitRight = fixedRobotsRight > 0 ? Math.max(taktTime, (sumRight / fixedRobotsRight) * 1.1) : taktTime;
        } else {
             const totalSum = sumLeft + sumRight; 
             const totalCount = fixedRobotsLeft + fixedRobotsRight; 
             limitGlobal = totalCount > 0 ? Math.max(taktTime, (totalSum / totalCount) * 1.1) : taktTime;
        }
    }

    // Setup Overhead Calculation
    // For Robot: Tool Change + Fixture Rotation
    // For Manual: Handling Time (Torch pick up) + (Jig Rotation Time * Rotations)
    let overhead = 0;
    if (mode === 'ROBOT') {
        overhead = robotSettings.toolChangeTime + robotSettings.fixtureRotationTime;
    } else {
        overhead = manualSettings.handlingTime + (manualSettings.jigRotationTime * manualSettings.jigRotationsPerCycle);
    }

    sortedIds.forEach(id => {
      const seg = model.segments.find(s => s.id === id);
      if (!seg) return;
      
      const weldTime = seg.length / seg.travelSpeed;
      const techTime = mode === 'MANUAL' ? seg.approachTime : (robotSettings.arcDelay + (robotSettings.cleaningTime / robotSettings.cleaningInterval));
      const liftTime = seg.liftTime || 0;
      const basicTime = weldTime + techTime + liftTime;

      // Cost
      const wireWeightKg = (seg.length / 1000) * (Math.pow(costSettings.wireDiameter/2, 2) * Math.PI * 7.85 / 1000); 
      const gasUsageL = (weldTime / 60) * costSettings.gasFlowRate;
      const powerUsageKwh = (costSettings.powerSourceKw * (weldTime / 3600));
      totalCost += ((wireWeightKg * costSettings.wirePricePerKg) + (gasUsageL * costSettings.gasPricePerLiter) + (powerUsageKwh * costSettings.electricPricePerKw));

      const forcedProcessIdx = manualOverrides[id];
      const preds = predecessors.get(id) || [];
      let minProcIndex = 0;
      for (const pId of preds) { const pIdx = taskProcessMap.get(pId); if (pIdx !== undefined) minProcIndex = Math.max(minProcIndex, pIdx); }

      let assignedIdx = -1;

      // Fit Function
      const tryAssign = (procIdx: number): boolean => {
          const proc = newProcesses[procIdx];
          let moveTime = 0;
          let distTravelled = 0;

          // Calculate Move Time
          if (mode === 'ROBOT' && robotSettings.includeMovementTime) {
              const moveSpeedMM = robotSettings.moveSpeed * 1000;
              const safeMoveSpeed = moveSpeedMM > 0 ? moveSpeedMM : 1000; // prevent divide by zero
              const lastPos = processLastPos.get(procIdx);
              if (lastPos && seg.x !== undefined && seg.y !== undefined) {
                  const distPct = Math.sqrt(Math.pow(seg.x - lastPos.x, 2) + Math.pow(seg.y - lastPos.y, 2));
                  const distMM = (distPct / 100) * modelWidthMM;
                  moveTime = distMM / safeMoveSpeed;
                  distTravelled = distMM;
              } else {
                  moveTime = robotSettings.avgMoveDist / safeMoveSpeed;
                  distTravelled = robotSettings.avgMoveDist;
              }
              if (robotSettings.optimizePath) moveTime *= 0.8;
          }

          const totalSegTime = basicTime + moveTime;
          let currentLimit = limitGlobal;
          
          if (targetProcessMode === 'FIXED') {
             if (separateSides) {
                 const effectiveSide = proc.side === 'MIXED' ? seg.side : proc.side;
                 currentLimit = effectiveSide === 'LEFT' ? limitLeft : limitRight;
             } else {
                 currentLimit = limitGlobal; // Shared Pool Limit
             }
          } else if (targetProcessMode === 'AUTO') {
              currentLimit = taktTime;
          }

          if (proc.cycleTime + totalSegTime > currentLimit) return false;
          
          // Strict Side Check only if Separate Sides is ON
          if (separateSides && proc.side !== 'MIXED' && proc.side !== seg.side) return false;

          // Commit Assignment
          proc.weldIds.push(id);
          const startTime = proc.cycleTime;
          
          if (moveTime > 0) {
             proc.timeline.push({ type: 'MOVE', duration: moveTime, startTime: startTime, endTime: startTime + moveTime, fromId: proc.weldIds[proc.weldIds.length-2] || 'START', toId: id });
          }
          const weldStart = startTime + moveTime;
          proc.timeline.push({ type: 'WELD', duration: techTime + weldTime, startTime: weldStart, endTime: weldStart + techTime + weldTime, targetId: id });
          const liftStart = weldStart + techTime + weldTime;
          if (liftTime > 0) {
             proc.timeline.push({ type: 'IDLE', duration: liftTime, startTime: liftStart, endTime: liftStart + liftTime });
          }

          proc.cycleTime += totalSegTime;
          proc.distanceTravelled = (proc.distanceTravelled || 0) + distTravelled;
          if (proc.side === 'MIXED') proc.side = seg.side;
          if (seg.x !== undefined && seg.y !== undefined) processLastPos.set(procIdx, {x: seg.x, y: seg.y});
          
          totalTime += totalSegTime;
          return true;
      };

      if (forcedProcessIdx !== undefined && forcedProcessIdx >= 0) {
          while (newProcesses.length <= forcedProcessIdx) {
              const tl: ScheduleItem[] = overhead > 0 ? [{type: 'SETUP', duration: overhead, startTime: 0, endTime: overhead}] : [];
              newProcesses.push({ id: newProcesses.length, weldIds: [], cycleTime: overhead, side: 'MIXED', distanceTravelled: 0, timeline: tl });
          }
          const proc = newProcesses[forcedProcessIdx];
          
          let moveTime = 0;
          if (mode === 'ROBOT' && robotSettings.includeMovementTime) {
             const moveSpeedMM = robotSettings.moveSpeed * 1000;
             const safeMoveSpeed = moveSpeedMM > 0 ? moveSpeedMM : 1000;
             const lastPos = processLastPos.get(forcedProcessIdx);
             if (lastPos && seg.x && seg.y) {
                 const distPct = Math.sqrt(Math.pow(seg.x - lastPos.x, 2) + Math.pow(seg.y - lastPos.y, 2));
                 moveTime = (((distPct / 100) * modelWidthMM) / safeMoveSpeed) * (robotSettings.optimizePath ? 0.8 : 1);
             } else moveTime = (robotSettings.avgMoveDist / safeMoveSpeed);
          }
          
          const startTime = proc.cycleTime;
          if (moveTime > 0) proc.timeline.push({ type: 'MOVE', duration: moveTime, startTime: startTime, endTime: startTime + moveTime, fromId: proc.weldIds[proc.weldIds.length-1] || 'START', toId: id });
          const weldStart = startTime + moveTime;
          proc.timeline.push({ type: 'WELD', duration: techTime + weldTime, startTime: weldStart, endTime: weldStart + techTime + weldTime, targetId: id });
          const liftStart = weldStart + techTime + weldTime;
          if (liftTime > 0) proc.timeline.push({ type: 'IDLE', duration: liftTime, startTime: liftStart, endTime: liftStart + liftTime });

          proc.weldIds.push(id);
          proc.cycleTime += (basicTime + moveTime);
          if (proc.side === 'MIXED') proc.side = seg.side;
          if (seg.x && seg.y) processLastPos.set(forcedProcessIdx, {x:seg.x, y:seg.y});
          totalTime += (basicTime + moveTime);
          taskProcessMap.set(id, forcedProcessIdx);
          return;
      }

      for (let i = minProcIndex; i < newProcesses.length; i++) { if (tryAssign(i)) { assignedIdx = i; break; } }

      if (assignedIdx === -1) {
         assignedIdx = newProcesses.length;
         const tl: ScheduleItem[] = overhead > 0 ? [{type: 'SETUP', duration: overhead, startTime: 0, endTime: overhead}] : [];
         newProcesses.push({ id: assignedIdx, weldIds: [], cycleTime: overhead, side: 'MIXED', distanceTravelled: 0, timeline: tl });
         tryAssign(assignedIdx);
      }
      taskProcessMap.set(id, assignedIdx);
    });

    // --- SMART PATH OPTIMIZATION (POST-PROCESSING) ---
    if (mode === 'ROBOT') {
        newProcesses.forEach(proc => {
            // Optimization Logic
            if (robotSettings.optimizePath) {
                const originalIds = [...proc.weldIds];
                if (originalIds.length > 1) {
                    const optimizedIds: string[] = [];
                    const remainingIds = [...originalIds];
                    let currentX = modelBases[proc.side === 'RIGHT' ? 'right' : 'left'].x;
                    let currentY = modelBases[proc.side === 'RIGHT' ? 'right' : 'left'].y;

                    while (remainingIds.length > 0) {
                        const candidates = remainingIds.filter(id => {
                            const preds = predecessors.get(id) || [];
                            return preds.every(pId => optimizedIds.includes(pId) || !originalIds.includes(pId));
                        });

                        let bestId = candidates[0];
                        let minDist = Infinity;

                        candidates.forEach(id => {
                            const seg = model.segments.find(s => s.id === id);
                            if (seg && seg.x !== undefined && seg.y !== undefined) {
                                const dist = Math.sqrt(Math.pow(seg.x - currentX, 2) + Math.pow(seg.y - currentY, 2));
                                if (dist < minDist) { minDist = dist; bestId = id; }
                            }
                        });
                        if (!bestId) bestId = remainingIds[0];
                        optimizedIds.push(bestId);
                        remainingIds.splice(remainingIds.indexOf(bestId), 1);
                        const bestSeg = model.segments.find(s => s.id === bestId);
                        if (bestSeg && bestSeg.x !== undefined && bestSeg.y !== undefined) { currentX = bestSeg.x; currentY = bestSeg.y; }
                    }
                    proc.weldIds = optimizedIds;
                }
            }
            
            // Re-calculate timeline completely
            proc.cycleTime = overhead;
            proc.timeline = overhead > 0 ? [{type: 'SETUP', duration: overhead, startTime: 0, endTime: overhead}] : [];
            let procLastX = modelBases[proc.side === 'RIGHT' ? 'right' : 'left'].x;
            let procLastY = modelBases[proc.side === 'RIGHT' ? 'right' : 'left'].y;
            proc.distanceTravelled = 0;

            proc.weldIds.forEach((id, idx) => {
               const seg = model.segments.find(s => s.id === id);
               if (!seg) return;
               const weldTime = seg.length / seg.travelSpeed;
               const techTime = robotSettings.arcDelay + (robotSettings.cleaningTime / robotSettings.cleaningInterval);
               const liftTime = seg.liftTime || 0;
               let moveTime = 0;
               if (robotSettings.includeMovementTime) {
                   // Special Case: First move from Home/Base
                   if (idx === 0 && robotSettings.useFixedHomeTimes) {
                       moveTime = robotSettings.fixedApproachTime;
                       // We can still calculate distance for tracking stats if needed, 
                       // but primarily override time here.
                       if (seg.x !== undefined && seg.y !== undefined) {
                           const distPct = Math.sqrt(Math.pow(seg.x - procLastX, 2) + Math.pow(seg.y - procLastY, 2));
                           const distMM = (distPct / 100) * modelWidthMM;
                           proc.distanceTravelled = (proc.distanceTravelled || 0) + distMM;
                           procLastX = seg.x; procLastY = seg.y;
                       }
                   } else {
                       const moveSpeedMM = robotSettings.moveSpeed * 1000;
                       const safeMoveSpeed = moveSpeedMM > 0 ? moveSpeedMM : 1000;
                       if (seg.x !== undefined && seg.y !== undefined) {
                           const distPct = Math.sqrt(Math.pow(seg.x - procLastX, 2) + Math.pow(seg.y - procLastY, 2));
                           const distMM = (distPct / 100) * modelWidthMM;
                           moveTime = distMM / safeMoveSpeed;
                           proc.distanceTravelled = (proc.distanceTravelled || 0) + distMM;
                           procLastX = seg.x; procLastY = seg.y;
                       } else {
                           moveTime = robotSettings.avgMoveDist / safeMoveSpeed;
                           proc.distanceTravelled = (proc.distanceTravelled || 0) + robotSettings.avgMoveDist;
                       }
                   }
               }
               const startTime = proc.cycleTime;
               if (moveTime > 0) proc.timeline.push({ type: 'MOVE', duration: moveTime, startTime: startTime, endTime: startTime + moveTime, fromId: idx === 0 ? 'START' : proc.weldIds[idx-1], toId: id });
               const weldStart = startTime + moveTime;
               proc.timeline.push({ type: 'WELD', duration: techTime + weldTime, startTime: weldStart, endTime: weldStart + techTime + weldTime, targetId: id });
               const liftStart = weldStart + techTime + weldTime;
               if (liftTime > 0) proc.timeline.push({ type: 'IDLE', duration: liftTime, startTime: liftStart, endTime: liftStart + liftTime });
               proc.cycleTime += (moveTime + techTime + weldTime + liftTime);
            });

            // --- RETURN TO HOME LOGIC ---
            if (robotSettings.includeReturnHome && proc.weldIds.length > 0) {
                const homeX = modelBases[proc.side === 'RIGHT' ? 'right' : 'left'].x;
                const homeY = modelBases[proc.side === 'RIGHT' ? 'right' : 'left'].y;
                let returnTime = 0;
                
                if (robotSettings.useFixedHomeTimes) {
                    returnTime = robotSettings.fixedReturnTime;
                    // Track distance
                    if (robotSettings.includeMovementTime) {
                        const distPct = Math.sqrt(Math.pow(homeX - procLastX, 2) + Math.pow(homeY - procLastY, 2));
                        const distMM = (distPct / 100) * modelWidthMM;
                        proc.distanceTravelled = (proc.distanceTravelled || 0) + distMM;
                    }
                } else if (robotSettings.includeMovementTime) {
                    const moveSpeedMM = robotSettings.moveSpeed * 1000;
                    const safeMoveSpeed = moveSpeedMM > 0 ? moveSpeedMM : 1000;
                    const distPct = Math.sqrt(Math.pow(homeX - procLastX, 2) + Math.pow(homeY - procLastY, 2));
                    const distMM = (distPct / 100) * modelWidthMM;
                    returnTime = distMM / safeMoveSpeed;
                    proc.distanceTravelled = (proc.distanceTravelled || 0) + distMM;
                }

                if (returnTime > 0) {
                    const startTime = proc.cycleTime;
                    proc.timeline.push({ 
                        type: 'MOVE', 
                        duration: returnTime, 
                        startTime: startTime, 
                        endTime: startTime + returnTime, 
                        fromId: proc.weldIds[proc.weldIds.length - 1], 
                        toId: 'HOME' 
                    });
                    proc.cycleTime += returnTime;
                }
            }
        });
        totalTime = newProcesses.reduce((acc, p) => acc + p.cycleTime, 0);
    }

    // --- COLLISION DETECTION ---
    let collisionDetected = false;
    if (mode === 'ROBOT') {
        const eventsInZone: {processId: number, startTime: number, endTime: number}[] = [];
        newProcesses.forEach(proc => {
            proc.timeline.forEach(item => {
                let isInZone = false;
                const seg = item.targetId ? model.segments.find(s=>s.id===item.targetId) : item.toId && item.toId !== 'HOME' ? model.segments.find(s=>s.id===item.toId) : null;
                if (seg && seg.x && seg.x >= robotSettings.interferenceZoneMinX && seg.x <= robotSettings.interferenceZoneMaxX) isInZone = true;
                if (isInZone) eventsInZone.push({ processId: proc.id, startTime: item.startTime, endTime: item.endTime });
            });
        });
        for (let i = 0; i < eventsInZone.length; i++) {
            for (let j = i + 1; j < eventsInZone.length; j++) {
                const e1 = eventsInZone[i]; const e2 = eventsInZone[j];
                if (e1.processId !== e2.processId && e1.startTime < e2.endTime && e2.startTime < e1.endTime) {
                    collisionDetected = true;
                }
            }
        }
    }

    const maxCycleTime = newProcesses.length > 0 ? Math.max(...newProcesses.map(p => p.cycleTime)) : 0;
    const efficiency = newProcesses.length > 0 ? (totalTime / (newProcesses.length * maxCycleTime)) * 100 : 0;
    return { modelId: model.id, modelName: model.name, totalSegments: model.segments.length, totalTime, processes: newProcesses, maxCycleTime, efficiency, isBalanced: maxCycleTime <= taktTime, totalCost, collisionDetected };
  }, [taktTime, calculateSegmentTime, separateSides, balancingAlgo, targetProcessMode, fixedRobotsLeft, fixedRobotsRight, mode, robotSettings, manualSettings, costSettings]);

  useEffect(() => { balAlgoRef.current = balancingAlgo; }, [balancingAlgo]);

  const currentStats = useMemo(() => calculateBalancingForModel(activeModel), [activeModel, calculateBalancingForModel]);
  const maxCycleTime = currentStats.maxCycleTime;
  const lineEfficiency = currentStats.efficiency;

  // Collision Real-time (Simple Check)
  const isCollisionNow = useMemo(() => {
     if (mode !== 'ROBOT' || !showInterferenceZone) return false;
     let count = 0;
     currentStats.processes.forEach(proc => {
         const active = proc.timeline.find(t => simTime >= t.startTime && simTime <= t.endTime);
         if (active && (active.targetId || active.toId)) {
             const segId = active.targetId || active.toId;
             const seg = segments.find(s => s.id === segId);
             if (seg && seg.x && seg.x >= robotSettings.interferenceZoneMinX && seg.x <= robotSettings.interferenceZoneMaxX) {
                 count++;
             }
         }
     });
     return count > 1;
  }, [simTime, currentStats, mode, showInterferenceZone, robotSettings, segments]);

  // Waste Data
  const wasteData = useMemo(() => {
     if (!currentStats) return [];
     let welding = 0, moving = 0, idle = 0, setup = 0;
     currentStats.processes.forEach(p => {
         p.timeline.forEach(t => {
             if (t.type === 'WELD') welding += t.duration;
             else if (t.type === 'MOVE') moving += t.duration;
             else if (t.type === 'IDLE') idle += t.duration;
             else if (t.type === 'SETUP') setup += t.duration;
         });
         // Add idle time waiting for cycle completion
         if (p.cycleTime < maxCycleTime) idle += (maxCycleTime - p.cycleTime);
     });
     return [
         { name: 'Value Added (Weld)', value: welding, color: '#10b981' },
         { name: 'Motion', value: moving, color: '#f59e0b' },
         { name: 'Idle/Wait', value: idle, color: '#ef4444' },
         { name: 'Setup/Change', value: setup, color: '#6366f1' }
     ].filter(d => d.value > 0);
  }, [currentStats, maxCycleTime]);

  // Yamazumi Data
  const yamazumiData = useMemo(() => {
     return currentStats.processes.map(proc => {
         const data: any = { name: `P${proc.id + 1}`, side: proc.side, dummy: 0 };
         proc.timeline.forEach(t => {
             if (t.type === 'WELD' && t.targetId) {
                 data[t.targetId] = t.duration;
             } else {
                 data.dummy += t.duration;
             }
         });
         return data;
     });
  }, [currentStats]);

  // All Models Stats for Overview
  const allModelsStats = useMemo(() => models.map(m => calculateBalancingForModel(m)), [models, calculateBalancingForModel]);
  const minCycleTime = Math.min(...allModelsStats.map(m => m.maxCycleTime));
  const minCost = Math.min(...allModelsStats.map(m => m.totalCost || 0));
  
  const radarData = useMemo(() => {
     // Normalize based on best in class
     const bestEff = Math.max(...allModelsStats.map(s => s.efficiency));
     const bestSpeed = minCycleTime; // lower is better
     const bestCost = minCost; // lower is better
     
     return allModelsStats.map(s => ({
         subject: s.modelName,
         Efficiency: (s.efficiency / bestEff) * 100,
         Speed: (bestSpeed / s.maxCycleTime) * 100,
         Cost: (bestCost / (s.totalCost || 1)) * 100,
         fullMark: 100
     }));
  }, [allModelsStats, minCycleTime, minCost]);

  // Unmapped Segments
  const unmappedSegments = useMemo(() => segments.filter(s => s.x === undefined || s.y === undefined), [segments]);

  // --- Actions ---

  const addSegment = () => {
     // Find max ID to ensure uniqueness even after deletions
     const maxIdNum = segments.reduce((max, seg) => {
         const match = seg.id.match(/^W(\d+)$/);
         return match ? Math.max(max, parseInt(match[1], 10)) : max;
     }, 0);
     const newId = `W${(maxIdNum + 1).toString().padStart(3, '0')}`;
     
     const newSeg: WeldSegment = {
         id: newId, name: `New Weld ${maxIdNum + 1}`, length: 100,
         travelSpeed: 10, approachTime: 2, liftTime: 0.5, position: 'FLAT', side: 'LEFT', groupId: 'G1'
     };
     setSegments([...segments, newSeg]);
  };
  
  const updateSegment = (id: string, field: keyof WeldSegment, value: any) => {
     setSegments(prev => prev.map(s => s.id === id ? { ...s, [field]: value } : s));
  };
  
  const removeSegment = (id: string) => {
     // Perform both updates on the model at once to avoid state overwrite race conditions
     const updatedModels = models.map(m => {
        if (m.id === activeModelId) {
           return {
              ...m,
              segments: m.segments.filter(s => s.id !== id),
              constraints: m.constraints.filter(c => c.firstWeldId !== id && c.secondWeldId !== id)
           };
        }
        return m;
     });
     handleModelUpdate(updatedModels);
  };
  
  const duplicateSegment = (seg: WeldSegment) => {
     const maxIdNum = segments.reduce((max, s) => {
         const match = s.id.match(/^W(\d+)$/);
         return match ? Math.max(max, parseInt(match[1], 10)) : max;
     }, 0);
     const newId = `W${(maxIdNum + 1).toString().padStart(3, '0')}`;
     
     const newSeg = { ...seg, id: newId, name: `${seg.name} (Copy)`, x: (seg.x || 0) + 2, y: (seg.y || 0) + 2 };
     setSegments([...segments, newSeg]);
  };

  const addGroup = () => {
      const id = `G${weldGroups.length + 1}`;
      setWeldGroups([...weldGroups, { id, name: `Group ${id}`, color: PRESET_COLORS[weldGroups.length % PRESET_COLORS.length] }]);
  };
  const updateGroup = (id: string, field: keyof WeldGroup, value: any) => {
      setWeldGroups(prev => prev.map(g => g.id === id ? { ...g, [field]: value } : g));
  };
  const removeGroup = (id: string) => {
      setWeldGroups(prev => prev.filter(g => g.id !== id));
  };

  const addPosition = () => {
      const id = `POS_${weldPositions.length + 1}`;
      setWeldPositions([...weldPositions, { id, label: 'New Position', factor: 0.1 }]);
  };
  const updatePosition = (id: string, field: keyof WeldPositionDefinition, value: any) => {
      setWeldPositions(prev => prev.map(p => p.id === id ? { ...p, [field]: field === 'factor' ? Number(value) : value } : p));
  };
  const removePosition = (id: string) => {
      setWeldPositions(prev => prev.filter(p => p.id !== id));
  };

  const addConstraint = () => {
      const id = `C${constraints.length + 1}`;
      setConstraints([...constraints, { id, firstWeldId: '', secondWeldId: '', description: '' }]);
  };
  const updateConstraint = (id: string, field: keyof WeldConstraint, value: any) => {
      setConstraints(prev => prev.map(c => c.id === id ? { ...c, [field]: value } : c));
  };
  const removeConstraint = (id: string) => {
      setConstraints(prev => prev.filter(c => c.id !== id));
  };

  const handleSaveNewModel = () => {
      if (!newModelName) return;
      let newModel: ModelData;
      if (copyFromId && copyFromId !== 'EMPTY') {
          const source = models.find(m => m.id === copyFromId);
          if (source) {
              newModel = JSON.parse(JSON.stringify(source));
              newModel.id = `m${Date.now()}`;
              newModel.name = newModelName;
          } else {
             newModel = { ...models[0], id: `m${Date.now()}`, name: newModelName, segments: [] }; 
          }
      } else {
          newModel = { ...models[0], id: `m${Date.now()}`, name: newModelName, segments: [] };
      }
      setModels([...models, newModel]);
      setActiveModelId(newModel.id);
      setShowAddModal(false);
      setNewModelName('');
  };

  const clearManualOverrides = () => setManualOverrides({});

  // --- Interaction Handlers ---

  const checkReachability = (seg: WeldSegment) => {
     if (!seg.x || !seg.y) return false;
     const base = seg.side === 'RIGHT' ? robotBases.right : robotBases.left;
     const distPct = Math.sqrt(Math.pow(seg.x - base.x, 2) + Math.pow(seg.y - base.y, 2));
     const distMM = (distPct / 100) * frameWidthMM;
     return distMM <= robotSettings.maxReach;
  };

  const getWeldStatus = (segId: string) => {
      // Find which process handles this weld
      const proc = currentStats.processes.find(p => p.weldIds.includes(segId));
      if (!proc) return 'PENDING';
      
      const weldItem = proc.timeline.find(t => t.type === 'WELD' && t.targetId === segId);
      if (!weldItem) return 'PENDING';

      if (simTime >= weldItem.startTime && simTime <= weldItem.endTime) return 'WELDING';
      if (simTime > weldItem.endTime) return 'COMPLETED';
      
      // Check if moving to this weld
      const moveItem = proc.timeline.find(t => t.type === 'MOVE' && t.toId === segId);
      if (moveItem && simTime >= moveItem.startTime && simTime <= moveItem.endTime) return 'MOVING_TO';

      return 'PENDING';
  };

  const handleImageUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
      const file = e.target.files?.[0];
      if (file) {
          const reader = new FileReader();
          reader.onload = (evt) => {
              const updatedModels = models.map(m => m.id === activeModelId ? { ...m, frameImage: evt.target?.result as string } : m);
              handleModelUpdate(updatedModels);
          };
          reader.readAsDataURL(file);
      }
  };

  const handleZoom = (delta: number) => setZoomLevel(prev => Math.max(20, Math.min(300, prev + delta)));

  // Drag & Drop logic variables
  // const [draggingId, setDraggingId] = useState<string | null>(null); // Already in state
  // const [draggingBase, setDraggingBase] = useState<'left'|'right'|null>(null); // Already in state

  const handleDragStart = (e: React.DragEvent, id: string) => {
     e.dataTransfer.setData('text/plain', id);
     setDraggingId(id);
  };

  const handleFrameDrop = (e: React.DragEvent) => {
      e.preventDefault();
      const id = e.dataTransfer.getData('text/plain');
      if (!imageContainerRef.current) return;
      
      const rect = imageContainerRef.current.getBoundingClientRect();
      const x = ((e.clientX - rect.left) / rect.width) * 100;
      const y = ((e.clientY - rect.top) / rect.height) * 100;

      if (id) {
          setSegments(prev => prev.map(s => s.id === id ? { ...s, x, y } : s));
          setDraggingId(null);
      }
  };
  
  const handleFrameMouseMove = (e: React.MouseEvent) => {
      if (!imageContainerRef.current) return;
      const rect = imageContainerRef.current.getBoundingClientRect();
      const x = ((e.clientX - rect.left) / rect.width) * 100;
      const y = ((e.clientY - rect.top) / rect.height) * 100;

      if (draggingBase) {
          setRobotBases(prev => ({ ...prev, [draggingBase]: { x, y } }));
      } else if (draggingId && !unmappedSegments.find(s => s.id === draggingId)) {
          // Only if it's an existing point on map
          setSegments(prev => prev.map(s => s.id === draggingId ? { ...s, x, y } : s));
      }
  };

  const handleFrameMouseUp = () => {
      setDraggingId(null);
      setDraggingBase(null);
  };

  const handlePointMouseDown = (e: React.MouseEvent, id: string) => {
      e.stopPropagation();
      setDraggingId(id);
  };

  const handlePointClick = (e: React.MouseEvent, id: string) => {
      e.stopPropagation();
      if (isManualBalanceMode) {
          if (selectedManualProcess >= 0) {
              const currentOverrides = activeModel.manualOverrides || {};
              // Toggle or Assign
              if (currentOverrides[id] === selectedManualProcess) {
                  const newO = { ...currentOverrides };
                  delete newO[id];
                  setManualOverrides(newO);
              } else {
                  setManualOverrides({ ...currentOverrides, [id]: selectedManualProcess });
              }
          } else {
               // Auto mode (clear override)
               const newO = { ...activeModel.manualOverrides };
               delete newO[id];
               setManualOverrides(newO);
          }
      } else {
          setSelectedSegmentId(id);
      }
  };
  
  const handlePointContextMenu = (e: React.MouseEvent, id: string, name: string) => {
      e.preventDefault();
      // Optional: context menu
  };

  const handleRobotBaseMouseDown = (e: React.MouseEvent, base: 'left' | 'right') => {
      e.stopPropagation();
      setDraggingBase(base);
  };

  const handleImageClick = (e: React.MouseEvent) => {
      if (isManualBalanceMode) return;
      
      // Feature: Click to Place Unmapped Weld
      if (selectedSegmentId) {
          const isUnmapped = unmappedSegments.find(s => s.id === selectedSegmentId);
          if (isUnmapped && imageContainerRef.current) {
              const rect = imageContainerRef.current.getBoundingClientRect();
              const x = ((e.clientX - rect.left) / rect.width) * 100;
              const y = ((e.clientY - rect.top) / rect.height) * 100;
              
              setSegments(prev => prev.map(s => s.id === selectedSegmentId ? { ...s, x, y } : s));
              
              // Automatically select the next unmapped segment for rapid placement
              const currentIndex = unmappedSegments.findIndex(s => s.id === selectedSegmentId);
              if (currentIndex < unmappedSegments.length - 1) {
                  setSelectedSegmentId(unmappedSegments[currentIndex + 1].id);
              } else {
                  setSelectedSegmentId(null);
              }
              return;
          }
      }

      setSelectedSegmentId(null);
  };

  const handleRenameModel = (id: string, name: string) => {
      setModels(prev => prev.map(m => m.id === id ? { ...m, name } : m));
  };

  const handleDeleteModel = (e: React.MouseEvent, id: string) => {
      e.stopPropagation();
      if (models.length > 1) {
          if (confirm('Delete this model?')) {
             const remaining = models.filter(m => m.id !== id);
             setModels(remaining);
             if (activeModelId === id) setActiveModelId(remaining[0].id);
          }
      } else {
          alert('Cannot delete the last model.');
      }
  };

  const handleOpenAddModal = () => {
      setNewModelName('');
      setCopyFromId('EMPTY');
      setShowAddModal(true);
  };


  // --- Render Helpers ---

  const renderInteractiveColumn = (proc: ProcessResult, maxVal: number, chartHeight: number) => {
      return (
          <div key={proc.id} className="flex flex-col items-center group relative h-full justify-end w-16">
             <div className="absolute -top-8 bg-slate-800 text-white text-[10px] px-2 py-1 rounded opacity-0 group-hover:opacity-100 transition-opacity whitespace-nowrap z-20">
                 Time: {proc.cycleTime.toFixed(1)}s ({(proc.cycleTime/taktTime*100).toFixed(0)}%)
             </div>
             {/* Stacked Bar */}
             <div className="w-full flex flex-col-reverse relative rounded-t-md overflow-hidden bg-slate-200" style={{ height: `${(proc.cycleTime / maxVal) * chartHeight}px` }}>
                 {/* Iterate timeline or weldIds to build stack */}
                 {proc.weldIds.map((wid, idx) => {
                     const seg = segments.find(s => s.id === wid);
                     const h = seg ? ((calculateSegmentTime(seg) / proc.cycleTime) * 100) : 0;
                     return (
                         <div 
                            key={wid} 
                            className="w-full border-b border-white/20 cursor-grab active:cursor-grabbing hover:brightness-110 transition-all flex items-center justify-center text-[8px] text-white font-bold select-none"
                            style={{ height: `${h}%`, backgroundColor: PRESET_COLORS[idx % PRESET_COLORS.length] }}
                            draggable
                            onDragStart={(e) => { e.dataTransfer.setData('text/plain', wid); setIsDragMode(true); }}
                         >
                             {wid}
                         </div>
                     );
                 })}
                 {/* Drop Zone Overlay */}
                 <div 
                    className="absolute inset-0 z-10 opacity-0 hover:opacity-100 bg-white/30 border-2 border-dashed border-slate-600 transition-opacity"
                    onDragOver={(e) => e.preventDefault()}
                    onDrop={(e) => {
                        e.preventDefault();
                        const draggedId = e.dataTransfer.getData('text/plain');
                        if (draggedId) {
                            setManualOverrides({ ...(activeModel.manualOverrides || {}), [draggedId]: proc.id });
                        }
                    }}
                 />
             </div>
             <div className="mt-2 text-xs font-bold text-slate-600">P{proc.id + 1}</div>
             {proc.cycleTime > taktTime && <div className="text-[10px] text-red-500 font-bold">+{ (proc.cycleTime - taktTime).toFixed(0) }s</div>}
          </div>
      );
  };

  const renderProcessCard = (proc: ProcessResult, idx: number) => {
      const isOver = proc.cycleTime > taktTime;
      return (
          <div key={proc.id} className={`p-4 rounded-xl border ${isOver ? 'bg-red-50 border-red-200' : 'bg-white border-slate-200 shadow-sm'}`}>
              <div className="flex justify-between items-center mb-3">
                  <div className="flex items-center gap-2">
                      <span className={`w-8 h-8 flex items-center justify-center rounded-lg font-bold text-white ${isOver ? 'bg-red-500' : 'bg-blue-600'}`}>P{proc.id + 1}</span>
                      <div>
                          <h4 className="font-bold text-slate-900 text-sm">Process {proc.id + 1}</h4>
                          <span className="text-xs text-slate-500">{proc.weldIds.length} welds • {proc.side}</span>
                      </div>
                  </div>
                  <div className="text-right">
                      <div className={`text-xl font-bold ${isOver ? 'text-red-600' : 'text-slate-900'}`}>{proc.cycleTime.toFixed(1)}s</div>
                      <div className="text-xs text-slate-500">Target: {taktTime}s</div>
                  </div>
              </div>
              <div className="space-y-1">
                  {proc.weldIds.map(wid => {
                      const seg = segments.find(s => s.id === wid);
                      return (
                          <div key={wid} className="flex justify-between items-center text-xs p-1.5 bg-slate-50 rounded border border-slate-100">
                              <span className="font-bold text-slate-700">{wid} <span className="font-normal text-slate-500">- {seg?.name}</span></span>
                              <span className="font-mono text-slate-600">{seg ? calculateSegmentTime(seg).toFixed(1) : 0}s</span>
                          </div>
                      );
                  })}
              </div>
          </div>
      );
  };

  // --- Render (Modals) ---
  return (
    <div className={`min-h-screen pb-10 transition-colors duration-300 ${isDarkMode ? 'bg-slate-900 text-slate-100' : 'bg-slate-50 text-slate-900'}`}>
      <style>{`
        @keyframes dash { to { stroke-dashoffset: -10; } }
        @keyframes pulse-red { 0% { box-shadow: 0 0 0 0 rgba(239, 68, 68, 0.7); } 70% { box-shadow: 0 0 0 10px rgba(239, 68, 68, 0); } 100% { box-shadow: 0 0 0 0 rgba(239, 68, 68, 0); } }
        @keyframes flash-warning { 0%, 100% { opacity: 1; } 50% { opacity: 0.5; } }
        .path-flow-line { animation: dash 1s linear infinite; }
        .welding-pulse { animation: pulse-red 1s infinite; }
        .flash-collision { animation: flash-warning 0.5s infinite; background-color: rgba(239, 68, 68, 0.3); border: 2px solid #ef4444; }
        .writing-vertical { writing-mode: vertical-rl; }
        @media print {
          body { background-color: white !important; -webkit-print-color-adjust: exact; }
          .no-print { display: none !important; }
          .print-header { display: block !important; margin-bottom: 20px; border-bottom: 2px solid black; padding-bottom: 10px; }
        }
        .print-header { display: none; }
      `}</style>
      <header className="border-b px-6 py-3 shadow-sm sticky top-0 z-50 transition-colors duration-300 bg-white border-slate-200 no-print">
        <div className="flex flex-col md:flex-row justify-between items-center gap-4">
          <h1 className={`text-2xl font-bold tracking-tight ${isDarkMode ? 'text-white' : 'text-slate-900'}`}>WeldBalance Pro</h1>
          <div className="flex flex-1 items-center justify-center gap-4 w-full md:w-auto">
            <input ref={projectNameInputRef} value={projectName} onChange={(e) => setProjectName(e.target.value)} className="border rounded-lg px-4 py-2 font-medium text-slate-900 focus:ring-2 focus:ring-blue-500 outline-none w-64 text-sm" />
            <button onClick={handleSaveProject} className="flex items-center gap-2 px-4 py-2 bg-emerald-500 text-white rounded-lg text-sm font-bold shadow-sm"><Save size={16} /> บันทึก</button>
            <button onClick={handleLoadClick} className="flex items-center gap-2 px-4 py-2 bg-blue-600 text-white rounded-lg text-sm font-bold shadow-sm"><Download size={16} /> โหลด</button>
            <input type="file" ref={loadFileInputRef} className="hidden" accept=".json" onChange={handleFileLoad} />
            <div className="flex gap-1 relative text-slate-400">
               <button onClick={undo} disabled={history.past.length === 0} className="p-2 hover:bg-slate-100 rounded-lg"><Undo size={18}/></button>
               <button onClick={redo} disabled={history.future.length === 0} className="p-2 hover:bg-slate-100 rounded-lg"><Redo size={18}/></button>
               <button onClick={toggleDarkMode} className="p-2 hover:bg-slate-100 rounded-lg">{isDarkMode ? <Sun size={16}/> : <Moon size={16}/>}</button>
            </div>
          </div>
          <div className="text-right flex flex-col items-end">
             <div className="text-xs text-slate-700 dark:text-slate-400 font-semibold uppercase">เวลา Takt Time</div>
             <div className="text-3xl font-bold text-blue-600 leading-none">{taktTime}s</div>
          </div>
        </div>
      </header>
      <div className={`border-b px-6 py-3 flex items-center justify-between shadow-sm relative z-40 transition-colors duration-300 no-print ${isDarkMode ? 'bg-slate-800 border-slate-700' : 'bg-white border-slate-200'}`}>
        <div className="flex items-center gap-3 overflow-x-auto pb-1 md:pb-0">
          <span className="font-bold text-sm mr-2 text-slate-700 dark:text-slate-400">โมเดล:</span>
          {models.map((m) => (
             <div key={m.id} className={`flex items-center gap-2 px-4 py-1.5 rounded-lg border text-sm font-medium cursor-pointer transition-all whitespace-nowrap group relative ${activeModelId === m.id ? 'bg-blue-600 text-white border-blue-600 shadow-md' : 'bg-slate-100 text-slate-800 dark:bg-slate-800 dark:text-slate-300 border-slate-300'}`} onClick={() => setActiveModelId(m.id)}>
                {activeModelId === m.id ? <input className="bg-transparent border-none outline-none text-white font-medium w-auto min-w-[60px] max-w-[120px]" value={m.name} onChange={(e) => handleRenameModel(m.id, e.target.value)} onClick={(e) => e.stopPropagation()}/> : <span>{m.name}</span>}
                {models.length > 1 && <button onClick={(e) => handleDeleteModel(e, m.id)} className={`ml-2 p-1 rounded-full hover:bg-white/20 text-red-400 hover:text-red-200 transition-all ${activeModelId === m.id ? '' : 'opacity-50 hover:opacity-100'}`}><X size={14}/></button>}
             </div>
          ))}
          <button onClick={handleOpenAddModal} className="flex items-center gap-1 px-3 py-1.5 border border-emerald-500 text-emerald-600 bg-emerald-50 rounded-lg text-sm font-medium hover:bg-emerald-100"><Plus size={14}/> เพิ่ม</button>
        </div>
        <div className="flex items-center gap-4">
          <div className="text-sm font-medium text-slate-700 dark:text-slate-400">จุดเชื่อม: <span className="font-bold text-slate-900 dark:text-white">{segments.length} จุด</span></div>
          <button onClick={() => setShowOverview(true)} className="px-4 py-1.5 bg-orange-500 text-white rounded-lg text-sm font-bold shadow-sm flex items-center gap-2"><Layout size={14}/> ภาพรวม</button>
        </div>
      </div>

      <div className="p-6 max-w-[1600px] mx-auto print:p-0 print:max-w-none">
        <div className={`rounded-t-xl border border-b-0 flex overflow-x-auto transition-colors duration-300 no-print ${isDarkMode ? 'bg-slate-800 border-slate-700' : 'bg-white border-slate-200'}`}>
          {[ { id: 'FRAME_VIEW', label: 'มุมมองภาพ (Frame View)', icon: ImageIcon }, { id: 'WELD_LIST', label: 'รายการเชื่อม (Weld List)', icon: Layers }, { id: 'GROUPS', label: 'กลุ่ม (Groups)', icon: Folder }, { id: 'STANDARD_TIMES', label: 'เวลามาตรฐาน (Std Times)', icon: Timer }, { id: 'CONSTRAINTS', label: 'เงื่อนไข (Constraints)', icon: LinkIcon }, { id: 'RESULTS', label: 'ผลลัพธ์ (Results)', icon: BarChart3 } ].map((tab) => (
             <button key={tab.id} onClick={() => setActiveTab(tab.id as any)} className={`flex items-center gap-2 px-6 py-4 text-sm font-bold border-b-2 transition-colors whitespace-nowrap ${activeTab === tab.id ? 'border-blue-500 text-blue-600 bg-blue-50/50 dark:bg-slate-700 dark:text-blue-400' : 'border-transparent text-slate-700 dark:text-slate-400 hover:text-black dark:hover:text-white hover:bg-slate-50'}`}>
                <tab.icon size={18} /> {tab.label}
             </button>
          ))}
        </div>

        <div className={`border rounded-b-xl shadow-sm min-h-[600px] p-6 relative transition-colors duration-300 print:border-none print:shadow-none print:p-0 ${isDarkMode ? 'bg-slate-800 border-slate-700' : 'bg-white border-slate-200'}`}>
          {activeTab === 'WELD_LIST' && (
            <div className="space-y-6 animate-in fade-in zoom-in-95 duration-200">
               <div className="bg-white border border-slate-200 rounded-xl p-6 shadow-sm relative overflow-hidden no-print">
                  <div className="grid grid-cols-1 md:grid-cols-3 gap-8 mb-6">
                      <div className="space-y-3">
                          <label className="flex items-center gap-2 text-sm font-bold text-slate-900 dark:text-slate-300"><Clock size={16}/> Target Takt Time (s)</label>
                          <input type="number" value={taktTime} onChange={(e) => setTaktTime(Number(e.target.value))} className="w-full bg-slate-50 border border-slate-200 rounded-xl px-4 py-3 text-2xl font-mono font-bold text-slate-900 dark:text-white focus:ring-2 focus:ring-blue-500 outline-none" />
                      </div>
                      <div className="space-y-3">
                          <label className="flex items-center gap-2 text-sm font-bold text-slate-900 dark:text-slate-300"><Zap size={16}/> Welding Mode</label>
                          <div className="flex bg-slate-100 p-1.5 rounded-xl">
                              <button onClick={() => setMode('MANUAL')} className={`flex-1 py-3 rounded-lg text-sm font-bold transition-all ${mode === 'MANUAL' ? 'bg-white text-blue-600 shadow-sm' : 'text-slate-700 dark:text-slate-400 hover:bg-slate-200'}`}>Manual</button>
                              <button onClick={() => setMode('ROBOT')} className={`flex-1 py-3 rounded-lg text-sm font-bold transition-all ${mode === 'ROBOT' ? 'bg-white text-indigo-600 shadow-sm' : 'text-slate-700 dark:text-slate-400 hover:bg-slate-200'}`}>Robot</button>
                          </div>
                      </div>
                      
                      <div className="space-y-3">
                          <label className="flex items-center gap-2 text-sm font-bold text-slate-900 dark:text-slate-300"><Cpu size={16}/> Resource Strategy</label>
                          <div className="flex gap-2">
                            <select value={targetProcessMode} onChange={(e) => setTargetProcessMode(e.target.value)} className="w-full bg-slate-50 border border-slate-200 rounded-xl px-4 py-3 font-bold text-slate-900 dark:text-white focus:ring-2 focus:ring-blue-500 outline-none appearance-none cursor-pointer flex-1">
                               <option value="AUTO">Auto Balance (Fit Takt)</option> <option value="FIXED">Fixed Resources</option>
                            </select>
                            {mode === 'ROBOT' ? (
                                <button onClick={() => setShowRobotSettingsModal(true)} className="px-4 bg-indigo-50 border border-indigo-200 text-indigo-600 rounded-xl hover:bg-indigo-100 transition-colors" title="Robot Parameters">
                                    <Settings size={20} />
                                </button>
                            ) : (
                                <button onClick={() => setShowManualSettingsModal(true)} className="px-4 bg-orange-50 border border-orange-200 text-orange-600 rounded-xl hover:bg-orange-100 transition-colors" title="Manual Operations">
                                    <Settings size={20} />
                                </button>
                            )}
                          </div>
                      </div>
                  </div>
                  
                  <div className={`mb-6 flex flex-col md:flex-row items-center gap-4 p-4 rounded-xl border ${mode === 'ROBOT' ? 'bg-indigo-50/50 border-indigo-100' : 'bg-blue-50/50 border-blue-100'}`}>
                        <div className="flex items-center gap-2"><span className="font-bold text-sm text-slate-900 dark:text-slate-300">Balancing Scope:</span></div>
                        <div className={`flex items-center gap-3 bg-white px-4 py-2 rounded-full border shadow-sm cursor-pointer ${mode === 'ROBOT' ? 'border-indigo-100' : 'border-blue-100'}`} onClick={() => setSeparateSides(!separateSides)}>
                            <span className={`text-xs font-bold transition-colors ${separateSides ? (mode === 'ROBOT' ? 'text-indigo-600' : 'text-blue-600') : 'text-slate-400'}`}>Separate L/R</span>
                            <div className={`w-12 h-6 rounded-full p-1 transition-colors duration-300 relative ${separateSides ? (mode === 'ROBOT' ? 'bg-indigo-600' : 'bg-blue-600') : 'bg-slate-300'}`}>
                                <div className={`w-4 h-4 bg-white rounded-full shadow-sm transition-transform duration-300 absolute top-1 ${separateSides ? 'left-7' : 'left-1'}`} />
                            </div>
                            <span className={`text-xs font-bold transition-colors ${!separateSides ? 'text-slate-900 dark:text-slate-300' : 'text-slate-600 dark:text-slate-400'}`}>Shared Pool</span>
                        </div>
                  </div>
                  {targetProcessMode === 'FIXED' && (
                      <div className={`rounded-xl p-6 mb-6 border ${mode === 'ROBOT' ? 'bg-indigo-50 border-indigo-100' : 'bg-blue-50 border-blue-100'}`}>
                          <div className="flex flex-col md:flex-row justify-between items-start md:items-center mb-4 gap-2">
                              <h4 className={`font-bold flex items-center gap-2 text-sm uppercase tracking-wider ${mode === 'ROBOT' ? 'text-indigo-800' : 'text-blue-800'}`}>{mode === 'ROBOT' ? <Bot size={16}/> : <Users size={16}/>} {mode === 'ROBOT' ? 'Robot Allocation' : 'Operator Allocation'}</h4>
                          </div>
                          {separateSides ? (
                              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                                  <div className="flex items-center gap-4 bg-white p-4 rounded-lg border shadow-sm"><div className="w-12 h-12 rounded-full flex items-center justify-center font-bold border shadow-inner text-lg bg-blue-100 text-blue-600 border-blue-200">L</div><div className="flex-1"><label className="block text-xs font-bold text-slate-700 dark:text-slate-400 uppercase mb-1">Left {mode === 'ROBOT' ? 'Robots' : 'Operators'}</label><input type="number" min="0" value={fixedRobotsLeft} onChange={(e) => setFixedRobotsLeft(Math.max(0, Number(e.target.value)))} className="w-full text-2xl font-bold text-slate-900 dark:text-white outline-none border-b-2 border-slate-200 bg-transparent"/></div></div>
                                  <div className="flex items-center gap-4 bg-white p-4 rounded-lg border shadow-sm"><div className="w-12 h-12 rounded-full flex items-center justify-center font-bold border shadow-inner text-lg bg-orange-100 text-orange-600 border-orange-200">R</div><div className="flex-1"><label className="block text-xs font-bold text-slate-700 dark:text-slate-400 uppercase mb-1">Right {mode === 'ROBOT' ? 'Robots' : 'Operators'}</label><input type="number" min="0" value={fixedRobotsRight} onChange={(e) => setFixedRobotsRight(Math.max(0, Number(e.target.value)))} className="w-full text-2xl font-bold text-slate-900 dark:text-white outline-none border-b-2 border-slate-200 bg-transparent"/></div></div>
                              </div>
                          ) : (
                              <div className="bg-white p-6 rounded-lg border shadow-sm flex items-center gap-6"><div className="w-14 h-14 rounded-full flex items-center justify-center font-bold border shadow-inner bg-emerald-100 text-emerald-600 border-emerald-200"><Users size={28}/></div><div className="flex-1"><label className="block text-xs font-bold text-slate-700 dark:text-slate-400 uppercase mb-1">Total {mode === 'ROBOT' ? 'Robots' : 'Operators'}</label><input type="number" min="1" value={fixedRobotsLeft} onChange={(e) => { setFixedRobotsLeft(Math.max(1, Number(e.target.value))); setFixedRobotsRight(0); }} className="w-full text-3xl font-bold outline-none border-b-2 border-slate-200 bg-transparent text-emerald-700"/></div></div>
                          )}
                      </div>
                  )}
               </div>
               
               <div className="border border-slate-200 rounded-xl overflow-hidden print:border-black">
                  <div className="bg-slate-50 px-6 py-3 border-b border-slate-200 flex justify-between items-center no-print">
                     <h3 className="font-bold text-slate-900">รายการแนวเชื่อม (Weld Segments)</h3>
                     <div className="flex gap-2">
                       <button onClick={handleExportCSV} className="text-xs px-3 py-1.5 bg-emerald-600 text-white rounded font-medium">CSV Export</button>
                       <button onClick={() => setShowAIModal(true)} className="text-xs px-3 py-1.5 bg-purple-600 text-white rounded font-bold">AI Generate</button>
                       <button onClick={() => addSegment()} className="text-xs px-3 py-1.5 bg-blue-600 text-white rounded font-medium">Add Row</button>
                     </div>
                  </div>
                  <div className="overflow-x-auto max-h-[500px] print:max-h-none">
                    <table className="w-full text-sm text-left">
                      <thead className="bg-slate-200 dark:bg-slate-800 text-slate-800 dark:text-slate-300 font-bold uppercase text-xs sticky top-0 z-10 print:static print:bg-white print:text-black print:border-b-2 print:border-black"><tr><th className="px-4 py-3 text-center w-12">#</th><th className="px-6 py-3">ID</th><th className="px-6 py-3">Name</th><th className="px-6 py-3">Side</th><th className="px-6 py-3">Len(mm)</th><th className="px-6 py-3">Pos</th><th className="px-6 py-3">Lift(s)</th><th className="px-6 py-3">Calc(s)</th><th className="px-6 py-3 text-right no-print">Act</th></tr></thead>
                      <tbody className="divide-y divide-slate-100 print:divide-black">
                        {segments.map((seg, idx) => (
                          <tr key={seg.id} onClick={() => setSelectedSegmentId(seg.id)} className={`cursor-pointer transition-colors ${selectedSegmentId === seg.id ? 'bg-blue-50 ring-1 ring-blue-500 z-10 relative' : 'hover:bg-slate-50'} print:hover:bg-white`}>
                            <td className="px-4 py-3 text-center">
                                <div className={`w-6 h-6 rounded-full flex items-center justify-center font-bold text-[10px] mx-auto ${seg.x ? 'bg-blue-600 text-white shadow-sm' : 'bg-slate-200 text-slate-500'}`}>{idx + 1}</div>
                            </td>
                            <td className="px-6 py-3 font-mono text-blue-600 flex items-center gap-2 print:text-black">
                                {seg.id} 
                                {!seg.x && <span className="text-[10px] bg-red-100 text-red-600 px-1.5 py-0.5 rounded border border-red-200 flex items-center gap-1" title="Missing Map Coordinates"><MapPin size={10}/> No Map</span>}
                                {seg.x && !checkReachability(seg) && <div title="Out of Robot Reach Range!"><AlertCircle size={14} className="text-red-500" /></div>}
                            </td>
                            <td className="px-6 py-3 text-slate-900 dark:text-white"><input value={seg.name} onChange={(e) => updateSegment(seg.id, 'name', e.target.value)} className="bg-transparent outline-none w-full" onClick={(e) => e.stopPropagation()}/></td>
                            <td className="px-6 py-3 text-slate-900 dark:text-white"><select value={seg.side} onChange={(e) => updateSegment(seg.id, 'side', e.target.value)} className="bg-slate-100 rounded px-2 py-1 print:bg-transparent print:appearance-none text-slate-900" onClick={(e) => e.stopPropagation()}><option value="LEFT">Left</option><option value="RIGHT">Right</option></select></td>
                            <td className="px-6 py-3 text-slate-900 dark:text-white"><input type="number" value={seg.length} onChange={(e) => updateSegment(seg.id, 'length', Number(e.target.value))} className="bg-transparent outline-none w-20" onClick={(e) => e.stopPropagation()}/></td>
                            <td className="px-6 py-3 text-slate-900 dark:text-white"><select value={seg.position} onChange={(e) => updateSegment(seg.id, 'position', e.target.value)} className="bg-slate-100 rounded px-2 py-1 max-w-[100px] print:bg-transparent print:appearance-none text-slate-900" onClick={(e) => e.stopPropagation()}>{weldPositions.map(p=><option key={p.id} value={p.id}>{p.label}</option>)}</select></td>
                            <td className="px-6 py-3 text-slate-900 dark:text-white"><input type="number" step="0.1" value={seg.liftTime||0} onChange={(e) => updateSegment(seg.id, 'liftTime', Number(e.target.value))} className="bg-transparent outline-none w-16 text-center" onClick={(e) => e.stopPropagation()}/></td>
                            <td className="px-6 py-3 text-center font-bold text-emerald-600 print:text-black">{calculateSegmentTime(seg).toFixed(1)}</td>
                            <td className="px-6 py-3 text-right flex justify-end gap-2 no-print"><button onClick={(e) => { e.stopPropagation(); duplicateSegment(seg); }} className="text-slate-600 dark:text-slate-400 hover:text-blue-500"><Copy size={14}/></button><button onClick={(e) => { e.stopPropagation(); removeSegment(seg.id); }} className="text-slate-600 dark:text-slate-400 hover:text-red-500"><Trash2 size={14}/></button></td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  </div>
               </div>
            </div>
          )}
          
          {activeTab === 'GROUPS' && (
             <div className="space-y-6 animate-in fade-in zoom-in-95 duration-200">
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                    {weldGroups.map((group) => (
                        <div key={group.id} className="p-6 rounded-xl border relative overflow-hidden transition-all hover:shadow-md bg-white border-slate-200">
                            <div className="absolute top-0 left-0 right-0 h-1.5" style={{backgroundColor: group.color}}></div>
                            <div className="flex justify-between items-start mb-4 pt-2">
                                <div className="flex items-center gap-3">
                                    <div className="w-10 h-10 rounded-lg flex items-center justify-center text-white font-bold shadow-sm" style={{backgroundColor: group.color}}>{group.name.charAt(0)}</div>
                                    <div><input value={group.name} onChange={(e) => updateGroup(group.id, 'name', e.target.value)} className="font-bold bg-transparent outline-none border-b border-transparent focus:border-blue-500 text-slate-900"/></div>
                                </div>
                                <button onClick={() => removeGroup(group.id)} className="text-slate-300 hover:text-red-500 transition-colors"><Trash2 size={18}/></button>
                            </div>
                            <div className="flex items-center gap-2 bg-slate-50 p-2 rounded-lg border border-slate-100"><Palette size={16} className="text-slate-400 ml-2"/><input type="color" value={group.color} onChange={(e) => updateGroup(group.id, 'color', e.target.value)} className="w-8 h-8 rounded cursor-pointer border-0 p-0 bg-transparent"/></div>
                        </div>
                    ))}
                    <button onClick={addGroup} className="flex flex-col items-center justify-center p-6 border-2 border-dashed rounded-xl text-slate-400 hover:bg-slate-50"><Plus size={32} className="mb-2"/>Add Group</button>
                </div>
             </div>
          )}

          {activeTab === 'STANDARD_TIMES' && (
             <div className="p-6 rounded-xl border shadow-sm bg-white border-slate-200">
                 <div className="flex justify-between items-center mb-6">
                    <h3 className="font-bold text-lg flex items-center gap-2 text-slate-900"><Clock size={20} className="text-blue-500"/> Weld Position Standards</h3>
                    <button onClick={addPosition} className="flex items-center gap-2 px-4 py-2 bg-blue-600 text-white rounded-lg text-xs font-bold shadow hover:bg-blue-700"><Plus size={16}/> Add Standard</button>
                 </div>
                 <table className="w-full text-sm text-left">
                    <thead className="text-xs uppercase font-bold bg-slate-200 text-slate-800"><tr><th className="px-6 py-4">Position Name</th><th className="px-6 py-4 text-right">Time Factor (s/mm)</th><th className="px-6 py-4 text-center">Action</th></tr></thead>
                    <tbody className="divide-y divide-slate-100">
                       {weldPositions.map((pos) => (
                          <tr key={pos.id} className="hover:bg-slate-50"><td className="px-6 py-4"><input value={pos.label} onChange={(e) => updatePosition(pos.id, 'label', e.target.value)} className="w-full bg-transparent outline-none font-medium text-slate-900"/></td><td className="px-6 py-4 text-right"><input type="number" step="0.001" value={pos.factor} onChange={(e) => updatePosition(pos.id, 'factor', e.target.value)} className="w-24 text-right bg-slate-100 rounded px-2 py-1 font-mono font-bold text-blue-600 outline-none focus:ring-2 focus:ring-blue-500"/></td><td className="px-6 py-4 text-center"><button onClick={() => removePosition(pos.id)} className="text-slate-600 hover:text-red-500"><Trash2 size={16}/></button></td></tr>
                       ))}
                    </tbody>
                 </table>
             </div>
          )}

          {activeTab === 'CONSTRAINTS' && (
             <div className="p-6 rounded-xl border shadow-sm bg-white border-slate-200">
                 <div className="flex justify-between items-center mb-6">
                    <h3 className="font-bold text-xl flex items-center gap-2 text-slate-900"><LinkIcon size={20} className="text-amber-500"/> Sequence Constraints</h3>
                    <button onClick={addConstraint} className="flex items-center gap-2 px-5 py-2 bg-amber-500 text-white rounded-xl font-bold text-sm shadow hover:bg-amber-600"><Plus size={18}/> Add Constraint</button>
                 </div>
                 {constraints.map((c, idx) => (
                    <div key={c.id} className="flex items-center gap-4 bg-slate-50 p-4 rounded-xl border border-slate-200 mb-2">
                        <span className="w-8 h-8 flex items-center justify-center bg-white rounded-full font-bold text-xs shadow-sm text-slate-700">{idx+1}</span>
                        <div className="flex items-center gap-2 flex-1"><select value={c.firstWeldId} onChange={(e) => updateConstraint(c.id, 'firstWeldId', e.target.value)} className="flex-1 border rounded-lg px-3 py-2 bg-white text-slate-900"><option value="">-- Select Predecessor --</option>{segments.map(s => <option key={s.id} value={s.id}>{s.name} ({s.id})</option>)}</select><ArrowRightLeft size={16} className="text-slate-400"/><select value={c.secondWeldId} onChange={(e) => updateConstraint(c.id, 'secondWeldId', e.target.value)} className="flex-1 border rounded-lg px-3 py-2 bg-white text-slate-900"><option value="">-- Select Successor --</option>{segments.map(s => <option key={s.id} value={s.id}>{s.name} ({s.id})</option>)}</select></div>
                        <button onClick={() => removeConstraint(c.id)} className="p-2 text-slate-400 hover:text-red-500 hover:bg-red-50 rounded-lg"><Trash2 size={18}/></button>
                    </div>
                 ))}
             </div>
          )}

          {activeTab === 'RESULTS' && (
             <div className="space-y-6 animate-in fade-in zoom-in-95 duration-200 pb-10">
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 no-print">
                   {/* KPI Card 1: JPH */}
                   <div className="p-6 rounded-xl border shadow-sm bg-white border-slate-200 flex flex-col justify-between hover:shadow-md transition-shadow">
                      <div className="flex justify-between items-start mb-2">
                          <div className="text-xs font-bold text-slate-700 dark:text-slate-400 uppercase tracking-wider flex items-center gap-1"><Zap size={14}/> JPH</div>
                          <div className={`p-1 rounded bg-blue-50 text-blue-500`}><Activity size={16}/></div>
                      </div>
                      <div>
                          <div className="text-3xl font-bold text-slate-900 dark:text-white">{maxCycleTime > 0 ? (3600 / maxCycleTime).toFixed(1) : 0}</div>
                          <div className="text-xs text-slate-600 dark:text-slate-500 mt-1">Jobs Per Hour</div>
                      </div>
                   </div>

                   {/* KPI Card 2: Output / Shift */}
                   <div className="p-6 rounded-xl border shadow-sm bg-white border-slate-200 flex flex-col justify-between hover:shadow-md transition-shadow">
                      <div className="flex justify-between items-start mb-2">
                          <div className="text-xs font-bold text-slate-700 dark:text-slate-400 uppercase tracking-wider flex items-center gap-1"><Package size={14}/> Output</div>
                          <div className={`p-1 rounded bg-purple-50 text-purple-500`}><Target size={16}/></div>
                      </div>
                      <div>
                          <div className="text-3xl font-bold text-purple-600">{(maxCycleTime > 0 ? (3600*8 / maxCycleTime) : 0).toFixed(0)}</div>
                          <div className="text-xs text-slate-600 dark:text-slate-500 mt-1">Units per 8hr Shift</div>
                      </div>
                   </div>

                   {/* KPI Card 3: Efficiency */}
                   <div className="p-6 rounded-xl border shadow-sm bg-white border-slate-200 flex flex-col justify-between hover:shadow-md transition-shadow">
                      <div className="flex justify-between items-start mb-2">
                          <div className="text-xs font-bold text-slate-700 dark:text-slate-400 uppercase tracking-wider flex items-center gap-1"><TrendingUp size={14}/> Line Eff.</div>
                          <div className={`p-1 rounded bg-emerald-50 text-emerald-500`}><Gauge size={16}/></div>
                      </div>
                      <div>
                          <div className="text-3xl font-bold text-emerald-600">{lineEfficiency.toFixed(1)}%</div>
                          <div className="text-xs text-slate-600 dark:text-slate-500 mt-1">Resource Utilization</div>
                      </div>
                   </div>

                   {/* KPI Card 4: Cycle Time */}
                   <div className={`p-6 rounded-xl border shadow-sm bg-white border-slate-200 flex flex-col justify-between hover:shadow-md transition-shadow ${!isBalanced ? 'ring-2 ring-red-500 ring-offset-2' : ''}`}>
                      <div className="flex justify-between items-start mb-2">
                          <div className="text-xs font-bold text-slate-700 dark:text-slate-400 uppercase tracking-wider flex items-center gap-1"><Timer size={14}/> Cycle Time</div>
                          <div className={`p-1 rounded ${!isBalanced ? 'bg-red-50 text-red-500' : 'bg-slate-50 text-slate-500'}`}><AlertCircle size={16}/></div>
                      </div>
                      <div>
                          <div className={`text-3xl font-bold ${!isBalanced ? 'text-red-500' : 'text-slate-900 dark:text-white'}`}>{maxCycleTime.toFixed(1)}<span className="text-lg text-slate-600 dark:text-slate-400 font-normal">s</span></div>
                          <div className="text-xs text-slate-600 dark:text-slate-500 mt-1">Target: {taktTime}s</div>
                      </div>
                   </div>
                </div>

                <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
                    {/* Waste Analysis */}
                    <div className="p-6 rounded-xl border shadow-sm bg-white border-slate-200 lg:col-span-1 flex flex-col h-[400px]">
                         <h3 className="font-bold text-lg mb-6 flex items-center gap-2 text-slate-900"><PieChartIcon size={20} className="text-blue-500"/> Waste Analysis</h3>
                         <div className="flex-1 w-full h-full relative">
                             {wasteData.length > 0 ? (
                                <ResponsiveContainer width="100%" height="100%">
                                    <PieChart>
                                        <Pie data={wasteData} cx="50%" cy="50%" innerRadius={60} outerRadius={100} paddingAngle={2} dataKey="value">
                                            {wasteData.map((entry, index) => <Cell key={`cell-${index}`} fill={entry.color} stroke="none"/>)}
                                        </Pie>
                                        <Tooltip formatter={(value: number) => `${value.toFixed(1)}s`} contentStyle={{borderRadius: '8px', border: 'none', boxShadow: '0 4px 6px -1px rgb(0 0 0 / 0.1)'}}/>
                                        <Legend verticalAlign="bottom" height={36} iconType="circle"/>
                                    </PieChart>
                                </ResponsiveContainer>
                             ) : (
                                <div className="flex items-center justify-center h-full text-slate-600 text-sm">No data available</div>
                             )}
                             <div className="absolute inset-0 flex items-center justify-center pointer-events-none">
                                <div className="text-center">
                                    <div className="text-xs font-bold text-slate-600 uppercase">Total Time</div>
                                    <div className="text-2xl font-bold text-slate-900">{(currentStats.totalTime).toFixed(0)}s</div>
                                </div>
                             </div>
                         </div>
                    </div>

                    {/* Yamazumi Chart */}
                    <div className="p-6 rounded-xl border shadow-sm bg-white border-slate-200 lg:col-span-2 flex flex-col min-h-[400px]">
                        <div className="flex justify-between items-center mb-6">
                            <h3 className="font-bold text-lg flex items-center gap-2 text-slate-900"><BarChart3 size={20} className="text-blue-500"/> Line Balance (Yamazumi)</h3>
                            <div className="flex items-center gap-3 no-print">
                                {isDragMode && (
                                    <button onClick={clearManualOverrides} className="text-xs px-3 py-1.5 bg-red-100 text-red-600 hover:bg-red-200 rounded font-bold border border-red-200 transition-colors flex items-center gap-1"><RotateCcw size={12}/> Reset</button>
                                )}
                                <button onClick={() => setIsDragMode(!isDragMode)} className={`flex items-center gap-2 px-3 py-1.5 rounded-lg text-xs font-bold border transition-all ${isDragMode ? 'bg-indigo-600 text-white border-indigo-700 ring-2 ring-indigo-200' : 'bg-white text-slate-800 border-slate-300 hover:bg-slate-50'}`}>{isDragMode ? <><CheckCircle2 size={14}/> Done</> : <><Edit3 size={14}/> Edit</>}</button>
                            </div>
                        </div>
                        <div className="flex-1 w-full overflow-hidden">
                            {isDragMode ? (
                                <div className="w-full overflow-x-auto pb-4 h-full">
                                    {(() => {
                                        const maxVal = Math.max(taktTime * 1.2, currentStats.maxCycleTime * 1.1, 10);
                                        const chartHeight = 300; 
                                        if (separateSides) {
                                            return (
                                                <div className="flex gap-12 min-w-max h-full items-end pb-6">
                                                    <div className="flex gap-4 p-4 border rounded-xl bg-slate-50/50 h-full"><div className="writing-vertical text-xs font-bold text-blue-400 rotate-180 flex items-center justify-center tracking-widest">LEFT LINE</div>{currentStats.processes.filter(p => p.side === 'LEFT').map(proc => renderInteractiveColumn(proc, maxVal, chartHeight))}</div>
                                                    <div className="flex gap-4 p-4 border rounded-xl bg-slate-50/50 h-full"><div className="writing-vertical text-xs font-bold text-orange-400 rotate-180 flex items-center justify-center tracking-widest">RIGHT LINE</div>{currentStats.processes.filter(p => p.side === 'RIGHT').map(proc => renderInteractiveColumn(proc, maxVal, chartHeight))}</div>
                                                </div>
                                            );
                                        } else {
                                            return <div className="flex gap-4 min-w-max p-4 border rounded-xl bg-slate-50/50 h-full items-end pb-6">{currentStats.processes.map(proc => renderInteractiveColumn(proc, maxVal, chartHeight))}</div>;
                                        }
                                    })()}
                                </div>
                            ) : (
                                separateSides ? (
                                    <div className="grid grid-cols-1 lg:grid-cols-2 gap-8 h-full">
                                        <div className="flex flex-col h-full border-r border-slate-100 pr-4">
                                            <h4 className="text-xs font-bold text-blue-500 mb-4 uppercase tracking-widest text-center bg-blue-50 py-1.5 rounded-md">Left Line</h4>
                                            <ResponsiveContainer width="100%" height={300}>
                                                <BarChart data={yamazumiData.filter(d => d.side === 'LEFT')} margin={{top: 30, right: 10, left: 0, bottom: 5}}>
                                                    <defs>
                                                        <marker id="arrowHead" markerWidth="10" markerHeight="7" refX="0" refY="3.5" orient="auto">
                                                            <polygon points="0 0, 10 3.5, 0 7" fill="#cbd5e1" />
                                                        </marker>
                                                    </defs>
                                                    <CartesianGrid strokeDasharray="3 3" vertical={false}/>
                                                    <XAxis dataKey="name" tick={{fontSize: 10}} axisLine={false} tickLine={false}/>
                                                    <YAxis 
                                                        axisLine={{ stroke: '#cbd5e1', strokeWidth: 1, markerEnd: 'url(#arrowHead)' }} 
                                                        tickLine={false} 
                                                        tick={{fontSize: 10, fill: '#334155'}} 
                                                        domain={[0, (dataMax: number) => {
                                                            const maxVal = Math.max(dataMax || 0, taktTime);
                                                            const step = maxVal > 100 ? 50 : 20;
                                                            return Math.ceil((maxVal * 1.15) / step) * step;
                                                        }]}
                                                        allowDecimals={false}
                                                        label={{ value: 'sec.', position: 'top', offset: 10, dy: -20, dx: 0, fill: '#334155', fontSize: 10, fontWeight: 'bold' }}
                                                    />
                                                    <Tooltip cursor={{fill: 'transparent'}} contentStyle={{borderRadius: '8px', border: 'none', boxShadow: '0 4px 6px -1px rgb(0 0 0 / 0.1)'}}/>
                                                    <ReferenceLine y={taktTime} stroke="#ef4444" strokeDasharray="3 3" label={{ value: `Takt time = ${taktTime}`, position: 'insideTopRight', fill: '#ef4444', fontSize: 11, fontWeight: 'bold', dy: -20 }} />
                                                    <Bar dataKey="dummy" fill="transparent" stackId="a" />
                                                    {segments.map((seg, idx) => <Bar key={seg.id} dataKey={seg.id} stackId="a" fill={PRESET_COLORS[idx % PRESET_COLORS.length]} radius={[2, 2, 0, 0]} />)}
                                                </BarChart>
                                            </ResponsiveContainer>
                                        </div>
                                        <div className="flex flex-col h-full">
                                            <h4 className="text-xs font-bold text-orange-500 mb-4 uppercase tracking-widest text-center bg-orange-50 py-1.5 rounded-md">Right Line</h4>
                                            <ResponsiveContainer width="100%" height={300}>
                                                <BarChart data={yamazumiData.filter(d => d.side === 'RIGHT')} margin={{top: 30, right: 10, left: 0, bottom: 5}}>
                                                    <defs>
                                                        <marker id="arrowHead" markerWidth="10" markerHeight="7" refX="0" refY="3.5" orient="auto">
                                                            <polygon points="0 0, 10 3.5, 0 7" fill="#cbd5e1" />
                                                        </marker>
                                                    </defs>
                                                    <CartesianGrid strokeDasharray="3 3" vertical={false}/>
                                                    <XAxis dataKey="name" tick={{fontSize: 10}} axisLine={false} tickLine={false}/>
                                                    <YAxis 
                                                        axisLine={{ stroke: '#cbd5e1', strokeWidth: 1, markerEnd: 'url(#arrowHead)' }} 
                                                        tickLine={false} 
                                                        tick={{fontSize: 10, fill: '#334155'}} 
                                                        domain={[0, (dataMax: number) => {
                                                            const maxVal = Math.max(dataMax || 0, taktTime);
                                                            const step = maxVal > 100 ? 50 : 20;
                                                            return Math.ceil((maxVal * 1.15) / step) * step;
                                                        }]}
                                                        allowDecimals={false}
                                                        label={{ value: 'sec.', position: 'top', offset: 10, dy: -20, dx: 0, fill: '#334155', fontSize: 10, fontWeight: 'bold' }}
                                                    />
                                                    <Tooltip cursor={{fill: 'transparent'}} contentStyle={{borderRadius: '8px', border: 'none', boxShadow: '0 4px 6px -1px rgb(0 0 0 / 0.1)'}}/>
                                                    <ReferenceLine y={taktTime} stroke="#ef4444" strokeDasharray="3 3" label={{ value: `Takt time = ${taktTime}`, position: 'insideTopRight', fill: '#ef4444', fontSize: 11, fontWeight: 'bold', dy: -20 }} />
                                                    <Bar dataKey="dummy" fill="transparent" stackId="a" />
                                                    {segments.map((seg, idx) => <Bar key={seg.id} dataKey={seg.id} stackId="a" fill={PRESET_COLORS[idx % PRESET_COLORS.length]} radius={[2, 2, 0, 0]} />)}
                                                </BarChart>
                                            </ResponsiveContainer>
                                        </div>
                                    </div>
                                ) : (
                                    <div className="h-full w-full min-h-[300px]">
                                        <ResponsiveContainer width="100%" height={300}>
                                            <BarChart data={yamazumiData} margin={{top: 30, right: 10, left: 0, bottom: 5}}>
                                                <defs>
                                                    <marker id="arrowHead" markerWidth="10" markerHeight="7" refX="0" refY="3.5" orient="auto">
                                                        <polygon points="0 0, 10 3.5, 0 7" fill="#cbd5e1" />
                                                    </marker>
                                                </defs>
                                                <CartesianGrid strokeDasharray="3 3" vertical={false}/>
                                                <XAxis dataKey="name" tick={{fontSize: 12}} axisLine={false} tickLine={false}/>
                                                <YAxis 
                                                    axisLine={{ stroke: '#cbd5e1', strokeWidth: 1, markerEnd: 'url(#arrowHead)' }} 
                                                    tickLine={false} 
                                                    tick={{fontSize: 10, fill: '#334155'}} 
                                                    domain={[0, (dataMax: number) => {
                                                        const maxVal = Math.max(dataMax || 0, taktTime);
                                                        const step = maxVal > 100 ? 50 : 20;
                                                        return Math.ceil((maxVal * 1.15) / step) * step;
                                                    }]}
                                                    allowDecimals={false}
                                                    label={{ value: 'sec.', position: 'top', offset: 10, dy: -20, dx: 0, fill: '#334155', fontSize: 10, fontWeight: 'bold' }}
                                                />
                                                <Tooltip cursor={{fill: 'transparent'}} contentStyle={{borderRadius: '8px', border: 'none', boxShadow: '0 4px 6px -1px rgb(0 0 0 / 0.1)'}}/>
                                                <ReferenceLine y={taktTime} stroke="#ef4444" strokeDasharray="3 3" label={{ value: `Takt time = ${taktTime}`, position: 'insideTopRight', fill: '#ef4444', fontSize: 11, fontWeight: 'bold', dy: -20 }} />
                                                {segments.map((seg, idx) => <Bar key={seg.id} dataKey={seg.id} stackId="a" fill={PRESET_COLORS[idx % PRESET_COLORS.length]} name={seg.name} radius={[2, 2, 0, 0]} />)}
                                            </BarChart>
                                        </ResponsiveContainer>
                                    </div>
                                )
                            )}
                        </div>
                    </div>
                </div>
                
                {separateSides ? (
                    <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
                        <div className="space-y-4"><h4 className="font-bold text-slate-700 dark:text-slate-400 uppercase text-xs border-b pb-2 mb-4 tracking-wider">Left Line Processes</h4>{currentStats.processes.filter(p => p.side === 'LEFT').map((proc, idx) => renderProcessCard(proc, idx))}</div>
                        <div className="space-y-4"><h4 className="font-bold text-slate-700 dark:text-slate-400 uppercase text-xs border-b pb-2 mb-4 tracking-wider">Right Line Processes</h4>{currentStats.processes.filter(p => p.side === 'RIGHT').map((proc, idx) => renderProcessCard(proc, idx))}</div>
                    </div>
                ) : (
                    <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">{currentStats.processes.map((proc, pIdx) => renderProcessCard(proc, pIdx))}</div>
                )}
             </div>
          )}

          {activeTab === 'FRAME_VIEW' && (
             <div className="h-[750px] flex animate-in fade-in zoom-in-95 duration-200">
                {/* --- Main Content Area (Image) --- */}
                <div className="flex-1 flex flex-col h-full mr-4">
                    <div className="flex flex-col gap-2 mb-4 no-print">
                       <div className="flex justify-between items-center">
                          <div className="flex items-center gap-4">
                              <button onClick={() => { setIsManualBalanceMode(!isManualBalanceMode); setShowPathFlow(false); }} className={`flex items-center gap-2 px-3 py-1.5 rounded-lg border text-sm font-bold transition-all ${isManualBalanceMode ? 'bg-purple-600 text-white' : 'bg-white text-slate-800 border-slate-300'}`}><MousePointer2 size={14} /> Manual Balance</button>
                              {!isManualBalanceMode && (<><button onClick={() => setShowPathFlow(!showPathFlow)} className={`flex items-center gap-2 px-3 py-1.5 rounded-lg border text-sm font-bold transition-all ${showPathFlow ? 'bg-indigo-600 text-white' : 'bg-white text-slate-800 border-slate-300'}`}><Move size={14} /> Path Flow</button><button onClick={() => setShowReachZones(!showReachZones)} className={`flex items-center gap-2 px-3 py-1.5 rounded-lg border text-sm font-bold transition-all ${showReachZones ? 'bg-blue-600 text-white' : 'bg-white text-slate-800 border-slate-300'}`}><Circle size={14} /> Zones</button><button onClick={() => setShowInterferenceZone(!showInterferenceZone)} className={`flex items-center gap-2 px-3 py-1.5 rounded-lg border text-sm font-bold transition-all ${showInterferenceZone ? 'bg-amber-500 text-white border-amber-600' : 'bg-white text-slate-800 border-slate-300'}`}><Siren size={14} /> Interference Area</button></>)}
                          </div>
                          <div className="flex gap-2 items-center">
                             <div className="flex items-center gap-2 bg-orange-50 border border-orange-200 px-3 py-1.5 rounded text-xs text-orange-800 font-bold mr-2"><Scale size={14}/> Width:<input type="number" value={frameWidthMM} onChange={e=>setFrameWidthMM(Number(e.target.value))} className="w-16 bg-white border border-orange-300 rounded px-1 text-center outline-none"/>mm</div>
                             <button onClick={() => fileInputRef.current?.click()} className="px-3 py-1.5 border border-slate-400 text-slate-800 rounded text-sm hover:bg-slate-50 flex items-center gap-2"><Upload size={14}/> Upload Img</button>
                             <input type="file" ref={fileInputRef} className="hidden" accept="image/*" onChange={handleImageUpload} />
                             <div className="flex items-center gap-1 bg-slate-100 rounded px-2 border border-slate-200"><button onClick={() => handleZoom(-10)} className="p-1.5"><ZoomOut size={14}/></button><span className="text-xs w-12 text-center text-slate-900">{zoomLevel}%</span><button onClick={() => handleZoom(10)} className="p-1.5"><ZoomIn size={14}/></button></div>
                          </div>
                       </div>
                       {isManualBalanceMode && (<div className="flex items-center gap-2 animate-in slide-in-from-top-2 duration-200 bg-purple-50 p-2 rounded-lg border border-purple-100"><span className="text-sm font-bold text-purple-800 mr-2 flex items-center gap-1"><Hand size={14}/> Assignment Tool:</span><button onClick={() => setSelectedManualProcess(-1)} className={`px-3 py-1 rounded-md text-xs font-bold transition-colors ${selectedManualProcess === -1 ? 'bg-slate-600 text-white shadow-sm' : 'bg-white text-slate-800 border border-slate-300 hover:bg-slate-100'}`}>Auto (Clear)</button>{[0, 1, 2, 3].map(idx => (<button key={idx} onClick={() => setSelectedManualProcess(idx)} className={`px-3 py-1 rounded-md text-xs font-bold transition-colors flex items-center gap-1 shadow-sm ${selectedManualProcess === idx ? 'ring-2 ring-offset-1 ring-purple-400 text-white' : 'text-slate-800 bg-white border border-slate-300 hover:bg-slate-50'}`} style={{ backgroundColor: selectedManualProcess === idx ? PRESET_COLORS[idx % PRESET_COLORS.length] : undefined }}>{idx < 2 ? (idx === 0 ? 'L' : 'R') : `P${idx+1}`}</button>))}</div>)}
                       {selectedSegmentId && !isManualBalanceMode && unmappedSegments.find(s => s.id === selectedSegmentId) && (
                          <div className="flex items-center gap-2 animate-in slide-in-from-top-2 duration-200 bg-red-50 p-2 rounded-lg border border-red-200 shadow-sm justify-center">
                              <span className="text-sm font-bold text-red-600 flex items-center gap-2"><MousePointer2 size={16} className="animate-bounce"/> Click anywhere on the image to place <span className="underline">{unmappedSegments.find(s => s.id === selectedSegmentId)?.name}</span></span>
                          </div>
                       )}
                    </div>
                    <div className="flex-1 bg-slate-100 rounded-xl overflow-hidden border border-slate-200 relative flex items-center justify-center group select-none">
                      <div 
                        ref={imageContainerRef} 
                        className={`relative shadow-xl transition-transform duration-200 ${draggingId || draggingBase ? 'cursor-grabbing' : (selectedSegmentId && unmappedSegments.find(s => s.id === selectedSegmentId) ? 'cursor-crosshair' : 'cursor-default')}`} 
                        style={{ transform: `scale(${zoomLevel/100})` }} 
                        onClick={handleImageClick} 
                        onMouseMove={handleFrameMouseMove} 
                        onMouseUp={handleFrameMouseUp} 
                        onMouseLeave={handleFrameMouseUp} 
                        onContextMenu={(e) => e.preventDefault()}
                        onDragOver={(e) => e.preventDefault()}
                        onDrop={handleFrameDrop}
                      >
                         {frameImage ? (
                            <>
                               <img src={frameImage} className="max-w-full h-auto pointer-events-none" alt="Frame"/>
                               <SimulationVisualizer showPathFlow={showPathFlow || isManualBalanceMode} currentStats={currentStats} segments={segments} robotBases={robotBases} simTime={simTime} frameWidthMM={frameWidthMM} robotSettings={robotSettings} showReachZones={showReachZones} showInterferenceZone={showInterferenceZone} isCollisionNow={isCollisionNow}/>
                               <div className={`absolute w-12 h-12 -ml-6 -mt-6 rounded-full bg-white/80 border-2 border-blue-500 shadow-xl z-20 flex flex-col items-center justify-center cursor-move hover:scale-110 transition-transform select-none ${draggingBase === 'left' ? 'scale-110 ring-4 ring-blue-200' : ''}`} style={{ left: `${robotBases.left.x}%`, top: `${robotBases.left.y}%` }} onMouseDown={(e) => handleRobotBaseMouseDown(e, 'left')}><Bot size={20} className="text-blue-600"/><span className="text-[9px] font-bold text-blue-800">BASE L</span></div>
                               <div className={`absolute w-12 h-12 -ml-6 -mt-6 rounded-full bg-white/80 border-2 border-rose-500 shadow-xl z-20 flex flex-col items-center justify-center cursor-move hover:scale-110 transition-transform select-none ${draggingBase === 'right' ? 'scale-110 ring-4 ring-rose-200' : ''}`} style={{ left: `${robotBases.right.x}%`, top: `${robotBases.right.y}%` }} onMouseDown={(e) => handleRobotBaseMouseDown(e, 'right')}><Bot size={20} className="text-rose-600"/><span className="text-[9px] font-bold text-rose-800">BASE R</span></div>
                               {segments.map((seg, idx) => {
                                 const status = getWeldStatus(seg.id); 
                                 const isReachable = checkReachability(seg); 
                                 let pointClass = 'bg-blue-600 border-white'; 
                                 let scaleClass = '';
                                 
                                 if (isManualBalanceMode) { 
                                    const assignedProc = processes.find(p => p.weldIds.includes(seg.id)); 
                                    pointClass = assignedProc ? `border-white ring-2 ring-white shadow-sm` : 'bg-slate-400 border-white opacity-50'; 
                                 } else { 
                                    if (status === 'WELDING') { pointClass = 'bg-red-500 border-red-200 welding-pulse z-30'; scaleClass = 'scale-150'; } 
                                    else if (status === 'COMPLETED') { pointClass = 'bg-emerald-500 border-emerald-200'; } 
                                    else if (status === 'MOVING_TO') { pointClass = 'bg-amber-400 border-white scale-125 z-20'; } 
                                    else if (!isReachable && showReachZones) { pointClass = 'bg-slate-400 border-red-500 ring-2 ring-red-500 ring-offset-1 opacity-80'; } 
                                    if (selectedSegmentId === seg.id) { pointClass = 'bg-orange-500 border-orange-200'; scaleClass = 'scale-110 ring-4 ring-orange-200/60'; } 
                                 }
                                 
                                 const assignedProc = isManualBalanceMode ? processes.find(p => p.weldIds.includes(seg.id)) : null;
                                 
                                 return seg.x !== undefined && (
                                    <React.Fragment key={seg.id}>
                                        <div 
                                            className={`absolute w-7 h-7 -ml-3.5 -mt-3.5 rounded-full flex items-center justify-center text-[10px] font-bold border-2 shadow-md transition-all cursor-move ${pointClass} ${scaleClass}`} 
                                            style={{ left: `${seg.x}%`, top: `${seg.y}%`, backgroundColor: isManualBalanceMode && assignedProc ? PRESET_COLORS[assignedProc.id % PRESET_COLORS.length] : undefined }} 
                                            onMouseDown={(e) => handlePointMouseDown(e, seg.id)} 
                                            onClick={(e) => handlePointClick(e, seg.id)} 
                                            onContextMenu={(e) => handlePointContextMenu(e, seg.id, seg.name)} 
                                            title={`${seg.name}\n${isManualBalanceMode ? (assignedProc ? `Assigned to P${assignedProc.id+1}` : 'Unassigned') : status}`}
                                        >
                                            {idx + 1}
                                        </div>
                                        {selectedSegmentId === seg.id && !isManualBalanceMode && (
                                            <div className="absolute -mt-12 z-50 transform -translate-x-1/2 flex flex-col items-center animate-in fade-in zoom-in-95 duration-200" style={{ left: `${seg.x}%`, top: `${seg.y}%` }} onMouseDown={(e) => e.stopPropagation()} onClick={(e) => e.stopPropagation()}>
                                                <div className="bg-white rounded-lg shadow-xl border border-slate-200 p-1.5 flex items-center gap-1">
                                                    <button onClick={() => { if (window.confirm(`Delete ${seg.name}?`)) removeSegment(seg.id); }} className="p-1.5 bg-red-50 text-red-500 hover:bg-red-600 hover:text-white rounded-md transition-colors shadow-sm" title="Delete Point"><Trash2 size={14} strokeWidth={2.5} /></button>
                                                    <div className="w-px h-4 bg-slate-200 mx-0.5"></div>
                                                    <button onClick={() => duplicateSegment(seg)} className="p-1.5 bg-slate-50 text-slate-500 hover:bg-blue-500 hover:text-white rounded-md transition-colors shadow-sm" title="Duplicate Point"><Copy size={14} strokeWidth={2.5} /></button>
                                                </div>
                                                <div className="w-2 h-2 bg-white border-r border-b border-slate-200 transform rotate-45 -mt-1"></div>
                                            </div>
                                        )}
                                    </React.Fragment>
                                 );
                               })}
                            </>
                         ) : (
                            <div className="text-slate-400 flex flex-col items-center pointer-events-none"><ImageIcon size={64} className="mb-4 opacity-30"/><p>Upload frame image to start</p></div>
                         )}
                      </div>
                    </div>
                    <div className="mt-4 bg-slate-900 text-white p-4 rounded-xl shadow-lg flex items-center gap-4 relative overflow-hidden no-print">
                        {isCollisionNow && <div className="absolute inset-0 bg-red-600/30 animate-pulse pointer-events-none z-0"></div>}
                        <button onClick={() => { setIsPlaying(!isPlaying); if (simTime >= maxCycleTime) setSimTime(0); }} className="p-3 bg-blue-600 hover:bg-blue-500 rounded-full shadow-lg transition-transform active:scale-95 z-10">{isPlaying ? <Pause fill="white" /> : <Play fill="white" className="ml-1"/>}</button>
                        <button onClick={() => { setSimTime(0); setIsPlaying(false); }} className="p-2 hover:bg-slate-700 rounded-full text-slate-300 hover:text-white z-10"><RotateCcw size={20}/></button>
                        <div className="flex-1 z-10">
                            <div className="flex justify-between text-xs text-slate-300 mb-1 font-mono uppercase tracking-wider"><span>Process Simulation {isCollisionNow && <span className="text-red-400 font-bold ml-2 animate-bounce">⚠ COLLISION WARNING</span>}</span><span>{simTime.toFixed(1)}s / {maxCycleTime.toFixed(1)}s</span></div>
                            <input type="range" min="0" max={maxCycleTime + 0.1} step="0.1" value={simTime} onChange={(e) => { setSimTime(Number(e.target.value)); setIsPlaying(false); }} className="w-full h-2 bg-slate-700 rounded-lg appearance-none cursor-pointer accent-blue-500"/>
                        </div>
                        <div className="flex items-center gap-2 border-l border-slate-700 pl-4 z-10"><span className="text-xs text-slate-300 font-bold">SPEED</span><button onClick={() => setSimSpeed(1)} className={`px-2 py-1 rounded text-xs font-bold ${simSpeed === 1 ? 'bg-blue-600' : 'bg-slate-800 text-slate-300'}`}>1x</button><button onClick={() => setSimSpeed(2)} className={`px-2 py-1 rounded text-xs font-bold ${simSpeed === 2 ? 'bg-blue-600' : 'bg-slate-800 text-slate-300'}`}>2x</button><button onClick={() => setSimSpeed(5)} className={`px-2 py-1 rounded text-xs font-bold ${simSpeed === 5 ? 'bg-blue-600' : 'bg-slate-800 text-slate-300'}`}>5x</button></div>
                    </div>
                </div>

                {/* --- Unmapped Welds Sidebar --- */}
                {unmappedSegments.length > 0 && (
                    <div className="w-64 bg-white border border-slate-200 rounded-xl shadow-lg flex flex-col overflow-hidden animate-in slide-in-from-right duration-300">
                        <div className="p-4 bg-red-50 border-b border-red-100">
                            <h3 className="text-sm font-bold text-red-700 flex items-center gap-2">
                                <MapPin size={16}/> Unmapped Welds
                            </h3>
                            <p className="text-[10px] text-red-500 mt-1">
                                {unmappedSegments.length} items missing coordinates. Click to select, then click on image to place.
                            </p>
                        </div>
                        <div className="flex-1 overflow-y-auto p-2 space-y-2">
                            {unmappedSegments.map((seg, idx) => {
                                // Find original index in full segment list
                                const originalIdx = segments.findIndex(s => s.id === seg.id);
                                return (
                                    <div 
                                        key={seg.id}
                                        draggable
                                        onDragStart={(e) => handleDragStart(e, seg.id)}
                                        onClick={() => setSelectedSegmentId(seg.id)}
                                        className={`p-3 bg-white border rounded-lg shadow-sm hover:shadow-md cursor-pointer transition-all ${selectedSegmentId === seg.id ? 'ring-2 ring-blue-500 border-transparent bg-blue-50' : 'border-slate-200'}`}
                                    >
                                        <div className="flex items-center gap-2 mb-1">
                                            <span className="w-5 h-5 rounded-full bg-slate-200 text-slate-600 text-[10px] font-bold flex items-center justify-center">
                                                {originalIdx + 1}
                                            </span>
                                            <span className="font-bold text-xs text-slate-900 truncate">{seg.id}</span>
                                        </div>
                                        <div className="text-[10px] text-slate-700 truncate">{seg.name}</div>
                                        {selectedSegmentId === seg.id && (
                                            <div className="text-[9px] text-blue-600 font-bold mt-1 animate-pulse">
                                                Active: Click on map to place
                                            </div>
                                        )}
                                    </div>
                                );
                            })}
                        </div>
                    </div>
                )}
             </div>
          )}
        </div>
      </div>
      
      {/* Robot Settings Modal */}
      {showRobotSettingsModal && (
        <div className="fixed inset-0 bg-black/60 flex items-center justify-center z-[70] p-4 animate-in fade-in zoom-in-95 duration-200">
            <div className="bg-white rounded-xl shadow-2xl w-full max-w-lg border border-slate-200">
                <div className="p-4 border-b flex justify-between items-center bg-indigo-50 rounded-t-xl">
                    <h3 className="font-bold text-lg text-indigo-900 flex items-center gap-2"><Bot size={20}/> Robot Configuration</h3>
                    <button onClick={() => setShowRobotSettingsModal(false)} className="p-1 hover:bg-indigo-100 rounded-lg text-indigo-700"><X size={20}/></button>
                </div>
                <div className="p-6 space-y-6">
                    <div className="space-y-4">
                        <div className="flex items-center justify-between">
                            <label className="text-sm font-bold text-slate-700">Air Cut Speed (m/s)</label>
                            <input type="number" step="0.1" value={robotSettings.moveSpeed} onChange={(e) => setRobotSettings({...robotSettings, moveSpeed: Number(e.target.value)})} className="w-24 border rounded px-2 py-1 text-right font-mono"/>
                        </div>
                        <div className="flex items-center justify-between">
                            <label className="text-sm font-bold text-slate-700">Arc On/Off Delay (s)</label>
                            <input type="number" step="0.1" value={robotSettings.arcDelay} onChange={(e) => setRobotSettings({...robotSettings, arcDelay: Number(e.target.value)})} className="w-24 border rounded px-2 py-1 text-right font-mono"/>
                        </div>
                        <div className="flex items-center justify-between">
                            <label className="text-sm font-bold text-slate-700">Cleaning Interval (cycles)</label>
                            <input type="number" step="1" value={robotSettings.cleaningInterval} onChange={(e) => setRobotSettings({...robotSettings, cleaningInterval: Number(e.target.value)})} className="w-24 border rounded px-2 py-1 text-right font-mono"/>
                        </div>
                    </div>
                    
                    <div className="border-t pt-4 space-y-3">
                        <div className="flex items-center justify-between">
                            <span className="text-sm font-medium text-slate-700">Calculate Air Cut Time</span>
                            <button onClick={() => setRobotSettings({...robotSettings, includeMovementTime: !robotSettings.includeMovementTime})} className={`w-10 h-5 rounded-full relative transition-colors ${robotSettings.includeMovementTime ? 'bg-indigo-600' : 'bg-slate-300'}`}>
                                <div className={`absolute w-3 h-3 bg-white rounded-full top-1 transition-all ${robotSettings.includeMovementTime ? 'left-6' : 'left-1'}`}></div>
                            </button>
                        </div>
                        <div className="flex items-center justify-between">
                            <span className="text-sm font-medium text-slate-700">Optimize Path (TSP)</span>
                            <button onClick={() => setRobotSettings({...robotSettings, optimizePath: !robotSettings.optimizePath})} className={`w-10 h-5 rounded-full relative transition-colors ${robotSettings.optimizePath ? 'bg-indigo-600' : 'bg-slate-300'}`}>
                                <div className={`absolute w-3 h-3 bg-white rounded-full top-1 transition-all ${robotSettings.optimizePath ? 'left-6' : 'left-1'}`}></div>
                            </button>
                        </div>
                        <div className="flex items-center justify-between">
                            <span className="text-sm font-medium text-slate-700 flex items-center gap-2"><Home size={14}/> Return to Home after Cycle</span>
                            <button onClick={() => setRobotSettings({...robotSettings, includeReturnHome: !robotSettings.includeReturnHome})} className={`w-10 h-5 rounded-full relative transition-colors ${robotSettings.includeReturnHome ? 'bg-indigo-600' : 'bg-slate-300'}`}>
                                <div className={`absolute w-3 h-3 bg-white rounded-full top-1 transition-all ${robotSettings.includeReturnHome ? 'left-6' : 'left-1'}`}></div>
                            </button>
                        </div>
                        
                        {/* New Home Position Timing Configuration */}
                        <div className="bg-slate-50 rounded-lg p-3 border border-slate-100">
                            <div className="flex items-center justify-between mb-3">
                                <span className="text-sm font-bold text-slate-800 flex items-center gap-2"><TimerReset size={16} className="text-indigo-500"/> Home Position Timing</span>
                                <button onClick={() => setRobotSettings({...robotSettings, useFixedHomeTimes: !robotSettings.useFixedHomeTimes})} className={`w-10 h-5 rounded-full relative transition-colors ${robotSettings.useFixedHomeTimes ? 'bg-indigo-600' : 'bg-slate-300'}`}>
                                    <div className={`absolute w-3 h-3 bg-white rounded-full top-1 transition-all ${robotSettings.useFixedHomeTimes ? 'left-6' : 'left-1'}`}></div>
                                </button>
                            </div>
                            
                            {robotSettings.useFixedHomeTimes ? (
                                <div className="grid grid-cols-2 gap-4 animate-in fade-in slide-in-from-top-2">
                                    <div>
                                        <label className="text-[10px] uppercase font-bold text-slate-500 mb-1 block">Approach Time (s)</label>
                                        <div className="relative">
                                            <input type="number" step="0.1" value={robotSettings.fixedApproachTime} onChange={(e) => setRobotSettings({...robotSettings, fixedApproachTime: Number(e.target.value)})} className="w-full border rounded px-2 py-1.5 text-sm font-mono focus:ring-1 focus:ring-indigo-500 outline-none"/>
                                            <span className="absolute right-2 top-1.5 text-xs text-slate-400">sec</span>
                                        </div>
                                        <div className="text-[10px] text-slate-400 mt-1">Home → 1st Weld</div>
                                    </div>
                                    <div>
                                        <label className="text-[10px] uppercase font-bold text-slate-500 mb-1 block">Return Time (s)</label>
                                        <div className="relative">
                                            <input type="number" step="0.1" value={robotSettings.fixedReturnTime} onChange={(e) => setRobotSettings({...robotSettings, fixedReturnTime: Number(e.target.value)})} className="w-full border rounded px-2 py-1.5 text-sm font-mono focus:ring-1 focus:ring-indigo-500 outline-none"/>
                                            <span className="absolute right-2 top-1.5 text-xs text-slate-400">sec</span>
                                        </div>
                                        <div className="text-[10px] text-slate-400 mt-1">Last Weld → Home</div>
                                    </div>
                                </div>
                            ) : (
                                <div className="text-xs text-slate-500 italic text-center py-2">
                                    Timing calculated automatically based on distance & speed.
                                </div>
                            )}
                        </div>
                    </div>
                </div>
                <div className="p-4 bg-slate-50 border-t rounded-b-xl flex justify-end">
                    <button onClick={() => setShowRobotSettingsModal(false)} className="px-4 py-2 bg-indigo-600 text-white rounded-lg font-bold text-sm hover:bg-indigo-700">Close & Apply</button>
                </div>
            </div>
        </div>
      )}

      {/* Manual Settings Modal */}
      {showManualSettingsModal && (
        <div className="fixed inset-0 bg-black/60 flex items-center justify-center z-[70] p-4 animate-in fade-in zoom-in-95 duration-200">
            <div className="bg-white rounded-xl shadow-2xl w-full max-w-lg border border-slate-200">
                <div className="p-4 border-b flex justify-between items-center bg-orange-50 rounded-t-xl">
                    <h3 className="font-bold text-lg text-orange-900 flex items-center gap-2"><Briefcase size={20}/> Manual Process Config</h3>
                    <button onClick={() => setShowManualSettingsModal(false)} className="p-1 hover:bg-orange-100 rounded-lg text-orange-700"><X size={20}/></button>
                </div>
                <div className="p-6 space-y-6">
                    <div className="space-y-1">
                        <h4 className="text-sm font-bold text-slate-800 border-b pb-2 mb-4">Initial Setup / Handling</h4>
                        <div className="flex items-center justify-between mb-4">
                            <div>
                                <label className="text-sm font-bold text-slate-700 block">Start/End Handling (s)</label>
                                <span className="text-xs text-slate-500">Pick up torch, mask down, etc. (Per Cycle)</span>
                            </div>
                            <input type="number" step="0.5" value={manualSettings.handlingTime} onChange={(e) => setManualSettings({...manualSettings, handlingTime: Number(e.target.value)})} className="w-24 border rounded px-2 py-1 text-right font-mono"/>
                        </div>
                    </div>

                    <div className="space-y-1">
                        <h4 className="text-sm font-bold text-slate-800 border-b pb-2 mb-4">Jig Operations</h4>
                        <div className="flex items-center justify-between mb-2">
                            <label className="text-sm font-bold text-slate-700">Rotation Time (s)</label>
                            <input type="number" step="0.5" value={manualSettings.jigRotationTime} onChange={(e) => setManualSettings({...manualSettings, jigRotationTime: Number(e.target.value)})} className="w-24 border rounded px-2 py-1 text-right font-mono"/>
                        </div>
                        <div className="flex items-center justify-between">
                            <label className="text-sm font-bold text-slate-700">Rotations per Cycle</label>
                            <input type="number" step="1" min="0" value={manualSettings.jigRotationsPerCycle} onChange={(e) => setManualSettings({...manualSettings, jigRotationsPerCycle: Number(e.target.value)})} className="w-24 border rounded px-2 py-1 text-right font-mono"/>
                        </div>
                    </div>

                    <div className="bg-orange-50 p-4 rounded-lg text-xs text-orange-800 border border-orange-100 mt-4">
                        <div className="font-bold mb-1">Total Manual Overhead per Cycle:</div>
                        <div className="text-lg font-mono font-bold">
                            {(manualSettings.handlingTime + (manualSettings.jigRotationTime * manualSettings.jigRotationsPerCycle)).toFixed(1)}s
                        </div>
                        <div className="mt-1 opacity-75">This time is added as SETUP/IDLE time at the start of each process.</div>
                    </div>
                </div>
                <div className="p-4 bg-slate-50 border-t rounded-b-xl flex justify-end">
                    <button onClick={() => setShowManualSettingsModal(false)} className="px-4 py-2 bg-orange-600 text-white rounded-lg font-bold text-sm hover:bg-orange-700">Close & Apply</button>
                </div>
            </div>
        </div>
      )}

      {/* Add Modal */}
      {showAddModal && <div className="fixed inset-0 bg-black/60 flex items-center justify-center z-50 p-4"><div className="bg-white rounded-xl shadow-2xl w-full max-w-md animate-in fade-in zoom-in-95 duration-200"><div className="p-4 border-b flex justify-between items-center"><h3 className="font-bold text-lg text-slate-900">New Welding Model</h3><button onClick={() => setShowAddModal(false)} className="p-1 hover:bg-slate-100 rounded-lg"><X size={20}/></button></div><div className="p-6 space-y-4"><div><label className="block text-sm font-bold text-slate-700 mb-1">Model Name</label><input value={newModelName} onChange={(e) => setNewModelName(e.target.value)} className="w-full border rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 outline-none" autoFocus/></div><div><label className="block text-sm font-bold text-slate-700 mb-1">Copy From (Template)</label><select value={copyFromId} onChange={(e) => setCopyFromId(e.target.value)} className="w-full border rounded-lg px-3 py-2 bg-white"><option value="EMPTY">-- Empty --</option>{models.map(m => <option key={m.id} value={m.id}>{m.name}</option>)}</select></div><button onClick={handleSaveNewModel} className="w-full py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg font-bold shadow-sm transition-colors mt-4">Create Model</button></div></div></div>}
      
      {/* AI Modal */}
      {showAIModal && <div className="fixed inset-0 bg-black/60 flex items-center justify-center z-50 p-4"><div className="bg-white rounded-xl shadow-2xl w-full max-w-lg animate-in fade-in zoom-in-95 duration-200"><div className="p-4 border-b flex justify-between items-center bg-gradient-to-r from-purple-600 to-indigo-600 text-white rounded-t-xl"><h3 className="font-bold text-lg flex items-center gap-2"><Sparkles size={20}/> AI Weld Generation</h3><button onClick={() => setShowAIModal(false)} className="p-1 hover:bg-white/20 rounded-lg"><X size={20}/></button></div><div className="p-6 space-y-4"><p className="text-sm text-slate-700">Describe the welding points you want to add.<br/><span className="text-xs text-slate-500 italic">Example: "Add 4 welds on the left side, flat position, length 50mm each for brackets"</span></p><textarea value={aiPrompt} onChange={(e) => setAiPrompt(e.target.value)} className="w-full h-32 border rounded-lg px-3 py-2 focus:ring-2 focus:ring-purple-500 outline-none resize-none" placeholder="Type your prompt here..."></textarea><button onClick={handleAIGenerate} disabled={isAiLoading || !aiPrompt.trim()} className={`w-full py-3 rounded-lg font-bold shadow-sm transition-all flex items-center justify-center gap-2 ${isAiLoading || !aiPrompt.trim() ? 'bg-slate-100 text-slate-400 cursor-not-allowed' : 'bg-purple-600 hover:bg-purple-700 text-white'}`}>{isAiLoading ? <><Loader2 className="animate-spin" size={18}/> Generating...</> : <><Sparkles size={18}/> Generate Welds</>}</button></div></div></div>}
      
      {/* Overview Modal */}
      {showOverview && (
        <div className="fixed inset-0 bg-slate-900/60 backdrop-blur-sm z-[60] overflow-y-auto animate-in fade-in duration-200">
           <div className="min-h-screen px-4 py-8 flex items-center justify-center">
              <div className="bg-white rounded-2xl shadow-2xl w-full max-w-6xl overflow-hidden flex flex-col relative animate-in zoom-in-95 duration-200 border border-slate-200">
                  {/* Header */}
                  <div className="px-8 py-6 border-b border-slate-100 flex justify-between items-center bg-white sticky top-0 z-20">
                      <div>
                         <h2 className="text-2xl font-bold text-slate-900 flex items-center gap-2"><Layout size={24} className="text-blue-600"/> Model Overview & Comparison</h2>
                         <p className="text-slate-600 text-sm mt-1">Compare efficiency, cost, and balance across your scenarios.</p>
                      </div>
                      <button onClick={() => setShowOverview(false)} className="p-2 hover:bg-slate-100 rounded-full transition-colors bg-slate-50 border border-slate-200">
                          <X size={24} className="text-slate-400 hover:text-slate-600"/>
                      </button>
                  </div>
                  
                  <div className="p-8 bg-slate-50/50 min-h-[600px] overflow-y-auto">
                      <div className="flex flex-col lg:flex-row gap-8">
                          {/* Left Column: Radar Chart & Summary */}
                          <div className="lg:w-1/3 space-y-6">
                              <div className="bg-white rounded-2xl p-6 shadow-sm border border-slate-200">
                                  <h3 className="text-lg font-bold text-slate-800 mb-6 flex items-center gap-2"><RadarIcon size={20} className="text-indigo-500"/> Performance Radar</h3>
                                  <div className="h-[320px] w-full relative">
                                      <ResponsiveContainer width="100%" height="100%">
                                          <RadarChart cx="50%" cy="50%" outerRadius="70%" data={radarData}>
                                              <PolarGrid gridType="polygon" stroke="#e2e8f0"/>
                                              <PolarAngleAxis dataKey="subject" tick={{ fill: '#334155', fontSize: 12, fontWeight: 600 }} />
                                              <PolarRadiusAxis angle={30} domain={[0, 100]} tick={false} axisLine={false} />
                                              <Radar name="Performance" dataKey="Efficiency" stroke="#8b5cf6" fill="#8b5cf6" fillOpacity={0.5} />
                                              <Radar name="Speed" dataKey="Speed" stroke="#10b981" fill="#10b981" fillOpacity={0.3} />
                                              <Radar name="Cost" dataKey="Cost" stroke="#f59e0b" fill="#f59e0b" fillOpacity={0.3} />
                                              <Legend />
                                              <Tooltip contentStyle={{borderRadius: '12px', border: 'none', boxShadow: '0 10px 15px -3px rgb(0 0 0 / 0.1)'}}/>
                                          </RadarChart>
                                      </ResponsiveContainer>
                                  </div>
                                  <div className="mt-4 p-4 bg-slate-50 rounded-xl border border-slate-100 text-sm text-slate-600 text-center">
                                      Scores are normalized to 100 based on the best performing model in each category.
                                  </div>
                              </div>
                          </div>

                          {/* Right Column: Model Cards Grid */}
                          <div className="lg:w-2/3">
                              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                                  {allModelsStats.map(stat => (
                                      <div key={stat.modelId} 
                                           onClick={() => { setActiveModelId(stat.modelId); setShowOverview(false); }}
                                           className={`group bg-white rounded-2xl p-6 shadow-sm border transition-all duration-200 relative cursor-pointer hover:shadow-lg hover:translate-y-[-2px] ${activeModelId === stat.modelId ? 'ring-2 ring-blue-500 border-transparent' : 'border-slate-200 hover:border-blue-300'}`}>
                                          
                                          {/* Badges */}
                                          <div className="absolute top-0 right-0 flex flex-col items-end gap-1 mt-4 mr-4 pointer-events-none z-10">
                                              {stat.maxCycleTime === minCycleTime && (
                                                  <span className="bg-emerald-500 text-white text-[10px] font-bold px-3 py-1 rounded-full shadow-sm flex items-center gap-1">
                                                      <Trophy size={10} fill="currentColor"/> FASTEST
                                                  </span>
                                              )}
                                              {stat.totalCost === minCost && (
                                                  <span className="bg-amber-500 text-white text-[10px] font-bold px-3 py-1 rounded-full shadow-sm flex items-center gap-1">
                                                      <TrendingDown size={10}/> CHEAPEST
                                                  </span>
                                              )}
                                              {activeModelId === stat.modelId && (
                                                  <span className="bg-blue-600 text-white text-[10px] font-bold px-3 py-1 rounded-full shadow-sm flex items-center gap-1">
                                                      <CheckCircle2 size={10}/> ACTIVE
                                                  </span>
                                              )}
                                          </div>

                                          {/* Card Header */}
                                          <div className="mb-6 pr-16">
                                              <h3 className="text-xl font-bold text-slate-900 group-hover:text-blue-600 transition-colors">{stat.modelName}</h3>
                                              <p className="text-xs font-bold text-slate-500 mt-1 uppercase tracking-wider">{stat.totalSegments} WELDS</p>
                                          </div>

                                          {/* Stats Grid */}
                                          <div className="space-y-3 mb-6">
                                              <div className="flex justify-between items-center py-2 border-b border-slate-50">
                                                  <span className="text-sm font-medium text-slate-600">Max Cycle Time</span>
                                                  <span className={`text-base font-bold font-mono ${stat.maxCycleTime > taktTime ? 'text-red-500' : 'text-emerald-500'}`}>
                                                      {stat.maxCycleTime.toFixed(1)}s
                                                  </span>
                                              </div>
                                              <div className="flex justify-between items-center py-2 border-b border-slate-50">
                                                  <span className="text-sm font-medium text-slate-600">Efficiency</span>
                                                  <span className="text-base font-bold text-slate-800">{stat.efficiency.toFixed(1)}%</span>
                                              </div>
                                              <div className="flex justify-between items-center py-2 border-b border-slate-50">
                                                  <span className="text-sm font-medium text-slate-600">Est. Cost</span>
                                                  <span className="text-base font-bold text-slate-800">${(stat.totalCost||0).toFixed(2)}</span>
                                              </div>
                                          </div>

                                          {/* Process Visualization (Simple Bars) */}
                                          <div>
                                              <h4 className="text-[10px] font-bold text-slate-500 uppercase tracking-widest mb-3">Process Times</h4>
                                              <div className="space-y-2">
                                                  {stat.processes.map((p, idx) => {
                                                      const percentage = (p.cycleTime / (taktTime || 1)) * 100;
                                                      const isOver = p.cycleTime > taktTime;
                                                      return (
                                                          <div key={p.id} className="flex items-center gap-3">
                                                              <span className="text-xs font-bold text-slate-600 w-6">P{idx+1}</span>
                                                              <div className="flex-1 h-2.5 bg-slate-100 rounded-full overflow-hidden relative">
                                                                  <div 
                                                                    className={`h-full rounded-full transition-all duration-500 ${isOver ? 'bg-red-500' : 'bg-blue-500'}`} 
                                                                    style={{width: `${Math.min(100, (p.cycleTime / Math.max(taktTime, stat.maxCycleTime)) * 100)}%`}}
                                                                  ></div>
                                                                  {/* Takt Line Marker */}
                                                                  <div className="absolute top-0 bottom-0 w-0.5 bg-slate-300 z-10" style={{left: `${(taktTime / Math.max(taktTime, stat.maxCycleTime)) * 100}%`}}></div>
                                                              </div>
                                                              <span className={`text-xs font-bold w-12 text-right ${isOver ? 'text-red-500' : 'text-slate-700'}`}>
                                                                  {p.cycleTime.toFixed(0)}s
                                                              </span>
                                                          </div>
                                                      );
                                                  })}
                                              </div>
                                          </div>
                                          
                                          {/* Hover Overlay for Switching */}
                                          <div className="absolute inset-0 bg-white/90 opacity-0 group-hover:opacity-100 transition-opacity duration-200 flex items-center justify-center rounded-2xl z-20 pointer-events-none">
                                              <span className="px-6 py-2 bg-blue-600 text-white font-bold rounded-full shadow-lg transform translate-y-4 group-hover:translate-y-0 transition-transform duration-200 flex items-center gap-2">
                                                 <CheckCircle2 size={16}/> Switch to Model
                                              </span>
                                          </div>
                                      </div>
                                  ))}
                              </div>
                          </div>
                      </div>
                  </div>
              </div>
           </div>
        </div>
      )}
    </div>
  );
};

const container = document.getElementById('root');
if (container) {
  const root = createRoot(container);
  root.render(
    <ErrorBoundary>
       <App />
    </ErrorBoundary>
  );
}