'use client';

import { useState, useEffect, useRef, useMemo } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { useSession } from '../lib/session-context';
import { getPlanCapabilities } from '../lib/plan-access';
import {
  FolderPlus, GitBranch, Globe, Lock, ChevronRight, ChevronLeft,
  Zap, Check, Loader2, ArrowRight, Search, Users, Tag, Calendar,
  AlertTriangle, Shield, Bell, Settings, Server,
  CheckCircle2, Clock, Building2, UserPlus, Workflow, Key, Eye,
  Star, TrendingUp, X, XCircle, Info, Database
} from 'lucide-react';
import type { TeamMember } from '../data/projectsData';
import { PIPELINE_PLUGINS } from '../lib/pipeline-plugins';
import { ARCH_PATTERNS, errorOptions } from '../lib/platform-run';

const SHOW_ENGINE_MULTI_STAGE =
  process.env.NEXT_PUBLIC_SCRIBA_ENGINE_STAGES === '1' ||
  process.env.NEXT_PUBLIC_SCRIBA_ENGINE_STAGES === 'true';

const SHOW_ENGINE_REPAIR =
  process.env.NEXT_PUBLIC_SCRIBA_ENGINE_REPAIR === '1' ||
  process.env.NEXT_PUBLIC_SCRIBA_ENGINE_REPAIR === 'true';

const sourceLanguages = [
  // ── Legacy Mainframe ──────────────────────────────────────────────────────
  { id: 'cobol', name: 'COBOL', desc: 'COBOL-85/2002/2014/2023, CICS, JCL, Copybooks', category: 'legacy', versions: ['COBOL-74', 'COBOL-85', 'COBOL-2002', 'COBOL-2014', 'COBOL-2023'], dialects: ['Standard', 'IBM Enterprise COBOL', 'IBM COBOL for z/OS', 'Micro Focus COBOL', 'ACUCOBOL-GT', 'Fujitsu NetCOBOL', 'Unisys MCP COBOL', 'HP COBOL', 'GnuCOBOL', 'Liant RM/COBOL'] },
  { id: 'cobol_as400', name: 'COBOL AS/400', desc: 'COBOL for IBM i / AS/400, ILE COBOL, embedded SQL, CL integration, copybooks', category: 'legacy', versions: ['COBOL/400', 'ILE COBOL', 'COBOL for IBM i'], dialects: ['IBM i', 'AS/400', 'System i', 'Power Systems'] },
  { id: 'pli', name: 'PL/I', desc: 'PL/I for z/OS, IMS, DB2, CICS', category: 'legacy', versions: ['PL/I for z/OS 5.x', 'PL/I for z/OS 6.x', 'PL/I Enterprise', 'Visual PL/I'], dialects: ['IBM Enterprise PL/I', 'IBM Optimizing Compiler', 'Micro Focus PL/I', 'Iron Spring PL/I'] },
  { id: 'rpg', name: 'RPG/400', desc: 'RPG II/III/IV, ILE RPG, CL, DDS', category: 'legacy', versions: ['RPG II', 'RPG III', 'RPG IV (Fixed)', 'RPG IV Free-Format', 'ILE RPG', '**FREE'], dialects: ['IBM i', 'AS/400', 'System/38', 'System i', 'Power Systems'] },
  { id: 'natural', name: 'Natural/ADABAS', desc: 'Software AG Natural, ADABAS, Predict, Entire', category: 'legacy', versions: ['Natural 4.x', 'Natural 6.x', 'Natural 8.x', 'Natural 9.x', 'Natural 10.x'], dialects: ['Mainframe', 'Open Systems', 'Unix', 'Windows', 'Natural for Ajax'] },
  { id: 'jcl', name: 'JCL', desc: 'IBM Job Control Language, JES2/JES3, PROC', category: 'legacy', versions: ['JES2', 'JES3', 'z/OS JCL'], dialects: ['IBM z/OS', 'VSE/ESA', 'MVS', 'z/VSE'] },
  { id: 'rexx', name: 'REXX / NetREXX', desc: 'REXX scripting, NetREXX, Object REXX, CLIST', category: 'legacy', versions: ['Classic REXX', 'Object REXX', 'Open Object REXX', 'NetREXX 3.x', 'NetREXX 4.x'], dialects: ['IBM TSO/ISPF REXX', 'VM/CMS REXX', 'Object REXX (z/OS)', 'NetREXX (JVM)', 'Regina REXX', 'Open Object REXX'] },
  { id: 'clist', name: 'CLIST / ISPF', desc: 'TSO Command List, ISPF panels and scripts', category: 'legacy', versions: ['CLIST (TSO/E)', 'ISPF 3.x', 'ISPF 4.x', 'ISPF 5.x'], dialects: ['TSO/E CLIST', 'ISPF Edit Macros', 'ISPF Dialogs', 'IBM z/OS ISPF'] },
  { id: 'assembly', name: 'Assembly', desc: 'x86, ARM, IBM HLASM, z/Architecture', category: 'legacy', versions: ['x86-64', 'ARM32', 'ARM64 (AArch64)', 'z/Architecture', 'PowerPC', 'RISC-V', 'MIPS'], dialects: ['Intel (MASM)', 'Intel (NASM)', 'AT&T (GAS)', 'IBM HLASM', 'IBM Structured Macros', 'Thumb / Thumb-2'] },
  { id: 'ada', name: 'Ada', desc: 'Ada 83/95/2005/2012/2022, SPARK, Ravenscar', category: 'legacy', versions: ['Ada 83', 'Ada 95', 'Ada 2005', 'Ada 2012', 'Ada 2022'], dialects: ['GNAT (FSF/AdaCore)', 'ObjectAda (DDC-I)', 'Janus/Ada', 'SPARK 2014', 'SPARK 2022', 'Ravenscar Profile'] },
  { id: 'fortran', name: 'Fortran', desc: 'Fortran 66–2023, HPC and scientific', category: 'legacy', versions: ['Fortran 66', 'Fortran 77', 'Fortran 90', 'Fortran 95', 'Fortran 2003', 'Fortran 2008', 'Fortran 2018', 'Fortran 2023'], dialects: ['GNU Fortran (gfortran)', 'Intel Fortran (ifx/ifort)', 'IBM XL Fortran', 'PGI/NVHPC Fortran', 'NAG Fortran', 'Cray Fortran (ftn)'] },
  { id: 'mumps', name: 'MUMPS / M', desc: 'MUMPS, InterSystems Caché, IRIS ObjectScript', category: 'legacy', versions: ['Classic M (1977)', 'ANSI MUMPS (1995)', 'Caché ObjectScript', 'IRIS ObjectScript 2022.x', 'IRIS 2023.x', 'GT.M / YottaDB'], dialects: ['InterSystems Caché', 'InterSystems IRIS', 'GT.M (Greystone)', 'YottaDB', 'VistA (VA)', 'Mirth Connect'] },
  // ── Legacy Business / ERP ──────────────────────────────────────────────────
  { id: 'sap', name: 'SAP ABAP', desc: 'ABAP, ABAP OO, BTP, SAP S/4HANA', category: 'legacy', versions: ['ABAP 7.31', 'ABAP 7.40', 'ABAP 7.50', 'ABAP 7.54', 'ABAP 7.77', 'ABAP 7.80 (S/4)', 'ABAP Cloud (BTP)'], dialects: ['Classic ABAP', 'ABAP OO', 'SAP R/3', 'SAP ECC', 'SAP S/4HANA', 'SAP BW/BI', 'SAP BTP Cloud', 'ABAP for HANA'] },
  { id: 'oracle', name: 'Oracle PL/SQL', desc: 'Oracle SQL, PL/SQL, Forms, Reports', category: 'legacy', versions: ['Oracle 9i', 'Oracle 10g', 'Oracle 11g', 'Oracle 12c', 'Oracle 18c', 'Oracle 19c', 'Oracle 21c', 'Oracle 23ai'], dialects: ['Standard PL/SQL', 'Oracle Enterprise', 'Oracle Express (XE)', 'Oracle Forms 6i', 'Oracle Reports', 'Oracle APEX'] },
  { id: 'tsql', name: 'T-SQL / SQL Server', desc: 'Microsoft T-SQL, Stored Procs, SSIS, SSRS', category: 'legacy', versions: ['SQL Server 2008', 'SQL Server 2012', 'SQL Server 2014', 'SQL Server 2016', 'SQL Server 2017', 'SQL Server 2019', 'SQL Server 2022'], dialects: ['T-SQL Standard', 'Sybase ASE T-SQL', 'Azure SQL', 'Azure Synapse', 'SQL Server on Linux', 'PDW / APS'] },
  { id: 'db2', name: 'DB2 SQL / Db2', desc: 'IBM Db2 SQL, Stored Procedures, UDFs', category: 'legacy', versions: ['DB2 9.7', 'DB2 10.1', 'DB2 10.5', 'DB2 11.1', 'DB2 11.5', 'Db2 12 (z/OS)', 'Db2 for i'], dialects: ['Db2 for z/OS', 'Db2 LUW (Linux/Unix/Win)', 'Db2 for IBM i', 'IBM Cloud Db2', 'Db2 Warehouse'] },
  { id: 'pascal', name: 'Pascal / Delphi', desc: 'Object Pascal, Delphi VCL, FireMonkey, Lazarus', category: 'legacy', versions: ['Turbo Pascal 7', 'Delphi 5', 'Delphi 7', 'Delphi 2007', 'Delphi XE', 'Delphi XE8', 'Delphi 10.x', 'Delphi 11', 'Delphi 12 Athens', 'Free Pascal 3.x'], dialects: ['Borland Pascal', 'Turbo Pascal', 'Embarcadero Delphi', 'Free Pascal (FPC)', 'Lazarus IDE', 'Kylix (Linux)'] },
  { id: 'vb6', name: 'Visual Basic 6 / VBA', desc: 'VB6, VBA, COM, ActiveX, ASP Classic', category: 'legacy', versions: ['VB6 SP6', 'VBA 6.0', 'VBA 7.0', 'VBA 7.1'], dialects: ['VB6', 'VBA (Office)', 'VBScript', 'ASP Classic', 'VB for Excel', 'VB for Access'] },
  { id: 'powerbuilder', name: 'PowerBuilder', desc: 'PowerBuilder, DataWindow, PowerScript, PowerServer', category: 'legacy', versions: ['PB 9.x', 'PB 10.x', 'PB 12.5', 'PB 2017', 'PB 2019', 'PB 2021', 'PB 2022', 'PB 2025'], dialects: ['Classic PowerBuilder', 'PowerServer (Web)', 'Appeon PowerBuilder', 'Sybase PowerBuilder'] },
  { id: 'progress', name: 'Progress 4GL / ABL', desc: 'Progress 4GL, OpenEdge ABL, WebSpeed', category: 'legacy', versions: ['Progress 8.x', 'Progress 9.x', 'Progress 10.x', 'Progress 11.x', 'OpenEdge 11.x', 'OpenEdge 12.x'], dialects: ['Progress 4GL', 'OpenEdge ABL', 'WebSpeed', 'Telerik UI for OpenEdge'] },
  { id: 'coldfusion', name: 'ColdFusion / CFML', desc: 'ColdFusion CFML, CFScript, Lucee', category: 'legacy', versions: ['ColdFusion 9', 'ColdFusion 10', 'ColdFusion 2016', 'ColdFusion 2018', 'ColdFusion 2021', 'ColdFusion 2023', 'Lucee 5.x', 'Lucee 6.x'], dialects: ['Adobe ColdFusion', 'Lucee CFML', 'Railo', 'Open BlueDragon (OpenBD)'] },
  { id: 'clipper', name: 'Clipper / xBase', desc: 'Clipper, FoxPro, dBASE, Harbour', category: 'legacy', versions: ['Clipper 5.2', 'Clipper 5.3', 'FoxPro 2.6', 'dBASE III', 'dBASE IV', 'dBASE 11'], dialects: ['CA-Clipper', 'FoxPro 2.x', 'dBASE III+', 'dBASE IV', 'Harbour', 'xHarbour'] },
  { id: 'visualfoxpro', name: 'Visual FoxPro', desc: 'VFP, VFP OOP, COM automation, VFP reports', category: 'legacy', versions: ['VFP 3.0', 'VFP 5.0', 'VFP 6.0', 'VFP 7.0', 'VFP 8.0', 'VFP 9.0 SP2'], dialects: ['Standard VFP', 'FoxPro 2.x (DOS/Win)', 'Microsoft FoxPro 2.6'] },
  { id: 'lotusscript', name: 'LotusScript / IBM Notes', desc: 'LotusScript, @Formula, XPages, Domino Java', category: 'legacy', versions: ['Notes 4.x', 'Notes 5.x', 'Notes/Domino 6.x', 'Domino 7.x', 'Domino 8.x', 'Domino 9.x', 'Domino 10.x', 'Domino 12.x'], dialects: ['LotusScript', '@Formula language', 'XPages (JSF)', 'Domino Java APIs', 'HCL Notes/Domino'] },
  { id: 'informix', name: 'Informix 4GL / SPL', desc: 'Informix 4GL, SPL, ESQL/C, IDS', category: 'legacy', versions: ['Informix 7.x', 'Informix 9.x', 'IDS 11.x', 'IDS 12.x', 'IDS 14.x'], dialects: ['Informix 4GL', 'ESQL/C', 'SPL (Stored Procedure Language)', 'IBM Informix Dynamic Server'] },
  { id: 'sas', name: 'SAS', desc: 'SAS Language, SAS Macro, DATA Step, Viya', category: 'legacy', versions: ['SAS 9.2', 'SAS 9.3', 'SAS 9.4', 'SAS Viya 3.5', 'SAS Viya 4.x'], dialects: ['Base SAS', 'SAS/STAT', 'SAS/ETS', 'SAS/IML', 'SAS Enterprise Guide', 'SAS Studio', 'SAS Viya'] },
  { id: 'pick', name: 'PICK / MultiValue', desc: 'PICK BASIC, BASIC+, UniBasic, jBC', category: 'legacy', versions: ['D3', 'Universe (UniData)', 'UniVerse', 'jBASE 5.x', 'Revelation OpenInsight', 'MVON#'], dialects: ['Pick BASIC', 'UniBasic', 'jBC (jBASE)', 'QBasic (D3)', 'BASIC+ (OpenInsight)', 'MVON (Open QM)'] },
  { id: 'uniface', name: 'UNIFACE', desc: 'Uniface 4GL, component-based enterprise apps', category: 'legacy', versions: ['Uniface 9.x', 'Uniface 10.x', 'Uniface 10.3', 'Uniface 10.4'], dialects: ['Uniface Standard', 'Uniface Web', 'Uniface Cloud Deployment'] },
  { id: 'apl', name: 'APL / Dyalog / J / K', desc: 'Array programming languages for financial systems', category: 'legacy', versions: ['APL2', 'Dyalog APL 17', 'Dyalog APL 18', 'Dyalog APL 19', 'J 9.x', 'K 4', 'K 9', 'Q (KDB+)'], dialects: ['IBM APL2', 'Dyalog APL', 'APLX', 'J (Jsoftware)', 'K (Kx Systems)', 'Q / KDB+', 'SHARP APL'] },
  { id: 'smalltalk', name: 'Smalltalk', desc: 'Smalltalk-80, Pharo, VisualWorks, Squeak, VA', category: 'legacy', versions: ['Smalltalk-80', 'Pharo 10', 'Pharo 11', 'Pharo 12', 'VisualWorks 9.x', 'VA Smalltalk 10.x'], dialects: ['Pharo', 'VisualWorks (Cincom)', 'VA Smalltalk (Instantiations)', 'Squeak', 'GNU Smalltalk', 'Dolphin Smalltalk', 'GemStone/S'] },
  // ── Legacy PC / Desktop ───────────────────────────────────────────────────
  { id: 'objective_c', name: 'Objective-C', desc: 'Objective-C, Cocoa, CocoaTouch, macOS/iOS legacy', category: 'legacy', versions: ['Objective-C 1.0', 'Objective-C 2.0', 'Objective-C GNUstep'], dialects: ['Apple Objective-C (Cocoa)', 'Apple Objective-C (CocoaTouch)', 'GNUstep', 'NeXTSTEP'] },
  { id: 'actionscript', name: 'ActionScript / Flash', desc: 'ActionScript 2/3, Flex MXML, Adobe AIR', category: 'legacy', versions: ['ActionScript 1.0', 'ActionScript 2.0', 'ActionScript 3.0', 'Flex 3', 'Flex 4', 'Flex 4.6', 'Adobe AIR'], dialects: ['Flash ActionScript', 'Flex / MXML', 'Adobe AIR', 'OpenFL', 'Apache Flex (Royale)'] },
  { id: 'basic', name: 'BASIC / QuickBASIC', desc: 'GW-BASIC, QBasic, QuickBASIC, TI BASIC', category: 'legacy', versions: ['GW-BASIC', 'QBasic 1.1', 'QuickBASIC 4.5', 'Microsoft BASIC PDS 7.1', 'Power BASIC', 'FreeBASIC'], dialects: ['Microsoft GW-BASIC', 'Microsoft QBasic', 'Microsoft QuickBASIC', 'Turbo Basic (Borland)', 'Power BASIC', 'FreeBASIC', 'TI BASIC', 'BBC BASIC', 'BASICA (IBM PC)'] },
  { id: 'tcl', name: 'Tcl / Tk', desc: 'Tcl scripting, Tk GUI, Expect, itcl', category: 'legacy', versions: ['Tcl 8.4', 'Tcl 8.5', 'Tcl 8.6', 'Tcl 9.0'], dialects: ['Standard Tcl/Tk', 'Expect', 'itcl (Incr Tcl)', 'Tix', 'XOTcl', 'TclOO'] },
  // ── Modern Systems ─────────────────────────────────────────────────────────
  { id: 'c', name: 'C', desc: 'ANSI C, C89–C23, embedded and systems', category: 'modern', versions: ['C89 / ANSI C', 'C99', 'C11', 'C17', 'C23'], dialects: ['GNU C (gcc)', 'Clang C', 'Microsoft MSVC', 'IBM XL C', 'TI ARM C', 'IAR C', 'MISRA-C'] },
  { id: 'cpp', name: 'C++', desc: 'C++98–C++26, systems and high-performance', category: 'modern', versions: ['C++98', 'C++03', 'C++11', 'C++14', 'C++17', 'C++20', 'C++23', 'C++26 (Draft)'], dialects: ['GNU C++ (g++)', 'Clang C++', 'MSVC C++', 'Intel C++ (icx)', 'IBM XL C++', 'Embedded C++', 'MISRA C++'] },
  { id: 'java', name: 'Java', desc: 'Enterprise Java, Jakarta EE, Spring, Quarkus', category: 'modern', versions: ['Java 8 LTS', 'Java 11 LTS', 'Java 17 LTS', 'Java 21 LTS', 'Java 22', 'Java 23', 'Java 24', 'Java 25 LTS', 'Java 26'], frameworks: ['Spring Boot', 'Spring Framework', 'Quarkus', 'Micronaut', 'Jakarta EE', 'Grails', 'Vert.x', 'Struts', 'Hibernate', 'None / Plain Java'], dialects: ['OpenJDK', 'Oracle JDK', 'Amazon Corretto', 'Azul Zulu', 'IBM Semeru', 'Eclipse Temurin', 'GraalVM CE/EE'] },
  { id: 'csharp', name: 'C#', desc: '.NET / .NET Core / .NET Framework ecosystem', category: 'modern', versions: ['.NET Framework 2.0', '.NET Framework 3.5', '.NET Framework 4.x', '.NET Core 3.1', '.NET 6', '.NET 7', '.NET 8', '.NET 9', '.NET 10', '.NET 11 (Preview)'], frameworks: ['ASP.NET Core', 'ASP.NET MVC', 'Blazor', 'WPF', 'WinForms', 'MAUI', 'WCF', 'None / Console'], dialects: ['Microsoft .NET', 'Mono', '.NET MAUI', 'Unity C#', 'Blazor WASM'] },
  { id: 'python', name: 'Python', desc: 'Python 2/3, web, data, ML, scripting', category: 'modern', versions: ['Python 2.7', 'Python 3.8', 'Python 3.9', 'Python 3.10', 'Python 3.11', 'Python 3.12', 'Python 3.13', 'Python 3.14'], frameworks: ['Django', 'FastAPI', 'Flask', 'Starlette', 'Litestar', 'Pyramid', 'Tornado', 'Sanic', 'None / Script'], dialects: ['CPython', 'PyPy', 'Jython', 'IronPython', 'MicroPython', 'CircuitPython', 'Cython'] },
  { id: 'javascript', name: 'JavaScript', desc: 'JavaScript for web and server (ES5–ESNext)', category: 'modern', versions: ['ES5 (2009)', 'ES6 (2015)', 'ES2017', 'ES2018', 'ES2019', 'ES2020', 'ES2021', 'ES2022', 'ES2023', 'ES2024', 'ES2025'], frameworks: ['Express', 'Fastify', 'NestJS', 'Next.js', 'Nuxt 3', 'Angular', 'React', 'Vue 3', 'SvelteKit', 'Astro', 'Koa', 'Hapi', 'Hono', 'Elysia', 'Vanilla JS'], dialects: ['Browser JS (V8/SpiderMonkey)', 'Node.js', 'Bun', 'Deno', 'GraalJS'] },
  { id: 'typescript', name: 'TypeScript', desc: 'TypeScript 4.x–6.x for type-safe JavaScript', category: 'modern', versions: ['TypeScript 4.5', 'TypeScript 4.9', 'TypeScript 5.0', 'TypeScript 5.3', 'TypeScript 5.5', 'TypeScript 5.7', 'TypeScript 6.0'], frameworks: ['Angular', 'React', 'Vue 3', 'Svelte 5', 'NestJS', 'Next.js', 'SvelteKit', 'Express', 'Fastify', 'Hono', 'Vanilla TS'], dialects: ['Standard TS', 'TSX (React)', 'Deno TypeScript', 'Bun TypeScript'] },
  { id: 'php', name: 'PHP', desc: 'PHP for web, WordPress, Laravel, Symfony', category: 'modern', versions: ['PHP 5.6', 'PHP 7.0', 'PHP 7.4', 'PHP 8.0', 'PHP 8.1', 'PHP 8.2', 'PHP 8.3', 'PHP 8.4', 'PHP 8.5'], frameworks: ['Symfony', 'Laravel', 'Slim', 'CodeIgniter', 'CakePHP', 'Yii', 'WordPress', 'Drupal', 'Magento', 'Zend / Laminas', 'Phalcon', 'None / Vanilla PHP'], dialects: ['Standard PHP', 'HHVM (Facebook)', 'PHP-FPM', 'Hack (Meta)'] },
  { id: 'ruby', name: 'Ruby', desc: 'Ruby for web, Rails, DevOps scripting', category: 'modern', versions: ['Ruby 2.7', 'Ruby 3.0', 'Ruby 3.1', 'Ruby 3.2', 'Ruby 3.3', 'Ruby 3.4', 'Ruby 4.0'], frameworks: ['Rails', 'Sinatra', 'Hanami', 'Grape', 'Padrino', 'None / Vanilla Ruby'], dialects: ['MRI (CRuby)', 'JRuby', 'TruffleRuby', 'Rubinius', 'mruby (embedded)'] },
  { id: 'go', name: 'Go', desc: 'Go for cloud-native and high-performance services', category: 'modern', versions: ['Go 1.18', 'Go 1.20', 'Go 1.21', 'Go 1.22', 'Go 1.23', 'Go 1.24', 'Go 1.25', 'Go 1.26'], frameworks: ['Gin', 'Echo', 'Fiber', 'Chi', 'Gorilla Mux', 'Beego', 'Standard Library', 'Encore', 'None / Plain Go'], dialects: ['Standard Go (gc compiler)', 'TinyGo (embedded)', 'GopherJS (JS target)'] },
  { id: 'rust', name: 'Rust', desc: 'Rust for memory-safe systems and WebAssembly', category: 'modern', versions: ['Rust 1.65', 'Rust 1.75', 'Rust 1.80', 'Rust 1.84', 'Rust 1.87', 'Rust 1.90', 'Rust 1.95 (Stable)', 'Rust Nightly'], frameworks: ['Axum', 'Actix Web', 'Rocket', 'Warp', 'None / Vanilla Rust'], dialects: ['Stable', 'Beta', 'Nightly', 'no_std (embedded)', 'WASM target'] },
  { id: 'swift', name: 'Swift', desc: 'Swift for Apple platforms and server-side', category: 'modern', versions: ['Swift 5.0', 'Swift 5.9', 'Swift 5.10', 'Swift 6.0', 'Swift 6.1', 'Swift 6.2', 'Swift 6.3', 'Swift 6.4'], dialects: ['Apple Xcode Swift', 'Swift on Server', 'Swift WASM', 'SwiftUI', 'Swift for TensorFlow (S4TF)'] },
  { id: 'kotlin', name: 'Kotlin', desc: 'Kotlin for JVM, Android, Multiplatform', category: 'modern', versions: ['Kotlin 1.8', 'Kotlin 1.9', 'Kotlin 2.0', 'Kotlin 2.1', 'Kotlin 2.2', 'Kotlin 2.3'], frameworks: ['Spring Boot', 'Ktor', 'Quarkus', 'Micronaut', 'Android', 'KMP', 'None / Plain Kotlin'], dialects: ['Kotlin/JVM', 'Kotlin/Native', 'Kotlin/JS', 'Kotlin/Wasm', 'KMP (Multiplatform)'] },
  { id: 'scala', name: 'Scala', desc: 'Scala 2/3 for functional and distributed systems', category: 'modern', versions: ['Scala 2.12', 'Scala 2.13', 'Scala 3.3 LTS', 'Scala 3.4', 'Scala 3.5', 'Scala 3.6', 'Scala 3.7', 'Scala 3.8'], frameworks: ['Play Framework', 'Akka HTTP / Pekko HTTP', 'http4s', 'ZIO-HTTP', 'Spark', 'None / Plain Scala'], dialects: ['Scala 2 (standard)', 'Scala 3 (Dotty)', 'Scala.js', 'Scala Native', 'ScalaFX'] },
  { id: 'elixir', name: 'Elixir', desc: 'Elixir on BEAM/OTP for concurrent systems', category: 'modern', versions: ['Elixir 1.14', 'Elixir 1.15', 'Elixir 1.16', 'Elixir 1.17', 'Elixir 1.18', 'Elixir 1.19', 'Elixir 1.20'], frameworks: ['Phoenix', 'Phoenix LiveView', 'Plug', 'None / Plain Elixir'], dialects: ['Standard', 'Nerves (IoT)', 'Liveview Phoenix'] },
  { id: 'clojure', name: 'Clojure', desc: 'Clojure for functional JVM programming', category: 'modern', versions: ['Clojure 1.8', 'Clojure 1.9', 'Clojure 1.10', 'Clojure 1.11', 'Clojure 1.12'], dialects: ['Clojure (JVM)', 'ClojureScript (JS)', 'ClojureCLR (.NET)', 'Babashka (scripting)'] },
  { id: 'fsharp', name: 'F#', desc: 'F# for functional .NET programming', category: 'modern', versions: ['F# 4.5', 'F# 5', 'F# 6', 'F# 7', 'F# 8', 'F# 9'], dialects: ['F# (.NET)', 'Fable (JS)', 'F# (Mono)'] },
  { id: 'haskell', name: 'Haskell', desc: 'Haskell for pure functional programming', category: 'modern', versions: ['GHC 8.8', 'GHC 8.10', 'GHC 9.0', 'GHC 9.2', 'GHC 9.4', 'GHC 9.6', 'GHC 9.8', 'GHC 9.10'], dialects: ['GHC Haskell', 'Hugs (legacy)', 'GHCJS (JS)', 'Eta (JVM)'] },
  { id: 'dart', name: 'Dart', desc: 'Dart for Flutter mobile, web, and server', category: 'modern', versions: ['Dart 2.19', 'Dart 3.0', 'Dart 3.3', 'Dart 3.5', 'Dart 3.7', 'Dart 3.9', 'Dart 3.11'], dialects: ['Dart VM', 'Flutter (mobile/web/desktop)', 'Dart2JS', 'Dart Native'] },
  { id: 'lua', name: 'Lua', desc: 'Lua for embedded scripting and game engines', category: 'modern', versions: ['Lua 5.1', 'Lua 5.2', 'Lua 5.3', 'Lua 5.4', 'LuaJIT 2.1', 'Luau (Roblox)'], dialects: ['Standard Lua', 'LuaJIT', 'Luau (Roblox)', 'MoonScript', 'LÖVE 2D'] },
  { id: 'perl', name: 'Perl', desc: 'Perl 5/Raku for scripting and bioinformatics', category: 'modern', versions: ['Perl 5.20', 'Perl 5.26', 'Perl 5.30', 'Perl 5.32', 'Perl 5.34', 'Perl 5.36', 'Perl 5.38', 'Perl 5.40', 'Raku (Perl 6)'], dialects: ['Standard Perl 5', 'Strawberry Perl (Win)', 'ActivePerl', 'Raku (formerly Perl 6)', 'Bioperl'] },
  { id: 'r', name: 'R', desc: 'R for statistical computing and data science', category: 'modern', versions: ['R 3.6', 'R 4.0', 'R 4.1', 'R 4.2', 'R 4.3', 'R 4.4', 'R 4.5'], dialects: ['Base R (CRAN)', 'Bioconductor', 'R/tidyverse', 'Microsoft R Open'] },
  { id: 'julia', name: 'Julia', desc: 'Julia for scientific computing and HPC', category: 'modern', versions: ['Julia 1.6 LTS', 'Julia 1.9', 'Julia 1.10 LTS', 'Julia 1.11', 'Julia 1.12'], dialects: ['Standard Julia', 'Julia GPU (CUDA.jl)', 'Julia for HPC (MPI.jl)'] },
  { id: 'crystal', name: 'Crystal', desc: 'Crystal language, Ruby-like syntax, compiled', category: 'modern', versions: ['Crystal 1.0', 'Crystal 1.1', 'Crystal 1.2', 'Crystal 1.3', 'Crystal 1.4', 'Crystal 1.5'], dialects: ['Standard Crystal'] },
  { id: 'nim', name: 'Nim', desc: 'Nim — Python-like, C-speed systems language', category: 'modern', versions: ['Nim 1.4', 'Nim 1.6', 'Nim 2.0', 'Nim 2.2'], dialects: ['Standard (C backend)', 'Nim (C++ backend)', 'Nim (JS backend)', 'NimScript'] },
  { id: 'zig', name: 'Zig', desc: 'Zig — modern C alternative with safety', category: 'modern', versions: ['Zig 0.9', 'Zig 0.10', 'Zig 0.11', 'Zig 0.12', 'Zig 0.13', 'Zig 0.14'], dialects: ['Standard Zig', 'Zig (WASM)', 'TigerBeetle Zig', 'Bun (Zig-based)'] },
  { id: 'vlang', name: 'V', desc: 'V — Go-like simplicity with safety guarantees', category: 'modern', versions: ['V 0.2', 'V 0.3', 'V 0.4'], dialects: ['Standard V', 'V (C backend)', 'V (WASM backend)'] },
  { id: 'odin', name: 'Odin', desc: 'Odin — C-like language for game dev and systems', category: 'modern', versions: ['Odin dev-2023', 'Odin dev-2024', 'Odin dev-2025'], dialects: ['Standard Odin'] },
  { id: 'wasm', name: 'WebAssembly', desc: 'WebAssembly binary, WAT text format, WASI', category: 'modern', versions: ['WASM 1.0 (2019)', 'WASM 2.0 (2022)', 'WASM 3.0 (Draft)', 'WASI Preview 1', 'WASI Preview 2'], dialects: ['WAT (text format)', 'Binary Format', 'WASI (system interface)', 'Component Model'] },
  { id: 'sql', name: 'SQL (Generic)', desc: 'ANSI SQL, stored procs, views, triggers', category: 'modern', versions: ['SQL-89', 'SQL-92', 'SQL:1999', 'SQL:2003', 'SQL:2011', 'SQL:2016', 'SQL:2019', 'SQL:2023'], dialects: ['PostgreSQL', 'MySQL 8.x', 'MariaDB', 'SQLite 3.x', 'Oracle SQL', 'IBM Db2 SQL', 'Snowflake SQL', 'BigQuery SQL', 'DuckDB SQL'] },
  { id: 'graphql', name: 'GraphQL', desc: 'GraphQL schema, queries, mutations, subscriptions', category: 'modern', versions: ['GraphQL June 2018', 'GraphQL October 2021'], dialects: ['Standard GraphQL', 'Apollo Federation', 'Relay', 'Hasura GraphQL', 'Strawberry (Python)'] },
  { id: 'matlab', name: 'MATLAB / Octave', desc: 'MATLAB for numerical computing, Simulink', category: 'modern', versions: ['MATLAB R2018b', 'MATLAB R2020b', 'MATLAB R2022b', 'MATLAB R2023b', 'MATLAB R2024a', 'GNU Octave 8.x', 'GNU Octave 9.x'], dialects: ['MATLAB (MathWorks)', 'GNU Octave', 'MATLAB Coder', 'Simulink'] },
  { id: 'powershell', name: 'PowerShell', desc: 'Windows PowerShell and PowerShell Core', category: 'modern', versions: ['PowerShell 2.0', 'PowerShell 3.0', 'PowerShell 5.1 (Windows)', 'PowerShell 6 (Core)', 'PowerShell 7.0', 'PowerShell 7.2 LTS', 'PowerShell 7.4 LTS', 'PowerShell 7.5'], dialects: ['Windows PowerShell (5.1)', 'PowerShell Core (7.x)', 'Azure Cloud Shell', 'PowerShell DSC'] },
  { id: 'bash', name: 'Bash / Shell', desc: 'Bash, sh, Zsh, Fish, ksh, dash scripting', category: 'modern', versions: ['sh (POSIX)', 'Bash 3.x', 'Bash 4.x', 'Bash 5.0', 'Bash 5.1', 'Bash 5.2', 'Zsh 5.x', 'Fish 3.x'], dialects: ['POSIX sh', 'Bash', 'Zsh', 'Fish', 'ksh88', 'ksh93', 'mksh', 'dash', 'tcsh'] },
  { id: 'groovy', name: 'Groovy', desc: 'Groovy for JVM scripting, Gradle, Spock', category: 'modern', versions: ['Groovy 2.5', 'Groovy 3.0', 'Groovy 4.0', 'Groovy 5.0', 'Groovy 6.0 (Preview)'], frameworks: ['Grails', 'Gradle DSL', 'Spock', 'Micronaut (Groovy)', 'None / Plain Groovy'], dialects: ['Standard Groovy', 'Groovysh REPL', 'Gradle Groovy DSL'] },
  { id: 'scheme', name: 'Scheme', desc: 'Scheme, Racket, Guile for Lisp-family FP', category: 'modern', versions: ['R5RS', 'R6RS', 'R7RS'], dialects: ['MIT Scheme', 'Racket', 'GNU Guile', 'Chicken Scheme', 'Chez Scheme', 'Gambit Scheme'] },
  { id: 'lisp', name: 'Common Lisp', desc: 'ANSI Common Lisp, SBCL, CCL, Allegro', category: 'modern', versions: ['ANSI Common Lisp (1994)'], dialects: ['SBCL (Steel Bank)', 'CCL (Clozure)', 'ABCL (JVM)', 'Allegro CL', 'LispWorks', 'ECL'] },
  { id: 'erlang', name: 'Erlang / OTP', desc: 'Erlang and OTP for distributed fault-tolerant systems', category: 'modern', versions: ['Erlang/OTP 24', 'Erlang/OTP 25', 'Erlang/OTP 26', 'Erlang/OTP 27', 'Erlang/OTP 28'], dialects: ['Standard Erlang', 'Gleam (compiled to BEAM)', 'Elixir (BEAM)', 'LFE (Lisp Flavoured Erlang)'] },
  { id: 'ocaml', name: 'OCaml', desc: 'OCaml for functional systems, compilers, finance', category: 'modern', versions: ['OCaml 4.14', 'OCaml 5.0', 'OCaml 5.1', 'OCaml 5.2', 'OCaml 5.3'], dialects: ['Standard OCaml', 'Reason (React/OCaml)', 'ReScript (JS target)', 'js_of_ocaml'] },
  { id: 'elm', name: 'Elm', desc: 'Elm for web frontend functional programming', category: 'modern', versions: ['Elm 0.18', 'Elm 0.19', 'Elm 0.19.1'], dialects: ['Standard Elm'] },
  { id: 'purescript', name: 'PureScript', desc: 'PureScript strictly-typed Haskell-like for JS', category: 'modern', versions: ['PureScript 0.14', 'PureScript 0.15', 'PureScript 0.15.10'], dialects: ['Standard PureScript', 'Halogen framework', 'React Basic'] },
  { id: 'verilog', name: 'Verilog / SystemVerilog', desc: 'RTL design, FPGA, ASIC, UVM verification', category: 'modern', versions: ['Verilog-1995', 'Verilog-2001', 'Verilog-2005', 'SystemVerilog 2009', 'SystemVerilog 2012', 'SystemVerilog 2017', 'SystemVerilog 2023'], dialects: ['Verilog', 'SystemVerilog', 'UVM (Universal Verification Methodology)', 'OVM'] },
  { id: 'vhdl', name: 'VHDL', desc: 'VHDL for hardware description and simulation', category: 'modern', versions: ['VHDL-87', 'VHDL-93', 'VHDL-2000', 'VHDL-2002', 'VHDL-2008', 'VHDL-2019'], dialects: ['Standard VHDL', 'VHDL-AMS (analog)', 'PSL (property spec)', 'OSVVM'] },
  { id: 'solidity', name: 'Solidity', desc: 'Solidity for EVM smart contracts', category: 'modern', versions: ['Solidity 0.6.x', 'Solidity 0.7.x', 'Solidity 0.8.x'], dialects: ['Ethereum', 'Polygon', 'BSC', 'Avalanche', 'Arbitrum'] },
  { id: 'move', name: 'Move', desc: 'Move resource-oriented blockchain language', category: 'modern', versions: ['Move 2022', 'Move 2023', 'Move 2024'], dialects: ['Aptos Move', 'Sui Move', 'Starcoin Move'] },
  // ── Modern Cross-Platform / Game / GPU ────────────────────────────────────
  { id: 'coffeescript', name: 'CoffeeScript', desc: 'CoffeeScript — Ruby-like JS transpiler (legacy web)', category: 'modern', versions: ['CoffeeScript 1.x', 'CoffeeScript 2.x'], dialects: ['CoffeeScript 1 (CS1)', 'CoffeeScript 2 (ES6 output)', 'IcedCoffeeScript'] },
  { id: 'haxe', name: 'Haxe', desc: 'Haxe cross-platform: JS, Java, C++, C#, Python targets', category: 'modern', versions: ['Haxe 3.x', 'Haxe 4.0', 'Haxe 4.1', 'Haxe 4.2', 'Haxe 4.3', 'Haxe 5.0 (Preview)'], dialects: ['Standard Haxe', 'OpenFL', 'Heaps.io', 'HaxeFlixel', 'Kha'] },
  { id: 'gdscript', name: 'GDScript / Godot', desc: 'GDScript for Godot Engine 3.x and 4.x', category: 'modern', versions: ['GDScript 3.x (Godot 3)', 'GDScript 4.0 (Godot 4)', 'GDScript 4.1', 'GDScript 4.2', 'GDScript 4.3', 'GDScript 4.4'], dialects: ['GDScript', 'Godot C# (Mono/C# 10)', 'GDNative (C/C++)', 'GDExtension'] },
  { id: 'glsl', name: 'GLSL / HLSL / WGSL', desc: 'Shader languages for GPU programming', category: 'modern', versions: ['GLSL 1.30', 'GLSL 3.30', 'GLSL 4.50', 'GLSL 4.60', 'HLSL SM 5.0', 'HLSL SM 5.1', 'HLSL SM 6.x', 'WGSL (WebGPU)', 'MSL (Metal)'], dialects: ['GLSL (OpenGL)', 'HLSL (DirectX)', 'WGSL (WebGPU)', 'MSL (Metal / Apple)', 'SPIR-V (Vulkan)', 'CG (Nvidia/legacy)'] },
  // ── Logic / Formal Methods ────────────────────────────────────────────────
  { id: 'prolog', name: 'Prolog / Datalog', desc: 'SWI-Prolog, GNU Prolog, Mercury, Datalog — logic programming', category: 'modern', versions: ['ISO Prolog', 'SWI-Prolog 8.x', 'SWI-Prolog 9.x', 'GNU Prolog 1.x', 'YAP Prolog', 'Ciao 1.x', 'Souffle Datalog'], dialects: ['ISO Prolog', 'SWI-Prolog', 'GNU Prolog', 'YAP', 'Mercury', 'Ciao', 'ECLiPSe', 'Datalog (Souffle)', 'Logtalk'] },
  { id: 'forth', name: 'Forth / Factor', desc: 'ANS Forth, gForth, Factor — stack-based embedded and scripting', category: 'legacy', versions: ['ANS Forth (1994)', 'Forth 2012', 'gForth 0.7.3', 'SwiftForth 3.x', 'Factor 0.99'], dialects: ['ANS Forth', 'gForth', 'SwiftForth', 'VFX Forth', 'ZForth (embedded)', 'RetroForth', 'Factor'] },
  { id: 'coq', name: 'Coq / Rocq', desc: 'Coq / Rocq proof assistant and dependently typed language', category: 'modern', versions: ['Coq 8.15', 'Coq 8.16', 'Coq 8.17', 'Coq 8.18', 'Rocq 9.0'], dialects: ['Coq (Gallina)', 'Rocq Prover', 'SSReflect (MathComp)', 'Equations plugin'] },
  { id: 'lean4', name: 'Lean 4', desc: 'Lean 4 theorem prover and functional programming language', category: 'modern', versions: ['Lean 4.0', 'Lean 4.3', 'Lean 4.6', 'Lean 4.10 (stable)'], dialects: ['Lean 4 (standard)', 'Mathlib4', 'LeanDojo'] },
  { id: 'idris2', name: 'Idris 2', desc: 'Idris 2 — dependently typed functional language', category: 'modern', versions: ['Idris 2 0.5', 'Idris 2 0.6', 'Idris 2 0.7'], dialects: ['Standard Idris 2', 'Idris 2 (LLVM)', 'Idris 2 (Node backend)'] },
  { id: 'wolfram', name: 'Wolfram / Mathematica', desc: 'Wolfram Language, Mathematica — symbolic and numeric computing', category: 'modern', versions: ['Mathematica 12.x', 'Mathematica 13.x', 'Wolfram Language 13', 'Wolfram Language 14'], dialects: ['Mathematica', 'Wolfram Cloud', 'Wolfram Desktop', 'Wolfram Alpha API'] },
  // ── Platform / Enterprise CRM / Integration ───────────────────────────────
  { id: 'tibco_bw', name: 'TIBCO BusinessWorks', desc: 'TIBCO BW 5.x / BW 6.x, process definitions, adapters, EAI/ESB integration flows', category: 'legacy', versions: ['TIBCO BW 5.9', 'TIBCO BW 5.11', 'TIBCO BW 5.14', 'TIBCO BW 6.4', 'TIBCO BW 6.5', 'TIBCO BW 6.6', 'TIBCO BW 6.9'], dialects: ['BW 5.x (Designer)', 'BW 6.x (Eclipse/BWCE)', 'BWCE (Container Edition)', 'TIBCO ActiveMatrix BW', 'TIBCO ActiveSpaces', 'TIBCO EMS', 'TIBCO Hawk', 'TIBCO Rendezvous'] },
  { id: 'apex', name: 'Salesforce Apex', desc: 'Apex, SOQL, SOSL, LWC, Flow, Visualforce — Salesforce platform', category: 'legacy', versions: ['Apex (Spring 2021)', 'Apex (Summer 2022)', 'Apex (Winter 2023)', 'Apex (Summer 2024)', 'Apex (Winter 2025)'], dialects: ['Apex', 'SOQL', 'SOSL', 'Visualforce', 'Lightning Web Components (LWC)', 'Aura Components', 'Salesforce Flow'] },
  { id: 'ballerina', name: 'Ballerina', desc: 'Ballerina — cloud-native integration language for APIs and services', category: 'modern', versions: ['Ballerina 2201.1 (Swan Lake)', 'Ballerina 2201.7', 'Ballerina 2201.8', 'Ballerina 2201.9', 'Ballerina 2201.10'], dialects: ['Ballerina Swan Lake', 'Ballerina Cloud'] },
  { id: 'hack', name: 'Hack / HHVM', desc: 'Meta Hack — gradually typed PHP superset on HHVM', category: 'modern', versions: ['Hack 4.x', 'Hack 4.150+', 'HHVM 4.x'], dialects: ['Hack (HHVM)', 'XHP (HTML templating)', 'Hack Async'] },
  { id: 'reason', name: 'Reason / ReScript', desc: 'Reason (OCaml syntax) and ReScript — type-safe JS compilation', category: 'modern', versions: ['Reason 3.x', 'ReScript 9.x', 'ReScript 10.x', 'ReScript 11.x'], dialects: ['Reason (BuckleScript)', 'ReScript (standalone)', 'ReasonReact', 'rescript-react'] },
  { id: 'mojo', name: 'Mojo', desc: 'Mojo — Python superset for AI/systems programming by Modular', category: 'modern', versions: ['Mojo 24.1', 'Mojo 24.3', 'Mojo 24.4', 'Mojo 24.5', 'Mojo 24.6'], dialects: ['Mojo (Modular)', 'MAX (Modular platform)'] },
  { id: 'd', name: 'D Language', desc: 'D (dlang) — C/C++ alternative with GC and systems features', category: 'modern', versions: ['D 2.080', 'D 2.090', 'D 2.100', 'D 2.105', 'D 2.107', 'D 2.108'], dialects: ['D (DMD)', 'D (GDC — GCC)', 'D (LDC — LLVM)', 'DUB packages', 'BetterC (no-GC subset)'] },
  { id: 'nix', name: 'Nix / NixOS', desc: 'Nix expression language — reproducible builds and system config', category: 'modern', versions: ['Nix 2.18', 'Nix 2.19', 'Nix 2.21', 'Nix 2.22', 'Nix 2.24'], dialects: ['Nix language', 'NixOS modules', 'Nix flakes', 'home-manager', 'nix-darwin'] },
  // ── Industrial / Scientific / Simulation ─────────────────────────────────
  { id: 'labview', name: 'LabVIEW / G', desc: 'NI LabVIEW G language — scientific instrumentation and control systems', category: 'legacy', versions: ['LabVIEW 2015', 'LabVIEW 2017', 'LabVIEW 2019', 'LabVIEW 2020', 'LabVIEW 2021', 'LabVIEW 2023', 'LabVIEW NXG'], dialects: ['LabVIEW (Dataflow/G)', 'LabVIEW FPGA', 'LabVIEW RT (Real-Time)', 'TestStand', 'LabVIEW NXG'] },
  { id: 'simulink', name: 'Simulink / Stateflow', desc: 'MATLAB Simulink model-based design, Stateflow, Embedded Coder', category: 'legacy', versions: ['Simulink R2018b', 'Simulink R2020b', 'Simulink R2022b', 'Simulink R2023b', 'Simulink R2024a'], dialects: ['Simulink', 'Stateflow', 'Embedded Coder', 'Simulink Coder', 'HDL Coder', 'Motor Control Blockset'] },
  { id: 'plc', name: 'IEC 61131-3 / PLC', desc: 'PLC Ladder Logic, Structured Text, FBD, SFC — industrial automation', category: 'legacy', versions: ['IEC 61131-3 (2013)', 'IEC 61131-3 (2023)', 'STEP 7 (Siemens)', 'TIA Portal V16/V17/V18', 'RSLogix 5000', 'CODESYS 3.5'], dialects: ['Ladder Diagram (LD)', 'Function Block Diagram (FBD)', 'Structured Text (ST)', 'Instruction List (IL)', 'Sequential Function Chart (SFC)', 'Siemens SCL', 'Allen-Bradley RSLogix', 'CODESYS ST'] },
  { id: 'xslt', name: 'XSLT / XQuery', desc: 'XSLT 1/2/3, XQuery, XPath — XML data transformation', category: 'legacy', versions: ['XSLT 1.0', 'XSLT 2.0', 'XSLT 3.0', 'XQuery 1.0', 'XQuery 3.1', 'XPath 3.1'], dialects: ['XSLT (Xalan)', 'XSLT (Saxon)', 'XQuery (BaseX)', 'XQuery (MarkLogic)', 'XProc 3.0'] },
  { id: 'spss', name: 'SPSS / Stata', desc: 'IBM SPSS Syntax, Stata .do files — statistical language migration', category: 'legacy', versions: ['SPSS 25', 'SPSS 26', 'SPSS 27', 'SPSS 28', 'SPSS 29', 'Stata 15', 'Stata 16', 'Stata 17', 'Stata 18'], dialects: ['SPSS Syntax', 'SPSS Python Scripting', 'Stata .do', 'Stata .ado', 'Stata Mata'] },
];

const targetLanguages = [
  // ── Modern Enterprise ──────────────────────────────────────────────────────
  { id: 'java', name: 'Java', desc: 'Enterprise Java, Spring Boot, Quarkus, Jakarta EE', category: 'modern', versions: ['Java 11 LTS', 'Java 17 LTS', 'Java 21 LTS', 'Java 22', 'Java 23', 'Java 24', 'Java 25 LTS', 'Java 26'], frameworks: ['Spring Boot 3.x', 'Spring Boot 4.x', 'Spring Framework 6.x', 'Spring WebFlux', 'Spring Cloud', 'Quarkus', 'Micronaut', 'Jakarta EE 10', 'Vert.x', 'Dropwizard', 'Javalin', 'Jooby', 'Play Java', 'Helidon', 'Ratpack'], build: ['Maven', 'Gradle', 'Gradle KTS', 'Bazel', 'Ant', 'Ivy'], arch: ['Monolith', 'Microservices', 'Modular Monolith', 'Serverless', 'Event-Driven', 'Hexagonal', 'Clean Architecture', 'Reactive', 'DDD', 'CQRS'] },
  { id: 'csharp', name: 'C#', desc: '.NET 8/9/10/11, ASP.NET Core, Blazor, MAUI', category: 'modern', versions: ['.NET 6', '.NET 7', '.NET 8', '.NET 9', '.NET 10', '.NET 11 (Preview)'], frameworks: ['ASP.NET Core 8/9/10', 'Blazor Server', 'Blazor WASM', 'MAUI', 'WPF (.NET)', 'WinUI 3', 'Avalonia', 'Orleans', 'MassTransit', 'MediatR', 'Dapper', 'Entity Framework Core 8/9/10', 'NHibernate 5.x', 'ServiceStack 8.x', 'FastEndpoints', 'Carter'], build: ['MSBuild', 'dotnet CLI', 'NuGet', 'Paket'], arch: ['Monolith', 'Microservices', 'Clean Architecture', 'N-Layer', 'Onion', 'DDD', 'CQRS', 'Event-Driven', 'Vertical Slice'] },
  { id: 'python', name: 'Python', desc: 'Python 3.10–3.14 web, data, AI/ML frameworks', category: 'modern', versions: ['Python 3.10', 'Python 3.11', 'Python 3.12', 'Python 3.13', 'Python 3.14'], frameworks: ['FastAPI', 'Django 4.x/5.x', 'Django 6.x', 'Flask', 'Starlette', 'Litestar', 'Sanic', 'Aiohttp', 'Tornado', 'Falcon', 'CherryPy', 'Dash', 'Streamlit', 'Gradio', 'Airflow', 'Celery', 'SQLAlchemy 2.x', 'Django REST Framework', 'Tortoise ORM', 'Pydantic v2', 'Marshmallow', 'Click', 'Typer', 'Prefect', 'Luigi'], build: ['pip', 'poetry', 'uv (Astral)', 'pipenv', 'conda', 'PDM', 'flit', 'hatch'], arch: ['Monolith', 'Microservices', 'Hexagonal', 'Serverless', 'Event-Driven', 'Clean Architecture', 'DDD', 'N-Layer', 'Data Pipeline'] },
  { id: 'kotlin', name: 'Kotlin', desc: 'Kotlin JVM/Multiplatform, Android, Ktor', category: 'modern', versions: ['Kotlin 1.9', 'Kotlin 2.0', 'Kotlin 2.1', 'Kotlin 2.2', 'Kotlin 2.3'], frameworks: ['Spring Boot', 'Ktor 2.x/3.x', 'Quarkus', 'Micronaut', 'Compose Multiplatform', 'Exposed', 'Koin', 'Arrow', 'KVision', 'Ktorm', 'Kotest', 'MockK'], build: ['Maven', 'Gradle', 'Gradle KTS', 'Amper (Preview)'], arch: ['Monolith', 'Microservices', 'DDD', 'Clean Architecture', 'Hexagonal', 'Reactive', 'Event-Driven', 'KMP (Multiplatform)'] },
  { id: 'node', name: 'Node.js', desc: 'TypeScript/JavaScript — Node, Bun, Deno runtimes', category: 'modern', versions: ['Node 18 LTS', 'Node 20 LTS', 'Node 22 LTS', 'Node 23', 'Node 24 LTS', 'Node 26', 'Bun 1.x', 'Bun 2.x', 'Deno 2.x'], frameworks: ['Express', 'Fastify', 'NestJS 10/11', 'NestJS 12', 'Koa', 'Hapi', 'Hono', 'Elysia', 'Next.js 14/15', 'Next.js 16', 'Nuxt 3', 'Nuxt 4', 'SvelteKit', 'Remix', 'Astro 5/6', 'TanStack Start', 'SolidStart', 'Fresh (Deno)', 'Bun.serve'], build: ['npm', 'yarn', 'pnpm', 'bun', 'Turbo', 'Rush', 'Lerna', 'Nx', 'Vite', 'Rollup', 'esbuild', 'Webpack'], arch: ['Monolith', 'Microservices', 'Serverless', 'Edge', 'Jamstack', 'Isomorphic', 'SPA', 'MPA', 'PWA', 'SSG', 'ISR'] },
  { id: 'go', name: 'Go', desc: 'Go 1.22–1.26 for cloud-native and microservices', category: 'modern', versions: ['Go 1.21', 'Go 1.22', 'Go 1.23', 'Go 1.24', 'Go 1.25', 'Go 1.26'], frameworks: ['Gin', 'Echo', 'Fiber', 'Chi', 'Standard Library (net/http)', 'Gorilla Mux', 'Beego', 'Hertz (ByteDance)', 'GoFr', 'GoZero', 'Fuego', 'Encore'], build: ['Go Modules', 'Bazel', 'Gazelle', 'GoReleaser'], arch: ['Monolith', 'Microservices', 'Hexagonal', 'Serverless', 'Event-Driven', 'Clean Architecture', 'DDD'] },
  { id: 'rust', name: 'Rust', desc: 'Rust 1.84+ for memory-safe systems and WASM', category: 'modern', versions: ['Rust 1.80', 'Rust 1.84', 'Rust 1.87', 'Rust 1.90', 'Rust 1.95 (Stable)', 'Rust Nightly'], frameworks: ['Axum', 'Actix Web 4.x', 'Rocket 0.5.x', 'Warp', 'Tonic (gRPC)', 'Poem', 'Salvo', 'Loco', 'Pavex', 'Yew', 'Leptos', 'Dioxus', 'Egui', 'Bevy', 'Wgpu'], build: ['Cargo', 'Cargo Workspaces', 'cross (cross-compilation)', 'cargo-make'], arch: ['Monolith', 'Microservices', 'Hexagonal', 'Serverless', 'Event-Driven', 'Reactive', 'Actor Model', 'Embedded', 'no_std'] },
  { id: 'php', name: 'PHP', desc: 'PHP 8.1–8.5 for web, Laravel, Symfony, WordPress', category: 'modern', versions: ['PHP 8.1', 'PHP 8.2', 'PHP 8.3', 'PHP 8.4', 'PHP 8.5'], frameworks: ['Laravel 10/11', 'Laravel 12/13', 'Symfony 6/7', 'Symfony 8.x', 'Slim 4', 'Lumen', 'CodeIgniter 4', 'CakePHP 4/5', 'Yii 2/3', 'Phalcon', 'Nette', 'WordPress', 'Drupal 10', 'Magento 2', 'Shopware 6', 'PrestaShop', 'Craft CMS', 'Statamic', 'October CMS'], build: ['Composer', 'Pickle'], arch: ['Monolith', 'Microservices', 'Hexagonal', 'Headless CMS', 'E-commerce'] },
  { id: 'ruby', name: 'Ruby', desc: 'Ruby 3.x/4.x for web, Rails, Hotwire, API', category: 'modern', versions: ['Ruby 3.0', 'Ruby 3.1', 'Ruby 3.2', 'Ruby 3.3', 'Ruby 3.4', 'Ruby 4.0'], frameworks: ['Rails 7.x/8.x', 'Rails 8.1', 'Sinatra', 'Hanami 2.x', 'Grape', 'Padrino', 'Rodauth', 'Sidekiq', 'ActionCable', 'Hotwire', 'Turbo', 'Stimulus', 'Phlex', 'Sorbet'], build: ['Bundler', 'RubyGems', 'Rbenv', 'RVM', 'asdf', 'mise'], arch: ['Monolith', 'Microservices', 'Serverless', 'Event-Driven', 'Hexagonal', 'DDD'] },
  { id: 'swift', name: 'Swift', desc: 'Swift 6.x for server and Apple platforms', category: 'modern', versions: ['Swift 5.10', 'Swift 6.0', 'Swift 6.1', 'Swift 6.2', 'Swift 6.3', 'Swift 6.4'], frameworks: ['Vapor 4', 'Hummingbird 2', 'SwiftNIO', 'Kitura', 'Perfect', 'Smoke', 'Distributed Actors', 'SwiftUI', 'AppKit'], build: ['Swift Package Manager (SwiftPM)', 'CocoaPods', 'Carthage', 'Bazel (rules_swift)'], arch: ['Monolith', 'Microservices', 'Serverless', 'Actor Model', 'SwiftUI MVVM', 'TCA (Composable Architecture)'] },
  { id: 'scala', name: 'Scala', desc: 'Scala 2/3 for functional, streaming, microservices', category: 'modern', versions: ['Scala 2.13', 'Scala 3.3 LTS', 'Scala 3.4', 'Scala 3.5', 'Scala 3.6', 'Scala 3.7', 'Scala 3.8'], frameworks: ['Play Framework 3', 'Akka HTTP / Pekko HTTP', 'Http4s', 'ZIO-HTTP', 'Tapir', 'Caliban', 'Cats Effect 3', 'ZIO 2', 'Kafka (fs2-kafka)', 'Spark 3.x', 'Flink (Scala API)'], build: ['SBT', 'Mill', 'Maven', 'Gradle', 'Bazel', 'Scala-CLI'], arch: ['Monolith', 'Microservices', 'Functional', 'Reactive', 'Event-Driven', 'CQRS', 'Actor Model', 'Data Pipeline'] },
  { id: 'elixir', name: 'Elixir', desc: 'Elixir 1.17–1.20 on BEAM for real-time systems', category: 'modern', versions: ['Elixir 1.15', 'Elixir 1.16', 'Elixir 1.17', 'Elixir 1.18', 'Elixir 1.19', 'Elixir 1.20'], frameworks: ['Phoenix 1.7', 'Phoenix LiveView', 'Plug', 'Bandit', 'Absinthe (GraphQL)', 'Ecto 3.x', 'Oban', 'Broadway', 'GenStage', 'Nerves', 'Nx (numerical Elixir)'], build: ['Mix', 'Hex', 'Rebar3'], arch: ['Monolith', 'Microservices', 'Event-Driven', 'Distributed', 'Actor Model', 'DDD', 'CQRS', 'Event Sourcing'] },
  { id: 'dart', name: 'Dart / Flutter', desc: 'Dart 3.x for Flutter cross-platform and server', category: 'modern', versions: ['Dart 3.3', 'Dart 3.5', 'Dart 3.7', 'Dart 3.9', 'Dart 3.11'], frameworks: ['Flutter 3.x', 'Dart Frog', 'Shelf', 'Serverpod', 'Drift (ORM)', 'Realm Dart', 'Riverpod', 'Bloc', 'GetX'], build: ['pub', 'melos', 'Flutter CLI'], arch: ['Monolith', 'Microservices', 'Serverless', 'Mobile-first (Flutter)', 'Desktop (Flutter)', 'Clean Architecture', 'BLoC', 'MVVM'] },
  { id: 'objective_c', name: 'Objective-C', desc: 'Objective-C for Apple platform modernisation / bridging', category: 'modern', versions: ['Objective-C 2.0 (Xcode 15)', 'Objective-C 2.0 (Xcode 16)'], frameworks: ['Cocoa (macOS)', 'CocoaTouch (iOS)', 'GNUstep', 'Foundation', 'UIKit', 'AppKit', 'CoreData'], build: ['Xcode (xcodebuild)', 'CocoaPods', 'Carthage', 'SwiftPM (bridging)'], arch: ['Monolith', 'MVC (Cocoa)', 'MVVM (bridging)', 'Modular Framework'] },
  { id: 'c', name: 'C', desc: 'C11/C17/C23 for systems, embedded, and WASM', category: 'modern', versions: ['C11', 'C17', 'C23'], frameworks: ['GLib', 'libuv', 'ZeroMQ (czmq)', 'libevent', 'libcurl', 'OpenSSL', 'SQLite', 'libpq (PostgreSQL)', 'mongoose', 'libmicrohttpd', 'libc (musl/glibc)', 'FreeRTOS (RTOS)'], build: ['Make', 'CMake 3.x', 'Meson', 'Bazel', 'Autotools', 'Ninja', 'xmake'], arch: ['Monolith', 'Event-Driven', 'Embedded', 'Real-Time', 'Systems', 'WASI/WASM'] },
  { id: 'cpp', name: 'C++', desc: 'C++17/20/23 for high-performance and systems', category: 'modern', versions: ['C++17', 'C++20', 'C++23', 'C++26 (Draft)'], frameworks: ['Drogon', 'Oat++', 'Pistache', 'Crow', 'Boost.Beast', 'Boost.Asio', 'POCO', 'Qt 6', 'gRPC', 'Protobuf', 'OpenCV 4.x', 'TensorFlow C++', 'PyTorch C++ (libtorch)', 'JUCE', 'Unreal Engine API'], build: ['CMake', 'Bazel', 'Meson', 'Conan 2.x', 'vcpkg', 'xmake'], arch: ['Monolith', 'Microservices', 'Event-Driven', 'Reactive', 'Real-time', 'High-Performance', 'Game Engine'] },
  { id: 'typescript', name: 'TypeScript', desc: 'TypeScript 5.x/6.x with modern frontend/backend frameworks', category: 'modern', versions: ['TypeScript 5.0', 'TypeScript 5.3', 'TypeScript 5.5', 'TypeScript 5.7', 'TypeScript 6.0'], frameworks: ['Angular 19/20/21', 'React 18/19', 'Vue 3', 'Svelte 5', 'Solid.js', 'Qwik', 'Astro 5/6', 'Remix', 'Next.js 14/15', 'Next.js 16', 'Nuxt 3', 'Nuxt 4', 'SvelteKit', 'TanStack Start', 'Hono', 'Elysia', 'NestJS 10/11', 'NestJS 12'], build: ['npm', 'yarn', 'pnpm', 'bun', 'Turbo', 'Vite', 'Webpack 5', 'esbuild', 'Rspack'], arch: ['Monolith', 'Microservices', 'Serverless', 'Edge', 'SPA', 'SSR', 'SSG', 'ISR', 'MPA', 'PWA'] },
  { id: 'gleam', name: 'Gleam', desc: 'Gleam — type-safe language on Erlang BEAM / JS', category: 'modern', versions: ['Gleam 1.0', 'Gleam 1.1', 'Gleam 1.2', 'Gleam 1.3', 'Gleam 1.4'], frameworks: ['Wisp (HTTP)', 'Glen (JS HTTP)', 'Gleam stdlib', 'Mist', 'Lustre (frontend)'], build: ['gleam (CLI)', 'Hex'], arch: ['Microservices', 'Actor Model', 'Functional', 'Distributed', 'Type-Safe'] },
  { id: 'haxe', name: 'Haxe', desc: 'Haxe 4/5 cross-compiling to JS, Java, C++, Python, C#', category: 'modern', versions: ['Haxe 4.2', 'Haxe 4.3', 'Haxe 5.0 (Preview)'], frameworks: ['OpenFL', 'Heaps.io', 'HaxeFlixel', 'Kha', 'Haxe stdlib', 'tink_web (REST)', 'lix.pm'], build: ['hxml', 'lix (package manager)', 'npm (JS target)'], arch: ['Monolith', 'Game Engine', 'Cross-Platform', 'Web', 'Desktop', 'Mobile'] },
  { id: 'clojure', name: 'Clojure', desc: 'Clojure 1.11/1.12 functional JVM programming', category: 'modern', versions: ['Clojure 1.10', 'Clojure 1.11', 'Clojure 1.12'], frameworks: ['Ring', 'Pedestal', 'Reitit', 'Luminus', 'Compojure-API', 'Yada', 'XTDB (formerly Crux)', 'Datomic', 'Datahike', 'Onyx', 'Kafka Streams (clj-kafka)', 'Jepsen'], build: ['Leiningen', 'deps.edn (tools.deps)', 'Boot', 'tools.build', 'Babashka (scripting)'], arch: ['Monolith', 'Microservices', 'Functional', 'Reactive', 'Event-Driven', 'Data-Intensive', 'Immutable-DB'] },
  { id: 'fsharp', name: 'F#', desc: 'F# 8/9 functional .NET', category: 'modern', versions: ['F# 7', 'F# 8', 'F# 9'], frameworks: ['Giraffe', 'Saturn', 'Fable 4 (JS)', 'SAFE Stack', 'Elmish', 'FSharp.Data', 'Hopac', 'Expecto', 'Farmer (Azure IaC)', 'Bolero (WASM)'], build: ['dotnet CLI', 'Paket', 'FAKE', 'NuGet'], arch: ['Monolith', 'Microservices', 'Functional', 'Clean Architecture', 'DDD', 'Actor Model', 'SAFE Stack'] },
  { id: 'haskell', name: 'Haskell', desc: 'Haskell GHC 9.6/9.8/9.10 pure functional', category: 'modern', versions: ['GHC 9.4', 'GHC 9.6', 'GHC 9.8', 'GHC 9.10'], frameworks: ['Servant', 'Yesod', 'Scotty', 'Warp', 'Snap', 'Obelisk', 'Reflex-DOM (WASM)', 'PostgREST', 'Beam', 'Opaleye', 'Persistent', 'Esqueleto'], build: ['Cabal', 'Stack', 'Bazel (rules_haskell)'], arch: ['Monolith', 'Microservices', 'Functional', 'Serverless', 'Reactive', 'Type-Safe', 'Dependent Types'] },
  { id: 'julia', name: 'Julia', desc: 'Julia 1.10/1.12 for HPC and scientific computing', category: 'modern', versions: ['Julia 1.9', 'Julia 1.10 LTS', 'Julia 1.11', 'Julia 1.12'], frameworks: ['Genie.jl', 'Oxygen.jl', 'HTTP.jl', 'Dash.jl', 'Makie.jl', 'Plots.jl', 'DataFrames.jl', 'Flux.jl', 'DifferentialEquations.jl', 'Lux.jl', 'CUDA.jl', 'MPI.jl'], build: ['Pkg', 'Project.toml / Manifest.toml'], arch: ['Monolith', 'Microservices', 'Scientific', 'HPC', 'Data-Intensive', 'Numerical'] },
  { id: 'r', name: 'R', desc: 'R 4.3–4.5 for statistics, Shiny, analytics APIs', category: 'modern', versions: ['R 4.2', 'R 4.3', 'R 4.4', 'R 4.5'], frameworks: ['Plumber', 'Shiny', 'flexdashboard', 'golem', 'rhino', 'Shiny for Python (parallel)', 'dplyr', 'tidyverse', 'ggplot2', 'plotly', 'teal (pharma)'], build: ['renv', 'packrat', 'pak', 'r-universe'], arch: ['Monolith', 'Serverless', 'Data-Science', 'Analytics', 'Reporting', 'Pharma Pipeline'] },
  { id: 'crystal', name: 'Crystal', desc: 'Crystal 1.x — Ruby-like compiled language', category: 'modern', versions: ['Crystal 1.3', 'Crystal 1.4', 'Crystal 1.5'], frameworks: ['Kemal', 'Amber', 'Lucky', 'Spider-Gazelle', 'Orion', 'Raze'], build: ['Shards'], arch: ['Monolith', 'Microservices', 'Serverless'] },
  { id: 'nim', name: 'Nim', desc: 'Nim 2.x — Python-like, C-speed', category: 'modern', versions: ['Nim 1.6', 'Nim 2.0', 'Nim 2.2'], frameworks: ['Jester', 'HappyX', 'Prologue', 'Karax (frontend)', 'Chronicles (logging)'], build: ['Nimble'], arch: ['Monolith', 'Microservices', 'Frontend', 'Systems'] },
  { id: 'zig', name: 'Zig', desc: 'Zig 0.12–0.14 modern C alternative', category: 'modern', versions: ['Zig 0.12', 'Zig 0.13', 'Zig 0.14'], frameworks: ['ZigHTTP', 'zig-network', 'libxev (async)', 'zig-bearssl (TLS)'], build: ['zig build', 'zig fetch'], arch: ['Monolith', 'Systems', 'Embedded', 'no_libc', 'WASM'] },
  { id: 'sql', name: 'SQL / Modern DB', desc: 'PostgreSQL, MySQL, Snowflake, ClickHouse, DuckDB', category: 'modern', versions: ['PostgreSQL 14', 'PostgreSQL 15', 'PostgreSQL 16', 'PostgreSQL 17', 'MySQL 8.x', 'MariaDB 11.x', 'SQL Server 2022', 'Snowflake', 'BigQuery', 'ClickHouse 24.x', 'DuckDB 0.10'], frameworks: ['pl/pgSQL', 'pgTAP (testing)', 'Flyway', 'Liquibase', 'dbmate', 'sqitch'], build: ['SQL scripts', 'Stored Procedures', 'Flyway', 'Liquibase'], arch: ['OLTP', 'OLAP', 'Analytical', 'Data Warehouse', 'Time-Series', 'Columnar'] },
  { id: 'graphql', name: 'GraphQL', desc: 'GraphQL APIs — Apollo, Hasura, Hot Chocolate', category: 'modern', versions: ['GraphQL 2021', 'GraphQL Composite Schemas 2024'], frameworks: ['Apollo Server 4', 'Apollo Federation', 'Hot Chocolate 14', 'Strawberry Python', 'gqlgen (Go)', 'Juniper (Rust)', 'graphql-yoga', 'Hasura', 'PostGraphile', 'Urql', 'Relay'], build: ['npm', 'yarn', 'pip', 'cargo', 'go modules'], arch: ['API Gateway', 'BFF (Backend-for-Frontend)', 'Federation', 'Headless CMS'] },
  { id: 'powershell', name: 'PowerShell', desc: 'PowerShell 7.4/7.5 automation and DevOps', category: 'modern', versions: ['PowerShell 7.2 LTS', 'PowerShell 7.4 LTS', 'PowerShell 7.5'], frameworks: ['PSFramework', 'PowerShell Universal', 'Pester 5.x', 'PSScriptAnalyzer', 'InvokeBuild', 'Plaster', 'SecretManagement'], build: ['PowerShellGet', 'PSDepend', 'NuGet'], arch: ['Automation', 'DevOps', 'CI/CD', 'Configuration Management', 'Scripting'] },
  { id: 'bash', name: 'Bash / Shell', desc: 'Bash 5.x and POSIX sh for DevOps automation', category: 'modern', versions: ['Bash 5.1', 'Bash 5.2', 'POSIX sh', 'Zsh 5.x'], frameworks: ['ShellCheck', 'Bats-core', 'ShUnit2', 'bashunit', 'taskfile.dev', 'just (command runner)'], build: ['Shell scripts', 'Makefiles', 'Taskfile'], arch: ['Automation', 'DevOps', 'CI/CD', 'Systems Administration'] },
  { id: 'groovy', name: 'Groovy', desc: 'Groovy 4/5 for JVM scripting, Gradle DSL', category: 'modern', versions: ['Groovy 3.0', 'Groovy 4.0', 'Groovy 5.0', 'Groovy 6.0 (Preview)'], frameworks: ['Gradle DSL', 'Spock 2.x', 'Geb', 'Grails 5/6', 'Micronaut Groovy', 'Ratpack'], build: ['Gradle', 'Maven'], arch: ['Build Automation', 'Testing DSL', 'Web', 'Microservices'] },
  { id: 'erlang', name: 'Erlang / OTP', desc: 'Erlang OTP 26/27/28 for distributed fault-tolerant systems', category: 'modern', versions: ['OTP 25', 'OTP 26', 'OTP 27', 'OTP 28'], frameworks: ['Cowboy 2.x', 'Ranch', 'Gun', 'Mnesia', 'Riak Core', 'gRPC (grpc_erl)', 'Hackney (HTTP client)'], build: ['Rebar3', 'Hex', 'erlang.mk'], arch: ['Monolith', 'Microservices', 'Distributed', 'Actor Model', 'High-Availability', 'Soft Real-Time'] },
  { id: 'ocaml', name: 'OCaml', desc: 'OCaml 5.x with effects and multicore', category: 'modern', versions: ['OCaml 4.14', 'OCaml 5.0', 'OCaml 5.1', 'OCaml 5.2', 'OCaml 5.3'], frameworks: ['Dream', 'Eio (effects-based IO)', 'Cohttp', 'Lwt', 'Irmin (distributed DB)', 'Merlin', 'ReScript (JS compile target)'], build: ['Dune', 'OPAM', 'ocamlfind'], arch: ['Monolith', 'Microservices', 'Functional', 'Systems', 'Compilers', 'Finance'] },
  { id: 'elm', name: 'Elm', desc: 'Elm 0.19 for zero-runtime-error web UIs', category: 'modern', versions: ['Elm 0.19', 'Elm 0.19.1'], frameworks: ['The Elm Architecture (TEA)', 'elm-ui', 'elm-spa', 'elm-test', 'elm-review'], build: ['elm', 'elm-format', 'elm-review', 'vite-plugin-elm'], arch: ['SPA', 'Frontend', 'Functional', 'Type-Safe'] },
  { id: 'purescript', name: 'PureScript', desc: 'PureScript 0.15 type-safe Haskell-like for JS', category: 'modern', versions: ['PureScript 0.15', 'PureScript 0.15.10'], frameworks: ['Halogen', 'React Basic', 'Aff', 'Routing Duplex', 'PureScript Spec'], build: ['Spago', 'Purs', 'npm'], arch: ['SPA', 'Frontend', 'Functional', 'Type-Safe'] },
  { id: 'solidity', name: 'Solidity', desc: 'Solidity 0.8.x for EVM smart contracts', category: 'modern', versions: ['Solidity 0.8.20', 'Solidity 0.8.25', 'Solidity 0.8.26'], frameworks: ['Hardhat', 'Foundry', 'OpenZeppelin 5.x', 'Truffle', 'Brownie', 'Ape'], build: ['forge', 'npm', 'yarn'], arch: ['Smart Contracts', 'DeFi', 'NFT', 'DAO', 'Layer 2'] },
  { id: 'move', name: 'Move', desc: 'Move for Aptos / Sui resource-oriented blockchain', category: 'modern', versions: ['Move 2022', 'Move 2023', 'Move 2024'], frameworks: ['Aptos Framework', 'Sui Framework', 'Starcoin Framework', 'Aptos Wallet Adapter'], build: ['aptos CLI', 'sui CLI', 'starcoin CLI'], arch: ['Smart Contracts', 'Blockchain', 'Resource-Oriented'] },
  { id: 'verilog', name: 'SystemVerilog', desc: 'SystemVerilog 2017/2023 for FPGA and ASIC', category: 'modern', versions: ['SystemVerilog 2009', 'SystemVerilog 2012', 'SystemVerilog 2017', 'SystemVerilog 2023'], frameworks: ['UVM (Universal Verification Methodology)', 'OSVVM', 'VUnit', 'Cocotb', 'Verilator'], build: ['Verilator', 'Yosys', 'Vivado', 'Quartus Prime', 'Questa'], arch: ['Hardware', 'FPGA', 'ASIC', 'Simulation', 'Formal Verification'] },
  { id: 'vhdl', name: 'VHDL', desc: 'VHDL 2008/2019 for hardware description', category: 'modern', versions: ['VHDL-2008', 'VHDL-2019'], frameworks: ['OSVVM', 'VUnit', 'GHDL', 'PSL (Property Specification Language)'], build: ['GHDL', 'Vivado', 'Quartus', 'Modelsim', 'Questa'], arch: ['Hardware', 'FPGA', 'ASIC', 'Simulation', 'Formal Verification'] },
  // ── Legacy Targets (in-dialect refactoring / step-up migrations) ───────────
  { id: 'rpg_free', name: 'RPG Free (**FREE)', desc: 'IBM i free-format RPG — modernise fixed-format RPG IV', category: 'legacy', versions: ['RPG IV Free-Format', '**FREE (ILE RPG)', 'RPGLE Service Programs'], frameworks: ['**FREE', 'ILE Binding', 'CLP integration'], build: ['IBM i CRTBNDRPG', 'IBM i CRTRPGMOD', 'ARCAD Transformer'], arch: ['IBM i', 'AS/400', 'ILE Service Programs'] },
  { id: 'cobol', name: 'COBOL (Modern)', desc: 'OO COBOL, GnuCOBOL, COBOL-2023 for refactoring', category: 'legacy', versions: ['COBOL-2002', 'COBOL-2014', 'COBOL-2023', 'GnuCOBOL 3.x'], frameworks: ['Object-Oriented COBOL', 'Managed COBOL (Micro Focus)', 'GnuCOBOL'], build: ['Enterprise COBOL', 'Micro Focus COBOL', 'GnuCOBOL', 'OpenCOBOL'], arch: ['Monolith', 'Batch', 'CICS Online'] },
  { id: 'java_legacy', name: 'Java Legacy', desc: 'Java 7/8 EE2/J2EE for step-up refactoring', category: 'legacy', versions: ['Java 7', 'Java 8 (LTS)', 'J2EE 1.4'], frameworks: ['J2EE', 'EJB 2.x / 3.x', 'Struts 1.x', 'JSF 1.x', 'Spring 3.x', 'Hibernate 3.x', 'JSP / Servlet', 'Apache Wicket 7.x'], build: ['Ant', 'Maven 2.x', 'Ivy'], arch: ['Monolith', 'N-Tier', 'EAR deployment'] },
  { id: 'dotnet_legacy', name: '.NET Framework', desc: '.NET Framework 4.x for step-up refactoring', category: 'legacy', versions: ['.NET Framework 3.5', '.NET Framework 4.0', '.NET Framework 4.5', '.NET Framework 4.8'], frameworks: ['ASP.NET Web Forms', 'WCF', 'WF (Windows Workflow)', 'Entity Framework 6', 'ASP.NET MVC 3-5', 'WPF', 'WinForms', 'Silverlight'], build: ['MSBuild', 'NuGet'], arch: ['Monolith', 'SOA', '3-Tier'] },
  { id: 'vbnet', name: 'VB.NET', desc: 'VB.NET for .NET Framework migration target', category: 'legacy', versions: ['VB.NET 11 (.NET 4.5)', 'VB.NET 14 (.NET 4.6)', 'VB.NET 15.x (.NET 4.7)', 'VB.NET 16.x (.NET 4.8)'], frameworks: ['ASP.NET Web Forms', 'WinForms', 'WPF', 'Entity Framework 6'], build: ['MSBuild', 'NuGet'], arch: ['Monolith'] },
  { id: 'classic_asp', name: 'Classic ASP', desc: 'ASP 3.0 / VBScript / JScript — step-up from older tech', category: 'legacy', versions: ['ASP 3.0'], frameworks: ['VBScript', 'JScript', 'ADO', 'COM Components', 'IIS 6/7 ISAPI'], build: ['IIS'], arch: ['Monolith', 'CGI-style'] },
  { id: 'php_legacy', name: 'PHP Legacy', desc: 'PHP 5.x for step-up refactoring', category: 'legacy', versions: ['PHP 5.3', 'PHP 5.4', 'PHP 5.5', 'PHP 5.6', 'PHP 7.0', 'PHP 7.2'], frameworks: ['CodeIgniter 2.x', 'CakePHP 2.x', 'Zend Framework 1.x/2.x', 'PEAR', 'Symfony 2.x'], build: ['Composer (legacy)', 'PEAR'], arch: ['Monolith', 'LAMP Stack'] },
  { id: 'perl_legacy', name: 'Perl Legacy', desc: 'Perl 5.8–5.20 CGI / Catalyst refactoring', category: 'legacy', versions: ['Perl 5.8', 'Perl 5.10', 'Perl 5.12', 'Perl 5.14', 'Perl 5.16', 'Perl 5.18', 'Perl 5.20'], frameworks: ['CGI.pm', 'Mojolicious (legacy)', 'Catalyst', 'Mason', 'Template Toolkit', 'DBI'], build: ['CPAN', 'cpanm'], arch: ['Monolith', 'CGI', 'FastCGI'] },
  // ── Emerging / Specialized Targets ───────────────────────────────────────
  { id: 'd', name: 'D Language', desc: 'D 2.x for C/C++ modernization and high-performance systems', category: 'modern', versions: ['D 2.100', 'D 2.105', 'D 2.107', 'D 2.108'], frameworks: ['vibe.d (async web)', 'hunt-framework', 'Diamond MVC', 'Mir (numeric/SIMD)', 'std.concurrency'], build: ['DUB', 'Meson', 'CMake'], arch: ['Monolith', 'Microservices', 'Systems', 'Embedded', 'High-Performance'] },
  { id: 'mojo', name: 'Mojo', desc: 'Mojo 24.x — Python superset for AI/ML systems by Modular', category: 'modern', versions: ['Mojo 24.4', 'Mojo 24.5', 'Mojo 24.6'], frameworks: ['MAX Engine', 'Modular Platform', 'Mojo stdlib', 'Python interop (cpython bridge)'], build: ['magic (Modular package manager)', 'pixi'], arch: ['AI/ML', 'Systems', 'High-Performance', 'GPU', 'SIMD'] },
  { id: 'ballerina', name: 'Ballerina', desc: 'Ballerina 2201.x — cloud-native integration and API orchestration', category: 'modern', versions: ['Ballerina 2201.7', 'Ballerina 2201.8', 'Ballerina 2201.9', 'Ballerina 2201.10'], frameworks: ['Ballerina HTTP', 'Ballerina GraphQL', 'Ballerina gRPC', 'Ballerina Kafka', 'Ballerina RabbitMQ', 'Ballerina OpenAPI', 'Choreo (cloud)'], build: ['bal (Ballerina CLI)', 'Ballerina Central'], arch: ['Microservices', 'Integration', 'API Gateway', 'Event-Driven', 'Cloud-Native'] },
  { id: 'reason', name: 'ReScript / Reason', desc: 'ReScript 11.x / Reason — type-safe JavaScript from OCaml lineage', category: 'modern', versions: ['ReScript 10.x', 'ReScript 11.x', 'Reason 3.x'], frameworks: ['ReasonReact', 'rescript-react', 'rescript-schema', 'rescript-core', 'Melange'], build: ['rescript build', 'bsb', 'Melange (Dune)'], arch: ['SPA', 'Frontend', 'Functional', 'Type-Safe', 'SSR (Next.js)'] },
  { id: 'apex', name: 'Salesforce Apex', desc: 'Apex for Salesforce CRM — LWC, Flow, Visualforce, Platform Events', category: 'modern', versions: ['Apex (Winter 2024)', 'Apex (Summer 2024)', 'Apex (Winter 2025)'], frameworks: ['Lightning Web Components (LWC)', 'Aura Framework', 'Salesforce Flow', 'SOQL/SOSL', 'Visualforce', 'Platform Events', 'Salesforce Functions'], build: ['Salesforce CLI (sf)', 'sfdx', 'VS Code Salesforce Extensions'], arch: ['Monolith', 'Event-Driven', 'Trigger-Handler', 'Domain Model', 'Salesforce Platform'] },
  { id: 'prolog', name: 'Prolog / Datalog', desc: 'SWI-Prolog, Datalog, Souffle for logic rule engines and knowledge systems', category: 'modern', versions: ['SWI-Prolog 9.x', 'GNU Prolog 1.x', 'Souffle Datalog 2.x', 'DLV Datalog'], frameworks: ['SWI-Prolog stdlib', 'Logtalk (OOP Prolog)', 'Pengines', 'Souffle', 'Nemo'], build: ['SWI-Prolog packs', 'spack'], arch: ['Rule Engine', 'Knowledge Base', 'Expert System', 'Logic Programming', 'Datalog Analytics'] },
  { id: 'wasm', name: 'WebAssembly / WASI', desc: 'WASM 2.0 / WASI Preview 2 — universal binary runtime target', category: 'modern', versions: ['WASM 1.0', 'WASM 2.0', 'WASI Preview 1', 'WASI Preview 2', 'Component Model'], frameworks: ['Wasmtime', 'WasmEdge', 'Spin (Fermyon)', 'wasmCloud', 'Fastly Compute', 'Cloudflare Workers (WASM)', 'component-model toolchain'], build: ['wasm-pack', 'wasm-bindgen', 'wit-bindgen', 'cargo (Rust→WASM)', 'emscripten (C/C++→WASM)'], arch: ['Edge', 'Serverless', 'Portable Binary', 'Plugin System', 'Sandboxed Execution'] },
  { id: 'nix', name: 'Nix / NixOS', desc: 'Nix for reproducible builds, NixOS modules, flakes, home-manager', category: 'modern', versions: ['Nix 2.18', 'Nix 2.19', 'Nix 2.22', 'Nix 2.24'], frameworks: ['nixpkgs', 'NixOS modules', 'home-manager', 'nix-darwin', 'devenv.sh', 'flake-parts', 'flake-utils'], build: ['nix build', 'nix develop', 'nix flake'], arch: ['Infrastructure', 'Reproducible Builds', 'Configuration Management', 'DevOps', 'IaC'] },
];

const providers = [
  { name: 'GitHub', icon: '🐙', auth: ['Personal Access Token', 'OAuth App', 'GitHub App'] },
  { name: 'GitLab', icon: '🦊', auth: ['Personal Access Token', 'OAuth 2.0', 'GitLab App'] },
  { name: 'Azure DevOps', icon: '🔷', auth: ['Personal Access Token', 'OAuth 2.0', 'Service Principal'] },
  { name: 'Bitbucket', icon: '🪣', auth: ['App Password', 'OAuth 2.0', 'Bitbucket App'] },
  { name: 'Local folder', icon: '📁', auth: [] as string[] },
];

const domains = [
  { id: 'banking', name: 'Banking & Finance', icon: '🏦' },
  { id: 'insurance', name: 'Insurance', icon: '🛡️' },
  { id: 'healthcare', name: 'Healthcare', icon: '🏥' },
  { id: 'retail', name: 'Retail & E-commerce', icon: '🛒' },
  { id: 'manufacturing', name: 'Manufacturing', icon: '🏭' },
  { id: 'logistics', name: 'Logistics & Supply Chain', icon: '🚚' },
  { id: 'government', name: 'Government', icon: '🏛️' },
  { id: 'telecom', name: 'Telecommunications', icon: '📡' },
  { id: 'other', name: 'Other', icon: '📦' },
];

const priorities = [
  { id: 'critical', name: 'Critical', desc: 'Production system, immediate migration needed', color: 'text-red-400 bg-red-500/15' },
  { id: 'high', name: 'High', desc: 'Important system, migration within 3 months', color: 'text-amber-400 bg-amber-500/15' },
  { id: 'medium', name: 'Medium', desc: 'Standard migration timeline', color: 'text-blue-400 bg-blue-500/15' },
  { id: 'low', name: 'Low', desc: 'Exploratory migration, flexible timeline', color: 'text-muted bg-surface-light' },
];

const ciCDPlatforms = [
  { id: 'github', name: 'GitHub Actions', icon: '🐙' },
  { id: 'gitlab', name: 'GitLab CI/CD', icon: '🦊' },
  { id: 'jenkins', name: 'Jenkins', icon: '🔧' },
  { id: 'azure', name: 'Azure DevOps', icon: '🔷' },
  { id: 'circle', name: 'CircleCI', icon: '⭕' },
  { id: 'none', name: 'None / Manual', icon: '📋' },
];

const complianceStandards = [
  { id: 'gdpr', name: 'GDPR', desc: 'General Data Protection Regulation' },
  { id: 'sox', name: 'SOX', desc: 'Sarbanes-Oxley Act' },
  { id: 'pci', name: 'PCI DSS', desc: 'Payment Card Industry Data Security Standard' },
  { id: 'hipaa', name: 'HIPAA', desc: 'Health Insurance Portability and Accountability Act' },
  { id: 'iso27001', name: 'ISO 27001', desc: 'Information Security Management' },
  { id: 'none', name: 'None', desc: 'No specific compliance requirements' },
];

const LANG_TEST_FRAMEWORKS: Record<string, string[]> = {
  javascript: ['Jest', 'Vitest', 'Mocha', 'Jasmine', 'AVA'],
  typescript: ['Jest', 'Vitest', 'Mocha', 'Jasmine', 'AVA'],
  node: ['Jest', 'Vitest', 'Mocha', 'Jasmine', 'AVA', 'tap'],
  coffeescript: ['Jest', 'Mocha'],
  java: ['JUnit 5', 'TestNG', 'Mockito', 'AssertJ', 'Spock'],
  java_legacy: ['JUnit 4', 'TestNG', 'Mockito', 'JUnit 3'],
  kotlin: ['JUnit 5', 'Kotest', 'MockK', 'Spek'],
  scala: ['ScalaTest', 'Specs2', 'MUnit', 'ZIO Test'],
  groovy: ['Spock', 'JUnit 5', 'Geb'],
  csharp: ['xUnit', 'NUnit', 'MSTest', 'FluentAssertions'],
  fsharp: ['xUnit', 'NUnit', 'Expecto', 'FsCheck'],
  dotnet_legacy: ['MSTest', 'NUnit', 'xUnit'],
  vbnet: ['MSTest', 'NUnit', 'xUnit'],
  python: ['pytest', 'unittest', 'nose2', 'Hypothesis'],
  ruby: ['RSpec', 'MiniTest', 'Cucumber'],
  php: ['PHPUnit', 'Pest', 'Codeception'],
  php_legacy: ['PHPUnit', 'SimpleTest'],
  go: ['go test', 'testify', 'Ginkgo/Gomega', 'GoConvey'],
  rust: ['cargo test', 'nextest', 'proptest'],
  swift: ['XCTest', 'Quick/Nimble', 'swift-testing'],
  dart: ['flutter_test', 'test', 'mockito'],
  elixir: ['ExUnit', 'StreamData', 'Wallaby'],
  clojure: ['clojure.test', 'Kaocha', 'Midje'],
  haskell: ['HSpec', 'QuickCheck', 'Tasty'],
  erlang: ['EUnit', 'Common Test', 'PropEr'],
  ocaml: ['OUnit', 'Alcotest', 'QCheck'],
  crystal: ['crystal spec', 'spectator'],
  nim: ['unittest', 'testament'],
  zig: ['std.testing'],
  elm: ['elm-test'],
  purescript: ['PureScript Spec', 'QuickCheck'],
  julia: ['Test.jl', 'ReTest.jl'],
  r: ['testthat', 'tinytest'],
  perl: ['Test::More', 'Test2', 'Test::Simple'],
  perl_legacy: ['Test::More', 'Test::Simple'],
  lua: ['busted', 'lunit'],
  c: ['CUnit', 'Unity', 'Check', 'cmocka', 'Google Test'],
  cpp: ['Google Test', 'Catch2', 'Boost.Test', 'doctest'],
  scheme: ['SRFI-64', 'Rackunit'],
  lisp: ['FiveAM', 'CLUNIT'],
  solidity: ['Hardhat', 'Foundry', 'Waffle'],
  move: ['aptos test', 'sui::test_utils'],
  powershell: ['Pester'],
  bash: ['bats-core', 'shunit2'],
  tcl: ['tcltest'],
  haxe: ['utest', 'buddy'],
  gleam: ['gleeunit'],
  vlang: ['vtest'],
  mojo: ['testing module'],
  ballerina: ['test module'],
  apex: ['Apex Test'],
};

function isTierAllowedLanguage(category: string, tier: 'starter' | 'professional' | 'enterprise') {
  if (category !== 'legacy') return true;
  return tier !== 'starter';
}

interface Props {
  onNavigate: (section: string, projectId?: string, options?: { settingsTab?: string; settingsProviderTab?: 'github' | 'gitlab' | 'azure' | 'bitbucket' }) => void;
  onProjectCreated?: () => void;
}

import { api } from '../lib/api';
import { matchWizardOption } from '../lib/wizard-detect-match';
import { SOURCE_EXTENSIONS, findManifestPaths } from '../lib/analyze-source';

export default function NewProjectWizardExpanded({ onNavigate, onProjectCreated }: Props) {
  const { user: sessionUser } = useSession();
  const capabilities = getPlanCapabilities(sessionUser?.tier);
  const sourceLanguageAllowed = (id: string) => {
    const lang = sourceLanguages.find((item) => item.id === id);
    return lang ? isTierAllowedLanguage(lang.category, capabilities.tier) : true;
  };
  const targetLanguageAllowed = (id: string) => {
    const lang = targetLanguages.find((item) => item.id === id);
    return lang ? isTierAllowedLanguage(lang.category, capabilities.tier) : true;
  };

  const [step, setStep] = useState(0);
  
  // Project Info
  const [projectName, setProjectName] = useState('');
  const [projectDesc, setProjectDesc] = useState('');
  const [selectedDomain, setSelectedDomain] = useState('');
  const [selectedPriority, setSelectedPriority] = useState('medium');
  const [deadline, setDeadline] = useState('');
  const [projectOwner, setProjectOwner] = useState('');
  const [businessUnit, setBusinessUnit] = useState('');
  const [projectCode, setProjectCode] = useState('');
  const [legacySystem, setLegacySystem] = useState('');
  const [targetSystem, setTargetSystem] = useState('');
  const [estimatedLOC, setEstimatedLOC] = useState('');
  const [riskLevel, setRiskLevel] = useState('medium');
  const [technicalContact, setTechnicalContact] = useState('');
  const [businessContact, setBusinessContact] = useState('');
  const [stakeholders, setStakeholders] = useState('');
  
  // Languages
  const [selectedSource, setSelectedSource] = useState('');
  const [sourceVersion, setSourceVersion] = useState('');
  const [sourceDialect, setSourceDialect] = useState('');
  const [sourceFramework, setSourceFramework] = useState('');
  const [sourceSearch, setSourceSearch] = useState('');
  const [sourceCategoryFilter, setSourceCategoryFilter] = useState<'all' | 'legacy' | 'modern'>('all');
  const [selectedTarget, setSelectedTarget] = useState('');
  const [targetVersion, setTargetVersion] = useState('');

  const availablePackageManagers = useMemo(() => {
    const lang = targetLanguages.find(l => l.id === selectedTarget) as (typeof targetLanguages[0] & { build?: string[] }) | undefined;
    const build = lang?.build;
    return (build && build.length > 0) ? build : ['None / Not applicable'];
  }, [selectedTarget]);

  const availableTestFrameworks = useMemo(() => {
    return LANG_TEST_FRAMEWORKS[selectedTarget] ?? ['None / Not applicable'];
  }, [selectedTarget]);

  const availableErrorOptions = useMemo(() => errorOptions(selectedTarget), [selectedTarget]);
  const [targetBuild, setTargetBuild] = useState('');
  const [targetSearch, setTargetSearch] = useState('');
  const [targetCategoryFilter, setTargetCategoryFilter] = useState<'all' | 'legacy' | 'modern'>('all');
  
  // Repository
  const [selectedProvider, setSelectedProvider] = useState('GitHub');
  const [repoUrl, setRepoUrl] = useState('');
  const [branch, setBranch] = useState('main');
  const [authMethod, setAuthMethod] = useState('Personal Access Token');
  const [includePatterns, setIncludePatterns] = useState('');
  const [excludePatterns, setExcludePatterns] = useState('');
  const [encoding, setEncoding] = useState('UTF-8');
  const [branchStrategy, setBranchStrategy] = useState('main');

  // Local folder source (no Git repo)
  const [localFolderFiles, setLocalFolderFiles] = useState<File[]>([]);
  const [localFolderLabel, setLocalFolderLabel] = useState('');
  const localFolderInputRef = useRef<HTMLInputElement>(null);

  const isLocalFolderSource = selectedProvider === 'Local folder';
  const hasLocalFolder = localFolderFiles.length > 0;
  const [ghTab, setGhTab] = useState<'browse' | 'manual'>('browse');
  const [ghConnected, setGhConnected] = useState(false);
  const [ghUser, setGhUser] = useState('');
  const [ghOrgs, setGhOrgs] = useState<{ login: string; avatarUrl: string }[]>([]);
  const [ghSelectedOwner, setGhSelectedOwner] = useState('');
  const [ghRepos, setGhRepos] = useState<{
    id: number; name: string; fullName: string; description: string | null;
    private: boolean; language: string | null; defaultBranch: string; htmlUrl: string; updatedAt: string;
  }[]>([]);
  const [ghLoading, setGhLoading] = useState(false);
  const [ghSearch, setGhSearch] = useState('');
  const [ghPage, setGhPage] = useState(1);
  const [ghHasMore, setGhHasMore] = useState(false);
  const [ghBranches, setGhBranches] = useState<string[]>([]);
  const [ghBranchesLoading, setGhBranchesLoading] = useState(false);
  const [ghBranchSearch, setGhBranchSearch] = useState('');
  const [ghBranchOpen, setGhBranchOpen] = useState(false);

  // GitLab repo picker
  const [glTab, setGlTab] = useState<'browse' | 'manual'>('browse');
  const [glConnected, setGlConnected] = useState(false);
  const [glUser, setGlUser] = useState('');
  const [glGroups, setGlGroups] = useState<{ id: number; name: string; fullPath: string }[]>([]);
  const [glSelectedOwner, setGlSelectedOwner] = useState('');
  const [glRepos, setGlRepos] = useState<{
    id: number; name: string; pathWithNamespace: string; description: string | null;
    visibility: string; defaultBranch: string; webUrl: string; lastActivityAt: string;
  }[]>([]);
  const [glLoading, setGlLoading] = useState(false);
  const [glSearch, setGlSearch] = useState('');
  const [glHasMore, setGlHasMore] = useState(false);
  const [glBranches, setGlBranches] = useState<string[]>([]);
  const [glBranchesLoading, setGlBranchesLoading] = useState(false);
  const [glBranchSearch, setGlBranchSearch] = useState('');
  const [glBranchOpen, setGlBranchOpen] = useState(false);
  const [glSelectedRepoPath, setGlSelectedRepoPath] = useState('');

  // Azure DevOps repo picker
  const [azTab, setAzTab] = useState<'browse' | 'manual'>('browse');
  const [azConnected, setAzConnected] = useState(false);
  const [azOrgs, setAzOrgs] = useState<{ login: string }[]>([]);
  const [azSelectedOrg, setAzSelectedOrg] = useState('');
  const [azRepos, setAzRepos] = useState<{
    id: string; name: string; project: string; org: string;
    defaultBranch: string; webUrl: string;
  }[]>([]);
  const [azLoading, setAzLoading] = useState(false);
  const [azSearch, setAzSearch] = useState('');
  const [azBranches, setAzBranches] = useState<string[]>([]);
  const [azBranchesLoading, setAzBranchesLoading] = useState(false);
  const [azBranchSearch, setAzBranchSearch] = useState('');
  const [azBranchOpen, setAzBranchOpen] = useState(false);
  const [azSelectedRepoMeta, setAzSelectedRepoMeta] = useState<{ org: string; project: string; repoId: string } | null>(null);

  // Bitbucket repo picker
  const [bbTab, setBbTab] = useState<'browse' | 'manual'>('browse');
  const [bbConnected, setBbConnected] = useState(false);
  const [bbUser, setBbUser] = useState('');
  const [bbWorkspaces, setBbWorkspaces] = useState<{ slug: string; name: string }[]>([]);
  const [bbSelectedOwner, setBbSelectedOwner] = useState('');
  const [bbRepos, setBbRepos] = useState<{
    slug: string; name: string; workspace: string; description: string | null;
    isPrivate: boolean; language: string | null; mainBranch: string; htmlUrl: string; updatedOn: string;
  }[]>([]);
  const [bbLoading, setBbLoading] = useState(false);
  const [bbSearch, setBbSearch] = useState('');
  const [bbHasMore, setBbHasMore] = useState(false);
  const [bbBranches, setBbBranches] = useState<string[]>([]);
  const [bbBranchesLoading, setBbBranchesLoading] = useState(false);
  const [bbBranchSearch, setBbBranchSearch] = useState('');
  const [bbBranchOpen, setBbBranchOpen] = useState(false);
  const [bbSelectedRepoMeta, setBbSelectedRepoMeta] = useState<{ workspace: string; slug: string } | null>(null);

  // Language auto-detection
  const [detectingLang, setDetectingLang] = useState(false);
  const [detectedBreakdown, setDetectedBreakdown] = useState<{ name: string; scribaId: string | null; percent: number }[]>([]);
  const [detectedApplied, setDetectedApplied] = useState(false);

  // Multi-language source selection
  const [selectedSourceExtras, setSelectedSourceExtras] = useState<string[]>([]);

  const handleSourceClick = (id: string) => {
    if (id === selectedSource) {
      if (selectedSourceExtras.length === 0) { setSelectedSource(''); setSourceVersion(''); }
      else { setSelectedSource(selectedSourceExtras[0]); setSourceVersion(''); setSelectedSourceExtras(prev => prev.slice(1)); }
    } else if (selectedSourceExtras.includes(id)) {
      setSelectedSourceExtras(prev => prev.filter(x => x !== id));
    } else {
      if (!selectedSource) {
        setSelectedSource(id);
        setSourceVersion('');
        setSourceDialect('');
        setSourceFramework('');
      } else if (selectedSourceExtras.length === 0) {
        // Replace the primary language (single-selection mode) and reset version/dialect
        setSelectedSource(id);
        setSourceVersion('');
        setSourceDialect('');
        setSourceFramework('');
      } else {
        setSelectedSourceExtras(prev => [...prev, id]);
      }
    }
  };

  const promoteSourceToPrimary = (id: string) => {
    setSelectedSourceExtras(prev => [selectedSource, ...prev.filter(x => x !== id)]);
    setSelectedSource(id);
    setSourceVersion('');
    setSourceFramework('');
  };

  // Target Config
  const [namingConvention, setNamingConvention] = useState('camelCase');
  const [intent, setIntent] = useState('');
  const [architecturePattern, setArchitecturePattern] = useState('layered');
  const [packageManager, setPackageManager] = useState('npm');
  const [addTests, setAddTests] = useState(true);
  const [addDocs, setAddDocs] = useState(true);
  const [addLinter, setAddLinter] = useState(true);
  const [addFormatter, setAddFormatter] = useState(true);
  const [addTypeScript, setAddTypeScript] = useState(false);
  const [addDocker, setAddDocker] = useState(false);
  const [addKubernetes, setAddKubernetes] = useState(false);
  const [addCI, setAddCI] = useState(false);
  const [testingFramework, setTestingFramework] = useState('jest');
  const [apiFramework, setApiFramework] = useState('express');
  const [apiGatewayAuth, setApiGatewayAuth] = useState('jwt');
  const [enableOpenAPISpec, setEnableOpenAPISpec] = useState(true);
  
  // Translation Settings
  const [maxIterations, setMaxIterations] = useState(3);
  /** Engine hard quality gate: 0 = off, 1–3 thresholds (see engine Q1-GATE). */
  const [qualityLevel, setQualityLevel] = useState(0);
  /** Project profile: engine shape hint (auto = detect from source). FE-WIZ-2 */
  const [projectProfile, setProjectProfile] = useState<'auto' | 'batch' | 'online' | 'library' | 'utility' | 'mixed'>('auto');
  /** Multi-stage translator (Structure → Bodies → Polish). Off via wizard or SCRIBA_STAGES=0 on engine. */
  const [useStages, setUseStages] = useState(true);
  /** Opt-in surgical repair loop; only shown when NEXT_PUBLIC_SCRIBA_ENGINE_REPAIR is set. */
  const [useRepair, setUseRepair] = useState(true);

  // Pipeline modules — IDs of enabled post-translation stages. All on by default.
  const [enabledPlugins, setEnabledPlugins] = useState<string[]>(
    () => PIPELINE_PLUGINS.map(p => p.id),
  );
  const [preserveComments, setPreserveComments] = useState(true);
  const [customRules, setCustomRules] = useState('');
  const [errorHandling, setErrorHandling] = useState('preserve');
  const [preserveApiSignatures, setPreserveApiSignatures] = useState(true);
  
  // Team
  const [selectedTeam, setSelectedTeam] = useState<string[]>([]);
  const [teamRoles, setTeamRoles] = useState<Record<string, string>>({});
  const [teamModalOpen, setTeamModalOpen] = useState(false);
  const [teamModalName, setTeamModalName] = useState('');
  const [teamModalError, setTeamModalError] = useState('');
  
  // Deployment
  const [enableDeploymentConfig, setEnableDeploymentConfig] = useState(false);
  const [selectedCI, setSelectedCI] = useState('github');
  const [enableAutoDeploy, setEnableAutoDeploy] = useState(false);
  const [deployEnvironment, setDeployEnvironment] = useState('staging');
  const [infrastructure, setInfrastructure] = useState('kubernetes');
  const [enableRollback, setEnableRollback] = useState(true);
  const [enableHealthChecks, setEnableHealthChecks] = useState(true);
  const [buildTool, setBuildTool] = useState('npm');
  const [cacheStrategy, setCacheStrategy] = useState('aggressive');
  const [enableBuildTests, setEnableBuildTests] = useState(true);
  const [enableLinting, setEnableLinting] = useState(true);
  const [enableMinification, setEnableMinification] = useState(true);
  
  // Notifications
  const [notifyOnComplete, setNotifyOnComplete] = useState(true);
  const [notifyOnWarning, setNotifyOnWarning] = useState(true);
  const [notifyOnFailure, setNotifyOnFailure] = useState(true);
  const [notifyChannels, setNotifyChannels] = useState<string[]>(['email']);
  
  // Compliance
  const [selectedCompliance, setSelectedCompliance] = useState<string[]>([]);
  const [enableSecurityScan, setEnableSecurityScan] = useState(true);
  const [dataRetention, setDataRetention] = useState('90');

  // Environment Configuration (optional)
  const [enableEnvironmentConfig, setEnableEnvironmentConfig] = useState(false);
  const [serverConfig, setServerConfig] = useState({
    cpu: '2',
    memory: '4',
    storage: '20',
    os: 'ubuntu-22.04',
    region: 'eu-west-1'
  });
  const [sshKey, setSshKey] = useState('');
  const [sshKeyFileName, setSshKeyFileName] = useState('');
  const [configFeedback, setConfigFeedback] = useState<'optimal' | 'adequate' | 'insufficient' | 'overprovisioned' | null>(null);

  // Evaluate server configuration and provide feedback
  const evaluateServerConfig = () => {
    const cpu = parseInt(serverConfig.cpu);
    const memory = parseInt(serverConfig.memory);
    
    // Simple logic to evaluate configuration
    if (cpu < 2 || memory < 4) {
      setConfigFeedback('insufficient');
    } else if (cpu > 16 || memory > 64) {
      setConfigFeedback('overprovisioned');
    } else if (cpu >= 4 && memory >= 8) {
      setConfigFeedback('optimal');
    } else {
      setConfigFeedback('adequate');
    }
  };

  // Database configuration
  const [enableDatabaseConfig, setEnableDatabaseConfig] = useState(false);
  const [sourceDatabase, setSourceDatabase] = useState('');
  const [sourceDbVersion, setSourceDbVersion] = useState('');
  const [schemaFile, setSchemaFile] = useState<File | null>(null);
  const [schemaFileName, setSchemaFileName] = useState('');
  const [selectedDatabase, setSelectedDatabase] = useState('postgresql');
  const [dbVersion, setDbVersion] = useState('15');
  const [dbInstanceSize, setDbInstanceSize] = useState('medium');
  const [dbStorage, setDbStorage] = useState('100');
  const [enableReadReplica, setEnableReadReplica] = useState(true);
  const [enableBackup, setEnableBackup] = useState(true);
  const [enableEncryption, setEnableEncryption] = useState(true);
  const [enableConnectionPool, setEnableConnectionPool] = useState(true);
  const [migrationStrategy, setMigrationStrategy] = useState('full');
  const [preserveData, setPreserveData] = useState(true);
  const [preserveIndexes, setPreserveIndexes] = useState(true);

  // API & Services configuration
  const [enableApiGateway, setEnableApiGateway] = useState(true);
  const [apiGatewayType, setApiGatewayType] = useState('rest');
  const [enableGraphQL, setEnableGraphQL] = useState(false);
  const [enableServiceMesh, setEnableServiceMesh] = useState(false);

  // Monitoring configuration
  const [enablePrometheus, setEnablePrometheus] = useState(true);
  const [enableGrafana, setEnableGrafana] = useState(true);
  const [enableJaeger, setEnableJaeger] = useState(true);
  const [enableELK, setEnableELK] = useState(true);
  const [alertThreshold, setAlertThreshold] = useState('90');

  // Backup configuration
  const [backupFrequency, setBackupFrequency] = useState('daily');
  const [backupRetention, setBackupRetention] = useState('30');
  const [enableDisasterRecovery, setEnableDisasterRecovery] = useState(false);
  const [drRegion, setDrRegion] = useState('us-west-2');

  // Advanced security configuration
  const [encryptionType, setEncryptionType] = useState('aes256');
  const [enableSecretsManager, setEnableSecretsManager] = useState(true);
  const [secretsProvider, setSecretsProvider] = useState('aws');
  const [enableVulnerabilityScan, setEnableVulnerabilityScan] = useState(true);
  const [enableDependencyScan, setEnableDependencyScan] = useState(true);
  const [enableSAST, setEnableSAST] = useState(true);
  const [enableDAST, setEnableDAST] = useState(false);
  const [enableContainerScan, setEnableContainerScan] = useState(true);
  const [enableIAM, setEnableIAM] = useState(true);
  const [iamPolicy, setIamPolicy] = useState('least-privilege');

  // General
  const [tags, setTags] = useState('');
  const [connecting, setConnecting] = useState(false);
  const [connected, setConnected] = useState(false);
  const [creating, setCreating] = useState(false);
  const [createError, setCreateError] = useState<string | null>(null);

  const steps = [
    { label: 'Conversion Info', desc: 'Basic conversion information' },
    { label: 'Repository', desc: 'Source code connection' },
    { label: 'Source Language', desc: 'Select source language' },
    { label: 'Target Language', desc: 'Select target language' },
    { label: 'Target Config', desc: 'Target framework settings' },
    { label: 'Translation', desc: 'Translation engine options' },
    { label: 'Environment', desc: 'Server configuration (optional)' },
    { label: 'Database', desc: 'Database config (optional)' },
    { label: 'API Layer', desc: 'Generated API interface' },
    { label: 'Monitoring', desc: 'Observability config files' },
    { label: 'Team', desc: 'Team and permissions' },
    { label: 'Deployment', desc: 'CI/CD pipeline & infra' },
    { label: 'Notifications', desc: 'Alert preferences' },
    { label: 'Compliance', desc: 'Security & compliance' },
    { label: 'Modules', desc: 'Pipeline stage selection' },
    { label: 'Review', desc: 'Confirm and create' },
  ];

  // Steps hidden from UI but kept intact (config state is still saved)
  const HIDDEN_STEPS = new Set([6, 7, 8, 9, 11, 12]);
  const visibleSteps = steps.map((s, i) => ({ ...s, originalIndex: i })).filter(s => !HIDDEN_STEPS.has(s.originalIndex));

  const nextStep = (current: number) => {
    let n = current + 1;
    while (HIDDEN_STEPS.has(n) && n < steps.length - 1) n++;
    return n;
  };
  const prevStep = (current: number) => {
    let p = current - 1;
    while (HIDDEN_STEPS.has(p) && p > 0) p--;
    return p;
  };

  const canNext = () => {
    if (step === 0) return projectName.length > 0 && selectedDomain;
    if (step === 1) return isLocalFolderSource ? hasLocalFolder : connected;
    if (step === 2) return selectedSource && sourceVersion;
    if (step === 3) return selectedTarget && targetVersion;
    return true;
  };

  const stepBlockers = (): string[] => {
    if (step === 0) {
      const msgs: string[] = [];
      if (!projectName.trim()) msgs.push('Project name is required');
      if (!selectedDomain) msgs.push('Select an industry domain');
      return msgs;
    }
    if (step === 1) {
      if (isLocalFolderSource) {
        return hasLocalFolder ? [] : ['Select a project folder to continue'];
      }
      return connected ? [] : ['Connect a repository to continue — click a repo in the list or use Local folder'];
    }
    if (step === 2) {
      if (!selectedSource) return ['Select a source language'];
      if (!sourceVersion) return [`Select a version for ${sourceLanguages.find(l => l.id === selectedSource)?.name ?? 'the selected language'}`];
      return [];
    }
    if (step === 3) {
      if (!selectedTarget) return ['Select a target language'];
      if (!targetVersion) return [`Select a version for ${targetLanguages.find(l => l.id === selectedTarget)?.name ?? 'the selected language'}`];
      return [];
    }
    return [];
  };

  // Load GitHub status + orgs when arriving at step 1
  useEffect(() => {
    if (step !== 1 || selectedProvider !== 'GitHub') return;
    let cancelled = false;
    (async () => {
      const [statusRes, orgsRes] = await Promise.all([
        fetch('/api/github/status').catch(() => null),
        fetch('/api/github/orgs').catch(() => null),
      ]);
      if (cancelled) return;
      if (statusRes?.ok) {
        const s = await statusRes.json();
        if (s.connected) {
          setGhConnected(true);
          setGhUser(s.login ?? '');
          setGhSelectedOwner(prev => prev || (s.login ?? ''));
        } else {
          setGhConnected(false);
        }
      }
      if (orgsRes?.ok) {
        const o = await orgsRes.json();
        if (o.connected) setGhOrgs(o.orgs ?? []);
      }
    })();
    return () => { cancelled = true; };
  }, [step, selectedProvider]);

  // Load GitLab status + groups when provider selected
  useEffect(() => {
    if (step !== 1 || selectedProvider !== 'GitLab') return;
    let cancelled = false;
    (async () => {
      const [statusRes, groupsRes] = await Promise.all([
        fetch('/api/gitlab/status').catch(() => null),
        fetch('/api/gitlab/groups').catch(() => null),
      ]);
      if (cancelled) return;
      if (statusRes?.ok) {
        const s = await statusRes.json();
        if (s.connected) {
          setGlConnected(true);
          setGlUser(s.login ?? '');
          setGlSelectedOwner(prev => prev || (s.login ?? ''));
        } else { setGlConnected(false); }
      }
      if (groupsRes?.ok) {
        const g = await groupsRes.json();
        if (g.connected) setGlGroups(g.groups ?? []);
      }
    })();
    return () => { cancelled = true; };
  }, [step, selectedProvider]);

  // Load Azure DevOps status + orgs when provider selected
  useEffect(() => {
    if (step !== 1 || selectedProvider !== 'Azure DevOps') return;
    let cancelled = false;
    (async () => {
      const [statusRes, orgsRes] = await Promise.all([
        fetch('/api/azure/status').catch(() => null),
        fetch('/api/azure/orgs').catch(() => null),
      ]);
      if (cancelled) return;
      if (statusRes?.ok) {
        const s = await statusRes.json();
        setAzConnected(!!s.connected);
      }
      if (orgsRes?.ok) {
        const o = await orgsRes.json();
        if (o.connected) {
          setAzOrgs(o.orgs ?? []);
          setAzSelectedOrg(prev => prev || (o.orgs?.[0]?.login ?? ''));
        }
      }
    })();
    return () => { cancelled = true; };
  }, [step, selectedProvider]);

  // Load Bitbucket status + workspaces when provider selected
  useEffect(() => {
    if (step !== 1 || selectedProvider !== 'Bitbucket') return;
    let cancelled = false;
    (async () => {
      const [statusRes, wsRes] = await Promise.all([
        fetch('/api/bitbucket/status').catch(() => null),
        fetch('/api/bitbucket/workspaces').catch(() => null),
      ]);
      if (cancelled) return;
      if (statusRes?.ok) {
        const s = await statusRes.json();
        if (s.connected) {
          setBbConnected(true);
          setBbUser(s.login ?? '');
          setBbSelectedOwner(prev => prev || (s.login ?? ''));
        } else { setBbConnected(false); }
      }
      if (wsRes?.ok) {
        const w = await wsRes.json();
        if (w.connected) {
          setBbWorkspaces(w.workspaces ?? []);
          setBbSelectedOwner(prev => prev || (w.workspaces?.[0]?.slug ?? ''));
        }
      }
    })();
    return () => { cancelled = true; };
  }, [step, selectedProvider]);

  // Reset package manager / testing framework when target language changes
  useEffect(() => {
    if (!availablePackageManagers.includes(packageManager)) {
      setPackageManager(availablePackageManagers[0]);
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [availablePackageManagers]);

  useEffect(() => {
    if (!availableTestFrameworks.includes(testingFramework)) {
      setTestingFramework(availableTestFrameworks[0]);
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [availableTestFrameworks]);

  useEffect(() => {
    if (!availableErrorOptions.some(o => o.value === errorHandling)) {
      setErrorHandling('preserve');
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [availableErrorOptions]);

  // Debounced repo fetch — GitHub
  const searchTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
  useEffect(() => {
    if (!ghConnected || !ghSelectedOwner) return;
    if (searchTimer.current) clearTimeout(searchTimer.current);
    searchTimer.current = setTimeout(async () => {
      setGhLoading(true);
      setGhPage(1);
      const params = new URLSearchParams({ page: '1' });
      if (ghSearch) params.set('q', ghSearch);
      if (ghSelectedOwner !== ghUser) params.set('org', ghSelectedOwner);
      const res = await fetch(`/api/github/repos?${params}`).catch(() => null);
      if (res?.ok) {
        const data = await res.json();
        setGhRepos(data.repos ?? []);
        setGhHasMore((data.repos?.length ?? 0) === 50);
      }
      setGhLoading(false);
    }, ghSearch ? 400 : 0);
    return () => { if (searchTimer.current) clearTimeout(searchTimer.current); };
  }, [ghConnected, ghSelectedOwner, ghSearch, ghUser]);

  // Debounced repo fetch — GitLab
  const glSearchTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
  useEffect(() => {
    if (!glConnected) return;
    if (glSearchTimer.current) clearTimeout(glSearchTimer.current);
    glSearchTimer.current = setTimeout(async () => {
      setGlLoading(true);
      const params = new URLSearchParams();
      if (glSearch) params.set('q', glSearch);
      if (glSelectedOwner && glSelectedOwner !== glUser) params.set('group', glSelectedOwner);
      const res = await fetch(`/api/gitlab/repos?${params}`).catch(() => null);
      if (res?.ok) {
        const data = await res.json();
        setGlRepos(data.repos ?? []);
        setGlHasMore((data.repos?.length ?? 0) === 50);
      }
      setGlLoading(false);
    }, glSearch ? 400 : 0);
    return () => { if (glSearchTimer.current) clearTimeout(glSearchTimer.current); };
  }, [glConnected, glSelectedOwner, glSearch, glUser]);

  // Debounced repo fetch — Azure DevOps
  const azSearchTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
  useEffect(() => {
    if (!azConnected || !azSelectedOrg) return;
    if (azSearchTimer.current) clearTimeout(azSearchTimer.current);
    azSearchTimer.current = setTimeout(async () => {
      setAzLoading(true);
      const params = new URLSearchParams({ org: azSelectedOrg });
      if (azSearch) params.set('q', azSearch);
      const res = await fetch(`/api/azure/repos?${params}`).catch(() => null);
      if (res?.ok) {
        const data = await res.json();
        setAzRepos(data.repos ?? []);
      }
      setAzLoading(false);
    }, azSearch ? 400 : 0);
    return () => { if (azSearchTimer.current) clearTimeout(azSearchTimer.current); };
  }, [azConnected, azSelectedOrg, azSearch]);

  // Debounced repo fetch — Bitbucket
  const bbSearchTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
  useEffect(() => {
    if (!bbConnected || !bbSelectedOwner) return;
    if (bbSearchTimer.current) clearTimeout(bbSearchTimer.current);
    bbSearchTimer.current = setTimeout(async () => {
      setBbLoading(true);
      const params = new URLSearchParams({ workspace: bbSelectedOwner });
      if (bbSearch) params.set('q', bbSearch);
      const res = await fetch(`/api/bitbucket/repos?${params}`).catch(() => null);
      if (res?.ok) {
        const data = await res.json();
        setBbRepos(data.repos ?? []);
        setBbHasMore((data.repos?.length ?? 0) === 50);
      }
      setBbLoading(false);
    }, bbSearch ? 400 : 0);
    return () => { if (bbSearchTimer.current) clearTimeout(bbSearchTimer.current); };
  }, [bbConnected, bbSelectedOwner, bbSearch]);

  // Fetch real branches when a GitHub repo is selected
  useEffect(() => {
    if (!ghConnected || !repoUrl) { setGhBranches([]); return; }
    const match = repoUrl.match(/github\.com\/([^/]+)\/([^/\s]+?)(?:\.git)?\s*$/);
    if (!match) { setGhBranches([]); return; }
    const [, owner, repo] = match;
    setGhBranchesLoading(true);
    fetch(`/api/github/branches?owner=${encodeURIComponent(owner)}&repo=${encodeURIComponent(repo)}`)
      .then(r => r.ok ? r.json() : { branches: [] })
      .then(data => { setGhBranches(data.branches ?? []); setGhBranchesLoading(false); })
      .catch(() => setGhBranchesLoading(false));
  }, [repoUrl, ghConnected]);

  // Fetch branches when a GitLab repo is selected
  useEffect(() => {
    if (!glConnected || !glSelectedRepoPath) { setGlBranches([]); return; }
    setGlBranchesLoading(true);
    fetch(`/api/gitlab/branches?projectPath=${encodeURIComponent(glSelectedRepoPath)}`)
      .then(r => r.ok ? r.json() : { branches: [] })
      .then(data => { setGlBranches(data.branches ?? []); setGlBranchesLoading(false); })
      .catch(() => setGlBranchesLoading(false));
  }, [glSelectedRepoPath, glConnected]);

  // Fetch branches when an Azure DevOps repo is selected
  useEffect(() => {
    if (!azConnected || !azSelectedRepoMeta) { setAzBranches([]); return; }
    setAzBranchesLoading(true);
    const { org, project, repoId } = azSelectedRepoMeta;
    fetch(`/api/azure/branches?org=${encodeURIComponent(org)}&project=${encodeURIComponent(project)}&repoId=${encodeURIComponent(repoId)}`)
      .then(r => r.ok ? r.json() : { branches: [] })
      .then(data => { setAzBranches(data.branches ?? []); setAzBranchesLoading(false); })
      .catch(() => setAzBranchesLoading(false));
  }, [azSelectedRepoMeta, azConnected]);

  // Fetch branches when a Bitbucket repo is selected
  useEffect(() => {
    if (!bbConnected || !bbSelectedRepoMeta) { setBbBranches([]); return; }
    setBbBranchesLoading(true);
    const { workspace, slug } = bbSelectedRepoMeta;
    fetch(`/api/bitbucket/branches?workspace=${encodeURIComponent(workspace)}&repo=${encodeURIComponent(slug)}`)
      .then(r => r.ok ? r.json() : { branches: [] })
      .then(data => { setBbBranches(data.branches ?? []); setBbBranchesLoading(false); })
      .catch(() => setBbBranchesLoading(false));
  }, [bbSelectedRepoMeta, bbConnected]);

  const handleConnect = () => {
    setConnecting(true);
    setTimeout(() => {
      setConnecting(false);
      setConnected(true);
    }, 3000);
  };

  const handleLocalFolderSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
    const files = Array.from(e.target.files ?? []);
    if (!files.length) return;
    setLocalFolderFiles(files);
    const rootName = files[0]?.webkitRelativePath?.split('/')[0] ?? 'Selected folder';
    setLocalFolderLabel(rootName);
    setRepoUrl('');
    setConnected(false);
  };

  const clearLocalFolder = () => {
    setLocalFolderFiles([]);
    setLocalFolderLabel('');
    if (localFolderInputRef.current) localFolderInputRef.current.value = '';
  };

  const handleCreate = async () => {
    setCreating(true);
    setCreateError(null);
    
    // Generate a unique project ID
    const newProjectId = `proj-${Date.now().toString(36).slice(-4)}`;
    
    // Look up language names from IDs
    const sourceLang = sourceLanguages.find(l => l.id === selectedSource);
    const targetLang = targetLanguages.find(l => l.id === selectedTarget);
    const sourceId = (selectedSource || sourceLang?.id || '').trim();
    const targetId = (selectedTarget || targetLang?.id || '').trim();
    if (!sourceId || !targetId) {
      setCreateError('Select both a source language and a target language before creating the project.');
      setCreating(false);
      return;
    }
    
    try {
      // Create project in database with status 'analyzing' + full wizard config
      await api.createProject({
        id: newProjectId,
        name: projectName || 'New Conversion',
        description: projectDesc || `${sourceLang?.name ?? sourceId} to ${targetLang?.name ?? targetId} migration`,
        sourceLanguage: sourceId,
        targetLanguage: targetId,
        repoUrl: isLocalFolderSource ? undefined : (repoUrl || undefined),
        tags: selectedDomain ? [selectedDomain] : ['migration'],
        team: selectedTeam.map(name => ({ name, role: 'Team Member', avatar: name.slice(0, 2).toUpperCase() })),
        status: 'analyzing',
        config: {
          // Project info
          selectedPriority, deadline, riskLevel,
          projectOwner, businessUnit, projectCode, legacySystem, targetSystem,
          estimatedLOC, technicalContact, businessContact, stakeholders,
          // Repository
          selectedProvider, branch, branchStrategy, authMethod, encoding,
          includePatterns, excludePatterns,
          ...(isLocalFolderSource ? { sourceMode: 'local', localFolderLabel } : {}),
          // Source language
          sourceVersion, sourceDialect, sourceFramework,
          additionalSourceLanguages: selectedSourceExtras,
          // Target language
          targetVersion, targetBuild,
          // Target config
          namingConvention, intent, architecturePattern,
          packageManager, testingFramework, apiFramework,
          addTests, addDocs, addLinter, addFormatter, addTypeScript,
          addDocker, addKubernetes, addCI,
          // Translation
          preserveComments, preserveApiSignatures, errorHandling,
          customRules, maxIterations, qualityLevel, useStages, useRepair, projectProfile,
          // Database
          enableDatabaseConfig, sourceDatabase, sourceDbVersion, schemaFileName,
          selectedDatabase, dbVersion, dbInstanceSize, dbStorage,
          enableReadReplica, enableBackup, enableEncryption, enableConnectionPool,
          migrationStrategy, preserveData, preserveIndexes,
          // API
          enableApiGateway, apiGatewayType, apiGatewayAuth,
          enableGraphQL, enableOpenAPISpec, enableServiceMesh,
          // Monitoring
          enablePrometheus, enableGrafana, enableJaeger, enableELK, alertThreshold,
          // Backup
          backupFrequency, backupRetention, enableDisasterRecovery, drRegion,
          // Deployment
          enableDeploymentConfig, selectedCI, infrastructure, deployEnvironment,
          enableAutoDeploy, enableRollback, enableHealthChecks,
          buildTool, cacheStrategy, enableBuildTests, enableLinting, enableMinification,
          // Security / Compliance
          selectedCompliance, enableSecurityScan, dataRetention,
          encryptionType, enableSecretsManager, secretsProvider,
          enableVulnerabilityScan, enableDependencyScan, enableSAST, enableDAST,
          enableContainerScan, enableIAM, iamPolicy,
          // Notifications
          notifyOnComplete, notifyOnWarning, notifyOnFailure, notifyChannels,
          // Team
          selectedTeam: selectedTeam.map(name => ({ name, role: teamRoles[name] || 'Team Member' })),
          // Pipeline modules
          enabledPlugins,
          // Environment
          enableEnvironmentConfig, serverConfig, sshKey,
        },
      });

      if (isLocalFolderSource && localFolderFiles.length > 0) {
        const prep = await api.engine.uploadBundle(localFolderFiles);
        await api.updateProject(newProjectId, {
          config: {
            uploadId: prep.uploadId,
            uploadMeta: {
              fileCount: prep.fileCount,
              totalBytes: prep.totalBytes,
              preparedAt: new Date().toISOString(),
              source: 'browser',
              folderName: localFolderLabel,
            },
          },
        });
      }
      
      // Notify parent that project was created
      onProjectCreated?.();
      
      // Navigate to conversion overview after creation
      setTimeout(() => {
        onNavigate('conversion-dashboard', newProjectId);
      }, 1500);
    } catch (error) {
      console.error('Failed to create project:', error);
      setCreateError(error instanceof Error ? error.message : 'Failed to create project. Please try again.');
      setCreating(false);
    }
  };

  const toggleTeam = (name: string) => {
    setSelectedTeam(prev =>
      prev.includes(name) ? prev.filter(n => n !== name) : [...prev, name]
    );
  };

  const openAddTeamModal = () => {
    setTeamModalName('');
    setTeamModalError('');
    setTeamModalOpen(true);
  };

  const closeAddTeamModal = () => {
    setTeamModalOpen(false);
    setTeamModalName('');
    setTeamModalError('');
  };

  const confirmAddTeamMember = () => {
    const name = teamModalName.trim();
    if (!name) {
      setTeamModalError('Please enter a name.');
      return;
    }
    if (selectedTeam.includes(name)) {
      setTeamModalError('That person is already listed.');
      return;
    }
    setSelectedTeam(prev => [...prev, name]);
    setTeamRoles(prev => ({ ...prev, [name]: prev[name] || 'viewer' }));
    closeAddTeamModal();
  };

  const toggleChannel = (channel: string) => {
    setNotifyChannels(prev =>
      prev.includes(channel) ? prev.filter(c => c !== channel) : [...prev, channel]
    );
  };

  const toggleCompliance = (standard: string) => {
    setSelectedCompliance(prev => {
      if (standard === 'none') {
        return prev.includes('none') ? [] : ['none'];
      }
      const withoutNone = prev.filter(s => s !== 'none');
      return withoutNone.includes(standard)
        ? withoutNone.filter(s => s !== standard)
        : [...withoutNone, standard];
    });
  };

  return (
    <>
    <div className="max-w-4xl mx-auto space-y-8">
      <motion.div initial={{ opacity: 0, y: -10 }} animate={{ opacity: 1, y: 0 }}>
        <h2 className="text-2xl font-bold text-foreground">New Conversion</h2>
        <p className="text-sm text-muted mt-1">Configure your migration conversion with comprehensive options</p>
      </motion.div>

      <div className="flex items-center gap-1 overflow-x-auto pb-2">
        {visibleSteps.map((s, i) => {
          const orig = s.originalIndex;
          const isCompleted = step > orig;
          const isActive = step === orig;
          return (
            <div key={orig} className="flex items-center gap-1 flex-shrink-0">
              <div className={`flex items-center gap-1.5 ${orig <= step ? '' : 'opacity-40'}`}>
                <div className={`w-6 h-6 rounded-full flex items-center justify-center text-[10px] font-bold flex-shrink-0 ${
                  isCompleted ? 'bg-success text-white' : isActive ? 'gradient-accent text-white' : 'bg-surface-light text-muted'
                }`}>
                  {isCompleted ? <Check className="w-3 h-3" /> : i + 1}
                </div>
                <div className="min-w-0 hidden md:block">
                  <p className="text-[11px] font-medium text-foreground truncate">{s.label}</p>
                </div>
              </div>
              {i < visibleSteps.length - 1 && <div className={`h-px w-4 ${isCompleted ? 'bg-success' : 'bg-border'}`} />}
            </div>
          );
        })}
      </div>

      <AnimatePresence mode="wait">
        <motion.div key={step} initial={{ opacity: 0, x: 20 }} animate={{ opacity: 1, x: 0 }} exit={{ opacity: 0, x: -20 }} className="glass rounded-xl p-6">
          {step === 0 && (
            <div className="space-y-5">
              <h3 className="text-base font-semibold text-foreground">Conversion Information</h3>
              <p className="text-xs text-muted -mt-3 mb-1">
                Connect the source repository in the next step (GitHub). This screen only sets conversion name, description, and domain.
              </p>
              <div>
                <label className="text-[11px] text-muted uppercase tracking-wider block mb-1.5">Conversion Name</label>
                <input
                  type="text"
                  value={projectName}
                  onChange={(e) => setProjectName(e.target.value)}
                  placeholder="Enter conversion name..."
                  className="w-full glass-light rounded-lg px-4 py-3 text-sm text-foreground outline-none border border-transparent focus:border-accent/30 transition-colors placeholder-muted"
                />
              </div>
              <div>
                <label className="text-[11px] text-muted uppercase tracking-wider block mb-1.5">Description</label>
                <textarea
                  value={projectDesc}
                  onChange={(e) => setProjectDesc(e.target.value)}
                  placeholder="Conversion description..."
                  rows={3}
                  className="w-full glass-light rounded-lg px-4 py-3 text-sm text-foreground outline-none border border-transparent focus:border-accent/30 transition-colors resize-none placeholder-muted"
                />
              </div>
              <div>
                <label className="text-[11px] text-muted uppercase tracking-wider block mb-2">Domain</label>
                <div className="grid grid-cols-3 gap-2">
                  {domains.map(d => (
                    <button
                      key={d.id}
                      onClick={() => setSelectedDomain(d.id)}
                      className={`p-3 rounded-lg border text-center transition-all cursor-pointer ${
                        selectedDomain === d.id
                          ? 'border-accent/50 bg-accent/10'
                          : 'border-border bg-surface hover:border-accent/30'
                      }`}
                    >
                      <span className="text-xl block mb-1">{d.icon}</span>
                      <p className="text-xs font-medium text-foreground">{d.name}</p>
                    </button>
                  ))}
                </div>
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="text-[11px] text-muted uppercase tracking-wider block mb-1.5">Priority</label>
                  <select
                    value={selectedPriority}
                    onChange={(e) => setSelectedPriority(e.target.value)}
                    className="w-full glass-light rounded-lg px-4 py-2.5 text-sm text-foreground outline-none border border-transparent focus:border-accent/30"
                  >
                    {priorities.map(p => (
                      <option key={p.id} value={p.id}>{p.name}</option>
                    ))}
                  </select>
                </div>
                <div>
                  <label className="text-[11px] text-muted uppercase tracking-wider block mb-1.5">Risk Level</label>
                  <select
                    value={riskLevel}
                    onChange={(e) => setRiskLevel(e.target.value)}
                    className="w-full glass-light rounded-lg px-4 py-2.5 text-sm text-foreground outline-none border border-transparent focus:border-accent/30"
                  >
                    <option value="low">Low</option>
                    <option value="medium">Medium</option>
                    <option value="high">High</option>
                    <option value="critical">Critical</option>
                  </select>
                </div>
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="text-[11px] text-muted uppercase tracking-wider block mb-1.5">Deadline</label>
                  <input
                    type="date"
                    value={deadline}
                    onChange={(e) => setDeadline(e.target.value)}
                    className="w-full glass-light rounded-lg px-4 py-2.5 text-sm text-foreground outline-none border border-transparent focus:border-accent/30"
                  />
                </div>
                <div>
                  <label className="text-[11px] text-muted uppercase tracking-wider block mb-1.5">Estimated LOC</label>
                  <input
                    type="text"
                    value={estimatedLOC}
                    onChange={(e) => setEstimatedLOC(e.target.value)}
                    placeholder="e.g., 500K"
                    className="w-full glass-light rounded-lg px-4 py-2.5 text-sm text-foreground outline-none border border-transparent focus:border-accent/30 placeholder-muted"
                  />
                </div>
              </div>

              <div className="border-t border-border pt-5 mt-5">
                <h4 className="text-sm font-semibold text-foreground mb-4 flex items-center gap-2">
                  <Building2 className="w-4 h-4 text-accent-light" /> Client Information
                </h4>
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <label className="text-[11px] text-muted uppercase tracking-wider block mb-1.5">Client Owner</label>
                    <input
                      type="text"
                      value={projectOwner}
                      onChange={(e) => setProjectOwner(e.target.value)}
                      placeholder="Client's owner"
                      className="w-full glass-light rounded-lg px-4 py-2.5 text-sm text-foreground outline-none border border-transparent focus:border-accent/30 placeholder-muted"
                    />
                  </div>
                  <div>
                    <label className="text-[11px] text-muted uppercase tracking-wider block mb-1.5">Client Business Unit</label>
                    <input
                      type="text"
                      value={businessUnit}
                      onChange={(e) => setBusinessUnit(e.target.value)}
                      placeholder="e.g., IT, Finance, Operations"
                      className="w-full glass-light rounded-lg px-4 py-2.5 text-sm text-foreground outline-none border border-transparent focus:border-accent/30 placeholder-muted"
                    />
                  </div>
                </div>
                <div className="grid grid-cols-2 gap-4 mt-4">
                  <div>
                    <label className="text-[11px] text-muted uppercase tracking-wider block mb-1.5">Legacy System Name</label>
                    <input
                      type="text"
                      value={legacySystem}
                      onChange={(e) => setLegacySystem(e.target.value)}
                      placeholder="Current system name"
                      className="w-full glass-light rounded-lg px-4 py-2.5 text-sm text-foreground outline-none border border-transparent focus:border-accent/30 placeholder-muted"
                    />
                  </div>
                  <div>
                    <label className="text-[11px] text-muted uppercase tracking-wider block mb-1.5">Target System Name</label>
                    <input
                      type="text"
                      value={targetSystem}
                      onChange={(e) => setTargetSystem(e.target.value)}
                      placeholder="New system name"
                      className="w-full glass-light rounded-lg px-4 py-2.5 text-sm text-foreground outline-none border border-transparent focus:border-accent/30 placeholder-muted"
                    />
                  </div>
                </div>
                <div className="grid grid-cols-2 gap-4 mt-4">
                  <div>
                    <label className="text-[11px] text-muted uppercase tracking-wider block mb-1.5">Client Technical Contact</label>
                    <input
                      type="text"
                      value={technicalContact}
                      onChange={(e) => setTechnicalContact(e.target.value)}
                      placeholder="Client's technical contact"
                      className="w-full glass-light rounded-lg px-4 py-2.5 text-sm text-foreground outline-none border border-transparent focus:border-accent/30 placeholder-muted"
                    />
                  </div>
                  <div>
                    <label className="text-[11px] text-muted uppercase tracking-wider block mb-1.5">Client Business Contact</label>
                    <input
                      type="text"
                      value={businessContact}
                      onChange={(e) => setBusinessContact(e.target.value)}
                      placeholder="Client's business contact"
                      className="w-full glass-light rounded-lg px-4 py-2.5 text-sm text-foreground outline-none border border-transparent focus:border-accent/30 placeholder-muted"
                    />
                  </div>
                </div>
              </div>

              <div className="border-t border-border pt-5 mt-5">
                <h4 className="text-sm font-semibold text-foreground mb-4 flex items-center gap-2">
                  <Workflow className="w-4 h-4 text-accent-light" /> Internal Tracking
                </h4>
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <label className="text-[11px] text-muted uppercase tracking-wider block mb-1.5">Conversion Code</label>
                    <input
                      type="text"
                      value={projectCode}
                      onChange={(e) => setProjectCode(e.target.value)}
                      placeholder="e.g., MIG-2024-001"
                      className="w-full glass-light rounded-lg px-4 py-2.5 text-sm text-foreground outline-none border border-transparent focus:border-accent/30 placeholder-muted"
                    />
                  </div>
                  <div>
                    <label className="text-[11px] text-muted uppercase tracking-wider block mb-1.5">Stakeholders</label>
                    <input
                      type="text"
                      value={stakeholders}
                      onChange={(e) => setStakeholders(e.target.value)}
                      placeholder="Internal team members"
                      className="w-full glass-light rounded-lg px-4 py-2.5 text-sm text-foreground outline-none border border-transparent focus:border-accent/30 placeholder-muted"
                    />
                  </div>
                </div>
              </div>
              <div>
                <label className="text-[11px] text-muted uppercase tracking-wider block mb-1.5">Tags (comma-separated)</label>
                <input
                  type="text"
                  value={tags}
                  onChange={(e) => setTags(e.target.value)}
                  placeholder="legacy, banking, migration..."
                  className="w-full glass-light rounded-lg px-4 py-3 text-sm text-foreground outline-none border border-transparent focus:border-accent/30 transition-colors placeholder-muted"
                />
              </div>
            </div>
          )}

          {step === 2 && (
            <div className="space-y-4">
              <div className="flex items-center justify-between">
                <div>
                  <h3 className="text-base font-semibold text-foreground">Source Language</h3>
                  <p className="text-xs text-muted">Select the language you're converting FROM</p>
                </div>
                <div className="flex items-center gap-1.5 px-2 py-1 glass-light rounded-full">
                  <Zap className="w-3 h-3 text-accent-light" />
                  <span className="text-[10px] text-foreground font-medium">ANY-to-ANY</span>
                </div>
              </div>

              {/* Auto-detect from local folder */}
              {isLocalFolderSource && hasLocalFolder && (
                <div className={`rounded-lg border p-3 space-y-3 transition-colors ${detectedApplied ? 'border-success/30 bg-success/5' : 'border-accent/20 bg-accent/5'}`}>
                  <div className="flex items-center justify-between gap-3">
                    <div className="flex items-center gap-2 min-w-0">
                      {detectedApplied
                        ? <CheckCircle2 className="w-4 h-4 text-success flex-shrink-0" />
                        : <Zap className="w-4 h-4 text-accent-light flex-shrink-0" />}
                      <div className="min-w-0">
                        <p className="text-xs font-medium text-foreground">
                          {detectedApplied ? 'Language detected and applied' : 'Auto-detect from uploaded folder'}
                        </p>
                        <p className="text-[10px] text-muted truncate">
                          {detectedApplied
                            ? detectedBreakdown.slice(0, 3).map(b => `${b.name} ${b.percent}%`).join(' · ')
                            : 'Analyse the folder files to auto-fill this step'}
                        </p>
                      </div>
                    </div>
                    <button
                      onClick={async () => {
                        setDetectingLang(true);
                        setDetectedApplied(false);

                        // Build an inverted map: extension → [scribaId, ...]
                        const extToLangs: Record<string, string[]> = {};
                        for (const [langId, exts] of Object.entries(SOURCE_EXTENSIONS)) {
                          for (const ext of exts) {
                            if (!extToLangs[ext]) extToLangs[ext] = [];
                            extToLangs[ext].push(langId);
                          }
                        }

                        // Count source bytes per language ID
                        const langBytes: Record<string, number> = {};
                        const allFilePaths: string[] = [];
                        for (const file of localFolderFiles) {
                          const rel = file.webkitRelativePath || file.name;
                          allFilePaths.push(rel);
                          const ext = '.' + rel.split('.').pop()!.toLowerCase();
                          const langs = extToLangs[ext] ?? [];
                          for (const lang of langs) {
                            langBytes[lang] = (langBytes[lang] ?? 0) + file.size;
                          }
                        }

                        // Sort by byte count, build breakdown
                        const totalBytes = Object.values(langBytes).reduce((a, b) => a + b, 0) || 1;
                        const sorted = Object.entries(langBytes)
                          .sort(([, a], [, b]) => b - a)
                          .slice(0, 6);

                        const breakdown = sorted.map(([id, bytes]) => ({
                          scribaId: id,
                          name: id.charAt(0).toUpperCase() + id.slice(1),
                          percent: Math.round((bytes / totalBytes) * 100),
                        }));
                        setDetectedBreakdown(breakdown);

                        const topId = sorted[0]?.[0] ?? null;
                        let scribaId = topId;
                        if (topId) {
                          const autoLang = sourceLanguages.find(l => l.id === topId);
                          setSelectedSource(topId);
                          setSourceVersion(autoLang?.versions?.[0] ?? '');
                          setSourceFramework('');
                          setSourceSearch('');
                          const extras = sorted.slice(1).map(([id]) => id).filter(id => id !== topId);
                          setSelectedSourceExtras(extras.slice(0, 3));
                          setDetectedApplied(true);
                        }

                        // Second pass: read manifest files and detect framework + version
                        if (scribaId) {
                          const matchedPaths = new Set(findManifestPaths(allFilePaths, scribaId));
                          const manifests: { path: string; content: string }[] = [];
                          for (const file of localFolderFiles) {
                            const rel = file.webkitRelativePath || file.name;
                            if (matchedPaths.has(rel) && file.size < 512 * 1024) {
                              try {
                                const content = await file.text();
                                manifests.push({ path: rel, content });
                              } catch { /* skip unreadable */ }
                            }
                          }

                          if (manifests.length > 0) {
                            const stackRes = await fetch('/api/local/detect-stack', {
                              method: 'POST',
                              headers: { 'Content-Type': 'application/json' },
                              body: JSON.stringify({ sourceLanguage: scribaId, manifests, filePaths: allFilePaths.slice(0, 5000) }),
                            }).catch(() => null);
                            if (stackRes?.ok) {
                              const stack = await stackRes.json();
                              const langDef = sourceLanguages.find(l => l.id === scribaId);
                              if (stack.version && langDef?.versions?.length) {
                                const matchedVer = matchWizardOption(stack.version, langDef.versions);
                                if (matchedVer) setSourceVersion(matchedVer);
                              }
                              const frameworks = (langDef as { frameworks?: string[] })?.frameworks;
                              if (stack.framework && frameworks?.length) {
                                const matchedFw = matchWizardOption(stack.framework, frameworks);
                                if (matchedFw) setSourceFramework(matchedFw);
                              }
                            }
                          }
                        }

                        setDetectingLang(false);
                      }}
                      disabled={detectingLang}
                      className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg gradient-accent text-white text-xs font-medium hover:opacity-90 transition-opacity flex-shrink-0 disabled:opacity-50"
                    >
                      {detectingLang
                        ? <><Loader2 className="w-3 h-3 animate-spin" /> Detecting...</>
                        : <><Search className="w-3 h-3" /> {detectedApplied ? 'Re-detect' : 'Detect language'}</>}
                    </button>
                  </div>

                  {detectedBreakdown.length > 0 && (
                    <div className="space-y-1.5">
                      <div className="flex h-2 rounded-full overflow-hidden gap-px">
                        {detectedBreakdown.slice(0, 5).map((b, i) => (
                          <div
                            key={b.name}
                            style={{ width: `${b.percent}%` }}
                            className={`h-full transition-all ${
                              i === 0 ? 'bg-accent' :
                              i === 1 ? 'bg-accent/60' :
                              i === 2 ? 'bg-accent/40' :
                              'bg-accent/20'
                            }`}
                          />
                        ))}
                      </div>
                      <div className="flex flex-wrap gap-x-3 gap-y-1">
                        {detectedBreakdown.slice(0, 5).map(b => {
                          const isPrimary = b.scribaId === selectedSource;
                          const isExtra = b.scribaId ? selectedSourceExtras.includes(b.scribaId) : false;
                          const isSelected = isPrimary || isExtra;
                          return (
                            <button
                              key={b.name}
                              onClick={() => { if (b.scribaId) handleSourceClick(b.scribaId); }}
                              disabled={!b.scribaId}
                              className={`flex items-center gap-1 text-[10px] transition-colors ${
                                isPrimary ? 'text-accent-light font-medium cursor-pointer' :
                                isExtra ? 'text-foreground cursor-pointer' :
                                b.scribaId ? 'text-muted hover:text-foreground cursor-pointer' : 'text-muted cursor-default'
                              }`}
                            >
                              <span className={`w-2 h-2 rounded-full flex-shrink-0 border ${
                                isPrimary ? 'bg-accent border-accent' :
                                isExtra ? 'bg-accent/40 border-accent/40' :
                                'bg-transparent border-muted'
                              }`} />
                              {b.name} <span className="text-muted">{b.percent}%</span>
                              {isPrimary && <span className="text-[8px] text-accent-light ml-0.5">primary</span>}
                              {isExtra && <Check className="w-2.5 h-2.5 text-accent/60" />}
                            </button>
                          );
                        })}
                      </div>
                    </div>
                  )}
                </div>
              )}

              {/* Auto-detect from repository */}
              {!isLocalFolderSource && repoUrl && (
                <div className={`rounded-lg border p-3 space-y-3 transition-colors ${detectedApplied ? 'border-success/30 bg-success/5' : 'border-accent/20 bg-accent/5'}`}>
                  <div className="flex items-center justify-between gap-3">
                    <div className="flex items-center gap-2 min-w-0">
                      {detectedApplied
                        ? <CheckCircle2 className="w-4 h-4 text-success flex-shrink-0" />
                        : <Zap className="w-4 h-4 text-accent-light flex-shrink-0" />}
                      <div className="min-w-0">
                        <p className="text-xs font-medium text-foreground">
                          {detectedApplied ? 'Language detected and applied' : 'Auto-detect from repository'}
                        </p>
                        <p className="text-[10px] text-muted truncate">
                          {detectedApplied
                            ? detectedBreakdown.slice(0, 3).map(b => `${b.name} ${b.percent}%`).join(' · ')
                            : 'Analyse the repository code to auto-fill this step'}
                        </p>
                      </div>
                    </div>
                    <button
                      onClick={async () => {
                        setDetectingLang(true);
                        setDetectedApplied(false);

                        let apiUrl = '';
                        let params = '';

                        // Detect provider and build API call
                        if (repoUrl.match(/github\.com\/([^/]+)\/([^/\s]+?)(?:\.git)?\s*$/)) {
                          const match = repoUrl.match(/github\.com\/([^/]+)\/([^/\s]+?)(?:\.git)?\s*$/);
                          if (match) {
                            const [, owner, repo] = match;
                            apiUrl = `/api/github/languages`;
                            params = `owner=${encodeURIComponent(owner)}&repo=${encodeURIComponent(repo)}`;
                          }
                        } else if (repoUrl.match(/gitlab\.com\/([^/]+)\/([^/\s]+?)(?:\.git)?\s*$/)) {
                          const match = repoUrl.match(/gitlab\.com\/([^/]+)\/([^/\s]+?)(?:\.git)?\s*$/);
                          if (match) {
                            const [, owner, repo] = match;
                            // GitLab uses project ID or path with namespace
                            apiUrl = `/api/gitlab/languages`;
                            params = `projectId=${encodeURIComponent(`${owner}/${repo}`)}`;
                          }
                        } else if (repoUrl.match(/dev\.azure\.com\/([^/]+)\/([^/]+)\/_git\/([^/\s]+)\s*$/)) {
                          const match = repoUrl.match(/dev\.azure\.com\/([^/]+)\/([^/]+)\/_git\/([^/\s]+)\s*$/);
                          if (match) {
            const [, org, project, repo] = match;
            apiUrl = `/api/azure/languages`;
            params = `org=${encodeURIComponent(org)}&project=${encodeURIComponent(project)}&repo=${encodeURIComponent(repo)}`;
          }
        } else if (repoUrl.match(/bitbucket\.org\/([^/]+)\/([^/\s]+?)(?:\.git)?\s*$/)) {
          const match = repoUrl.match(/bitbucket\.org\/([^/]+)\/([^/\s]+?)(?:\.git)?\s*$/);
          if (match) {
            const [, workspace, repo] = match;
            apiUrl = `/api/bitbucket/languages`;
            params = `workspace=${encodeURIComponent(workspace)}&repo=${encodeURIComponent(repo)}`;
          }
        }

                        if (!apiUrl) {
                          setDetectingLang(false);
                          return;
                        }

                        const res = await fetch(`${apiUrl}?${params}`).catch(() => null);
                        let scribaId: string | null = null;
                        if (res?.ok) {
                          const data = await res.json();
                          setDetectedBreakdown(data.breakdown ?? []);
                          if (data.detected?.scribaId) {
                            const id = data.detected.scribaId;
                            scribaId = id;
                            setSelectedSource(id);
                            const autoLang = sourceLanguages.find(l => l.id === id);
                            setSourceVersion(autoLang?.versions?.[0] ?? '');
                            setSourceFramework('');
                            setSourceSearch('');
                            const extras = (data.breakdown as { scribaId: string | null; percent: number }[])
                              .filter(b => b.scribaId && b.scribaId !== id)
                              .map(b => b.scribaId!);
                            setSelectedSourceExtras(extras);
                            setDetectedApplied(true);
                          }
                        }

                        // Second pass: scriba-engine manifest analysis (framework + runtime version)
                        if (scribaId && repoUrl.trim()) {
                          const stackQs = new URLSearchParams({
                            repoUrl: repoUrl.trim(),
                            branch: branch || 'main',
                            sourceLanguage: scribaId,
                          });
                          const stackRes = await fetch(`/api/repo/detect-stack?${stackQs}`).catch(() => null);
                          if (stackRes?.ok) {
                            const stack = await stackRes.json();
                            const langDef = sourceLanguages.find(l => l.id === scribaId);
                            if (stack.version && langDef?.versions?.length) {
                              const matchedVer = matchWizardOption(stack.version, langDef.versions);
                              if (matchedVer) setSourceVersion(matchedVer);
                            }
                            const frameworks = (langDef as { frameworks?: string[] })?.frameworks;
                            if (stack.framework && frameworks?.length) {
                              const matchedFw = matchWizardOption(stack.framework, frameworks);
                              if (matchedFw) setSourceFramework(matchedFw);
                            }
                          }
                        }

                        setDetectingLang(false);
                      }}
                      disabled={detectingLang}
                      className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg gradient-accent text-white text-xs font-medium hover:opacity-90 transition-opacity flex-shrink-0 disabled:opacity-50"
                    >
                      {detectingLang
                        ? <><Loader2 className="w-3 h-3 animate-spin" /> Detecting...</>
                        : <><Search className="w-3 h-3" /> {detectedApplied ? 'Re-detect' : 'Detect language'}</>}
                    </button>
                  </div>

                  {/* Language breakdown bar */}
                  {detectedBreakdown.length > 0 && (
                    <div className="space-y-1.5">
                      <div className="flex h-2 rounded-full overflow-hidden gap-px">
                        {detectedBreakdown.slice(0, 5).map((b, i) => (
                          <div
                            key={b.name}
                            style={{ width: `${b.percent}%` }}
                            className={`h-full transition-all ${
                              i === 0 ? 'bg-accent' :
                              i === 1 ? 'bg-accent/60' :
                              i === 2 ? 'bg-accent/40' :
                              'bg-accent/20'
                            }`}
                          />
                        ))}
                      </div>
                      <div className="flex flex-wrap gap-x-3 gap-y-1">
                        {detectedBreakdown.slice(0, 5).map(b => {
                          const isPrimary = b.scribaId === selectedSource;
                          const isExtra = b.scribaId ? selectedSourceExtras.includes(b.scribaId) : false;
                          const isSelected = isPrimary || isExtra;
                          return (
                            <button
                              key={b.name}
                              onClick={() => { if (b.scribaId) handleSourceClick(b.scribaId); }}
                              disabled={!b.scribaId}
                              className={`flex items-center gap-1 text-[10px] transition-colors ${
                                isPrimary ? 'text-accent-light font-medium cursor-pointer' :
                                isExtra ? 'text-foreground cursor-pointer' :
                                b.scribaId ? 'text-muted hover:text-foreground cursor-pointer' : 'text-muted cursor-default'
                              }`}
                            >
                              <span className={`w-2 h-2 rounded-full flex-shrink-0 border ${
                                isPrimary ? 'bg-accent border-accent' :
                                isExtra ? 'bg-accent/40 border-accent/40' :
                                'bg-transparent border-muted'
                              }`} />
                              {b.name} <span className="text-muted">{b.percent}%</span>
                              {isPrimary && <span className="text-[8px] text-accent-light ml-0.5">primary</span>}
                              {isExtra && <Check className="w-2.5 h-2.5 text-accent/60" />}
                            </button>
                          );
                        })}
                      </div>
                    </div>
                  )}
                </div>
              )}

              <div className="glass-light rounded-lg p-3 space-y-3">
                <div className="flex gap-2">
                  <div className="relative flex-1">
                    <Search className="absolute left-2 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-muted" />
                    <input
                      type="text"
                      value={sourceSearch}
                      onChange={(e) => setSourceSearch(e.target.value)}
                      placeholder="Search..."
                      className="w-full bg-surface rounded-md pl-8 pr-8 py-1.5 text-xs text-foreground outline-none border border-transparent focus:border-accent/30 placeholder-muted"
                    />
                    {sourceSearch && (
                      <button
                        onClick={() => setSourceSearch('')}
                        className="absolute right-2 top-1/2 -translate-y-1/2 text-muted hover:text-foreground transition-colors"
                      >
                        <X className="w-3 h-3" />
                      </button>
                    )}
                  </div>
                  <select
                    value={sourceCategoryFilter}
                    onChange={(e) => setSourceCategoryFilter(e.target.value as any)}
                    className="bg-surface rounded-md px-2 py-1.5 text-xs text-foreground outline-none border border-transparent focus:border-accent/30"
                  >
                    <option value="all">All ({sourceLanguages.length})</option>
                    <option value="legacy">Legacy ({sourceLanguages.filter(l => l.category === 'legacy').length})</option>
                    <option value="modern">Modern ({sourceLanguages.filter(l => l.category === 'modern').length})</option>
                  </select>
                </div>

                {/* Multi-select summary chips */}
                {(selectedSource || selectedSourceExtras.length > 0) && (
                  <div className="flex flex-wrap gap-1.5 pb-1">
                    {selectedSource && (
                      <span className="inline-flex items-center gap-1 px-2 py-1 rounded-full bg-accent border border-accent/80 text-[10px] font-medium text-white">
                        <Star className="w-2.5 h-2.5" />
                        {sourceLanguages.find(l => l.id === selectedSource)?.name}
                        <span className="opacity-70">primary</span>
                        <button onClick={() => handleSourceClick(selectedSource)} className="ml-0.5 hover:text-white"><X className="w-2.5 h-2.5" /></button>
                      </span>
                    )}
                    {selectedSourceExtras.map(id => {
                      const lang = sourceLanguages.find(l => l.id === id);
                      if (!lang) return null;
                      return (
                        <span key={id} className="inline-flex items-center gap-1 px-2 py-1 rounded-full bg-surface-light border border-border text-[10px] text-foreground">
                          {lang.name}
                          <button onClick={() => promoteSourceToPrimary(id)} title="Set as primary" className="text-muted hover:text-accent transition-colors">
                            <Star className="w-2.5 h-2.5" />
                          </button>
                          <button onClick={() => handleSourceClick(id)} className="text-muted hover:text-foreground">
                            <X className="w-2.5 h-2.5" />
                          </button>
                        </span>
                      );
                    })}
                  </div>
                )}

                <div className="grid grid-cols-2 gap-2 max-h-64 overflow-y-auto pr-1">
                  {sourceLanguages
                    .filter(l => sourceCategoryFilter === 'all' || l.category === sourceCategoryFilter)
                    .filter(l => l.name.toLowerCase().includes(sourceSearch.toLowerCase()) || l.desc.toLowerCase().includes(sourceSearch.toLowerCase()))
                    .map(l => {
                      const isTierAllowed = sourceLanguageAllowed(l.id);
                      const isPrimary = selectedSource === l.id;
                      const isExtra = selectedSourceExtras.includes(l.id);
                      return (
                        <button
                          key={l.id}
                          onClick={() => {
                            if (!isTierAllowed) return;
                            handleSourceClick(l.id);
                          }}
                          disabled={!isTierAllowed}
                          className={`p-2 rounded-md border text-left transition-all cursor-pointer relative group ${
                            !isTierAllowed ? 'border-border bg-surface opacity-40 cursor-not-allowed' :
                            isPrimary ? 'border-accent bg-accent/15 ring-2 ring-accent/40 shadow-md' :
                            isExtra ? 'border-accent/40 bg-accent/8 ring-1 ring-accent/20' :
                            'border-border bg-surface hover:border-accent/30 hover:shadow-lg'
                          }`}
                        >
                          <div className="flex items-start justify-between">
                            <div className="flex-1 min-w-0">
                              <div className="flex items-center gap-1.5">
                                <p className="text-xs font-medium text-foreground truncate">{l.name}</p>
                                <span className={`px-1 py-0.5 rounded text-[8px] font-medium flex-shrink-0 ${l.category === 'legacy' ? 'bg-orange-400/20 text-orange-300' : 'bg-green-400/20 text-green-300'}`}>
                                  {l.category === 'legacy' ? 'L' : 'M'}
                                </span>
                                {!isTierAllowed && <span className="text-[8px] text-accent-light">Pro+</span>}
                              </div>
                              <p className="text-[9px] text-muted mt-0.5 truncate">{l.desc}</p>
                              <div className="flex items-center gap-2 mt-1">
                                <span className="text-[8px] text-muted">{l.versions.length} versions</span>
                                <span className="text-[8px] text-muted">•</span>
                                <span className="text-[8px] text-muted">{l.dialects.length} dialects</span>
                                {(l as any).frameworks?.length > 0 && <>
                                  <span className="text-[8px] text-muted">•</span>
                                  <span className="text-[8px] text-accent-light">{(l as any).frameworks.length} frameworks</span>
                                </>}
                              </div>
                            </div>
                            <div className="absolute top-1 right-1 flex-shrink-0 flex items-center gap-0.5">
                              {isPrimary && <Star className="w-3 h-3 text-accent" />}
                              {isExtra && <Check className="w-3 h-3 text-accent/60" />}
                              {!isPrimary && !isExtra && l.category === 'legacy' && <TrendingUp className="w-3 h-3 text-orange-400" />}
                            </div>
                          </div>
                        </button>
                      );
                    })}
                </div>

                {selectedSource && (
                  <motion.div initial={{ opacity: 0, height: 0 }} animate={{ opacity: 1, height: 'auto' }} className="pt-2 border-t border-border space-y-2">
                    <div className="grid grid-cols-2 gap-2">
                      <div>
                        <label className="text-[9px] text-muted uppercase tracking-wider block mb-1">Version *</label>
                        <select
                          value={sourceVersion || ''}
                          onChange={(e) => setSourceVersion(e.target.value)}
                          className="w-full bg-surface rounded-md px-2 py-1 text-xs text-foreground outline-none border border-transparent focus:border-accent/30"
                        >
                          <option value="">Select version...</option>
                          {sourceLanguages.find(l => l.id === selectedSource)?.versions.map(v => (
                            <option key={v} value={v}>{v}</option>
                          ))}
                        </select>
                      </div>
                      <div>
                        <label className="text-[9px] text-muted uppercase tracking-wider block mb-1">Dialect</label>
                        <select
                          value={sourceDialect || ''}
                          onChange={(e) => setSourceDialect(e.target.value)}
                          className="w-full bg-surface rounded-md px-2 py-1 text-xs text-foreground outline-none border border-transparent focus:border-accent/30"
                        >
                          <option value="">Auto</option>
                          {sourceLanguages.find(l => l.id === selectedSource)?.dialects.map(d => (
                            <option key={d} value={d}>{d}</option>
                          ))}
                        </select>
                      </div>
                    </div>
                    {(() => {
                      const frameworks = (sourceLanguages.find(l => l.id === selectedSource) as any)?.frameworks as string[] | undefined;
                      if (!frameworks?.length) return null;
                      return (
                        <div>
                          <label className="text-[9px] text-muted uppercase tracking-wider block mb-1.5">
                            Framework
                            {detectedApplied && sourceFramework && (
                              <span className="ml-1 text-accent-light normal-case">(detected: {sourceFramework})</span>
                            )}
                            {detectedApplied && !sourceFramework && (
                              <span className="ml-1 text-accent-light normal-case">(select to clarify)</span>
                            )}
                          </label>
                          <div className="flex flex-wrap gap-1.5">
                            {frameworks.map(fw => (
                              <button
                                key={fw}
                                onClick={() => setSourceFramework(prev => prev === fw ? '' : fw)}
                                className={`px-2 py-1 rounded-md text-[10px] font-medium border transition-all ${
                                  sourceFramework === fw
                                    ? 'border-accent bg-accent/15 text-accent-light'
                                    : 'border-border bg-surface text-muted hover:border-accent/30 hover:text-foreground'
                                }`}
                              >
                                {fw}
                              </button>
                            ))}
                          </div>
                        </div>
                      );
                    })()}
                  </motion.div>
                )}
              </div>
            </div>
          )}

          {step === 3 && (
            <div className="space-y-4">
              <div className="flex items-center justify-between">
                <div>
                  <h3 className="text-base font-semibold text-foreground">Target Language</h3>
                  <p className="text-xs text-muted">Select the language you're converting TO</p>
                </div>
                <div className="flex items-center gap-2">
                  <span className="text-xs text-muted">From: {sourceLanguages.find(l => l.id === selectedSource)?.name}</span>
                </div>
              </div>

              {/* Recommended Targets */}
              {selectedSource && !selectedTarget && (
                <motion.div 
                  initial={{ opacity: 0, y: -10 }} 
                  animate={{ opacity: 1, y: 0 }} 
                  className="glass-light rounded-lg p-3"
                >
                  <div className="flex items-center gap-2 mb-2">
                    <Zap className="w-3.5 h-3.5 text-accent-light" />
                    <span className="text-xs font-medium text-foreground">Recommended for {sourceLanguages.find(l => l.id === selectedSource)?.name}</span>
                  </div>
                  <div className="flex flex-wrap gap-2">
                    {(() => {
                      const recommendations: Record<string, string[]> = {
                        'cobol': ['java', 'csharp', 'python'],
                        'vb6': ['csharp', 'java', 'python'],
                        'pl/i': ['java', 'csharp'],
                        'rpg': ['rpg_free', 'java', 'csharp'],
                        'java_legacy': ['java'],
                        'natural': ['java', 'csharp'],
                        'fortran': ['python', 'java', 'c++'],
                        'powerbuilder': ['csharp', 'java'],
                        'progress': ['java', 'csharp'],
                        'sas': ['python', 'r', 'java'],
                        'tibco_bw': ['java', 'node', 'go'],
                      };
                      const recs = recommendations[selectedSource] ?? [];
                      if (recs.length === 0) {
                        return <span className="text-xs text-muted">Choose a target from the full list below.</span>;
                      }
                      return recs.map((targetId, idx) => {
                        const lang = targetLanguages.find(l => l.id === targetId);
                        if (!lang) return null;
                        return (
                          <button
                            key={idx}
                            onClick={() => setSelectedTarget(targetId)}
                            className="px-3 py-1.5 bg-surface hover:bg-success/10 border border-border hover:border-success/30 rounded-md text-xs text-foreground transition-all cursor-pointer"
                          >
                            {lang.name}
                          </button>
                        );
                      });
                    })()}
                  </div>
                </motion.div>
              )}

              {/* Selected Summary */}
              {selectedTarget && (
                <motion.div 
                  initial={{ opacity: 0, y: -10 }} 
                  animate={{ opacity: 1, y: 0 }} 
                  className="glass-light rounded-lg p-3 border-l-4 border-success"
                >
                  <div className="flex items-center justify-between">
                    <div className="flex items-center gap-3">
                      <CheckCircle2 className="w-5 h-5 text-success" />
                      <div>
                        <p className="text-xs font-medium text-foreground">
                          {sourceLanguages.find(l => l.id === selectedSource)?.name} → {targetLanguages.find(l => l.id === selectedTarget)?.name}
                        </p>
                        <p className="text-[10px] text-muted">Migration path ready</p>
                      </div>
                    </div>
                    <div className="flex items-center gap-2">
                      {sourceLanguages.find(l => l.id === selectedSource)?.category === 'legacy' && targetLanguages.find(l => l.id === selectedTarget)?.category === 'modern' && (
                        <span className="px-2 py-1 bg-green-500/20 text-green-300 rounded text-[10px] font-medium">Modernization</span>
                      )}
                      {sourceLanguages.find(l => l.id === selectedSource)?.category === 'modern' && targetLanguages.find(l => l.id === selectedTarget)?.category === 'modern' && (
                        <span className="px-2 py-1 bg-blue-500/20 text-blue-300 rounded text-[10px] font-medium">Modern Migration</span>
                      )}
                      {sourceLanguages.find(l => l.id === selectedSource)?.category === 'legacy' && targetLanguages.find(l => l.id === selectedTarget)?.category === 'legacy' && (
                        <span className="px-2 py-1 bg-orange-500/20 text-orange-300 rounded text-[10px] font-medium">Legacy Refactor</span>
                      )}
                    </div>
                  </div>
                </motion.div>
              )}

              <div className="glass-light rounded-lg p-3 space-y-3">
                <div className="flex gap-2">
                  <div className="relative flex-1">
                    <Search className="absolute left-2 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-muted" />
                    <input
                      type="text"
                      value={targetSearch}
                      onChange={(e) => setTargetSearch(e.target.value)}
                      placeholder="Search..."
                      className="w-full bg-surface rounded-md pl-8 pr-8 py-1.5 text-xs text-foreground outline-none border border-transparent focus:border-accent/30 placeholder-muted"
                    />
                    {targetSearch && (
                      <button
                        onClick={() => setTargetSearch('')}
                        className="absolute right-2 top-1/2 -translate-y-1/2 text-muted hover:text-foreground transition-colors"
                      >
                        <X className="w-3 h-3" />
                      </button>
                    )}
                  </div>
                  <select
                    value={targetCategoryFilter}
                    onChange={(e) => setTargetCategoryFilter(e.target.value as any)}
                    className="bg-surface rounded-md px-2 py-1.5 text-xs text-foreground outline-none border border-transparent focus:border-accent/30"
                  >
                    <option value="all">All ({targetLanguages.length})</option>
                    <option value="modern">Modern ({targetLanguages.filter(l => l.category === 'modern').length})</option>
                    <option value="legacy">Legacy ({targetLanguages.filter(l => l.category === 'legacy').length})</option>
                  </select>
                </div>

                <div className="grid grid-cols-2 gap-2 max-h-64 overflow-y-auto pr-1">
                  {targetLanguages
                    .filter(l => targetCategoryFilter === 'all' || l.category === targetCategoryFilter)
                    .filter(l => l.name.toLowerCase().includes(targetSearch.toLowerCase()) || l.desc.toLowerCase().includes(targetSearch.toLowerCase()))
                    .map(l => {
                    const isTierAllowed = targetLanguageAllowed(l.id);
                    return (
                    <button
                      key={l.id}
                      onClick={() => {
                      if (!isTierAllowed) return;
                      setSelectedTarget(l.id);
                      const autoT = targetLanguages.find(t => t.id === l.id);
                      setTargetVersion(autoT?.versions?.[0] ?? '');
                      setTargetBuild(autoT?.frameworks?.[0] ?? autoT?.build?.[0] ?? '');
                    }}
                      disabled={!isTierAllowed}
                      className={`p-2 rounded-md border text-left transition-all cursor-pointer relative group ${
                        !isTierAllowed
                          ? 'border-border bg-surface opacity-40 cursor-not-allowed'
                          : selectedTarget === l.id
                          ? 'border-success/50 bg-success/10 ring-1 ring-success/30'
                          : 'border-border bg-surface hover:border-success/30 hover:shadow-lg'
                      }`}
                    >
                      <div className="flex items-start justify-between">
                        <div className="flex-1 min-w-0">
                          <div className="flex items-center gap-1.5">
                            <p className="text-xs font-medium text-foreground truncate">{l.name}</p>
                            <span className={`px-1 py-0.5 rounded text-[8px] font-medium flex-shrink-0 ${l.category === 'legacy' ? 'bg-orange-400/20 text-orange-300' : 'bg-green-400/20 text-green-300'}`}>
                              {l.category === 'legacy' ? 'L' : 'M'}
                            </span>
                            {!isTierAllowed && <span className="text-[8px] text-accent-light">Pro+</span>}
                          </div>
                          <p className="text-[9px] text-muted mt-0.5 truncate">{l.desc}</p>
                          <div className="flex items-center gap-2 mt-1">
                            <span className="text-[8px] text-muted">{l.versions.length} versions</span>
                            {l.frameworks && (
                              <>
                                <span className="text-[8px] text-muted">•</span>
                                <span className="text-[8px] text-muted">{l.frameworks.length} frameworks</span>
                              </>
                            )}
                          </div>
                        </div>
                        {l.category === 'modern' && (
                          <div className="absolute top-1 right-1 flex gap-0.5 flex-shrink-0">
                            <Star className="w-3 h-3 text-yellow-400" />
                          </div>
                        )}
                      </div>
                    </button>
                  )})}
                </div>

                {selectedTarget && (
                  <motion.div initial={{ opacity: 0, height: 0 }} animate={{ opacity: 1, height: 'auto' }} className="pt-2 border-t border-border">
                    <div className="grid grid-cols-2 gap-2">
                      <div>
                        <label className="text-[9px] text-muted uppercase tracking-wider block mb-1">Version *</label>
                        <select
                          value={targetVersion || ''}
                          onChange={(e) => setTargetVersion(e.target.value)}
                          className="w-full bg-surface rounded-md px-2 py-1 text-xs text-foreground outline-none border border-transparent focus:border-accent/30"
                        >
                          <option value="">Select version...</option>
                          {targetLanguages.find(l => l.id === selectedTarget)?.versions.map(v => (
                            <option key={v} value={v}>{v}</option>
                          ))}
                        </select>
                      </div>
                      {targetLanguages.find(l => l.id === selectedTarget)?.frameworks && (
                        <div>
                          <label className="text-[9px] text-muted uppercase tracking-wider block mb-1">Framework *</label>
                          <select
                            value={targetBuild || ''}
                            onChange={(e) => setTargetBuild(e.target.value)}
                            className="w-full bg-surface rounded-md px-2 py-1 text-xs text-foreground outline-none border border-transparent focus:border-accent/30"
                          >
                            <option value="">Select framework...</option>
                            {targetLanguages.find(l => l.id === selectedTarget)?.frameworks?.map(f => (
                              <option key={f} value={f}>{f}</option>
                            ))}
                          </select>
                        </div>
                      )}
                    </div>
                  </motion.div>
                )}
              </div>
            </div>
          )}
          {step === 1 && (
            <div className="space-y-5">
              <div className="flex items-center justify-between">
                <h3 className="text-base font-semibold text-foreground">
                  {isLocalFolderSource ? 'Upload Source Folder' : 'Connect Repository'}
                </h3>
                {!isLocalFolderSource && (
                <button
                  onClick={() => onNavigate('settings', undefined, { settingsTab: 'github', settingsProviderTab: 'github' })}
                  className="text-xs text-accent-light hover:text-accent font-medium cursor-pointer"
                >
                  Manage connections
                </button>
                )}
              </div>

              {/* Provider Selector */}
              <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-3">
                {providers.map(p => (
                  <button
                    key={p.name}
                    onClick={() => {
                      setSelectedProvider(p.name);
                      if (p.name === 'Local folder') {
                        setConnected(false);
                        setRepoUrl('');
                      } else {
                        clearLocalFolder();
                        setConnected(false);
                      }
                    }}
                    className={`p-3 rounded-lg border text-center transition-all cursor-pointer ${
                      selectedProvider === p.name
                        ? 'border-accent/50 bg-accent/10 glow-accent'
                        : 'border-border bg-surface hover:border-accent/30'
                    }`}
                  >
                    <span className="text-2xl block mb-1">{p.icon}</span>
                    <p className="text-xs font-medium text-foreground">{p.name}</p>
                  </button>
                ))}
              </div>

              {/* ── Local folder picker ── */}
              {isLocalFolderSource && (
                <div className="space-y-4">
                  <p className="text-sm text-muted">
                    Choose a folder on your computer. Files are uploaded to the engine when you finish the wizard.
                    Use Chrome or Edge for best folder selection support.
                  </p>
                  <input
                    ref={localFolderInputRef}
                    type="file"
                    className="hidden"
                    // @ts-expect-error webkitdirectory is non-standard but supported in Chromium
                    webkitdirectory=""
                    directory=""
                    multiple
                    onChange={handleLocalFolderSelect}
                  />
                  {!hasLocalFolder ? (
                    <button
                      type="button"
                      onClick={() => localFolderInputRef.current?.click()}
                      className="w-full py-4 rounded-lg border-2 border-dashed border-accent/40 bg-accent/5 hover:bg-accent/10 transition-colors flex flex-col items-center justify-center gap-2 cursor-pointer"
                    >
                      <FolderPlus className="w-8 h-8 text-accent-light" />
                      <span className="text-sm font-medium text-foreground">Select project folder</span>
                      <span className="text-xs text-muted">Entire directory — not individual files</span>
                    </button>
                  ) : (
                    <div className="flex items-center gap-3 p-4 rounded-lg bg-success/10 border border-success/20">
                      <CheckCircle2 className="w-5 h-5 text-success flex-shrink-0" />
                      <div className="min-w-0 flex-1">
                        <p className="text-sm font-medium text-success">Folder selected</p>
                        <p className="text-[11px] text-muted truncate">
                          {localFolderLabel} · {localFolderFiles.length} files
                        </p>
                      </div>
                      <button
                        type="button"
                        onClick={clearLocalFolder}
                        className="text-xs text-muted hover:text-foreground px-2 py-1 rounded border border-border"
                      >
                        Change
                      </button>
                    </div>
                  )}
                </div>
              )}

              {/* ── GitHub picker ── */}
              {selectedProvider === 'GitHub' && (
                <div className="space-y-4">
                  {!ghConnected ? (
                    <div className="flex items-center justify-between gap-4 p-4 rounded-lg bg-warning/10 border border-warning/20">
                      <div className="flex items-center gap-3">
                        <AlertTriangle className="w-5 h-5 text-warning flex-shrink-0" />
                        <div>
                          <p className="text-sm font-medium text-foreground">GitHub not connected</p>
                          <p className="text-xs text-muted">Connect your account to browse personal and org repositories</p>
                        </div>
                      </div>
                      <button
                        onClick={() => onNavigate('settings', undefined, { settingsTab: 'github', settingsProviderTab: 'github' })}
                        className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg gradient-accent text-white text-xs font-medium hover:opacity-90 transition-opacity flex-shrink-0 cursor-pointer"
                      >
                        Connect GitHub
                      </button>
                    </div>
                  ) : (
                    <>
                      {/* Tabs */}
                      <div className="flex p-1 bg-surface rounded-lg gap-1">
                        <button
                          onClick={() => setGhTab('browse')}
                          className={`flex-1 py-1.5 text-xs font-medium rounded-md transition-colors ${ghTab === 'browse' ? 'bg-accent text-white shadow-sm' : 'text-muted hover:text-foreground'}`}
                        >
                          Browse GitHub
                        </button>
                        <button
                          onClick={() => setGhTab('manual')}
                          className={`flex-1 py-1.5 text-xs font-medium rounded-md transition-colors ${ghTab === 'manual' ? 'bg-accent text-white shadow-sm' : 'text-muted hover:text-foreground'}`}
                        >
                          Enter URL manually
                        </button>
                      </div>

                      {ghTab === 'browse' && (
                        <div className="space-y-3">
                          {/* Owner switcher + search */}
                          <div className="flex gap-2">
                            <div className="relative flex-shrink-0">
                              <select
                                value={ghSelectedOwner}
                                onChange={e => { setGhSelectedOwner(e.target.value); setGhSearch(''); }}
                                className="appearance-none pl-3 pr-7 py-2.5 glass-light rounded-lg text-sm text-foreground outline-none border border-transparent focus:border-accent/30 bg-transparent cursor-pointer min-w-[150px]"
                              >
                                {ghUser && <option value={ghUser}>{ghUser} (personal)</option>}
                                {ghOrgs.map(o => (
                                  <option key={o.login} value={o.login}>{o.login}</option>
                                ))}
                              </select>
                              <ChevronRight className="absolute right-2 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-muted rotate-90 pointer-events-none" />
                            </div>
                            <div className="flex-1 flex items-center gap-2 glass-light rounded-lg px-3 py-2.5">
                              <Search className="w-3.5 h-3.5 text-muted flex-shrink-0" />
                              <input
                                type="text"
                                value={ghSearch}
                                onChange={e => setGhSearch(e.target.value)}
                                placeholder="Search repositories..."
                                className="flex-1 bg-transparent text-sm text-foreground outline-none placeholder-muted"
                              />
                              {ghSearch && (
                                <button onClick={() => setGhSearch('')} className="text-muted hover:text-foreground">
                                  <X className="w-3 h-3" />
                                </button>
                              )}
                            </div>
                          </div>

                          {/* Repo list */}
                          <div className="rounded-lg border border-border overflow-hidden">
                            <div className="max-h-64 overflow-y-auto divide-y divide-border">
                              {ghLoading ? (
                                <div className="flex items-center justify-center gap-2 py-8 text-muted">
                                  <Loader2 className="w-4 h-4 animate-spin" />
                                  <span className="text-sm">Loading repositories...</span>
                                </div>
                              ) : ghRepos.length === 0 ? (
                                <div className="flex flex-col items-center justify-center py-8 text-muted gap-2">
                                  <Database className="w-7 h-7 opacity-30" />
                                  <p className="text-sm">{ghSearch ? 'No repositories match your search' : 'No repositories found'}</p>
                                </div>
                              ) : (
                                ghRepos.map(repo => {
                                  const isSelected = repoUrl === repo.htmlUrl;
                                  return (
                                    <button
                                      key={repo.id}
                                      onClick={() => { setRepoUrl(repo.htmlUrl); setBranch(repo.defaultBranch || 'main'); setGhBranchSearch(''); setConnected(true); }}
                                      className={`w-full px-4 py-3 text-left transition-colors hover:bg-surface-light ${isSelected ? 'bg-accent/10 border-l-2 border-l-accent' : 'bg-surface'}`}
                                    >
                                      <div className="flex items-center gap-2 mb-0.5">
                                        <span className="text-sm font-medium text-foreground">{repo.name}</span>
                                        {repo.private && (
                                          <span className="inline-flex items-center gap-0.5 text-[9px] px-1.5 py-0.5 rounded-full bg-surface-light text-muted border border-border">
                                            <Lock className="w-2.5 h-2.5" /> Private
                                          </span>
                                        )}
                                        {repo.language && (
                                          <span className="text-[9px] px-1.5 py-0.5 rounded-full bg-accent/10 text-accent-light font-medium">{repo.language}</span>
                                        )}
                                        {isSelected && <Check className="w-3.5 h-3.5 text-accent ml-auto flex-shrink-0" />}
                                      </div>
                                      {repo.description && (
                                        <p className="text-xs text-muted line-clamp-1">{repo.description}</p>
                                      )}
                                      <p className="text-[10px] text-muted mt-0.5">{repo.fullName} · {repo.defaultBranch}</p>
                                    </button>
                                  );
                                })
                              )}
                            </div>
                            {ghHasMore && !ghLoading && (
                              <div className="p-2 border-t border-border bg-surface text-center">
                                <button
                                  onClick={async () => {
                                    const next = ghPage + 1;
                                    setGhPage(next);
                                    setGhLoading(true);
                                    const params = new URLSearchParams({ page: String(next) });
                                    if (ghSearch) params.set('q', ghSearch);
                                    if (ghSelectedOwner !== ghUser) params.set('org', ghSelectedOwner);
                                    const res = await fetch(`/api/github/repos?${params}`).catch(() => null);
                                    if (res?.ok) {
                                      const data = await res.json();
                                      setGhRepos(prev => [...prev, ...(data.repos ?? [])]);
                                      setGhHasMore((data.repos?.length ?? 0) === 50);
                                    }
                                    setGhLoading(false);
                                  }}
                                  className="text-xs text-accent hover:underline"
                                >
                                  Load more
                                </button>
                              </div>
                            )}
                          </div>

                          {/* Selected repo pill */}
                          {repoUrl && (
                            <div className="flex items-center gap-2 px-3 py-2 rounded-lg bg-accent/10 border border-accent/20">
                              <Check className="w-4 h-4 text-accent flex-shrink-0" />
                              <span className="text-sm text-foreground font-medium truncate">{repoUrl}</span>
                              <button onClick={() => { setRepoUrl(''); setConnected(false); }} className="text-muted hover:text-foreground ml-auto flex-shrink-0">
                                <X className="w-3.5 h-3.5" />
                              </button>
                            </div>
                          )}
                        </div>
                      )}

                      {ghTab === 'manual' && (
                        <div className="space-y-4">
                          <div>
                            <label className="text-[11px] text-muted uppercase tracking-wider block mb-1.5">Repository URL</label>
                            <div className="flex items-center gap-2 glass-light rounded-lg px-4 py-3">
                              <Globe className="w-4 h-4 text-muted" />
                              <input
                                type="text"
                                value={repoUrl}
                                onChange={e => { setRepoUrl(e.target.value); setConnected(false); }}
                                placeholder="https://github.com/org/repository"
                                className="flex-1 bg-transparent text-sm text-foreground outline-none placeholder-muted"
                              />
                              {repoUrl && (
                                <button onClick={() => { setRepoUrl(''); setConnected(false); }} className="text-muted hover:text-foreground">
                                  <X className="w-3.5 h-3.5" />
                                </button>
                              )}
                            </div>
                          </div>
                          {/* Optional example repositories */}
                          <div className="glass-light rounded-lg p-4">
                            <p className="text-xs text-muted mb-2">Example repositories (optional shortcuts):</p>
                            <div className="grid grid-cols-2 gap-2">
                              <button
                                onClick={() => { setRepoUrl('https://github.com/scriba-ai-dev/test-cobol'); setBranch('main'); setConnected(false); }}
                                className={`p-3 rounded-lg text-left cursor-pointer transition-colors border ${repoUrl === 'https://github.com/scriba-ai-dev/test-cobol' ? 'border-accent/50 bg-accent/10 glow-accent' : 'bg-surface hover:bg-surface-light border-transparent hover:border-accent/20'}`}
                              >
                                <div className="flex items-center gap-2 mb-0.5">
                                  <p className="text-xs font-medium text-foreground">COBOL Test Suite</p>
                                  <span className="text-[9px] px-1.5 py-0.5 rounded-full bg-accent/10 text-accent-light font-medium">COBOL</span>
                                </div>
                                <p className="text-[10px] text-muted">scriba-ai-dev/test-cobol · main</p>
                              </button>
                              <button
                                onClick={() => { setRepoUrl('https://github.com/algoretico/pli-claims-engine'); setBranch('main'); setConnected(false); }}
                                className="p-2 rounded-lg bg-surface hover:bg-surface-light text-left cursor-pointer transition-colors border border-transparent hover:border-accent/20"
                              >
                                <p className="text-xs font-medium text-foreground">Insurance claims sample</p>
                                <p className="text-[10px] text-muted">PL/I → Python FastAPI</p>
                              </button>
                              <button
                                onClick={() => { setRepoUrl('https://github.com/algoretico/rpg-payroll'); setBranch('main'); setConnected(false); }}
                                className="p-2 rounded-lg bg-surface hover:bg-surface-light text-left cursor-pointer transition-colors border border-transparent hover:border-accent/20"
                              >
                                <p className="text-xs font-medium text-foreground">Payroll sample</p>
                                <p className="text-[10px] text-muted">RPG/400 → C# .NET</p>
                              </button>
                              <button
                                onClick={() => { setRepoUrl('https://github.com/algoretico/cobol-trade-settlement'); setBranch('main'); setConnected(false); }}
                                className="p-2 rounded-lg bg-surface hover:bg-surface-light text-left cursor-pointer transition-colors border border-transparent hover:border-accent/20"
                              >
                                <p className="text-xs font-medium text-foreground">Trade settlement sample</p>
                                <p className="text-[10px] text-muted">COBOL/CICS → Kotlin</p>
                              </button>
                            </div>
                          </div>
                        </div>
                      )}
                    </>
                  )}
                </div>
              )}

              {/* ── GitLab picker ── */}
              {selectedProvider === 'GitLab' && (
                <div className="space-y-4">
                  {!glConnected ? (
                    <div className="flex items-center justify-between gap-4 p-4 rounded-lg bg-warning/10 border border-warning/20">
                      <div className="flex items-center gap-3">
                        <AlertTriangle className="w-5 h-5 text-warning flex-shrink-0" />
                        <div>
                          <p className="text-sm font-medium text-foreground">GitLab not connected</p>
                          <p className="text-xs text-muted">Connect your account in Settings → Connections to browse repositories</p>
                        </div>
                      </div>
                      <button
                        onClick={() => onNavigate('settings', undefined, { settingsTab: 'github', settingsProviderTab: 'gitlab' })}
                        className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg gradient-accent text-white text-xs font-medium hover:opacity-90 transition-opacity flex-shrink-0 cursor-pointer"
                      >
                        Connect GitLab
                      </button>
                    </div>
                  ) : (
                    <>
                      <div className="flex p-1 bg-surface rounded-lg gap-1">
                        <button onClick={() => setGlTab('browse')} className={`flex-1 py-1.5 text-xs font-medium rounded-md transition-colors ${glTab === 'browse' ? 'bg-accent text-white shadow-sm' : 'text-muted hover:text-foreground'}`}>Browse GitLab</button>
                        <button onClick={() => setGlTab('manual')} className={`flex-1 py-1.5 text-xs font-medium rounded-md transition-colors ${glTab === 'manual' ? 'bg-accent text-white shadow-sm' : 'text-muted hover:text-foreground'}`}>Enter URL manually</button>
                      </div>
                      {glTab === 'browse' && (
                        <div className="space-y-3">
                          <div className="flex gap-2">
                            <div className="relative flex-shrink-0">
                              <select value={glSelectedOwner} onChange={e => { setGlSelectedOwner(e.target.value); setGlSearch(''); }}
                                className="appearance-none pl-3 pr-7 py-2.5 glass-light rounded-lg text-sm text-foreground outline-none border border-transparent focus:border-accent/30 bg-transparent cursor-pointer min-w-[150px]">
                                {glUser && <option value={glUser}>{glUser} (personal)</option>}
                                {glGroups.map(g => <option key={g.id} value={g.fullPath}>{g.name}</option>)}
                              </select>
                              <ChevronRight className="absolute right-2 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-muted rotate-90 pointer-events-none" />
                            </div>
                            <div className="flex-1 flex items-center gap-2 glass-light rounded-lg px-3 py-2.5">
                              <Search className="w-3.5 h-3.5 text-muted flex-shrink-0" />
                              <input type="text" value={glSearch} onChange={e => setGlSearch(e.target.value)} placeholder="Search projects..." className="flex-1 bg-transparent text-sm text-foreground outline-none placeholder-muted" />
                              {glSearch && <button onClick={() => setGlSearch('')} className="text-muted hover:text-foreground"><X className="w-3 h-3" /></button>}
                            </div>
                          </div>
                          <div className="rounded-lg border border-border overflow-hidden">
                            <div className="max-h-64 overflow-y-auto divide-y divide-border">
                              {glLoading ? (
                                <div className="flex items-center justify-center gap-2 py-8 text-muted"><Loader2 className="w-4 h-4 animate-spin" /><span className="text-sm">Loading projects...</span></div>
                              ) : glRepos.length === 0 ? (
                                <div className="flex flex-col items-center justify-center py-8 text-muted gap-2"><Database className="w-7 h-7 opacity-30" /><p className="text-sm">{glSearch ? 'No projects match your search' : 'No projects found'}</p></div>
                              ) : (
                                glRepos.map(repo => {
                                  const isSelected = repoUrl === repo.webUrl;
                                  return (
                                    <button key={repo.id} onClick={() => { setRepoUrl(repo.webUrl); setBranch(repo.defaultBranch || 'main'); setGlSelectedRepoPath(repo.pathWithNamespace); setGlBranchSearch(''); setConnected(true); }}
                                      className={`w-full px-4 py-3 text-left transition-colors hover:bg-surface-light ${isSelected ? 'bg-accent/10 border-l-2 border-l-accent' : 'bg-surface'}`}>
                                      <div className="flex items-center gap-2">
                                        <span className="text-sm font-medium text-foreground truncate flex-1">{repo.name}</span>
                                        <span className={`text-[10px] px-1.5 py-0.5 rounded-full ${repo.visibility === 'private' ? 'bg-surface-light text-muted' : 'bg-success/10 text-success'}`}>{repo.visibility}</span>
                                        {isSelected && <Check className="w-3.5 h-3.5 text-accent flex-shrink-0" />}
                                      </div>
                                      <p className="text-[11px] text-muted truncate mt-0.5">{repo.pathWithNamespace}</p>
                                    </button>
                                  );
                                })
                              )}
                            </div>
                          </div>
                        </div>
                      )}
                      {glTab === 'manual' && (
                        <div>
                          <label className="text-[11px] text-muted uppercase tracking-wider block mb-1.5">Repository URL</label>
                          <div className="flex items-center gap-2 glass-light rounded-lg px-4 py-3">
                            <Globe className="w-4 h-4 text-muted" />
                            <input type="text" value={repoUrl} onChange={e => { setRepoUrl(e.target.value); setConnected(false); }} placeholder="https://gitlab.com/org/repository" className="flex-1 bg-transparent text-sm text-foreground outline-none placeholder-muted" />
                            {repoUrl && <button onClick={() => { setRepoUrl(''); setConnected(false); }} className="text-muted hover:text-foreground"><X className="w-3.5 h-3.5" /></button>}
                          </div>
                        </div>
                      )}
                    </>
                  )}
                </div>
              )}

              {/* ── Azure DevOps picker ── */}
              {selectedProvider === 'Azure DevOps' && (
                <div className="space-y-4">
                  {!azConnected ? (
                    <div className="flex items-center justify-between gap-4 p-4 rounded-lg bg-warning/10 border border-warning/20">
                      <div className="flex items-center gap-3">
                        <AlertTriangle className="w-5 h-5 text-warning flex-shrink-0" />
                        <div>
                          <p className="text-sm font-medium text-foreground">Azure DevOps not connected</p>
                          <p className="text-xs text-muted">Add a PAT in Settings → Connections to browse repositories</p>
                        </div>
                      </div>
                      <button
                        onClick={() => onNavigate('settings', undefined, { settingsTab: 'github', settingsProviderTab: 'azure' })}
                        className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg gradient-accent text-white text-xs font-medium hover:opacity-90 transition-opacity flex-shrink-0 cursor-pointer"
                      >
                        Add PAT
                      </button>
                    </div>
                  ) : (
                    <>
                      <div className="flex p-1 bg-surface rounded-lg gap-1">
                        <button onClick={() => setAzTab('browse')} className={`flex-1 py-1.5 text-xs font-medium rounded-md transition-colors ${azTab === 'browse' ? 'bg-accent text-white shadow-sm' : 'text-muted hover:text-foreground'}`}>Browse Azure DevOps</button>
                        <button onClick={() => setAzTab('manual')} className={`flex-1 py-1.5 text-xs font-medium rounded-md transition-colors ${azTab === 'manual' ? 'bg-accent text-white shadow-sm' : 'text-muted hover:text-foreground'}`}>Enter URL manually</button>
                      </div>
                      {azTab === 'browse' && (
                        <div className="space-y-3">
                          <div className="flex gap-2">
                            {azOrgs.length > 0 && (
                              <div className="relative flex-shrink-0">
                                <select value={azSelectedOrg} onChange={e => { setAzSelectedOrg(e.target.value); setAzSearch(''); }}
                                  className="appearance-none pl-3 pr-7 py-2.5 glass-light rounded-lg text-sm text-foreground outline-none border border-transparent focus:border-accent/30 bg-transparent cursor-pointer min-w-[150px]">
                                  {azOrgs.map(o => <option key={o.login} value={o.login}>{o.login}</option>)}
                                </select>
                                <ChevronRight className="absolute right-2 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-muted rotate-90 pointer-events-none" />
                              </div>
                            )}
                            <div className="flex-1 flex items-center gap-2 glass-light rounded-lg px-3 py-2.5">
                              <Search className="w-3.5 h-3.5 text-muted flex-shrink-0" />
                              <input type="text" value={azSearch} onChange={e => setAzSearch(e.target.value)} placeholder="Search repositories..." className="flex-1 bg-transparent text-sm text-foreground outline-none placeholder-muted" />
                              {azSearch && <button onClick={() => setAzSearch('')} className="text-muted hover:text-foreground"><X className="w-3 h-3" /></button>}
                            </div>
                          </div>
                          <div className="rounded-lg border border-border overflow-hidden">
                            <div className="max-h-64 overflow-y-auto divide-y divide-border">
                              {azLoading ? (
                                <div className="flex items-center justify-center gap-2 py-8 text-muted"><Loader2 className="w-4 h-4 animate-spin" /><span className="text-sm">Loading repositories...</span></div>
                              ) : azRepos.length === 0 ? (
                                <div className="flex flex-col items-center justify-center py-8 text-muted gap-2"><Database className="w-7 h-7 opacity-30" /><p className="text-sm">{azSearch ? 'No repositories match your search' : azSelectedOrg ? 'No repositories found' : 'Select an organization above'}</p></div>
                              ) : (
                                azRepos.map(repo => {
                                  const isSelected = repoUrl === repo.webUrl;
                                  return (
                                    <button key={repo.id} onClick={() => { setRepoUrl(repo.webUrl); setBranch(repo.defaultBranch || 'main'); setAzSelectedRepoMeta({ org: repo.org, project: repo.project, repoId: repo.id }); setAzBranchSearch(''); setConnected(true); }}
                                      className={`w-full px-4 py-3 text-left transition-colors hover:bg-surface-light ${isSelected ? 'bg-accent/10 border-l-2 border-l-accent' : 'bg-surface'}`}>
                                      <div className="flex items-center gap-2">
                                        <span className="text-sm font-medium text-foreground truncate flex-1">{repo.name}</span>
                                        <span className="text-[10px] px-1.5 py-0.5 rounded-full bg-surface-light text-muted">{repo.project}</span>
                                        {isSelected && <Check className="w-3.5 h-3.5 text-accent flex-shrink-0" />}
                                      </div>
                                      <p className="text-[11px] text-muted truncate mt-0.5">{repo.org} / {repo.project}</p>
                                    </button>
                                  );
                                })
                              )}
                            </div>
                          </div>
                        </div>
                      )}
                      {azTab === 'manual' && (
                        <div>
                          <label className="text-[11px] text-muted uppercase tracking-wider block mb-1.5">Repository URL</label>
                          <div className="flex items-center gap-2 glass-light rounded-lg px-4 py-3">
                            <Globe className="w-4 h-4 text-muted" />
                            <input type="text" value={repoUrl} onChange={e => { setRepoUrl(e.target.value); setConnected(false); }} placeholder="https://dev.azure.com/org/project/_git/repo" className="flex-1 bg-transparent text-sm text-foreground outline-none placeholder-muted" />
                            {repoUrl && <button onClick={() => { setRepoUrl(''); setConnected(false); }} className="text-muted hover:text-foreground"><X className="w-3.5 h-3.5" /></button>}
                          </div>
                        </div>
                      )}
                    </>
                  )}
                </div>
              )}

              {/* ── Bitbucket picker ── */}
              {selectedProvider === 'Bitbucket' && (
                <div className="space-y-4">
                  {!bbConnected ? (
                    <div className="flex items-center justify-between gap-4 p-4 rounded-lg bg-warning/10 border border-warning/20">
                      <div className="flex items-center gap-3">
                        <AlertTriangle className="w-5 h-5 text-warning flex-shrink-0" />
                        <div>
                          <p className="text-sm font-medium text-foreground">Bitbucket not connected</p>
                          <p className="text-xs text-muted">Connect your account in Settings → Connections to browse repositories</p>
                        </div>
                      </div>
                      <button
                        onClick={() => onNavigate('settings', undefined, { settingsTab: 'github', settingsProviderTab: 'bitbucket' })}
                        className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg gradient-accent text-white text-xs font-medium hover:opacity-90 transition-opacity flex-shrink-0 cursor-pointer"
                      >
                        Connect Bitbucket
                      </button>
                    </div>
                  ) : (
                    <>
                      <div className="flex p-1 bg-surface rounded-lg gap-1">
                        <button onClick={() => setBbTab('browse')} className={`flex-1 py-1.5 text-xs font-medium rounded-md transition-colors ${bbTab === 'browse' ? 'bg-accent text-white shadow-sm' : 'text-muted hover:text-foreground'}`}>Browse Bitbucket</button>
                        <button onClick={() => setBbTab('manual')} className={`flex-1 py-1.5 text-xs font-medium rounded-md transition-colors ${bbTab === 'manual' ? 'bg-accent text-white shadow-sm' : 'text-muted hover:text-foreground'}`}>Enter URL manually</button>
                      </div>
                      {bbTab === 'browse' && (
                        <div className="space-y-3">
                          <div className="flex gap-2">
                            <div className="relative flex-shrink-0">
                              <select value={bbSelectedOwner} onChange={e => { setBbSelectedOwner(e.target.value); setBbSearch(''); }}
                                className="appearance-none pl-3 pr-7 py-2.5 glass-light rounded-lg text-sm text-foreground outline-none border border-transparent focus:border-accent/30 bg-transparent cursor-pointer min-w-[150px]">
                                {bbUser && <option value={bbUser}>{bbUser} (personal)</option>}
                                {bbWorkspaces.map(w => <option key={w.slug} value={w.slug}>{w.name || w.slug}</option>)}
                              </select>
                              <ChevronRight className="absolute right-2 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-muted rotate-90 pointer-events-none" />
                            </div>
                            <div className="flex-1 flex items-center gap-2 glass-light rounded-lg px-3 py-2.5">
                              <Search className="w-3.5 h-3.5 text-muted flex-shrink-0" />
                              <input type="text" value={bbSearch} onChange={e => setBbSearch(e.target.value)} placeholder="Search repositories..." className="flex-1 bg-transparent text-sm text-foreground outline-none placeholder-muted" />
                              {bbSearch && <button onClick={() => setBbSearch('')} className="text-muted hover:text-foreground"><X className="w-3 h-3" /></button>}
                            </div>
                          </div>
                          <div className="rounded-lg border border-border overflow-hidden">
                            <div className="max-h-64 overflow-y-auto divide-y divide-border">
                              {bbLoading ? (
                                <div className="flex items-center justify-center gap-2 py-8 text-muted"><Loader2 className="w-4 h-4 animate-spin" /><span className="text-sm">Loading repositories...</span></div>
                              ) : bbRepos.length === 0 ? (
                                <div className="flex flex-col items-center justify-center py-8 text-muted gap-2"><Database className="w-7 h-7 opacity-30" /><p className="text-sm">{bbSearch ? 'No repositories match your search' : 'No repositories found'}</p></div>
                              ) : (
                                bbRepos.map(repo => {
                                  const isSelected = repoUrl === repo.htmlUrl;
                                  return (
                                    <button key={repo.slug} onClick={() => { setRepoUrl(repo.htmlUrl); setBranch(repo.mainBranch || 'main'); setBbSelectedRepoMeta({ workspace: repo.workspace, slug: repo.slug }); setBbBranchSearch(''); setConnected(true); }}
                                      className={`w-full px-4 py-3 text-left transition-colors hover:bg-surface-light ${isSelected ? 'bg-accent/10 border-l-2 border-l-accent' : 'bg-surface'}`}>
                                      <div className="flex items-center gap-2">
                                        <span className="text-sm font-medium text-foreground truncate flex-1">{repo.name}</span>
                                        <span className={`text-[10px] px-1.5 py-0.5 rounded-full ${repo.isPrivate ? 'bg-surface-light text-muted' : 'bg-success/10 text-success'}`}>{repo.isPrivate ? 'private' : 'public'}</span>
                                        {repo.language && <span className="text-[10px] text-muted">{repo.language}</span>}
                                        {isSelected && <Check className="w-3.5 h-3.5 text-accent flex-shrink-0" />}
                                      </div>
                                      {repo.description && <p className="text-[11px] text-muted truncate mt-0.5">{repo.description}</p>}
                                    </button>
                                  );
                                })
                              )}
                            </div>
                          </div>
                        </div>
                      )}
                      {bbTab === 'manual' && (
                        <div>
                          <label className="text-[11px] text-muted uppercase tracking-wider block mb-1.5">Repository URL</label>
                          <div className="flex items-center gap-2 glass-light rounded-lg px-4 py-3">
                            <Globe className="w-4 h-4 text-muted" />
                            <input type="text" value={repoUrl} onChange={e => { setRepoUrl(e.target.value); setConnected(false); }} placeholder="https://bitbucket.org/workspace/repository" className="flex-1 bg-transparent text-sm text-foreground outline-none placeholder-muted" />
                            {repoUrl && <button onClick={() => { setRepoUrl(''); setConnected(false); }} className="text-muted hover:text-foreground"><X className="w-3.5 h-3.5" /></button>}
                          </div>
                        </div>
                      )}
                    </>
                  )}
                </div>
              )}

              {/* Branch picker — real branches when provider connected, text fallback otherwise */}
              {repoUrl && !isLocalFolderSource && (() => {
                const activeBranches = selectedProvider === 'GitHub' ? ghBranches
                  : selectedProvider === 'GitLab' ? glBranches
                  : selectedProvider === 'Azure DevOps' ? azBranches
                  : bbBranches;
                const activeBranchesLoading = selectedProvider === 'GitHub' ? ghBranchesLoading
                  : selectedProvider === 'GitLab' ? glBranchesLoading
                  : selectedProvider === 'Azure DevOps' ? azBranchesLoading
                  : bbBranchesLoading;
                const activeBranchOpen = selectedProvider === 'GitHub' ? ghBranchOpen
                  : selectedProvider === 'GitLab' ? glBranchOpen
                  : selectedProvider === 'Azure DevOps' ? azBranchOpen
                  : bbBranchOpen;
                const setActiveBranchOpen = selectedProvider === 'GitHub' ? setGhBranchOpen
                  : selectedProvider === 'GitLab' ? setGlBranchOpen
                  : selectedProvider === 'Azure DevOps' ? setAzBranchOpen
                  : setBbBranchOpen;
                const activeBranchSearch = selectedProvider === 'GitHub' ? ghBranchSearch
                  : selectedProvider === 'GitLab' ? glBranchSearch
                  : selectedProvider === 'Azure DevOps' ? azBranchSearch
                  : bbBranchSearch;
                const setActiveBranchSearch = selectedProvider === 'GitHub' ? setGhBranchSearch
                  : selectedProvider === 'GitLab' ? setGlBranchSearch
                  : selectedProvider === 'Azure DevOps' ? setAzBranchSearch
                  : setBbBranchSearch;
                const activeConnected = selectedProvider === 'GitHub' ? ghConnected
                  : selectedProvider === 'GitLab' ? glConnected
                  : selectedProvider === 'Azure DevOps' ? azConnected
                  : bbConnected;
                return (
                  <div>
                    <label className="text-[11px] text-muted uppercase tracking-wider block mb-1.5">Branch</label>
                    {activeConnected && activeBranches.length > 0 ? (
                      <div className="relative">
                        <button type="button" onClick={() => setActiveBranchOpen(o => !o)}
                          className="w-full flex items-center gap-2 glass-light rounded-lg px-4 py-3 text-left">
                          <GitBranch className="w-4 h-4 text-muted flex-shrink-0" />
                          <span className="flex-1 text-sm text-foreground">{branch || 'Select branch...'}</span>
                          {activeBranchesLoading ? <Loader2 className="w-3.5 h-3.5 text-muted animate-spin" /> : <ChevronRight className="w-3.5 h-3.5 text-muted rotate-90" />}
                        </button>
                        {activeBranchOpen && (
                          <div className="absolute z-20 mt-1 w-full bg-surface border border-border rounded-lg shadow-lg overflow-hidden">
                            <div className="p-2 border-b border-border">
                              <input autoFocus type="text" value={activeBranchSearch} onChange={e => setActiveBranchSearch(e.target.value)} placeholder="Filter branches..."
                                className="w-full bg-surface-light rounded-md px-3 py-1.5 text-sm text-foreground outline-none placeholder-muted" />
                            </div>
                            <div className="max-h-48 overflow-y-auto">
                              {activeBranches.filter(b => !activeBranchSearch || b.toLowerCase().includes(activeBranchSearch.toLowerCase())).map(b => (
                                <button key={b} type="button" onClick={() => { setBranch(b); setActiveBranchOpen(false); setActiveBranchSearch(''); }}
                                  className={`w-full flex items-center gap-2 px-4 py-2 text-sm text-left hover:bg-surface-light transition-colors ${branch === b ? 'text-accent-light bg-accent/10' : 'text-foreground'}`}>
                                  <GitBranch className="w-3 h-3 text-muted flex-shrink-0" />
                                  {b}
                                  {branch === b && <Check className="w-3 h-3 text-accent ml-auto" />}
                                </button>
                              ))}
                            </div>
                          </div>
                        )}
                      </div>
                    ) : (
                      <div className="flex items-center gap-2 glass-light rounded-lg px-4 py-3">
                        <GitBranch className="w-4 h-4 text-muted" />
                        <input type="text" value={branch} onChange={e => setBranch(e.target.value)} placeholder="main" className="flex-1 bg-transparent text-sm text-foreground outline-none placeholder-muted" />
                        {activeBranchesLoading && <Loader2 className="w-3.5 h-3.5 text-muted animate-spin" />}
                      </div>
                    )}
                  </div>
                );
              })()}

              {/* Patterns + encoding */}
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="text-[11px] text-muted uppercase tracking-wider block mb-1.5">Include Patterns</label>
                  <input
                    type="text"
                    value={includePatterns}
                    onChange={e => setIncludePatterns(e.target.value)}
                    placeholder="**/*.cbl, **/*.cpy, **/*.jcl"
                    className="w-full glass-light rounded-lg px-4 py-2.5 text-sm text-foreground outline-none border border-transparent focus:border-accent/30 font-mono placeholder-muted"
                  />
                  <p className="text-[10px] text-muted mt-1.5 leading-relaxed">
                    Comma-separated glob patterns of files to translate.<br />
                    <span className="text-muted/70">{isLocalFolderSource ? 'Leave empty to include all uploaded files.' : 'Leave empty to include all files in the repository.'}</span>
                  </p>
                </div>
                <div>
                  <label className="text-[11px] text-muted uppercase tracking-wider block mb-1.5">Exclude Patterns</label>
                  <input
                    type="text"
                    value={excludePatterns}
                    onChange={e => setExcludePatterns(e.target.value)}
                    placeholder="**/vendor/**, **/node_modules/**"
                    className="w-full glass-light rounded-lg px-4 py-2.5 text-sm text-foreground outline-none border border-transparent focus:border-accent/30 font-mono placeholder-muted"
                  />
                  <p className="text-[10px] text-muted mt-1.5 leading-relaxed">
                    Folders or files to ignore during translation.<br />
                    <span className="text-muted/70">Leave empty to process everything.</span>
                  </p>
                </div>
              </div>
              <div>
                <label className="text-[11px] text-muted uppercase tracking-wider block mb-1.5">Source Encoding</label>
                <select value={encoding} onChange={e => setEncoding(e.target.value)} className="w-full glass-light rounded-lg px-4 py-2.5 text-sm text-foreground outline-none border border-transparent focus:border-accent/30">
                  <option value="UTF-8">UTF-8 (default)</option>
                  <option value="EBCDIC">EBCDIC (IBM Mainframe / COBOL)</option>
                  <option value="ASCII">ASCII</option>
                  <option value="UTF-16">UTF-16</option>
                  <option value="ISO-8859-1">ISO-8859-1 (Latin-1)</option>
                </select>
                <p className="text-[10px] text-muted mt-1.5 leading-relaxed">
                  Character encoding of the source files. IBM mainframe systems (COBOL, PL/I)
                  use <span className="font-mono text-foreground/70">EBCDIC</span> instead of UTF-8 —
                  choosing the wrong encoding will corrupt characters during translation.
                </p>
              </div>

              {/* Connect button — only for Git providers (not local folder) */}
              {!isLocalFolderSource && (!ghConnected || ghTab === 'manual' || selectedProvider !== 'GitHub') && (
                !connected ? (
                  <button
                    onClick={handleConnect}
                    disabled={connecting || !repoUrl}
                    className="w-full py-3 rounded-lg gradient-accent text-white text-sm font-semibold hover:opacity-90 transition-opacity flex items-center justify-center gap-2 cursor-pointer disabled:opacity-40"
                  >
                    {connecting ? <><Loader2 className="w-4 h-4 animate-spin" /> Connecting...</> : <><Zap className="w-4 h-4" /> Connect Repository</>}
                  </button>
                ) : (
                  <div className="flex items-center gap-3 p-3 rounded-lg bg-success/10 border border-success/20">
                    <CheckCircle2 className="w-5 h-5 text-success" />
                    <div>
                      <p className="text-sm font-medium text-success">Connected successfully</p>
                      <p className="text-[11px] text-muted">{repoUrl}</p>
                    </div>
                  </div>
                )
              )}
              {isLocalFolderSource && hasLocalFolder && (
                <div className="flex items-center gap-3 p-3 rounded-lg bg-success/10 border border-success/20">
                  <CheckCircle2 className="w-5 h-5 text-success" />
                  <div className="min-w-0">
                    <p className="text-sm font-medium text-success">Ready to continue</p>
                    <p className="text-[11px] text-muted truncate">{localFolderLabel} · {localFolderFiles.length} files</p>
                  </div>
                </div>
              )}
              {/* Auto-connected state for GitHub browse */}
              {ghConnected && ghTab === 'browse' && selectedProvider === 'GitHub' && connected && repoUrl && (
                <div className="flex items-center gap-3 p-3 rounded-lg bg-success/10 border border-success/20">
                  <CheckCircle2 className="w-5 h-5 text-success" />
                  <div className="min-w-0">
                    <p className="text-sm font-medium text-success">Repository connected</p>
                    <p className="text-[11px] text-muted truncate">{repoUrl} · branch: {branch}</p>
                  </div>
                </div>
              )}
            </div>
          )}

          {step === 4 && (
            <div className="space-y-5">
              <h3 className="text-base font-semibold text-foreground">Target Configuration</h3>

              {/* Code Style & Structure */}
              <div className="glass-light rounded-lg p-4 space-y-4">
                <h4 className="text-xs font-medium text-foreground uppercase tracking-wider">Structure & Conventions</h4>
                <div className="grid grid-cols-2 gap-3">
                  <div>
                    <label className="text-[10px] text-muted uppercase tracking-wider block mb-1">Naming Convention</label>
                    <select
                      value={namingConvention}
                      onChange={(e) => setNamingConvention(e.target.value)}
                      className="w-full bg-surface rounded-md px-3 py-2 text-xs text-foreground outline-none border border-transparent focus:border-accent/30"
                    >
                      <option value="preserve">Preserve original names</option>
                      <option value="camelCase">camelCase</option>
                      <option value="PascalCase">PascalCase</option>
                      <option value="snake_case">snake_case</option>
                      <option value="kebab-case">kebab-case</option>
                    </select>
                    <p className="text-[10px] text-muted mt-1 leading-snug">
                      {namingConvention === 'preserve' ? 'Keep the original identifier names from the source.' : `Rename identifiers to ${namingConvention} in the generated code.`}
                    </p>
                  </div>
                  <div>
                    <label className="text-[10px] text-muted uppercase tracking-wider block mb-1">Architecture Pattern</label>
                    <select
                      value={architecturePattern}
                      onChange={(e) => setArchitecturePattern(e.target.value)}
                      className="w-full bg-surface rounded-md px-3 py-2 text-xs text-foreground outline-none border border-transparent focus:border-accent/30"
                    >
                      {ARCH_PATTERNS.map(p => (
                        <option key={p.value} value={p.value}>{p.label}</option>
                      ))}
                    </select>
                  </div>
                  <div>
                    <label className="text-[10px] text-muted uppercase tracking-wider block mb-1">Translation Intent</label>
                    <select
                      value={intent}
                      onChange={(e) => setIntent(e.target.value)}
                      className="w-full bg-surface rounded-md px-3 py-2 text-xs text-foreground outline-none border border-transparent focus:border-accent/30"
                    >
                      <option value="">Auto (engine default)</option>
                      <option value="compat-strict">Compatibility-strict — faithful behaviour</option>
                      <option value="parity">Parity — balanced (recommended)</option>
                      <option value="modernize">Modernize — idiomatic refactor</option>
                    </select>
                    <p className="text-[10px] text-muted mt-1 leading-snug">
                      {intent === 'compat-strict' && 'Reproduce the source behaviour as literally as possible; minimise changes.'}
                      {intent === 'parity' && 'Match behaviour while producing clean, idiomatic target code.'}
                      {intent === 'modernize' && 'Refactor towards modern idioms and patterns where safe.'}
                      {intent === '' && 'Let the engine pick the translation intent automatically.'}
                    </p>
                  </div>
                  <div>
                    <label className="text-[10px] text-muted uppercase tracking-wider block mb-1">Project profile</label>
                    <select
                      value={projectProfile}
                      onChange={(e) => setProjectProfile(e.target.value as typeof projectProfile)}
                      className="w-full bg-surface rounded-md px-3 py-2 text-xs text-foreground outline-none border border-transparent focus:border-accent/30"
                    >
                      <option value="auto">Auto — detect from source (default)</option>
                      <option value="batch">Batch — JCL / ETL / file-to-file</option>
                      <option value="online">Online — CICS / screens / REST</option>
                      <option value="library">Library — callable subprograms / API</option>
                      <option value="utility">Utility — small standalone tool / CLI</option>
                      <option value="mixed">Mixed — heterogeneous; generic skeleton</option>
                    </select>
                    <p className="text-[10px] text-muted mt-1 leading-snug">
                      Override auto-detection of the app shape. Affects scaffolding and framework choices.
                    </p>
                  </div>
                </div>
              </div>

              {/* Dependencies & Build */}
              <div className="glass-light rounded-lg p-4 space-y-4">
                <h4 className="text-xs font-medium text-foreground uppercase tracking-wider">Dependencies & Build</h4>
                <div className="grid grid-cols-2 gap-3">
                  <div>
                    <label className="text-[10px] text-muted uppercase tracking-wider block mb-1">Package Manager</label>
                    <select
                      value={packageManager}
                      onChange={(e) => setPackageManager(e.target.value)}
                      className="w-full bg-surface rounded-md px-3 py-2 text-xs text-foreground outline-none border border-transparent focus:border-accent/30"
                    >
                      {availablePackageManagers.map(pm => (
                        <option key={pm} value={pm}>{pm}</option>
                      ))}
                    </select>
                  </div>
                  <div>
                    <label className="text-[10px] text-muted uppercase tracking-wider block mb-1">Testing Framework</label>
                    <select
                      value={testingFramework}
                      onChange={(e) => setTestingFramework(e.target.value)}
                      className="w-full bg-surface rounded-md px-3 py-2 text-xs text-foreground outline-none border border-transparent focus:border-accent/30"
                    >
                      {availableTestFrameworks.map(fw => (
                        <option key={fw} value={fw}>{fw}</option>
                      ))}
                    </select>
                  </div>
                </div>
              </div>

              {/* Generated Artifacts */}
              <div className="glass-light rounded-lg p-4 space-y-3">
                <h4 className="text-xs font-medium text-foreground uppercase tracking-wider">Generated Artifacts</h4>
                {[
                  { key: 'addTests', label: 'Unit & Integration Tests', desc: 'Generate test scaffolds (also requires Test Generation module in Modules step)' },
                  { key: 'addDocs', label: 'Documentation', desc: 'Generate API docs and code comments' },
                  { key: 'addLinter', label: 'Linting Rules', desc: 'Include linting configuration' },
                  { key: 'addFormatter', label: 'Code Formatter', desc: 'Include formatter configuration' },
                ].map(opt => (
                  <div key={opt.key} className="flex items-center justify-between bg-surface rounded-md p-3">
                    <div>
                      <p className="text-xs font-medium text-foreground">{opt.label}</p>
                      <p className="text-[10px] text-muted">{opt.desc}</p>
                    </div>
                    <div
                      onClick={() => {
                        if (opt.key === 'addTests') setAddTests(!addTests);
                        if (opt.key === 'addDocs') setAddDocs(!addDocs);
                        if (opt.key === 'addLinter') setAddLinter(!addLinter);
                        if (opt.key === 'addFormatter') setAddFormatter(!addFormatter);
                      }}
                      className={`w-9 h-4.5 rounded-full flex items-center transition-colors cursor-pointer ${
                        (opt.key === 'addTests' ? addTests : opt.key === 'addDocs' ? addDocs : opt.key === 'addLinter' ? addLinter : addFormatter)
                          ? 'bg-accent justify-end'
                          : 'bg-border justify-start'
                      }`}
                    >
                      <div className="w-3.5 h-3.5 rounded-full bg-white mx-0.5 shadow-sm" />
                    </div>
                  </div>
                ))}
              </div>
            </div>
          )}

          {step === 5 && (
            <div className="space-y-5">
              <h3 className="text-base font-semibold text-foreground">Translation Settings</h3>
              <p className="text-xs text-muted">
                Configure how the AI engine translates your source code to the target language. These settings affect accuracy, performance, and output quality.
              </p>

              {/* SECTION 2: Parity Score & Max Iterations */}
              <div className="glass-light rounded-lg p-4 space-y-4 border border-accent/20">
                <h4 className="text-xs font-medium text-foreground uppercase tracking-wider flex items-center gap-2">
                  <Zap className="w-4 h-4 text-accent-light" />
                  Parity Score &amp; Iteration Depth
                </h4>

                {/* Parity score explanation */}
                <div className="bg-accent/5 border border-accent/15 rounded-lg p-3 space-y-1.5">
                  <p className="text-xs font-semibold text-accent-light">What is the Parity Score?</p>
                  <p className="text-[11px] text-muted leading-relaxed">
                    The <span className="text-foreground font-medium">parity score</span> measures how closely the translated code matches the behaviour of the original. It combines semantic equivalence, test pass rate, and structural similarity into a single 0–100% score. A higher score means the migrated code is more faithful to the source.
                  </p>
                  <p className="text-[11px] text-muted leading-relaxed">
                    The engine runs multiple refinement passes — each iteration compares the output against the source, flags divergences, and re-translates problematic sections until the parity score stops improving or the iteration limit is reached.
                  </p>
                </div>

                {/* Max Iterations input */}
                <div className="space-y-2">
                  <div className="flex items-center justify-between">
                    <label className="text-[10px] text-muted uppercase tracking-wider">Max Iterations</label>
                    <span className="text-xs font-bold text-accent">{maxIterations}</span>
                  </div>
                  <input
                    type="range"
                    min={1}
                    max={10}
                    step={1}
                    value={maxIterations}
                    onChange={(e) => setMaxIterations(parseInt(e.target.value))}
                    className="w-full accent-accent"
                  />
                  <div className="flex justify-between text-[10px] text-muted">
                    <span>1 (fastest)</span>
                    <span>3 (recommended)</span>
                    <span>10 (safety cap)</span>
                  </div>
                  <div className={`flex items-start gap-2 rounded-md px-3 py-2 text-[11px] mt-1 ${
                    maxIterations <= 3 ? 'bg-success/8 text-success' :
                    maxIterations <= 6 ? 'bg-amber-500/8 text-amber-400' :
                    'bg-red-500/8 text-red-400'
                  }`}>
                    <span className="font-semibold shrink-0">
                      {maxIterations <= 3 ? 'Low cost' : maxIterations <= 6 ? 'Moderate cost' : 'High cost'}
                    </span>
                    <span>
                      {maxIterations <= 3
                        ? '— covers most migrations. The engine converges here in practice.'
                        : maxIterations <= 6
                        ? '— extra headroom for tricky code. Rarely all used — the engine auto-stops on plateau.'
                        : '— upper safety cap only. Past ~5, extra passes rarely improve parity and just cost more tokens.'}
                    </span>
                  </div>
                  <p className="text-[10px] text-muted">
                    This is an upper bound, not a target. The engine stops early the moment parity converges, and also stops once the parity score has plateaued for a couple of passes with a clean build — so higher values rarely change the result, they only raise the ceiling for hard cases.
                  </p>
                </div>
              </div>

              {/* Engine quality gate (Q1) */}
              <div className="glass-light rounded-lg p-4 space-y-3 border border-accent/15">
                <h4 className="text-xs font-medium text-foreground uppercase tracking-wider flex items-center gap-2">
                  <Shield className="w-4 h-4 text-accent-light" />
                  Engine quality gate
                </h4>
                <p className="text-[10px] text-muted leading-relaxed">
                  Optional hard gate on the engine <span className="text-foreground font-medium">quality index</span> (compile + parity + polish). If the run finishes below the threshold after max iterations,
                  the conversion is marked <span className="text-foreground">failed</span> so you can adjust inputs and retry.
                </p>
                <div>
                  <label htmlFor="wizard-quality-level" className="text-[10px] text-muted uppercase tracking-wider block mb-1.5">Minimum quality</label>
                  <select
                    id="wizard-quality-level"
                    value={qualityLevel}
                    onChange={(e) => setQualityLevel(Math.min(3, Math.max(0, Number.parseInt(e.target.value, 10) || 0)))}
                    className="w-full bg-surface rounded-md px-3 py-2 text-xs text-foreground outline-none border border-transparent focus:border-accent/30"
                  >
                    <option value={0}>Any result — gate off (default)</option>
                    <option value={1}>Must at least compile — Q1 (index ≥ 70)</option>
                    <option value={2}>Idiomatic — Q2 (index ≥ 85)</option>
                    <option value={3}>Production-ready — Q3 (index ≥ 92)</option>
                  </select>
                </div>
              </div>

              {(SHOW_ENGINE_MULTI_STAGE || SHOW_ENGINE_REPAIR) && (
                <div className="glass-light rounded-lg p-4 space-y-3 border border-accent/15">
                  <h4 className="text-xs font-medium text-foreground uppercase tracking-wider flex items-center gap-2">
                    <Settings className="w-4 h-4 text-accent-light" />
                    Engine pipeline <span className="text-[9px] font-semibold uppercase tracking-wider text-amber-400 border border-amber-400/40 bg-amber-500/10 rounded px-1.5 py-0.5 leading-none">Beta</span>
                  </h4>
                  {SHOW_ENGINE_MULTI_STAGE && (
                    <div className="flex items-center justify-between bg-surface rounded-md p-3">
                      <div>
                        <p className="text-xs font-medium text-foreground">Multi-stage translator</p>
                        <p className="text-[10px] text-muted mt-0.5" title="Structure → Bodies → Polish pipeline with per-stage cache.">
                          Enables the Structure → Bodies → Polish pipeline when your engine supports it. Off by default.
                        </p>
                      </div>
                      <div
                        onClick={() => setUseStages(!useStages)}
                        className={`w-9 h-4.5 rounded-full flex items-center transition-colors cursor-pointer shrink-0 ${
                          useStages ? 'bg-accent justify-end' : 'bg-border justify-start'
                        }`}
                      >
                        <div className="w-3.5 h-3.5 rounded-full bg-white mx-0.5 shadow-sm" />
                      </div>
                    </div>
                  )}
                  {SHOW_ENGINE_REPAIR && (
                    <div className="flex items-center justify-between bg-surface rounded-md p-3">
                      <div>
                        <p className="text-xs font-medium text-foreground">Auto-repair compile errors</p>
                        <p className="text-[10px] text-muted mt-0.5" title="Surgical patch loop on compile errors — does not regenerate the full file.">
                          When compile fails, the engine attempts surgical patches on each error. Off by default.
                        </p>
                      </div>
                      <div
                        onClick={() => setUseRepair(!useRepair)}
                        className={`w-9 h-4.5 rounded-full flex items-center transition-colors cursor-pointer shrink-0 ${
                          useRepair ? 'bg-accent justify-end' : 'bg-border justify-start'
                        }`}
                      >
                        <div className="w-3.5 h-3.5 rounded-full bg-white mx-0.5 shadow-sm" />
                      </div>
                    </div>
                  )}
                </div>
              )}

              {/* SECTION 3: Code Preservation Options */}
              <div className="glass-light rounded-lg p-4 space-y-3">
                <h4 className="text-xs font-medium text-foreground uppercase tracking-wider flex items-center gap-2">
                  <Shield className="w-4 h-4" />
                  Code Preservation
                </h4>

                <p className="text-[10px] text-muted">Business logic is always preserved verbatim by the engine — these control optional stylistic preservation.</p>
                {[
                  { key: 'preserveComments', label: 'Preserve Comments', desc: 'Keep original code comments in translated output', value: preserveComments, setter: setPreserveComments },
                  { key: 'preserveApiSignatures', label: 'Preserve API Signatures', desc: 'Keep public function/method signatures unchanged where the target language allows', value: preserveApiSignatures, setter: setPreserveApiSignatures },
                ].map(opt => (
                  <div key={opt.key} className="flex items-center justify-between bg-surface rounded-md p-3">
                    <div>
                      <p className="text-xs font-medium text-foreground">{opt.label}</p>
                      <p className="text-[10px] text-muted">{opt.desc}</p>
                    </div>
                    <div
                      onClick={() => opt.setter(!opt.value)}
                      className={`w-9 h-4.5 rounded-full flex items-center transition-colors cursor-pointer ${
                        opt.value ? 'bg-accent justify-end' : 'bg-border justify-start'
                      }`}
                    >
                      <div className="w-3.5 h-3.5 rounded-full bg-white mx-0.5 shadow-sm" />
                    </div>
                  </div>
                ))}
              </div>

              {/* SECTION 4: Error Handling */}
              <div className="glass-light rounded-lg p-4 space-y-4">
                <h4 className="text-xs font-medium text-foreground uppercase tracking-wider flex items-center gap-2">
                  <AlertTriangle className="w-4 h-4" />
                  Error Handling
                </h4>

                <div>
                  <label className="text-[10px] text-muted uppercase tracking-wider block mb-1">Strategy</label>
                  <select
                    value={errorHandling}
                    onChange={(e) => setErrorHandling(e.target.value)}
                    className="w-full bg-surface rounded-md px-3 py-2 text-xs text-foreground outline-none border border-transparent focus:border-accent/30"
                  >
                    {availableErrorOptions.map(o => (
                      <option key={o.value} value={o.value}>{o.label}</option>
                    ))}
                  </select>
                  <p className="text-[10px] text-muted mt-1">
                    How errors are modelled in the generated target code (options tuned to the target language).
                  </p>
                </div>
              </div>

              {/* SECTION 6: Custom Rules */}
              <div className="glass-light rounded-lg p-4 space-y-3">
                <h4 className="text-xs font-medium text-foreground uppercase tracking-wider flex items-center gap-2">
                  <Workflow className="w-4 h-4" />
                  Custom Translation Rules
                </h4>
                <textarea
                  value={customRules}
                  onChange={(e) => setCustomRules(e.target.value)}
                  placeholder="Enter custom translation rules (one per line)...
Example:
- Replace 'DB2' with 'PostgreSQL'
- Convert 'CICS' calls to REST API
- Preserve all variable names containing 'ID'"
                  rows={4}
                  className="w-full bg-surface rounded-md px-3 py-2 text-xs text-foreground outline-none border border-transparent focus:border-accent/30 transition-colors resize-none placeholder-muted font-mono"
                />
                <p className="text-[10px] text-muted">
                  Define specific translation rules for your project. Use one rule per line to guide the AI engine on special cases.
                </p>
              </div>

            </div>
          )}

          {step === 6 && (
            <div className="space-y-5">
              <h3 className="text-base font-semibold text-foreground">Environment Configuration</h3>

              {/* Toggle to enable/disable environment configuration */}
              <div className="flex items-center justify-between glass-light rounded-lg p-4">
                <div>
                  <p className="text-sm font-medium text-foreground">Configure Deployment Server</p>
                  <p className="text-[11px] text-muted">Enable to specify server characteristics and deployment settings</p>
                </div>
                <div
                  onClick={() => {
                    setEnableEnvironmentConfig(!enableEnvironmentConfig);
                    if (!enableEnvironmentConfig) {
                      // Auto-evaluate config when enabling
                      evaluateServerConfig();
                    }
                  }}
                  className={`w-12 h-6 rounded-full flex items-center transition-colors cursor-pointer ${
                    enableEnvironmentConfig ? 'bg-accent justify-end' : 'bg-border justify-start'
                  }`}
                >
                  <div className="w-5 h-5 rounded-full bg-white mx-0.5 shadow-sm" />
                </div>
              </div>

              {enableEnvironmentConfig && (
                <motion.div
                  initial={{ opacity: 0, y: 10 }}
                  animate={{ opacity: 1, y: 0 }}
                  className="space-y-4"
                >
                  {/* Server Configuration */}
                  <div className="glass-light rounded-lg p-4 space-y-4">
                    <h4 className="text-xs font-medium text-foreground uppercase tracking-wider">Server Specifications</h4>
                    <div className="grid grid-cols-3 gap-3">
                      <div>
                        <label className="text-[10px] text-muted uppercase tracking-wider block mb-1">CPU Cores</label>
                        <select
                          value={serverConfig.cpu}
                          onChange={(e) => {
                            setServerConfig({ ...serverConfig, cpu: e.target.value });
                            evaluateServerConfig();
                          }}
                          className="w-full bg-surface rounded-md px-3 py-2 text-xs text-foreground outline-none border border-transparent focus:border-accent/30"
                        >
                          <option value="1">1 vCPU</option>
                          <option value="2">2 vCPU</option>
                          <option value="4">4 vCPU</option>
                          <option value="8">8 vCPU</option>
                          <option value="16">16 vCPU</option>
                          <option value="32">32 vCPU</option>
                        </select>
                      </div>
                      <div>
                        <label className="text-[10px] text-muted uppercase tracking-wider block mb-1">Memory</label>
                        <select
                          value={serverConfig.memory}
                          onChange={(e) => {
                            setServerConfig({ ...serverConfig, memory: e.target.value });
                            evaluateServerConfig();
                          }}
                          className="w-full bg-surface rounded-md px-3 py-2 text-xs text-foreground outline-none border border-transparent focus:border-accent/30"
                        >
                          <option value="2">2 GB</option>
                          <option value="4">4 GB</option>
                          <option value="8">8 GB</option>
                          <option value="16">16 GB</option>
                          <option value="32">32 GB</option>
                          <option value="64">64 GB</option>
                          <option value="128">128 GB</option>
                        </select>
                      </div>
                      <div>
                        <label className="text-[10px] text-muted uppercase tracking-wider block mb-1">Storage</label>
                        <select
                          value={serverConfig.storage}
                          onChange={(e) => {
                            setServerConfig({ ...serverConfig, storage: e.target.value });
                            evaluateServerConfig();
                          }}
                          className="w-full bg-surface rounded-md px-3 py-2 text-xs text-foreground outline-none border border-transparent focus:border-accent/30"
                        >
                          <option value="20">20 GB SSD</option>
                          <option value="50">50 GB SSD</option>
                          <option value="100">100 GB SSD</option>
                          <option value="200">200 GB SSD</option>
                          <option value="500">500 GB SSD</option>
                          <option value="1000">1 TB SSD</option>
                        </select>
                      </div>
                    </div>
                    <div className="grid grid-cols-2 gap-3">
                      <div>
                        <label className="text-[10px] text-muted uppercase tracking-wider block mb-1">Operating System</label>
                        <select
                          value={serverConfig.os}
                          onChange={(e) => setServerConfig({ ...serverConfig, os: e.target.value })}
                          className="w-full bg-surface rounded-md px-3 py-2 text-xs text-foreground outline-none border border-transparent focus:border-accent/30"
                        >
                          <option value="ubuntu-22.04">Ubuntu 22.04 LTS</option>
                          <option value="ubuntu-20.04">Ubuntu 20.04 LTS</option>
                          <option value="debian-12">Debian 12 (Bookworm)</option>
                          <option value="centos-9">CentOS 9 Stream</option>
                          <option value="rhel-9">RHEL 9</option>
                          <option value="amazon-linux-2023">Amazon Linux 2023</option>
                        </select>
                      </div>
                      <div>
                        <label className="text-[10px] text-muted uppercase tracking-wider block mb-1">Region</label>
                        <select
                          value={serverConfig.region}
                          onChange={(e) => setServerConfig({ ...serverConfig, region: e.target.value })}
                          className="w-full bg-surface rounded-md px-3 py-2 text-xs text-foreground outline-none border border-transparent focus:border-accent/30"
                        >
                          <option value="eu-west-1">EU (Ireland)</option>
                          <option value="eu-central-1">EU (Frankfurt)</option>
                          <option value="us-east-1">US East (N. Virginia)</option>
                          <option value="us-west-2">US West (Oregon)</option>
                          <option value="ap-northeast-1">Asia Pacific (Tokyo)</option>
                          <option value="ap-southeast-1">Asia Pacific (Singapore)</option>
                        </select>
                      </div>
                    </div>
                  </div>

                  {/* System Feedback */}
                  {configFeedback && (
                    <div className={`glass-light rounded-lg p-4 border-l-4 ${
                      configFeedback === 'optimal' ? 'border-l-success' :
                      configFeedback === 'adequate' ? 'border-l-warning' :
                      configFeedback === 'insufficient' ? 'border-l-error' :
                      'border-l-info'
                    }`}>
                      <div className="flex items-start gap-3">
                        {configFeedback === 'optimal' && <CheckCircle2 className="w-5 h-5 text-success mt-0.5" />}
                        {configFeedback === 'adequate' && <AlertTriangle className="w-5 h-5 text-warning mt-0.5" />}
                        {configFeedback === 'insufficient' && <XCircle className="w-5 h-5 text-error mt-0.5" />}
                        {configFeedback === 'overprovisioned' && <Info className="w-5 h-5 text-info mt-0.5" />}
                        <div>
                          <p className="text-xs font-medium text-foreground capitalize">
                            {configFeedback === 'optimal' ? 'Optimal Configuration' :
                             configFeedback === 'adequate' ? 'Adequate Configuration' :
                             configFeedback === 'insufficient' ? 'Insufficient Resources' :
                             'Overprovisioned'}
                          </p>
                          <p className="text-[10px] text-muted mt-1">
                            {configFeedback === 'optimal' && 'This configuration provides good performance for most workloads with efficient resource utilization.'}
                            {configFeedback === 'adequate' && 'This configuration will work but may have performance limitations under high load. Consider upgrading if you expect significant traffic.'}
                            {configFeedback === 'insufficient' && 'This configuration may not meet performance requirements. We recommend at least 4 vCPU and 8GB RAM for production workloads.'}
                            {configFeedback === 'overprovisioned' && 'This configuration exceeds typical requirements. You may be able to reduce costs by scaling down resources.'}
                          </p>
                        </div>
                      </div>
                    </div>
                  )}

                  {/* SSH Key Upload */}
                  <div className="glass-light rounded-lg p-4 space-y-3">
                    <h4 className="text-xs font-medium text-foreground uppercase tracking-wider">Auto-Deploy Configuration</h4>
                    <div className="space-y-2">
                      <label className="text-[10px] text-muted uppercase tracking-wider block">SSH Public Key</label>
                      <div className="flex gap-2">
                        <input
                          type="file"
                          accept=".pub,.txt"
                          onChange={(e) => {
                            const file = e.target.files?.[0];
                            if (file) {
                              setSshKeyFileName(file.name);
                              const reader = new FileReader();
                              reader.onload = (e) => setSshKey(e.target?.result as string);
                              reader.readAsText(file);
                            }
                          }}
                          className="hidden"
                          id="ssh-key-upload"
                        />
                        <label
                          htmlFor="ssh-key-upload"
                          className="flex-1 bg-surface rounded-md px-3 py-2 text-xs text-muted border border-dashed border-border flex items-center justify-center cursor-pointer hover:border-accent/30 transition-colors"
                        >
                          {sshKeyFileName ? sshKeyFileName : 'Upload SSH public key (.pub)'}
                        </label>
                        {sshKeyFileName && (
                          <button
                            onClick={() => {
                              setSshKey('');
                              setSshKeyFileName('');
                            }}
                            className="px-3 py-2 rounded-md bg-surface text-xs text-foreground hover:bg-surface-light transition-colors"
                          >
                            Clear
                          </button>
                        )}
                      </div>
                      {sshKey && (
                        <div className="bg-surface rounded-md p-3">
                          <p className="text-[10px] text-muted mb-1">SSH Key Preview:</p>
                          <p className="text-[10px] text-foreground font-mono break-all">{sshKey.substring(0, 60)}...</p>
                        </div>
                      )}
                      <p className="text-[10px] text-muted">
                        Upload your SSH public key to enable automatic deployment to your server. The key will be added to the server's authorized_keys during deployment.
                      </p>
                    </div>
                  </div>
                </motion.div>
              )}
            </div>
          )}

          {step === 7 && (
            <div className="space-y-5">
              <h3 className="text-base font-semibold text-foreground">Database Configuration</h3>
              <p className="text-xs text-muted">
                Optional. Configure database migration if your source application uses a database. Upload the schema for accurate translation of embedded SQL and data access patterns.
              </p>

              {/* Optional toggle */}
              <div className="flex items-center justify-between glass-light rounded-lg p-4">
                <div>
                  <p className="text-sm font-medium text-foreground">Configure Database Migration</p>
                  <p className="text-[11px] text-muted">Enable to specify source/target database and migration strategy</p>
                </div>
                <div
                  onClick={() => setEnableDatabaseConfig(!enableDatabaseConfig)}
                  className={`w-12 h-6 rounded-full flex items-center transition-colors cursor-pointer ${
                    enableDatabaseConfig ? 'bg-accent justify-end' : 'bg-border justify-start'
                  }`}
                >
                  <div className="w-5 h-5 rounded-full bg-white mx-0.5 shadow-sm" />
                </div>
              </div>

              {enableDatabaseConfig && <>
              {/* SECTION 1: Source Database */}
              <div className="glass-light rounded-lg p-4 space-y-4">
                <h4 className="text-xs font-medium text-foreground uppercase tracking-wider flex items-center gap-2">
                  <Database className="w-4 h-4" />
                  Source Database (Original)
                </h4>
                
                <div className="grid grid-cols-2 gap-3">
                  <div>
                    <label className="text-[10px] text-muted uppercase tracking-wider block mb-1">Database Technology</label>
                    <select
                      value={sourceDatabase}
                      onChange={(e) => setSourceDatabase(e.target.value)}
                      className="w-full bg-surface rounded-md px-3 py-2 text-xs text-foreground outline-none border border-transparent focus:border-accent/30"
                    >
                      <option value="">Select source...</option>
                      <option value="db2">IBM DB2</option>
                      <option value="oracle">Oracle Database</option>
                      <option value="sqlserver">SQL Server</option>
                      <option value="mysql">MySQL</option>
                      <option value="postgresql">PostgreSQL</option>
                      <option value="sybase">Sybase ASE</option>
                      <option value="informix">IBM Informix</option>
                      <option value="adabas">ADABAS</option>
                      <option value="idms">IDMS</option>
                      <option value="vsam">VSAM/Flat Files</option>
                      <option value="cobol-files">COBOL Indexed Files</option>
                    </select>
                  </div>
                  <div>
                    <label className="text-[10px] text-muted uppercase tracking-wider block mb-1">Version (if known)</label>
                    <input
                      type="text"
                      value={sourceDbVersion}
                      onChange={(e) => setSourceDbVersion(e.target.value)}
                      placeholder="e.g., 11g, 2019, 12.1"
                      className="w-full bg-surface rounded-md px-3 py-2 text-xs text-foreground outline-none border border-transparent focus:border-accent/30"
                    />
                  </div>
                </div>

                {/* Schema Upload */}
                <div className="space-y-2">
                  <label className="text-[10px] text-muted uppercase tracking-wider block">Database Schema</label>
                  <div className="flex gap-2">
                    <input
                      type="file"
                      accept=".sql,.ddl,.json,.xml,.txt"
                      onChange={(e) => {
                        const file = e.target.files?.[0];
                        if (file) {
                          setSchemaFile(file);
                          setSchemaFileName(file.name);
                        }
                      }}
                      className="hidden"
                      id="schema-upload"
                    />
                    <label
                      htmlFor="schema-upload"
                      className="flex-1 bg-surface rounded-md px-3 py-2 text-xs text-muted border border-dashed border-border flex items-center justify-center cursor-pointer hover:border-accent/30 transition-colors"
                    >
                      {schemaFileName ? schemaFileName : 'Upload schema file (.sql, .ddl, .json, .xml)'}
                    </label>
                    {schemaFileName && (
                      <button
                        onClick={() => {
                          setSchemaFile(null);
                          setSchemaFileName('');
                        }}
                        className="px-3 py-2 rounded-md bg-surface text-xs text-foreground hover:bg-surface-light transition-colors"
                      >
                        Clear
                      </button>
                    )}
                  </div>
                  <p className="text-[10px] text-muted">
                    Upload your database schema (DDL, ERD, or JSON export) for accurate table structure translation. This helps the AI understand relationships and constraints.
                  </p>
                </div>
              </div>

              {/* SECTION 2: Target Database */}
              <div className="glass-light rounded-lg p-4 space-y-4">
                <h4 className="text-xs font-medium text-foreground uppercase tracking-wider flex items-center gap-2">
                  <Server className="w-4 h-4" />
                  Target Database (New)
                </h4>

                <div className="grid grid-cols-2 gap-3">
                  <div>
                    <label className="text-[10px] text-muted uppercase tracking-wider block mb-1">Target Technology</label>
                    <select
                      value={selectedDatabase}
                      onChange={(e) => setSelectedDatabase(e.target.value)}
                      className="w-full bg-surface rounded-md px-3 py-2 text-xs text-foreground outline-none border border-transparent focus:border-accent/30"
                    >
                      <option value="postgresql">PostgreSQL</option>
                      <option value="mysql">MySQL</option>
                      <option value="mariadb">MariaDB</option>
                      <option value="mongodb">MongoDB</option>
                      <option value="oracle">Oracle</option>
                      <option value="sqlserver">SQL Server</option>
                      <option value="cockroachdb">CockroachDB</option>
                      <option value="clickhouse">ClickHouse</option>
                      <option value="timescaledb">TimescaleDB</option>
                    </select>
                  </div>
                  <div>
                    <label className="text-[10px] text-muted uppercase tracking-wider block mb-1">Version</label>
                    <select
                      value={dbVersion}
                      onChange={(e) => setDbVersion(e.target.value)}
                      className="w-full bg-surface rounded-md px-3 py-2 text-xs text-foreground outline-none border border-transparent focus:border-accent/30"
                    >
                      {selectedDatabase === 'postgresql' && (
                        <>
                          <option value="16">PostgreSQL 16</option>
                          <option value="15">PostgreSQL 15</option>
                          <option value="14">PostgreSQL 14</option>
                          <option value="13">PostgreSQL 13</option>
                        </>
                      )}
                      {selectedDatabase === 'mysql' && (
                        <>
                          <option value="8.0">MySQL 8.0</option>
                          <option value="5.7">MySQL 5.7</option>
                        </>
                      )}
                      {selectedDatabase === 'mongodb' && (
                        <>
                          <option value="7.0">MongoDB 7.0</option>
                          <option value="6.0">MongoDB 6.0</option>
                          <option value="5.0">MongoDB 5.0</option>
                        </>
                      )}
                      {selectedDatabase === 'oracle' && (
                        <>
                          <option value="23c">Oracle 23c</option>
                          <option value="21c">Oracle 21c</option>
                          <option value="19c">Oracle 19c</option>
                        </>
                      )}
                      {selectedDatabase === 'sqlserver' && (
                        <>
                          <option value="2022">SQL Server 2022</option>
                          <option value="2019">SQL Server 2019</option>
                        </>
                      )}
                    </select>
                  </div>
                </div>
              </div>

              {/* SECTION 3: Migration Strategy */}
              <div className="glass-light rounded-lg p-4 space-y-4">
                <h4 className="text-xs font-medium text-foreground uppercase tracking-wider flex items-center gap-2">
                  <Workflow className="w-4 h-4" />
                  Migration Strategy
                </h4>

                <div>
                  <label className="text-[10px] text-muted uppercase tracking-wider block mb-1">Approach</label>
                  <select
                    value={migrationStrategy}
                    onChange={(e) => setMigrationStrategy(e.target.value)}
                    className="w-full bg-surface rounded-md px-3 py-2 text-xs text-foreground outline-none border border-transparent focus:border-accent/30"
                  >
                    <option value="full">Full Migration (Schema + Data)</option>
                    <option value="schema-only">Schema Only (Structure Translation)</option>
                    <option value="data-only">Data Only (Existing Schema)</option>
                    <option value="incremental">Incremental (Phased Migration)</option>
                  </select>
                  <p className="text-[10px] text-muted mt-1">
                    {migrationStrategy === 'full' && 'Migrate both database structure and all data. Recommended for complete system replacement.'}
                    {migrationStrategy === 'schema-only' && 'Translate only the database schema structure. Data migration handled separately.'}
                    {migrationStrategy === 'data-only' && 'Migrate data to an existing target schema structure.'}
                    {migrationStrategy === 'incremental' && 'Migrate in phases for minimal downtime. Requires careful planning.'}
                  </p>
                </div>

                {/* Data Preservation Options */}
                <div className="space-y-2">
                  <label className="text-[10px] text-muted uppercase tracking-wider block">Data Preservation</label>
                  {[
                    { key: 'preserveData', label: 'Preserve All Data', desc: 'Migrate all records from source to target', value: preserveData, setter: setPreserveData },
                    { key: 'preserveIndexes', label: 'Preserve Indexes', desc: 'Recreate indexes for query performance', value: preserveIndexes, setter: setPreserveIndexes },
                  ].map(opt => (
                    <div key={opt.key} className="flex items-center justify-between bg-surface rounded-md p-3">
                      <div>
                        <p className="text-xs font-medium text-foreground">{opt.label}</p>
                        <p className="text-[10px] text-muted">{opt.desc}</p>
                      </div>
                      <div
                        onClick={() => opt.setter(!opt.value)}
                        className={`w-9 h-4.5 rounded-full flex items-center transition-colors cursor-pointer ${
                          opt.value ? 'bg-accent justify-end' : 'bg-border justify-start'
                        }`}
                      >
                        <div className="w-3.5 h-3.5 rounded-full bg-white mx-0.5 shadow-sm" />
                      </div>
                    </div>
                  ))}
                </div>
              </div>

              {/* SECTION 4: Target Instance Configuration */}
              <div className="glass-light rounded-lg p-4 space-y-4">
                <h4 className="text-xs font-medium text-foreground uppercase tracking-wider flex items-center gap-2">
                  <Settings className="w-4 h-4" />
                  Target Instance Configuration
                </h4>

                <div className="grid grid-cols-2 gap-3">
                  <div>
                    <label className="text-[10px] text-muted uppercase tracking-wider block mb-1">Instance Size</label>
                    <select
                      value={dbInstanceSize}
                      onChange={(e) => setDbInstanceSize(e.target.value)}
                      className="w-full bg-surface rounded-md px-3 py-2 text-xs text-foreground outline-none border border-transparent focus:border-accent/30"
                    >
                      <option value="small">Small (2 vCPU, 8 GB RAM)</option>
                      <option value="medium">Medium (4 vCPU, 16 GB RAM)</option>
                      <option value="large">Large (8 vCPU, 32 GB RAM)</option>
                      <option value="xlarge">X-Large (16 vCPU, 64 GB RAM)</option>
                    </select>
                  </div>
                  <div>
                    <label className="text-[10px] text-muted uppercase tracking-wider block mb-1">Storage</label>
                    <select
                      value={dbStorage}
                      onChange={(e) => setDbStorage(e.target.value)}
                      className="w-full bg-surface rounded-md px-3 py-2 text-xs text-foreground outline-none border border-transparent focus:border-accent/30"
                    >
                      <option value="50">50 GB SSD</option>
                      <option value="100">100 GB SSD</option>
                      <option value="250">250 GB SSD</option>
                      <option value="500">500 GB SSD</option>
                      <option value="1000">1 TB SSD</option>
                    </select>
                  </div>
                </div>

                {/* Database Features */}
                <div className="space-y-2">
                  <label className="text-[10px] text-muted uppercase tracking-wider block">Features</label>
                  {[
                    { key: 'enableReadReplica', label: 'Read Replicas', desc: 'Add read replicas for scaling read operations', value: enableReadReplica, setter: setEnableReadReplica },
                    { key: 'enableBackup', label: 'Automated Backups', desc: 'Daily automated backups with point-in-time recovery', value: enableBackup, setter: setEnableBackup },
                    { key: 'enableEncryption', label: 'Encryption at Rest', desc: 'Encrypt all data at rest using AES-256', value: enableEncryption, setter: setEnableEncryption },
                    { key: 'enableConnectionPool', label: 'Connection Pooling', desc: 'Optimize database connection management', value: enableConnectionPool, setter: setEnableConnectionPool },
                  ].map(opt => (
                    <div key={opt.key} className="flex items-center justify-between bg-surface rounded-md p-3">
                      <div>
                        <p className="text-xs font-medium text-foreground">{opt.label}</p>
                        <p className="text-[10px] text-muted">{opt.desc}</p>
                      </div>
                      <div
                        onClick={() => opt.setter(!opt.value)}
                        className={`w-9 h-4.5 rounded-full flex items-center transition-colors cursor-pointer ${
                          opt.value ? 'bg-accent justify-end' : 'bg-border justify-start'
                        }`}
                      >
                        <div className="w-3.5 h-3.5 rounded-full bg-white mx-0.5 shadow-sm" />
                      </div>
                    </div>
                  ))}
                </div>
              </div>
              </>
              }
            </div>
          )}

          {step === 8 && (
            <div className="space-y-5">
              <h3 className="text-base font-semibold text-foreground">API & Integration Layer</h3>
              <p className="text-xs text-muted">
                Configure how the translated application exposes its logic. These settings determine the generated API structure and authentication scaffolding.
              </p>

              <div className="flex items-center justify-between glass-light rounded-lg p-4">
                <div>
                  <p className="text-sm font-medium text-foreground">Generate API Layer</p>
                  <p className="text-[11px] text-muted">Wrap translated business logic behind a clean API interface</p>
                </div>
                <div
                  onClick={() => setEnableApiGateway(!enableApiGateway)}
                  className={`w-10 h-5 rounded-full flex items-center transition-colors cursor-pointer ${
                    enableApiGateway ? 'bg-accent justify-end' : 'bg-border justify-start'
                  }`}
                >
                  <div className="w-4 h-4 rounded-full bg-white mx-0.5 shadow-sm" />
                </div>
              </div>

              {enableApiGateway && (
                <motion.div initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} className="space-y-4">
                  <div className="glass-light rounded-lg p-4 space-y-4">
                    <h4 className="text-xs font-medium text-foreground uppercase tracking-wider">API Style</h4>
                    <div className="grid grid-cols-2 gap-3">
                      <div>
                        <label className="text-[10px] text-muted uppercase tracking-wider block mb-1">Protocol</label>
                        <select
                          value={apiGatewayType}
                          onChange={(e) => setApiGatewayType(e.target.value)}
                          className="w-full bg-surface rounded-md px-3 py-2 text-xs text-foreground outline-none border border-transparent focus:border-accent/30"
                        >
                          <option value="rest">REST</option>
                          <option value="graphql">GraphQL</option>
                          <option value="grpc">gRPC</option>
                          <option value="hybrid">REST + GraphQL</option>
                        </select>
                        <p className="text-[10px] text-muted mt-1">Shapes the generated endpoint structure and client contracts.</p>
                      </div>
                      <div>
                        <label className="text-[10px] text-muted uppercase tracking-wider block mb-1">Authentication</label>
                        <select
                          value={apiGatewayAuth}
                          onChange={(e) => setApiGatewayAuth(e.target.value)}
                          className="w-full bg-surface rounded-md px-3 py-2 text-xs text-foreground outline-none border border-transparent focus:border-accent/30"
                        >
                          <option value="none">None / Public</option>
                          <option value="jwt">JWT Bearer</option>
                          <option value="oauth2">OAuth 2.0</option>
                          <option value="apikey">API Key</option>
                          <option value="mutual-tls">Mutual TLS</option>
                        </select>
                        <p className="text-[10px] text-muted mt-1">Authentication scaffolding added to generated endpoints.</p>
                      </div>
                    </div>
                  </div>

                  <div className="glass-light rounded-lg p-4 space-y-3">
                    <h4 className="text-xs font-medium text-foreground uppercase tracking-wider">Generated Features</h4>
                    {[
                      { key: 'enableGraphQL', label: 'GraphQL Schema', desc: 'Generate GraphQL types and resolvers alongside REST endpoints', value: enableGraphQL, setter: setEnableGraphQL },
                      { key: 'enableOpenAPISpec', label: 'OpenAPI Specification', desc: 'Generate OpenAPI/Swagger docs for all translated endpoints', value: enableOpenAPISpec, setter: setEnableOpenAPISpec },
                    ].map(opt => (
                      <div key={opt.key} className="flex items-center justify-between bg-surface rounded-md p-3">
                        <div>
                          <p className="text-xs font-medium text-foreground">{opt.label}</p>
                          <p className="text-[10px] text-muted">{opt.desc}</p>
                        </div>
                        <div
                          onClick={() => opt.setter(!opt.value)}
                          className={`w-9 h-4.5 rounded-full flex items-center transition-colors cursor-pointer ${
                            opt.value ? 'bg-accent justify-end' : 'bg-border justify-start'
                          }`}
                        >
                          <div className="w-3.5 h-3.5 rounded-full bg-white mx-0.5 shadow-sm" />
                        </div>
                      </div>
                    ))}
                  </div>
                </motion.div>
              )}
            </div>
          )}

          {step === 9 && (
            <div className="space-y-5">
              <h3 className="text-base font-semibold text-foreground">Monitoring & Observability</h3>
              <p className="text-xs text-muted">
                Select monitoring tools to generate configuration files and instrumentation code alongside the translated application.
              </p>
              <div className="glass-light rounded-lg p-4 space-y-3">
                <h4 className="text-xs font-medium text-foreground uppercase tracking-wider">Generate Monitoring Config For</h4>
                {[
                  { key: 'enablePrometheus', label: 'Prometheus + Grafana', desc: 'Generate metrics exposition (prometheus.yml, Grafana dashboard JSON)', value: enablePrometheus, setter: setEnablePrometheus },
                  { key: 'enableJaeger', label: 'Distributed Tracing', desc: 'Instrument code with OpenTelemetry spans (Jaeger / Zipkin compatible)', value: enableJaeger, setter: setEnableJaeger },
                  { key: 'enableELK', label: 'Structured Logging', desc: 'Add structured log output (ELK / OpenSearch / Loki compatible)', value: enableELK, setter: setEnableELK },
                ].map(opt => (
                  <div key={opt.key} className="flex items-center justify-between bg-surface rounded-md p-3">
                    <div>
                      <p className="text-xs font-medium text-foreground">{opt.label}</p>
                      <p className="text-[10px] text-muted">{opt.desc}</p>
                    </div>
                    <div
                      onClick={() => opt.setter(!opt.value)}
                      className={`w-9 h-4.5 rounded-full flex items-center transition-colors cursor-pointer ${
                        opt.value ? 'bg-accent justify-end' : 'bg-border justify-start'
                      }`}
                    >
                      <div className="w-3.5 h-3.5 rounded-full bg-white mx-0.5 shadow-sm" />
                    </div>
                  </div>
                ))}
              </div>
            </div>
          )}

          {step === 10 && (
            <div className="space-y-5">
              <h3 className="text-base font-semibold text-foreground">Team & Permissions</h3>
              <div className="space-y-2">
                {selectedTeam.length > 0 ? selectedTeam.map((name: string) => (
                  <div key={name} className="glass-light rounded-lg p-4 flex items-center gap-4">
                    <div className="w-10 h-10 rounded-full bg-surface-light flex items-center justify-center text-xs font-bold text-muted border border-border">
                      {name.split(' ').map((w: string) => w[0]).join('').toUpperCase().slice(0, 2)}
                    </div>
                    <div className="flex-1">
                      <p className="text-sm font-medium text-foreground">{name}</p>
                      <p className="text-[11px] text-muted">{teamRoles[name] || 'viewer'}</p>
                    </div>
                    <select
                      value={teamRoles[name] || 'viewer'}
                      onChange={(e) => setTeamRoles(prev => ({ ...prev, [name]: e.target.value }))}
                      className="glass-light rounded-lg px-3 py-2 text-xs text-foreground outline-none border border-transparent focus:border-accent/30"
                    >
                      <option value="admin">Admin</option>
                      <option value="editor">Editor</option>
                      <option value="reviewer">Reviewer</option>
                      <option value="viewer">Viewer</option>
                    </select>
                    <button
                      onClick={() => toggleTeam(name)}
                      className="p-2 rounded-lg cursor-pointer transition-colors bg-accent/15 text-accent-light"
                    >
                      <X className="w-4 h-4" />
                    </button>
                  </div>
                )) : (
                  <div className="text-center py-6 text-sm text-muted">
                    <Users className="w-8 h-8 mx-auto mb-2 opacity-40" />
                    <p>No team members added yet</p>
                  </div>
                )}
                <button
                  type="button"
                  onClick={openAddTeamModal}
                  className="w-full flex items-center justify-center gap-2 px-4 py-2.5 rounded-lg border border-dashed border-border text-xs text-muted hover:text-foreground hover:border-accent/30 cursor-pointer transition-all"
                >
                  <UserPlus className="w-4 h-4" /> Add Team Member
                </button>
              </div>
              <div className="glass-light rounded-lg p-4">
                <p className="text-xs text-muted mb-2">Permission Levels:</p>
                <div className="grid grid-cols-4 gap-2 text-[10px]">
                  <div><span className="font-medium text-foreground">Admin:</span> Full access</div>
                  <div><span className="font-medium text-foreground">Editor:</span> Edit config</div>
                  <div><span className="font-medium text-foreground">Reviewer:</span> Review only</div>
                  <div><span className="font-medium text-foreground">Viewer:</span> Read only</div>
                </div>
              </div>
            </div>
          )}

          {step === 11 && (
            <div className="space-y-5">
              <h3 className="text-base font-semibold text-foreground">Deployment Configuration</h3>
              <p className="text-xs text-muted">
                Optionally configure CI/CD and deployment targets. Scriba will generate the corresponding pipeline and infra files only if enabled.
              </p>

              {/* Optional enable toggle */}
              <div
                onClick={() => setEnableDeploymentConfig(!enableDeploymentConfig)}
                className="flex items-center justify-between glass-light rounded-lg p-4 cursor-pointer hover:border-accent/30 border border-transparent transition-colors"
              >
                <div>
                  <p className="text-sm font-medium text-foreground">Enable Deployment Configuration</p>
                  <p className="text-[11px] text-muted">Generate CI/CD pipeline, Dockerfile, and infrastructure manifests</p>
                </div>
                <div className={`w-10 h-5 rounded-full flex items-center transition-colors ${
                  enableDeploymentConfig ? 'bg-accent justify-end' : 'bg-border justify-start'
                }`}>
                  <div className="w-4 h-4 rounded-full bg-white mx-0.5 shadow-sm" />
                </div>
              </div>

              {enableDeploymentConfig && (
              <>
              {/* SECTION 1: CI/CD Platform */}
              <div className="glass-light rounded-lg p-4 space-y-4">
                <h4 className="text-xs font-medium text-foreground uppercase tracking-wider flex items-center gap-2">
                  <Workflow className="w-4 h-4" />
                  CI/CD Platform
                </h4>
                
                <div className="grid grid-cols-3 gap-3">
                  {ciCDPlatforms.map(p => (
                    <button
                      key={p.id}
                      onClick={() => setSelectedCI(p.id)}
                      className={`p-3 rounded-md border text-center transition-all cursor-pointer ${
                        selectedCI === p.id
                          ? 'border-accent/50 bg-accent/10'
                          : 'border-border bg-surface hover:border-accent/30'
                      }`}
                    >
                      <span className="text-xl block mb-1">{p.icon}</span>
                      <p className="text-xs font-medium text-foreground">{p.name}</p>
                    </button>
                  ))}
                </div>
                <p className="text-[10px] text-muted">
                  Select the CI/CD platform for automated build, test, and deployment pipelines.
                </p>
              </div>

              {/* SECTION 2: Infrastructure & Environment */}
              <div className="glass-light rounded-lg p-4 space-y-4">
                <h4 className="text-xs font-medium text-foreground uppercase tracking-wider flex items-center gap-2">
                  <Server className="w-4 h-4" />
                  Target Infrastructure
                </h4>
                <p className="text-[10px] text-muted">Determines the generated Dockerfile, Kubernetes manifests, and CI pipeline syntax.</p>

                <div className="grid grid-cols-2 gap-3">
                  <div>
                    <label className="text-[10px] text-muted uppercase tracking-wider block mb-1">Deployment Target</label>
                    <select
                      value={infrastructure}
                      onChange={(e) => setInfrastructure(e.target.value)}
                      className="w-full bg-surface rounded-md px-3 py-2 text-xs text-foreground outline-none border border-transparent focus:border-accent/30"
                    >
                      <option value="kubernetes">Kubernetes</option>
                      <option value="docker">Docker Compose</option>
                      <option value="ecs">AWS ECS</option>
                      <option value="gke">Google Cloud Run</option>
                      <option value="azure">Azure App Service</option>
                      <option value="vercel">Vercel</option>
                      <option value="netlify">Netlify</option>
                    </select>
                  </div>
                  <div>
                    <label className="text-[10px] text-muted uppercase tracking-wider block mb-1">First Deploy Environment</label>
                    <select
                      value={deployEnvironment}
                      onChange={(e) => setDeployEnvironment(e.target.value)}
                      className="w-full bg-surface rounded-md px-3 py-2 text-xs text-foreground outline-none border border-transparent focus:border-accent/30"
                    >
                      <option value="development">Development</option>
                      <option value="staging">Staging</option>
                      <option value="production">Production</option>
                    </select>
                  </div>
                </div>
              </div>

              {/* SECTION 3: Build Configuration */}
              <div className="glass-light rounded-lg p-4 space-y-4">
                <h4 className="text-xs font-medium text-foreground uppercase tracking-wider flex items-center gap-2">
                  <Settings className="w-4 h-4" />
                  CI Pipeline Quality Gates
                </h4>
                <p className="text-[10px] text-muted">Steps added to the generated CI pipeline file.</p>

                <div className="space-y-2">
                  {[
                    { key: 'enableBuildTests', label: 'Run Test Suite', desc: 'Execute generated tests in CI before merging', value: enableBuildTests, setter: setEnableBuildTests },
                    { key: 'enableLinting', label: 'Linting & Static Analysis', desc: 'Run linter on translated code as a CI gate', value: enableLinting, setter: setEnableLinting },
                  ].map(opt => (
                    <div key={opt.key} className="flex items-center justify-between bg-surface rounded-md p-3">
                      <div>
                        <p className="text-xs font-medium text-foreground">{opt.label}</p>
                        <p className="text-[10px] text-muted">{opt.desc}</p>
                      </div>
                      <div
                        onClick={() => opt.setter(!opt.value)}
                        className={`w-9 h-4.5 rounded-full flex items-center transition-colors cursor-pointer ${
                          opt.value ? 'bg-accent justify-end' : 'bg-border justify-start'
                        }`}
                      >
                        <div className="w-3.5 h-3.5 rounded-full bg-white mx-0.5 shadow-sm" />
                      </div>
                    </div>
                  ))}
                </div>
              </div>
              </>
              )}
            </div>
          )}

          {step === 12 && (
            <div className="space-y-5">
              <h3 className="text-base font-semibold text-foreground">Notification Settings</h3>
              <div className="grid grid-cols-3 gap-2">
                {[
                  { key: 'email', label: 'Email', icon: '📧' },
                  { key: 'slack', label: 'Slack', icon: '💬' },
                  { key: 'teams', label: 'Microsoft Teams', icon: '👥' },
                  { key: 'webhook', label: 'Webhook', icon: '🔗' },
                  { key: 'sms', label: 'SMS', icon: '📱' },
                ].map(c => (
                  <button
                    key={c.key}
                    onClick={() => toggleChannel(c.key)}
                    className={`p-3 rounded-lg border text-center transition-all cursor-pointer ${
                      notifyChannels.includes(c.key)
                        ? 'border-accent/50 bg-accent/10'
                        : 'border-border bg-surface hover:border-accent/30'
                    }`}
                  >
                    <span className="text-xl block mb-1">{c.icon}</span>
                    <p className="text-xs font-medium text-foreground">{c.label}</p>
                  </button>
                ))}
              </div>
              <div className="space-y-3">
                {[
                  { key: 'notifyOnComplete', label: 'Conversion Completed', desc: 'Notify when migration finishes successfully' },
                  { key: 'notifyOnWarning', label: 'Warnings Detected', desc: 'Notify when warnings are found during conversion' },
                  { key: 'notifyOnFailure', label: 'Conversion Failed', desc: 'Notify immediately if conversion fails' },
                ].map(opt => (
                  <div key={opt.key} className="flex items-center justify-between glass-light rounded-lg p-4">
                    <div>
                      <p className="text-sm font-medium text-foreground">{opt.label}</p>
                      <p className="text-[11px] text-muted">{opt.desc}</p>
                    </div>
                    <div
                      onClick={() => {
                        if (opt.key === 'notifyOnComplete') setNotifyOnComplete(!notifyOnComplete);
                        if (opt.key === 'notifyOnWarning') setNotifyOnWarning(!notifyOnWarning);
                        if (opt.key === 'notifyOnFailure') setNotifyOnFailure(!notifyOnFailure);
                      }}
                      className={`w-10 h-5 rounded-full flex items-center transition-colors cursor-pointer ${
                        (opt.key === 'notifyOnComplete' ? notifyOnComplete : opt.key === 'notifyOnWarning' ? notifyOnWarning : notifyOnFailure)
                          ? 'bg-accent justify-end'
                          : 'bg-border justify-start'
                      }`}
                    >
                      <div className="w-4 h-4 rounded-full bg-white mx-0.5 shadow-sm" />
                    </div>
                  </div>
                ))}
              </div>
            </div>
          )}

          {step === 13 && (
            <div className="space-y-5">
              <h3 className="text-base font-semibold text-foreground">Compliance & Security</h3>
              <p className="text-xs text-muted">
                Select compliance frameworks and security checks. The translation engine uses these to flag risky patterns (e.g., hardcoded secrets, unencrypted data flows) in the generated code.
              </p>
              <div className="glass-light rounded-lg p-4 space-y-3">
                <h4 className="text-xs font-medium text-foreground uppercase tracking-wider">Applicable Compliance Standards</h4>
                <div className="grid grid-cols-3 gap-2">
                  {complianceStandards.map(s => {
                    const isNoneActive = selectedCompliance.includes('none');
                    const isSelected = selectedCompliance.includes(s.id);
                    const isTierAllowed = s.id === 'none' || capabilities.complianceOptions.includes(s.id);
                    const isDisabled = (isNoneActive && s.id !== 'none') || !isTierAllowed;
                    return (
                    <button
                      key={s.id}
                      onClick={() => toggleCompliance(s.id)}
                      disabled={isDisabled}
                      className={`p-3 rounded-lg border text-left transition-all ${
                        isDisabled
                          ? 'border-border bg-surface opacity-35 cursor-not-allowed'
                          : isSelected
                            ? 'border-accent/50 bg-accent/10 cursor-pointer'
                            : 'border-border bg-surface hover:border-accent/30 cursor-pointer'
                      }`}
                    >
                      <p className="text-sm font-medium text-foreground">{s.name}</p>
                      <p className="text-[10px] text-muted mt-0.5">{s.desc}</p>
                      {!isTierAllowed && <p className="text-[10px] text-accent-light mt-1">Available on a higher plan</p>}
                    </button>
                    );
                  })}
                </div>
                <p className="text-[10px] text-muted">
                  Your current plan: <span className="capitalize text-foreground">{capabilities.tier}</span>.
                  {capabilities.hasSoc2Iso27001 || capabilities.hasEuAiAct ? ' Professional and enterprise compliance options are enabled.' : ' Upgrade for SOC 2 / ISO 27001 and EU AI Act frameworks.'}
                </p>
              </div>
              <div className="glass-light rounded-lg p-4 space-y-3">
                <h4 className="text-xs font-medium text-foreground uppercase tracking-wider">Security Scanning in CI</h4>
                <p className="text-[10px] text-muted">Include these scanning steps in the generated CI pipeline.</p>
                {[
                  { key: 'enableVulnerabilityScan', label: 'Dependency Vulnerability Scan', desc: 'Check third-party dependencies against CVE databases (OWASP, Snyk)', value: enableVulnerabilityScan, setter: setEnableVulnerabilityScan },
                  { key: 'enableSAST', label: 'Static Code Analysis (SAST)', desc: 'Scan generated code for security antipatterns before deployment', value: enableSAST, setter: setEnableSAST },
                ].map(opt => (
                  <div key={opt.key} className="flex items-center justify-between bg-surface rounded-md p-3">
                    <div>
                      <p className="text-xs font-medium text-foreground">{opt.label}</p>
                      <p className="text-[10px] text-muted">{opt.desc}</p>
                    </div>
                    <div
                      onClick={() => opt.setter(!opt.value)}
                      className={`w-9 h-4.5 rounded-full flex items-center transition-colors cursor-pointer ${
                        opt.value ? 'bg-accent justify-end' : 'bg-border justify-start'
                      }`}
                    >
                      <div className="w-3.5 h-3.5 rounded-full bg-white mx-0.5 shadow-sm" />
                    </div>
                  </div>
                ))}
              </div>
            </div>
          )}

          {step === 14 && (
            <div className="space-y-5">
              <h3 className="text-base font-semibold text-foreground">Pipeline Modules</h3>
              <p className="text-xs text-muted">
                Choose which post-translation stages to include in this migration run. All modules are enabled by default.
                Disabling a module skips that stage and excludes it from the final report.
              </p>

              <div className="glass-light rounded-lg p-4 space-y-3">
                <h4 className="text-xs font-medium text-foreground uppercase tracking-wider">Post-Translation Stages</h4>
                {PIPELINE_PLUGINS.map(plugin => {
                  const enabled = enabledPlugins.includes(plugin.id);
                  return (
                    <div key={plugin.id} className="flex items-center justify-between bg-surface rounded-md p-3">
                      <div>
                        <p className="text-xs font-medium text-foreground">{plugin.name}</p>
                        <p className="text-[10px] text-muted">{plugin.description}</p>
                      </div>
                      <div
                        onClick={() =>
                          setEnabledPlugins(prev =>
                            enabled ? prev.filter(id => id !== plugin.id) : [...prev, plugin.id],
                          )
                        }
                        className={`w-9 h-4.5 rounded-full flex items-center transition-colors cursor-pointer shrink-0 ${
                          enabled ? 'bg-accent justify-end' : 'bg-border justify-start'
                        }`}
                      >
                        <div className="w-3.5 h-3.5 rounded-full bg-white mx-0.5 shadow-sm" />
                      </div>
                    </div>
                  );
                })}
              </div>

              {enabledPlugins.length < PIPELINE_PLUGINS.length && (
                <div className="flex items-start gap-2 rounded-md px-3 py-2.5 text-[11px] bg-amber-500/8 text-amber-400">
                  <AlertTriangle className="w-3.5 h-3.5 shrink-0 mt-0.5" />
                  <span>
                    {PIPELINE_PLUGINS.length - enabledPlugins.length} module
                    {PIPELINE_PLUGINS.length - enabledPlugins.length > 1 ? 's' : ''} disabled — skipped stages will not
                    appear in the final report.
                  </span>
                </div>
              )}
            </div>
          )}

          {step === 15 && (
            <div className="space-y-4">
              <h3 className="text-base font-semibold text-foreground">Review & Create</h3>
              <p className="text-xs text-muted">
                Review your migration project configuration before creating it.
              </p>

              {/* Conversion Info */}
              <div className="glass-light rounded-lg p-4">
                <p className="text-[10px] text-muted uppercase tracking-wider mb-3">Conversion Information</p>
                <div className="grid grid-cols-3 gap-3 text-xs">
                  <div><span className="text-muted">Name:</span> {projectName}</div>
                  <div><span className="text-muted">Domain:</span> {domains.find(d => d.id === selectedDomain)?.name}</div>
                  <div><span className="text-muted">Priority:</span> {priorities.find(p => p.id === selectedPriority)?.name}</div>
                  {deadline && <div><span className="text-muted">Deadline:</span> {deadline}</div>}
                  {projectOwner && <div><span className="text-muted">Owner:</span> {projectOwner}</div>}
                  {projectCode && <div><span className="text-muted">Code:</span> {projectCode}</div>}
                  {businessUnit && <div><span className="text-muted">Business Unit:</span> {businessUnit}</div>}
                  {legacySystem && <div><span className="text-muted">Legacy System:</span> {legacySystem}</div>}
                  {targetSystem && <div><span className="text-muted">Target System:</span> {targetSystem}</div>}
                </div>
              </div>

              {/* Languages */}
              <div className="glass-light rounded-lg p-4">
                <p className="text-[10px] text-muted uppercase tracking-wider mb-3">Language Migration</p>
                <div className="grid grid-cols-3 gap-3 text-xs">
                  <div><span className="text-muted">Source:</span> {sourceLanguages.find(l => l.id === selectedSource)?.name} ({sourceVersion})</div>
                  {sourceFramework && <div><span className="text-muted">Source Framework:</span> {sourceFramework}</div>}
                  <div><span className="text-muted">Target:</span> {targetLanguages.find(l => l.id === selectedTarget)?.name} ({targetVersion})</div>
                  <div><span className="text-muted">Build Tool:</span> {targetBuild || 'N/A'}</div>
                </div>
              </div>

              {/* Repository */}
              <div className="glass-light rounded-lg p-4">
                <p className="text-[10px] text-muted uppercase tracking-wider mb-3">Repository</p>
                <div className="grid grid-cols-3 gap-3 text-xs">
                  <div><span className="text-muted">Provider:</span> {selectedProvider}</div>
                  {isLocalFolderSource ? (
                    <div className="col-span-2"><span className="text-muted">Folder:</span> {localFolderLabel || '—'} ({localFolderFiles.length} files)</div>
                  ) : (
                    <>
                      <div><span className="text-muted">URL:</span> {repoUrl || '—'}</div>
                      <div><span className="text-muted">Branch:</span> {branch}</div>
                    </>
                  )}
                  {!isLocalFolderSource && <div><span className="text-muted">Auth Method:</span> {authMethod}</div>}
                  <div><span className="text-muted">Encoding:</span> {encoding}</div>
                </div>
              </div>

              {/* Target Configuration */}
              <div className="glass-light rounded-lg p-4">
                <p className="text-[10px] text-muted uppercase tracking-wider mb-3">Target Configuration</p>
                <div className="grid grid-cols-3 gap-3 text-xs">
                  <div><span className="text-muted">Naming:</span> {namingConvention}</div>
                  <div><span className="text-muted">Intent:</span> {intent || 'Auto'}</div>
                  <div><span className="text-muted">Architecture:</span> {architecturePattern}</div>
                  <div><span className="text-muted">Package Manager:</span> {packageManager}</div>
                  <div><span className="text-muted">Testing:</span> {testingFramework}</div>
                  <div><span className="text-muted">Tests:</span> {addTests && enabledPlugins.includes('test-generation') ? 'Yes' : 'No'}{addTests && !enabledPlugins.includes('test-generation') ? ' (module off)' : ''}</div>
                  <div><span className="text-muted">Docs:</span> {addDocs ? 'Yes' : 'No'}</div>
                  <div><span className="text-muted">Docker:</span> {addDocker ? 'Yes' : 'No'}</div>
                  <div><span className="text-muted">CI/CD:</span> {addCI ? 'Yes' : 'No'}</div>
                </div>
              </div>

              {/* Translation Settings */}
              <div className="glass-light rounded-lg p-4">
                <p className="text-[10px] text-muted uppercase tracking-wider mb-3">Translation Settings</p>
                <div className="grid grid-cols-3 gap-3 text-xs">
                  <div><span className="text-muted">Quality gate:</span>{' '}
                    {qualityLevel <= 0 ? 'Off'
                      : qualityLevel === 1 ? 'Compile (Q1)'
                      : qualityLevel === 2 ? 'Idiomatic (Q2)'
                      : 'Production (Q3)'}
                  </div>
                  {SHOW_ENGINE_MULTI_STAGE && (
                    <div><span className="text-muted">Multi-stage:</span> {useStages ? 'On' : 'Off'}</div>
                  )}
                  {SHOW_ENGINE_REPAIR && (
                    <div><span className="text-muted">Auto-repair:</span> {useRepair ? 'On' : 'Off'}</div>
                  )}
                  <div><span className="text-muted">Max iterations:</span> {maxIterations}</div>
                  <div><span className="text-muted">Error Handling:</span> {errorHandling}</div>
                  <div><span className="text-muted">Preserve Comments:</span> {preserveComments ? 'Yes' : 'No'}</div>
                  <div><span className="text-muted">Preserve API:</span> {preserveApiSignatures ? 'Yes' : 'No'}</div>
                  <div><span className="text-muted">Profile:</span> {projectProfile === 'auto' ? 'Auto-detect' : projectProfile}</div>
                </div>
              </div>

              {/* Environment Configuration */}
              {enableEnvironmentConfig && (
                <div className="glass-light rounded-lg p-4">
                  <p className="text-[10px] text-muted uppercase tracking-wider mb-3">Environment Configuration</p>
                  <div className="grid grid-cols-3 gap-3 text-xs">
                    <div><span className="text-muted">CPU:</span> {serverConfig.cpu} vCPU</div>
                    <div><span className="text-muted">Memory:</span> {serverConfig.memory} GB</div>
                    <div><span className="text-muted">Storage:</span> {serverConfig.storage} GB</div>
                    <div><span className="text-muted">OS:</span> {serverConfig.os}</div>
                    <div><span className="text-muted">Region:</span> {serverConfig.region}</div>
                    <div><span className="text-muted">SSH Key:</span> {sshKeyFileName ? 'Uploaded' : 'None'}</div>
                  </div>
                </div>
              )}

              {/* Database Configuration (optional) */}
              {enableDatabaseConfig && (
                <div className="glass-light rounded-lg p-4">
                  <p className="text-[10px] text-muted uppercase tracking-wider mb-3">Database Configuration</p>
                  <div className="grid grid-cols-3 gap-3 text-xs">
                    <div><span className="text-muted">Source DB:</span> {sourceDatabase || 'N/A'}</div>
                    <div><span className="text-muted">Source Version:</span> {sourceDbVersion || 'N/A'}</div>
                    <div><span className="text-muted">Schema:</span> {schemaFileName || 'None'}</div>
                    <div><span className="text-muted">Target DB:</span> {selectedDatabase} {dbVersion}</div>
                    <div><span className="text-muted">Migration:</span> {migrationStrategy}</div>
                  </div>
                </div>
              )}

              {/* Deployment Configuration (optional) */}
              {enableDeploymentConfig && (
                <div className="glass-light rounded-lg p-4">
                  <p className="text-[10px] text-muted uppercase tracking-wider mb-3">Deployment Configuration</p>
                  <div className="grid grid-cols-3 gap-3 text-xs">
                    <div><span className="text-muted">CI/CD:</span> {selectedCI}</div>
                    <div><span className="text-muted">Infrastructure:</span> {infrastructure}</div>
                    <div><span className="text-muted">Environment:</span> {deployEnvironment}</div>
                    <div><span className="text-muted">Run Tests in CI:</span> {enableBuildTests ? 'Yes' : 'No'}</div>
                    <div><span className="text-muted">Linting in CI:</span> {enableLinting ? 'Yes' : 'No'}</div>
                  </div>
                </div>
              )}

              {/* Team */}
              <div className="glass-light rounded-lg p-4">
                <p className="text-[10px] text-muted uppercase tracking-wider mb-3">Team</p>
                <div className="grid grid-cols-3 gap-3 text-xs">
                  <div><span className="text-muted">Members:</span> {selectedTeam.length}</div>
                  <div><span className="text-muted">Names:</span> {selectedTeam.join(', ') || 'None'}</div>
                </div>
              </div>

              {/* Notifications */}
              <div className="glass-light rounded-lg p-4">
                <p className="text-[10px] text-muted uppercase tracking-wider mb-3">Notifications</p>
                <div className="grid grid-cols-3 gap-3 text-xs">
                  <div><span className="text-muted">On Complete:</span> {notifyOnComplete ? 'Yes' : 'No'}</div>
                  <div><span className="text-muted">On Warning:</span> {notifyOnWarning ? 'Yes' : 'No'}</div>
                  <div><span className="text-muted">On Failure:</span> {notifyOnFailure ? 'Yes' : 'No'}</div>
                  <div><span className="text-muted">Channels:</span> {notifyChannels.join(', ')}</div>
                </div>
              </div>

              {/* Compliance */}
              {selectedCompliance.length > 0 && (
                <div className="glass-light rounded-lg p-4">
                  <p className="text-[10px] text-muted uppercase tracking-wider mb-3">Compliance & Security</p>
                  <div className="grid grid-cols-3 gap-3 text-xs">
                    <div><span className="text-muted">Standards:</span> {selectedCompliance.join(', ')}</div>
                    <div><span className="text-muted">Vuln. Scan:</span> {enableVulnerabilityScan ? 'Yes' : 'No'}</div>
                    <div><span className="text-muted">SAST:</span> {enableSAST ? 'Yes' : 'No'}</div>
                  </div>
                </div>
              )}

              {/* Pipeline Modules */}
              <div className="glass-light rounded-lg p-4">
                <p className="text-[10px] text-muted uppercase tracking-wider mb-3">Pipeline Modules</p>
                <div className="grid grid-cols-3 gap-3 text-xs">
                  {PIPELINE_PLUGINS.map(p => (
                    <div key={p.id}>
                      <span className="text-muted">{p.name}:</span>{' '}
                      <span className={enabledPlugins.includes(p.id) ? 'text-success' : 'text-muted/60'}>
                        {enabledPlugins.includes(p.id) ? 'On' : 'Off'}
                      </span>
                    </div>
                  ))}
                </div>
              </div>

              {createError && (
                <div className="flex items-start gap-2 text-xs text-danger bg-danger/10 border border-danger/20 rounded-lg px-3 py-2.5">
                  <AlertTriangle className="w-3.5 h-3.5 shrink-0 mt-0.5" />{createError}
                </div>
              )}
              <button
                onClick={handleCreate}
                disabled={creating}
                className="w-full py-3.5 rounded-lg gradient-accent text-white text-sm font-bold hover:opacity-90 transition-opacity flex items-center justify-center gap-2 cursor-pointer glow-accent disabled:opacity-60"
              >
                {creating ? <><Loader2 className="w-4 h-4 animate-spin" /> Creating conversion...</> : <><Zap className="w-4 h-4" /> Create Conversion & Start</>}
              </button>
            </div>
          )}
        </motion.div>
      </AnimatePresence>

      {(() => {
        const blockers = stepBlockers();
        return !canNext() && blockers.length > 0 ? (
          <div className="flex flex-wrap gap-1.5 pb-2">
            {blockers.map((msg, i) => (
              <span key={i} className="inline-flex items-center gap-1 text-[10px] font-medium text-white bg-danger border border-danger/60 px-2.5 py-1 rounded-full shadow-sm">
                <AlertTriangle className="w-2.5 h-2.5 flex-shrink-0" /> {msg}
              </span>
            ))}
          </div>
        ) : null;
      })()}
      <div className="flex items-center justify-between">
        <button
          onClick={() => step === 0 ? onNavigate('conversions') : setStep(prevStep(step))}
          className="flex items-center gap-2 px-4 py-2 rounded-lg text-sm text-muted hover:text-foreground transition-colors cursor-pointer"
        >
          <ChevronLeft className="w-4 h-4" /> {step === 0 ? 'Cancel' : 'Back'}
        </button>
        {step < steps.length - 1 && (
          <button
            onClick={() => setStep(nextStep(step))}
            disabled={!canNext()}
            className="flex items-center gap-2 px-5 py-2 rounded-lg gradient-accent text-white text-sm font-semibold hover:opacity-90 transition-opacity cursor-pointer disabled:opacity-40"
          >
            Next <ChevronRight className="w-4 h-4" />
          </button>
        )}
      </div>
    </div>

    <AnimatePresence>
      {teamModalOpen && (
        <motion.div
          key="team-modal"
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          exit={{ opacity: 0 }}
          transition={{ duration: 0.15 }}
          className="fixed inset-0 z-[200] flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm"
          role="presentation"
          onClick={(e) => { if (e.target === e.currentTarget) closeAddTeamModal(); }}
        >
          <motion.div
            initial={{ opacity: 0, y: 10 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: 10 }}
            transition={{ duration: 0.2 }}
            className="glass w-full max-w-md rounded-2xl p-6 border border-border shadow-xl"
            role="dialog"
            aria-modal="true"
            aria-labelledby="team-modal-title"
            onClick={(e) => e.stopPropagation()}
          >
            <h4 id="team-modal-title" className="text-sm font-semibold text-foreground mb-1">Add team member</h4>
            <p className="text-xs text-muted mb-4 leading-relaxed">
              Display name for planning on this project. This does not send an invite or create a Scriba account.
            </p>
            <input
              autoFocus
              value={teamModalName}
              onChange={(e) => { setTeamModalName(e.target.value); setTeamModalError(''); }}
              onKeyDown={(e) => {
                if (e.key === 'Enter') {
                  e.preventDefault();
                  confirmAddTeamMember();
                }
                if (e.key === 'Escape') closeAddTeamModal();
              }}
              placeholder="Name or initials"
              className="w-full rounded-lg px-3 py-2.5 text-sm text-foreground bg-surface border border-border focus:border-accent/40 outline-none mb-1"
            />
            {teamModalError ? (
              <p className="text-xs text-red-400 mb-3">{teamModalError}</p>
            ) : (
              <div className="mb-3" />
            )}
            <div className="flex justify-end gap-2 pt-1">
              <button
                type="button"
                onClick={closeAddTeamModal}
                className="px-4 py-2 rounded-lg text-sm text-muted hover:text-foreground transition-colors cursor-pointer"
              >
                Cancel
              </button>
              <button
                type="button"
                onClick={confirmAddTeamMember}
                className="px-4 py-2 rounded-lg text-sm font-semibold gradient-accent text-white hover:opacity-90 transition-opacity cursor-pointer"
              >
                Add
              </button>
            </div>
          </motion.div>
        </motion.div>
      )}
    </AnimatePresence>
    </>
  );
}
