import { DndProvider } from 'react-dnd';
import { HTML5Backend } from 'react-dnd-html5-backend';
import { DeveloperConsole } from "./components/DeveloperConsole";
import { DndContextWrapper } from "./components/contexts/DndContext";

import { useState, useEffect, useMemo } from "react";

import { Button } from "./components/ui/button";
import { Sidebar, SidebarContent, SidebarHeader, SidebarMenu, SidebarMenuItem, SidebarMenuButton, SidebarProvider, SidebarTrigger } from "./components/ui/sidebar";
import { Sheet, SheetContent, SheetTrigger, SheetTitle, SheetHeader } from "./components/ui/sheet";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "./components/ui/tooltip";
import { DataProvider } from "./components/contexts/DataContext";
import { DesignTokenProvider } from "./components/contexts/DesignTokenContext";
import { DesignSystemProvider } from "./components/contexts/DesignSystemContext";
import { DeveloperModeProvider, useDeveloperMode } from "./components/contexts/DeveloperModeContext";
import { LandingPage } from "./components/LandingPage";
import { SignupPage } from "./components/SignupPage";
import { LoginPage } from "./components/LoginPage";
import { DemoRequestPage } from "./components/DemoRequestPage";
import { SalesLeadDashboard } from "./components/SalesLeadDashboard";
import { Dashboard } from "./components/Dashboard";
import { MasterData } from "./components/MasterData";
import { MaterialManagement } from "./components/MaterialManagement";
import { InventoryManagement } from "./components/InventoryManagement";
import { OrderManagement } from "./components/OrderManagement";
import { ProductionManagement } from "./components/ProductionManagement_Standard";
import { ScreenProductionPage } from "./components/ScreenProductionPage";
import { SlatProductionPage } from "./components/SlatProductionPage";
import { BendingProductionPage } from "./components/BendingProductionPage";
import { StockProductionPage } from "./components/StockProductionPage";
import { ShippingManagement } from "./components/ShippingManagement";
import { ShipmentManagement } from "./components/ShipmentManagement";
import { QualityManagement } from "./components/QualityManagement_Standard";
import { Reports } from "./components/Reports";
import { Board } from "./components/Board";
import { SystemManagement } from "./components/SystemManagement";
import { BOMManagement } from "./components/BOMManagement";
import { BOMCreatePage } from "./components/BOMCreatePage";
import { EquipmentManagement } from "./components/EquipmentManagement";
import { VehicleManagement } from "./components/VehicleManagement";
import { SalesManagement } from "./components/SalesManagement";
import { WorkerPerformance } from "./components/WorkerPerformance";
import { AccountingManagement } from "./components/AccountingManagement";
import { ApprovalManagement } from "./components/ApprovalManagement";
import { HRManagement } from "./components/HRManagement";
import { OrganizationChart } from "./components/OrganizationChart";
import { AttendanceManagement } from "./components/AttendanceManagement";
import { PayrollManagement } from "./components/PayrollManagement";
import MenuCustomization from "./components/MenuCustomization";
import { ItemManagement } from "./components/ItemManagement";
// import { ItemManagementPage } from "./components/ItemManagementPage"; // Replaced with ItemManagement
import { ProductManagement } from "./components/ProductManagement";
import { PricingManagement } from "./components/PricingManagement";
import { QuoteSimulation } from "./components/QuoteSimulation";
import { MultiQuoteCalculator } from "./components/MultiQuoteCalculator";
import { ReceivingManagement } from "./components/ReceivingManagement";
import { NonconformingManagement } from "./components/NonconformingManagement";
import { IncomingInspectionManagement } from "./components/IncomingInspectionManagement";
import { ProcessInspectionManagement } from "./components/ProcessInspectionManagement";
import { FinalInspectionManagement } from "./components/FinalInspectionManagement";
import { ProductsManagement } from "./components/ProductsManagement";
import { ProcessManagement } from "./components/ProcessManagement";
import { CustomerManagement } from "./components/CustomerManagement";
import { CustomerDetailPage } from "./components/CustomerDetailPage";
import { MasterDataDashboard } from "./components/MasterDataDashboard";
import { SalesDashboard } from "./components/SalesDashboard";
import { ProductionDashboard } from "./components/ProductionDashboard";
import { QualityDashboard } from "./components/QualityDashboard";
import { MaterialDashboard } from "./components/MaterialDashboard";
import { ModelManagement } from "./components/ModelManagement";
import { LotManagementPage } from "./components/LotManagementPage";
import { InspectionStandardManagement } from "./components/InspectionStandardManagement";
import { CodeManagementPage } from "./components/CodeManagementPage";
import { SystemAdminDashboard } from "./components/SystemAdminDashboard";
import { StockStatus } from "./components/StockStatus";
import { PurchaseDashboard } from "./components/PurchaseDashboard";
import { DraftBox } from "./components/DraftBox";
import { ApprovalBox } from "./components/ApprovalBox";
import { ReferenceBox } from "./components/ReferenceBox";
import { DocumentWrite } from "./components/DocumentWrite";
import { EmployeeManagement } from "./components/EmployeeManagement";
import { DepartmentManagement } from "./components/DepartmentManagement";
import { ProductionBOMManagement } from "./components/ProductionBOMManagement";
import { AccountingDashboard } from "./components/AccountingDashboard";
import { SalesAccountingManagement } from "./components/SalesAccountingManagement";
import { PurchaseAccountingManagement } from "./components/PurchaseAccountingManagement";
import { CostManagement } from "./components/CostManagement";
import { FinancialStatements } from "./components/FinancialStatements";
import { SalesPerformance } from "./components/SalesPerformance";
import { SupplierManagement } from "./components/SupplierManagement";
import { PurchaseOrderManagement } from "./components/PurchaseOrderManagement";
import { PurchaseStatus } from "./components/PurchaseStatus";
import { CustomerAccountManagement } from "./components/CustomerAccountManagement";
import { BOMManagementEnhanced } from "./components/BOMManagementEnhanced";
import { BOMRegistration } from "./components/BOMRegistration";
import { QuoteManagement } from "./components/QuoteManagement";
import { QualityItemInspection } from "./components/QualityItemInspection";
import { QualityItemInspectionEnhanced } from "./components/QualityItemInspectionEnhanced";
import { ClientManagement } from "./components/ClientManagement";
import { SalesOrderManagement } from "./components/SalesOrderManagement";
import { SalesOrderWrite } from "./components/SalesOrderWrite";
import { SalesOrderView } from "./components/SalesOrderView";
import { SiteManagement } from "./components/SiteManagement";
import { FormulaManagement } from "./components/FormulaManagement";
import { FormulaManagement2 } from "./components/FormulaManagement2";
import { QuoteAutoCalculation } from "./components/QuoteAutoCalculation";
import { FormulaItemManagement } from "./components/FormulaItemManagement";
import { CategoryGroupManagementPage } from "./components/CategoryGroupManagementPage";
import { ItemPriceMappingPage } from "./components/ItemPriceMappingPage";
import { AutoCalculationPage } from "./components/AutoCalculationPage";
import { BOMTemplateManagement } from "./components/BOMTemplateManagement";
import { DesignSystemManagement } from "./components/DesignSystemManagement_Editable";
import { DesignSystemTemplateGuide } from "./components/DesignSystemTemplateGuide";
import { StandardPageExample } from "./components/examples/StandardPageExample";
import { StandardDialogExample } from "./components/examples/StandardDialogExample";
import { IntegratedFormTemplateV2Example } from "./components/examples/IntegratedFormTemplateV2Example";
import { IntegratedFormTemplateV3Example } from "./components/examples/IntegratedFormTemplateV3Example";
import { LOTNumberManagement } from "./components/LOTNumberManagement";
import { ItemMasterDataManagement } from "./components/ItemMasterDataManagement_fixed";
import { ItemMasterDataHierarchy } from "./components/ItemMasterDataHierarchy";
import { ItemTestPage } from "./components/ItemTestPage";
import { UserManagement } from "./components/UserManagement";
import { AccountantDashboard } from "./components/AccountantDashboard";
import { SalesManagerDashboard } from "./components/SalesManagerDashboard";
import { ItemManagement_DesignSystemExample } from "./components/ItemManagement_DesignSystemExample";
import { QuoteManagement_DesignSystemExample } from "./components/QuoteManagement_DesignSystemExample";
import { ResponsiveListTemplateExample } from "./components/templates/ResponsiveListTemplateExample";
import { BasicListUnifiedExample } from "./components/templates/BasicListUnifiedExample";
import { IntegratedSearch } from "./components/IntegratedSearch";
import { 
  LayoutDashboard, 
  Factory, 
  CheckSquare, 
  Package, 
  Settings, 
  Users,
  Menu,
  Bell,
  Search,
  User,
  Database,
  FileText,
  BarChart3,
  ShoppingCart,
  Calculator,
  Truck,
  Car,
  MessageSquare,
  Calculator,
  Shield,
  Server,
  Activity,
  Layers,
  Wrench,
  Warehouse,
  ClipboardList,
  ClipboardCheck,
  Moon,
  Sun,
  Eye,
  Palette,
  Briefcase,
  DollarSign,
  TrendingUp,
  TrendingDown,
  FileSignature,
  UserCog,
  LogOut,
  ArrowLeft,
  ChevronLeft,
  Code,
  Sparkles,
  Sliders,
  ChevronDown,
  ChevronRight,
  Box,
  FileText,
  FileText as FileTextIcon,
  Archive as ArchiveIcon,
  Calculator as CalculatorIcon,
  Tag,
  Archive,
  Calendar,
  CheckCircle,
  Building,
  Building2,
  XCircle,
  GitBranch,
  FileCheck,
  Edit,
  MapPin,
  Palette,
  TestTube,
  Hash,
  LayoutGrid,
  Home
} from "lucide-react";
import { Input } from "./components/ui/input";
import { Badge } from "./components/ui/badge";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "./components/ui/dropdown-menu";
import { Toaster } from "./components/ui/sonner";
import { toast } from "sonner@2.0.3";

const getMenuItems = (userRole: string) => {
  if (userRole === "SystemAdmin") {
    return [
      { id: "dashboard", label: "시스템 대시보드", icon: LayoutDashboard, component: Dashboard },
      { id: "users", label: "사용자 관리", icon: Users, component: UserManagement },
      { id: "menu-customization", label: "메뉴 커스터마이징", icon: Sliders, component: MenuCustomization },
      { 
        id: "master-data", 
        label: "기준정보 관리", 
        icon: Database,
        component: MasterDataDashboard,
        subItems: [
          { id: "models-management", label: "모델관리", icon: Box, component: ModelManagement },
          { id: "items-management", label: "자재관리", icon: Archive, component: ItemManagement },
          { id: "item-master-data-management", label: "품목기준관리", icon: Database, component: ItemMasterDataManagement },
          { id: "process-management", label: "공정관리", icon: Wrench, component: ProcessManagement },
          { id: "customer-management", label: "거래처관리", icon: Building, component: CustomerManagement },
          { id: "employee-management", label: "사원관리", icon: User, component: EmployeeManagement },
          { id: "department-management", label: "부서관리", icon: Building, component: DepartmentManagement },
          { id: "inspection-standard", label: "검사기준관리", icon: ClipboardCheck, component: InspectionStandardManagement },
          { id: "code-management", label: "코드관리", icon: Code, component: CodeManagementPage },
          { 
            id: "formula-management-2", 
            label: "견적수식관리", 
            icon: Calculator, 
            component: FormulaManagement2,
            subItems: [
              { id: "formula-management-2-all", label: "전체 통합", icon: LayoutGrid, component: FormulaManagement2 },
              { id: "formula-item-management", label: "단가 수식 관리", icon: Calculator, component: FormulaItemManagement },
              { id: "category-group-management", label: "분류 관리", icon: Layers, component: CategoryGroupManagementPage },
              { id: "item-price-mapping", label: "품목 수식 맵핑", icon: Tag, component: ItemPriceMappingPage },
              { id: "auto-calculation", label: "자동 견적 산출", icon: Calculator, component: AutoCalculationPage },
            ]
          },
        ]
      },
      { 
        id: "design-system-management-admin", 
        label: "디자인시스템관리", 
        icon: Palette, 
        component: DesignSystemManagement,
        subItems: [
          { id: "design-system", label: "디자인시스템 관리", icon: Palette, component: DesignSystemManagement },
          { id: "template-guide", label: "템플릿 가이드", icon: FileText, component: DesignSystemTemplateGuide },
          { id: "template-example", label: "목록 템플릿 예제", icon: Package, component: StandardPageExample },
          { id: "form-template-v2-example", label: "폼 템플릿 V2 예제", icon: FileText, component: IntegratedFormTemplateV2Example },
          { id: "form-template-v3-example", label: "폼 템플릿 V3 예제", icon: FileText, component: IntegratedFormTemplateV3Example },
          { id: "customer-detail-example", label: "거래처 상세 (템플릿V2)", icon: Building, component: CustomerDetailPage },
        ]
      },
      { 
        id: "sales-dept", 
        label: "영업관리", 
        icon: TrendingUp,
        component: SalesDashboard,
        subItems: [
          { id: "sales-leads", label: "리드관리", icon: Users, component: SalesLeadDashboard },
          { id: "customer-account-management", label: "매출처관리", icon: Building2, component: CustomerAccountManagement },
          { id: "sales-performance", label: "영업실적", icon: BarChart3, component: SalesPerformance },
        ]
      },
      { 
        id: "sales", 
        label: "판매관리", 
        icon: Briefcase,
        component: SalesDashboard,
        subItems: [
          { id: "client-management-sales-admin", label: "거래처관리", icon: Building2, component: ClientManagement },
          { id: "customer-detail-sales", label: "거래처 상세 (V3)", icon: Building, component: CustomerDetailPage },
          { id: "quote-management", label: "견적관리", icon: CalculatorIcon, component: QuoteManagement },
          { id: "order-management-sales", label: "수주관리", icon: ShoppingCart, component: SalesOrderManagement },
          { id: "shipment-management", label: "출하관리", icon: Truck, component: ShipmentManagement },
          { id: "site-management", label: "현장관리", icon: MapPin, component: SiteManagement },
          { id: "pricing-management", label: "단가관리", icon: DollarSign, component: PricingManagement },
        ]
      },
      { 
        id: "purchase", 
        label: "구매관리", 
        icon: ShoppingCart,
        component: PurchaseDashboard,
        subItems: [
          { id: "supplier-management", label: "거래처관리", icon: Building2, component: SupplierManagement },
          { id: "purchase-order", label: "발주관리", icon: FileText, component: PurchaseOrderManagement },
          { id: "purchase-status", label: "구매현황", icon: BarChart3, component: PurchaseStatus },
        ]
      },
      { 
        id: "production", 
        label: "생산관리", 
        icon: Factory,
        component: ProductionDashboard,
        subItems: [

          { id: "screen-production", label: "스크린 생산", icon: Package, component: ScreenProductionPage },
          { id: "slat-production", label: "슬랫 생산", icon: Package, component: SlatProductionPage },
          { id: "bending-production", label: "절곡 생산", icon: Package, component: BendingProductionPage },
          { id: "stock-production", label: "재고 생산", icon: Package, component: StockProductionPage },
        ]
      },
      { 
        id: "quality", 
        label: "품질관리", 
        icon: ClipboardCheck,
        component: QualityDashboard,
        subItems: [
          { id: "incoming-inspection", label: "수입검사", icon: CheckSquare, component: IncomingInspectionManagement },
          { id: "process-inspection", label: "중간검사", icon: ClipboardCheck, component: ProcessInspectionManagement },
          { id: "final-inspection", label: "제품검사", icon: CheckCircle, component: FinalInspectionManagement },
        ]
      },
      { 
        id: "material", 
        label: "자재관리", 
        icon: Warehouse,
        component: InventoryManagement,
        subItems: [
          { id: "stock-status", label: "재고현황", icon: Layers, component: StockStatus },
          { id: "receiving-management", label: "입고관리", icon: Package, component: ReceivingManagement },
          { id: "shipping-management", label: "출고관리", icon: Truck, component: ShippingManagement },
          { id: "nonconforming-management", label: "부적합품관리", icon: XCircle, component: NonconformingManagement },
        ]
      },
      { 
        id: "equipment", 
        label: "장비관리", 
        icon: Wrench,
        component: EquipmentManagement,
        subItems: [
          { id: "equipment-management", label: "설비관리", icon: Wrench, component: EquipmentManagement },
        ]
      },
      { 
        id: "vehicle", 
        label: "차량관리", 
        icon: Truck,
        component: VehicleManagement,
        subItems: [
          { id: "vehicle-management", label: "차량관리", icon: Car, component: VehicleManagement },
        ]
      },
      { 
        id: "accounting", 
        label: "회계관리", 
        icon: Calculator,
        component: AccountingDashboard,
        subItems: [
          { id: "client-management", label: "거래처관리", icon: Building2, component: ClientManagement },
          { id: "sales-accounting", label: "매출관리", icon: TrendingUp, component: SalesAccountingManagement },
          { id: "purchase-accounting", label: "매입관리", icon: TrendingDown, component: PurchaseAccountingManagement },
          { id: "cost-management", label: "원가관리", icon: DollarSign, component: CostManagement },
          { id: "financial-statements", label: "재무제표", icon: FileText, component: FinancialStatements },
        ]
      },
      { id: "permissions", label: "권한 관리", icon: Shield, component: SystemManagement },
      { id: "system", label: "시스템 설정", icon: Settings, component: SystemManagement },
      { id: "database", label: "데이터베이스", icon: Database, component: SystemManagement },
      { id: "monitoring", label: "시스템 모니터링", icon: Activity, component: SystemManagement },
      { id: "security", label: "보안 관리", icon: Server, component: SystemManagement },
    ];
  }

  // 회계담당자 전용 메뉴
  if (userRole === "Accountant") {
    return [
      { id: "dashboard", label: "대시보드", icon: LayoutDashboard, component: AccountantDashboard },
      { 
        id: "accounting", 
        label: "회계관리", 
        icon: Calculator,
        component: AccountingDashboard,
        subItems: [
          { id: "client-management-accountant", label: "거래처관리", icon: Building2, component: ClientManagement },
          { id: "sales-accounting", label: "매출관리", icon: TrendingUp, component: SalesAccountingManagement },
          { id: "purchase-accounting", label: "매입관리", icon: TrendingDown, component: PurchaseAccountingManagement },
          { id: "cost-management", label: "원가관리", icon: DollarSign, component: CostManagement },
          { id: "financial-statements", label: "재무제표", icon: FileText, component: FinancialStatements },
        ]
      },
      { 
        id: "approval", 
        label: "전자결재", 
        icon: FileSignature,
        component: ApprovalManagement,
        subItems: [
          { id: "draft-box-accountant", label: "기안함", icon: Edit, component: DraftBox },
          { id: "approval-box-accountant", label: "결재함", icon: CheckCircle, component: ApprovalBox },
          { id: "reference-box-accountant", label: "참조함", icon: Archive, component: ReferenceBox },
          { id: "document-write-accountant", label: "문서작성", icon: FileText, component: DocumentWrite },
        ]
      },
    ];
  }

  // 판매담당자 전용 메뉴
  if (userRole === "SalesManager") {
    return [
      { id: "dashboard", label: "대시보드", icon: LayoutDashboard, component: SalesManagerDashboard },
      { 
        id: "sales", 
        label: "판매관리", 
        icon: Briefcase,
        component: SalesDashboard,
        subItems: [
          { id: "client-management-sales-mgr", label: "거래처관리", icon: Building2, component: ClientManagement },
          { id: "quote-management-sales-mgr", label: "견적관리", icon: CalculatorIcon, component: QuoteManagement },
          { id: "order-management-sales-mgr", label: "수주관리", icon: ShoppingCart, component: SalesOrderManagement },
          { id: "shipment-management-sales-mgr", label: "출하관리", icon: Truck, component: ShipmentManagement },
          { id: "site-management-sales-mgr", label: "현장관리", icon: MapPin, component: SiteManagement },
          { id: "pricing-management-sales-mgr", label: "단가관리", icon: DollarSign, component: PricingManagement },
        ]
      },
      { 
        id: "approval", 
        label: "전자결재", 
        icon: FileSignature,
        component: ApprovalManagement,
        subItems: [
          { id: "draft-box-sales", label: "기안함", icon: Edit, component: DraftBox },
          { id: "approval-box-sales", label: "결재함", icon: CheckCircle, component: ApprovalBox },
          { id: "reference-box-sales", label: "참조함", icon: Archive, component: ReferenceBox },
          { id: "document-write-sales", label: "문서작성", icon: FileText, component: DocumentWrite },
        ]
      },
    ];
  }

  // 영업사원 전용 메뉴
  if (userRole === "Sales") {
    return [
      { id: "leads", label: "리드 관리", icon: Users, component: SalesLeadDashboard },
      { 
        id: "sales", 
        label: "판매관리", 
        icon: Briefcase,
        component: SalesDashboard,
        subItems: [
          { id: "quote-simulation", label: "견적 산출하기", icon: CalculatorIcon, component: QuoteSimulation },
          { id: "multi-quote-calculator", label: "다중 견적 산출", icon: CalculatorIcon, component: MultiQuoteCalculator },
          { id: "sales-management", label: "영업관리", icon: Briefcase, component: SalesManagement },
          { id: "quote-management-sales", label: "견적관리", icon: FileTextIcon, component: QuoteManagement },
        ]
      },
      { id: "dashboard", label: "대시보드", icon: LayoutDashboard, component: Dashboard },
    ];
  }

  // 생산작업자 전용 메뉴
  if (userRole === "Worker") {
    return [
      { id: "dashboard", label: "대시보드", icon: LayoutDashboard, component: Dashboard },
      { id: "performance", label: "작업 실적", icon: ClipboardList, component: WorkerPerformance },
      { 
        id: "quality", 
        label: "품질관리", 
        icon: CheckSquare,
        component: QualityDashboard,
        subItems: [
          { id: "incoming-inspection", label: "수입검사", icon: CheckSquare, component: IncomingInspectionManagement },
          { id: "process-inspection", label: "중간검사", icon: ClipboardCheck, component: ProcessInspectionManagement },
          { id: "final-inspection", label: "제품검사", icon: CheckCircle, component: FinalInspectionManagement },
        ]
      },
    ];
  }
  
  // CEO 및 기본 사용자 메뉴
  return [
    { id: "dashboard", label: "대시보드", icon: TrendingUp, component: Dashboard },
    { 
      id: "sales-dept-default", 
      label: "영업관리", 
      icon: TrendingUp,
      component: SalesDashboard,
      subItems: [
        { id: "sales-leads-default", label: "리드관리", icon: Users, component: SalesLeadDashboard },
        { id: "customer-account-management-default", label: "매출처관리", icon: Building2, component: CustomerAccountManagement },
        { id: "sales-performance-default", label: "영업실적", icon: BarChart3, component: SalesPerformance },
      ]
    },
    { 
      id: "sales", 
      label: "판매관리", 
      icon: Briefcase,
      component: SalesDashboard,
      subItems: [
        { id: "client-management-sales", label: "거래처관리", icon: Building2, component: ClientManagement },
        { id: "quote-management-default", label: "견적관리", icon: CalculatorIcon, component: QuoteManagement },
        { id: "order-management-sales-default", label: "수주관리", icon: ShoppingCart, component: SalesOrderManagement },
        { id: "shipment-management-default", label: "출하관리", icon: Truck, component: ShipmentManagement },
        { id: "site-management-default", label: "현장관리", icon: MapPin, component: SiteManagement },
        { id: "pricing-management", label: "단가관리", icon: DollarSign, component: PricingManagement },
      ]
    },
    { 
      id: "purchase", 
      label: "구매관리", 
      icon: ShoppingCart,
      component: PurchaseDashboard,
      subItems: [
        { id: "supplier-management-default", label: "거래처관리", icon: Building2, component: SupplierManagement },
        { id: "purchase-order-default", label: "발주관리", icon: FileText, component: PurchaseOrderManagement },
        { id: "purchase-status-default", label: "구매현황", icon: BarChart3, component: PurchaseStatus },
      ]
    },
    { 
      id: "production", 
      label: "생산관리", 
      icon: Factory,
      component: ProductionDashboard,
      subItems: [
        { id: "products-management-production-enhanced", label: "품목관리", icon: Package, component: ItemManagement },
        { id: "screen-production-default", label: "스크린 생산", icon: Package, component: ScreenProductionPage },
        { id: "slat-production-default", label: "슬랫 생산", icon: Package, component: SlatProductionPage },
        { id: "bending-production-default", label: "절곡 생산", icon: Package, component: BendingProductionPage },
        { id: "stock-production-default", label: "재고 생산", icon: Package, component: StockProductionPage },
      ]
    },
    { 
      id: "quality", 
      label: "품질관리", 
      icon: CheckSquare,
      component: QualityDashboard,
      subItems: [
        { id: "incoming-inspection", label: "수입검사", icon: CheckSquare, component: IncomingInspectionManagement },
        { id: "process-inspection", label: "중간검사", icon: ClipboardCheck, component: ProcessInspectionManagement },
        { id: "final-inspection", label: "제품검사", icon: CheckCircle, component: FinalInspectionManagement },
      ]
    },
    { 
      id: "materials", 
      label: "자재관리", 
      icon: Package,
      component: InventoryManagement,
      subItems: [
        { id: "stock-status-materials", label: "재고현황", icon: Layers, component: StockStatus },
        { id: "receiving-management", label: "입고관리", icon: Package, component: ReceivingManagement },
        { id: "shipping-management", label: "출고관리", icon: Truck, component: ShippingManagement },
        { id: "nonconforming-management", label: "부적합품관리", icon: XCircle, component: NonconformingManagement },
      ]
    },
    { 
      id: "equipment-default", 
      label: "장비관리", 
      icon: Wrench,
      component: EquipmentManagement,
      subItems: [
        { id: "equipment-management-default", label: "설비관리", icon: Wrench, component: EquipmentManagement },
      ]
    },
    { 
      id: "vehicle-default", 
      label: "차량관리", 
      icon: Truck,
      component: VehicleManagement,
      subItems: [
        { id: "vehicle-management-default", label: "차량관리", icon: Car, component: VehicleManagement },
      ]
    },
    { 
      id: "accounting-default", 
      label: "회계관리", 
      icon: Calculator,
      component: AccountingDashboard,
      subItems: [
        { id: "client-management-default", label: "거래처관리", icon: Building2, component: ClientManagement },
        { id: "sales-accounting-default", label: "매출관리", icon: TrendingUp, component: SalesAccountingManagement },
        { id: "purchase-accounting-default", label: "매입관리", icon: TrendingDown, component: PurchaseAccountingManagement },
        { id: "cost-management-default", label: "원가관리", icon: DollarSign, component: CostManagement },
        { id: "financial-statements-default", label: "재무제표", icon: FileText, component: FinancialStatements },
      ]
    },
    { 
      id: "hr", 
      label: "인사관리", 
      icon: UserCog, 
      component: HRManagement,
      subItems: [
        { id: "hr-dashboard", label: "인사대시보드", icon: LayoutDashboard, component: HRManagement },
        { id: "employee-management", label: "직원관리", icon: Users, component: EmployeeManagement },
        { id: "department-management", label: "부서관리", icon: Building2, component: DepartmentManagement },
        { id: "organization-chart", label: "조직도", icon: Building, component: OrganizationChart },
        { id: "attendance-management", label: "근태관리", icon: Calendar, component: AttendanceManagement },
        { id: "payroll-management", label: "급여관리", icon: DollarSign, component: PayrollManagement },
      ]
    },
    { 
      id: "approval", 
      label: "전자결재", 
      icon: FileSignature, 
      component: ApprovalManagement,
      subItems: [
        { id: "draft-box", label: "기안함", icon: FileText, component: DraftBox },
        { id: "approval-box", label: "결재함", icon: FileCheck, component: ApprovalBox },
        { id: "reference-box", label: "참조함", icon: Eye, component: ReferenceBox },
        { id: "document-write", label: "문서작성", icon: Edit, component: DocumentWrite },
      ]
    },
    { 
      id: "master", 
      label: "기준정보", 
      icon: Database,
      component: MasterDataDashboard,
      subItems: [
        { id: "item-master-data-management-default", label: "품목기준관리", icon: Database, component: ItemMasterDataManagement },
        { id: "process-management", label: "공정관리", icon: Wrench, component: ProcessManagement },
        { id: "customer-management", label: "거래처관리", icon: Building, component: CustomerManagement },
        { id: "employee-management-default", label: "사원관리", icon: User, component: EmployeeManagement },
        { id: "department-management-default", label: "부서관리", icon: Building, component: DepartmentManagement },
        { id: "inspection-standard", label: "검사기준관리", icon: ClipboardCheck, component: InspectionStandardManagement },
        { id: "code-management", label: "코드관리", icon: Code, component: CodeManagementPage },
        { id: "lot-number-management", label: "번호기준관리", icon: Hash, component: LOTNumberManagement },
        { 
          id: "formula-management-2-default", 
          label: "견적수식관리", 
          icon: Calculator, 
          component: FormulaManagement2,
          subItems: [
            { id: "formula-management-2-all-default", label: "전체 통합", icon: LayoutGrid, component: FormulaManagement2 },
            { id: "formula-item-management-default", label: "단가 수식 관리", icon: Calculator, component: FormulaItemManagement },
            { id: "category-group-management-default", label: "분류 관리", icon: Layers, component: CategoryGroupManagementPage },
            { id: "item-price-mapping-default", label: "품목 수식 맵핑", icon: Tag, component: ItemPriceMappingPage },
            { id: "auto-calculation-default", label: "자동 견적 산출", icon: Calculator, component: AutoCalculationPage },
          ]
        },
      ]
    },
    { 
      id: "design-system-management", 
      label: "디자인시스템관리", 
      icon: Palette, 
      component: DesignSystemManagement 
    },
    { id: "reports", label: "보고서 및 분석", icon: BarChart3, component: Reports },
  ];
};

export default function App() {
  return (
    <DesignTokenProvider>
      <DesignSystemProvider>
        <DataProvider>
          <DeveloperModeProvider>
            <AppContent />
            <DeveloperConsole />
            <Toaster />
          </DeveloperModeProvider>
        </DataProvider>
      </DesignSystemProvider>
    </DesignTokenProvider>
  );
}

function AppContent() {
  const { isDeveloperMode, setIsDeveloperMode } = useDeveloperMode();
  
  const [currentPage, setCurrentPage] = useState<"landing" | "demo-request" | "demo" | "sales-dashboard" | "login" | "signup">("landing");
  const [isDemoMode, setIsDemoMode] = useState(false);
  const [demoConfig, setDemoConfig] = useState<any>(null);
  const [viewMode, setViewMode] = useState<"client" | "sales">("client"); // 클라이언트 or 영업사원 화면
  const [userData, setUserData] = useState<any>(null); // 로그인한 사용자 데이터
  
  const [activeMenu, setActiveMenu] = useState("dashboard");
  const [previousMenu, setPreviousMenu] = useState("dashboard");
  const [isMobile, setIsMobile] = useState(false);
  const [isMobileSidebarOpen, setIsMobileSidebarOpen] = useState(false);
  const [isMobileSearchOpen, setIsMobileSearchOpen] = useState(false);
  // LNB 축소 상태를 localStorage에서 불러오기
  const [isSidebarCollapsed, setIsSidebarCollapsed] = useState(() => {
    const saved = localStorage.getItem('sidebar-collapsed');
    return saved ? JSON.parse(saved) : false;
  });
  const [userRole, setUserRole] = useState("CEO"); // CEO, ProductionManager, Worker, SystemAdmin, Sales
  const [theme, setTheme] = useState("light"); // light, dark
  const [systemManagementTab, setSystemManagementTab] = useState("dashboard");
  const [expandedMenus, setExpandedMenus] = useState<string[]>([]); // 확장된 메뉴 ID들
  const [bomToEdit, setBomToEdit] = useState<any>(null); // BOM 편집 데이터
  
  // 🎯 페이지 히스토리 추적 시스템
  const [pageHistory, setPageHistory] = useState<string[]>(["dashboard"]);
  
  // 통합검색 state
  const [searchQuery, setSearchQuery] = useState("");
  const [isSearchFocused, setIsSearchFocused] = useState(false);
  const [searchResults, setSearchResults] = useState<any[]>([]);
  const [isIntegratedSearchOpen, setIsIntegratedSearchOpen] = useState(false);
  
  const menuItems = getMenuItems(userRole);
  
  // 🎯 페이지 히스토리 추적 - activeMenu 변경 시 히스토리에 추가
  useEffect(() => {
    setPageHistory(prev => {
      // 같은 페이지 연속 방문은 추가하지 않음
      if (prev.length > 0 && prev[prev.length - 1] === activeMenu) {
        return prev;
      }
      return [...prev, activeMenu];
    });
  }, [activeMenu]);
  
  // 이전 페이지 추적 (activeMenu가 변경될 때 이전 값 저장)
  useEffect(() => {
    return () => {
      setPreviousMenu(activeMenu);
    };
  }, [activeMenu]);
  
  // 🎯 이전 페이지로 이동하는 핸들러
  const handleGoBack = () => {
    setPageHistory(prev => {
      if (prev.length <= 1) {
        // 히스토리가 없거나 현재 페이지만 있으면 대시보드로
        setActiveMenu('dashboard');
        return ['dashboard'];
      }
      
      // 현재 페이지를 제거하고 이전 페이지로 이동
      const newHistory = prev.slice(0, -1);
      const previousPage = newHistory[newHistory.length - 1] || 'dashboard';
      setActiveMenu(previousPage);
      return newHistory;
    });
  };
  
  // 통합검색 로직
  useEffect(() => {
    if (searchQuery.trim() === "") {
      setSearchResults([]);
      return;
    }

    const results: any[] = [];
    const query = searchQuery.toLowerCase();
    const currentMenuItems = getMenuItems(userRole);

    // 모든 메뉴와 서브메뉴 검색
    currentMenuItems.forEach((item: any) => {
      // 메인 메뉴 검색
      if (item.label.toLowerCase().includes(query)) {
        results.push({
          id: item.id,
          label: item.label,
          icon: item.icon,
          type: 'main',
          parentLabel: null
        });
      }

      // 서브메뉴 검색
      if (item.subItems) {
        item.subItems.forEach((subItem: any) => {
          if (subItem.label.toLowerCase().includes(query)) {
            results.push({
              id: subItem.id,
              label: subItem.label,
              icon: subItem.icon,
              type: 'sub',
              parentLabel: item.label
            });
          }
          // 3depth 메뉴 검색
          if (subItem.subItems) {
            subItem.subItems.forEach((subSubItem: any) => {
              if (subSubItem.label.toLowerCase().includes(query)) {
                results.push({
                  id: subSubItem.id,
                  label: subSubItem.label,
                  icon: subSubItem.icon,
                  type: 'subsub',
                  parentLabel: `${item.label} > ${subItem.label}`
                });
              }
            });
          }
        });
      }
    });

    setSearchResults(results.slice(0, 8)); // 최대 8개 결과만 표시
  }, [searchQuery, userRole]);

  // 검색 결과 선택 핸들러
  const handleSearchResultClick = (menuId: string) => {
    setActiveMenu(menuId);
    setSearchQuery("");
    setIsSearchFocused(false);
    setSearchResults([]);
    
    const currentMenuItems = getMenuItems(userRole);
    // 서브메뉴의 경우 부모 메뉴도 확장
    currentMenuItems.forEach((item: any) => {
      if (item.subItems) {
        const hasSubMenu = item.subItems.some((sub: any) => sub.id === menuId);
        if (hasSubMenu && !expandedMenus.includes(item.id)) {
          setExpandedMenus(prev => [...prev, item.id]);
        }
        // 3depth 메뉴의 경우 부모와 조부모 메뉴 모두 확장
        item.subItems.forEach((sub: any) => {
          if (sub.subItems) {
            const hasSubSubMenu = sub.subItems.some((subsub: any) => subsub.id === menuId);
            if (hasSubSubMenu) {
              if (!expandedMenus.includes(item.id)) {
                setExpandedMenus(prev => [...prev, item.id]);
              }
              if (!expandedMenus.includes(sub.id)) {
                setExpandedMenus(prev => [...prev, sub.id]);
              }
            }
          }
        });
      }
    });
  };
  
  // 서브메뉴 포함하여 active component 찾기
  const findActiveComponent = () => {
    for (const item of menuItems) {
      if (item.id === activeMenu) {
        return item.component;
      }
      if (item.subItems) {
        const subItem = item.subItems.find((sub: any) => sub.id === activeMenu);
        if (subItem) {
          return subItem.component;
        }
        // 3depth 메뉴 검색 추가
        for (const sub of item.subItems) {
          if (sub.subItems) {
            const subSubItem = sub.subItems.find((subsub: any) => subsub.id === activeMenu);
            if (subSubItem) {
              return subSubItem.component;
            }
          }
        }
      }
    }
    return Dashboard;
  };
  
  const ActiveComponent = findActiveComponent();
  
  // 거래처관리 컴포넌트에 필터 prop 전달
  const renderActiveComponent = () => {
    if (activeMenu === 'client-management' || activeMenu === 'client-management-default') {
      // 회계관리 -> 거래처관리: 모두 표시
      return <ActiveComponent filterByType="all" />;
    } else if (activeMenu === 'client-management-sales-admin' || activeMenu === 'client-management-sales') {
      // 판매관리 -> 거래처관리: 매출 거래처만
      return <ActiveComponent filterByType="sales" />;
    } else if (activeMenu === 'supplier-management' || activeMenu === 'supplier-management-default') {
      // 구매관리 -> 거래처관리: 매입 거래처만
      return <ActiveComponent filterByType="purchase" />;
    } else {
      return <ActiveComponent />;
    }
  };

  // 화면 크기 감지 및 타블릿 대응
  useEffect(() => {
    const checkScreenSize = () => {
      const width = window.innerWidth;
      setIsMobile(width < 768);
      
      // 타블릿 구간 (768px ~ 1024px)에서 자동으로 LNB 축소
      if (width >= 768 && width < 1024) {
        setIsSidebarCollapsed(true);
      }
    };

    checkScreenSize();
    window.addEventListener('resize', checkScreenSize);
    return () => window.removeEventListener('resize', checkScreenSize);
  }, []);

  // LNB 축소 상태를 localStorage에 저장
  useEffect(() => {
    localStorage.setItem('sidebar-collapsed', JSON.stringify(isSidebarCollapsed));
  }, [isSidebarCollapsed]);

  // 페이지 변경 시 스크롤을 맨 위로 이동
  useEffect(() => {
    window.scrollTo(0, 0);
  }, [activeMenu]);

  // Check for demo link in URL
  useEffect(() => {
    const checkDemoLink = () => {
      const hash = window.location.hash;
      console.log("Checking hash:", hash);
      const demoMatch = hash.match(/^#\/demo\/(.+)$/);
      
      if (demoMatch) {
        const demoId = demoMatch[1];
        console.log("Demo ID found:", demoId);
        const demoConfigs = JSON.parse(localStorage.getItem("demoConfigs") || "{}");
        console.log("All demo configs:", demoConfigs);
        const config = demoConfigs[demoId];
        
        if (config) {
          // Check if demo is expired
          const expiryDate = new Date(config.expiryDate);
          const now = new Date();
          
          if (now < expiryDate) {
            console.log("✅ Demo config loaded:", config);
            console.log("Setting currentPage to: demo");
            setDemoConfig(config);
            setIsDemoMode(true);
            setCurrentPage("demo");
            setActiveMenu("dashboard");
          } else {
            console.log("❌ Demo expired");
            alert("이 데모 링크는 만료되었습니다. 영업팀에 문의해주세요.");
            window.location.hash = "";
            setCurrentPage("landing");
          }
        } else {
          console.log("❌ Demo config not found for ID:", demoId);
          alert("유효하지 않은 데모 링크입니다.");
          window.location.hash = "";
          setCurrentPage("landing");
        }
      } else {
        console.log("No demo hash detected");
      }
    };
    
    // Check on mount
    checkDemoLink();
    
    // Listen for hash changes
    const handleHashChange = () => {
      console.log("Hash changed!");
      checkDemoLink();
    };
    
    window.addEventListener('hashchange', handleHashChange);
    return () => window.removeEventListener('hashchange', handleHashChange);
  }, []);

  useEffect(() => {
    // Apply theme to document
    document.documentElement.className = theme === 'light' ? '' : theme;
  }, [theme]);

  const handleMenuClick = (menuId: string) => {
    setActiveMenu(menuId);
    if (isMobile) {
      setIsMobileSidebarOpen(false);
    }
  };

  const handleStartDemo = () => {
    setIsDemoMode(true);
    setCurrentPage("demo");
    setActiveMenu("dashboard"); // 대시보드로 시작
  };

  const handleBackToLanding = () => {
    setIsDemoMode(false);
    setDemoConfig(null);
    setCurrentPage("landing");
    setActiveMenu("dashboard");
    window.location.hash = "";
  };

  const handleStartDemoWithConfig = (config: any) => {
    setDemoConfig(config);
    setIsDemoMode(true);
    setCurrentPage("demo");
    setActiveMenu("dashboard");
  };

  console.log("Current page:", currentPage);
  console.log("Is demo mode:", isDemoMode);
  console.log("Demo config:", demoConfig);

  // Show landing page
  if (currentPage === "landing") {
    return (
      <LandingPage
        onNavigateToDemoRequest={() => setCurrentPage("demo-request")}
        onNavigateToSalesDashboard={() => setCurrentPage("sales-dashboard")}
        onNavigateToDashboard={() => setCurrentPage("demo")}
        onNavigateToLogin={() => setCurrentPage("login")}
        onNavigateToSignup={() => setCurrentPage("signup")}
        viewMode={viewMode}
        onViewModeChange={setViewMode}
      />
    );
  }

  // Show login page
  if (currentPage === "login") {
    return (
      <LoginPage
        onNavigateToSignup={() => setCurrentPage("signup")}
        onNavigateToLanding={() => setCurrentPage("landing")}
        onLoginComplete={(data) => {
          setUserData(data);
          setUserRole(data.role);
          setCurrentPage("demo");
        }}
      />
    );
  }

  // Show signup page
  if (currentPage === "signup") {
    return (
      <SignupPage
        onNavigateToLogin={() => setCurrentPage("login")}
        onNavigateToLanding={() => setCurrentPage("landing")}
        onSignupComplete={(data) => {
          setUserData(data);
          setUserRole(data.role);
          setCurrentPage("demo");
        }}
      />
    );
  }

  // Show sales dashboard
  if (currentPage === "sales-dashboard") {
    return (
      <SalesLeadDashboard 
        onBackToLanding={() => setCurrentPage("landing")}
        onStartDemo={handleStartDemoWithConfig}
      />
    );
  }

  // Show demo request page
  if (currentPage === "demo-request") {
    return (
      <DemoRequestPage
        onNavigateToLanding={() => setCurrentPage("landing")}
        onRequestComplete={() => setCurrentPage("landing")}
      />
    );
  }

  // ✅ Demo mode or regular dashboard (currentPage === "demo")
  // This renders when:
  // 1. Demo link is accessed (e.g., /#/demo/demo_xxx)
  // 2. User starts demo from sales dashboard
  console.log("🎯 Rendering dashboard! currentPage:", currentPage);

  const SidebarContent = ({ isCollapsed = false }) => (
    <TooltipProvider delayDuration={300}>
      <div className={`h-full flex flex-col clean-glass rounded-2xl overflow-hidden transition-all duration-300 ${
        isCollapsed ? 'sidebar-collapsed' : ''
      }`}>
      <div 
        className={`flex-1 overflow-y-auto overscroll-contain transition-all duration-300 sidebar-scroll-container ${
          isCollapsed ? 'px-2 py-3 flex flex-col items-center' : 'px-3 py-4 md:px-4 md:py-4'
        }`}
        style={{
          scrollbarWidth: 'thin',
          scrollbarColor: 'transparent transparent',
          overscrollBehavior: 'contain',
        }}
        onScroll={(e) => {
          const target = e.currentTarget;
          target.style.scrollbarColor = 'rgb(203 213 225) transparent';
          target.classList.add('is-scrolling');
          clearTimeout((target as any).scrollTimeout);
          (target as any).scrollTimeout = setTimeout(() => {
            target.style.scrollbarColor = 'transparent transparent';
            target.classList.remove('is-scrolling');
          }, 1000);
        }}
      >
        <div className={`transition-all duration-300 ${
          isCollapsed ? 'space-y-1.5 w-full flex flex-col items-center' : 'space-y-1.5'
        }`}>
          {menuItems.map((item: any) => {
            const Icon = item.icon;
            const hasSubItems = item.subItems && item.subItems.length > 0;
            const isExpanded = expandedMenus.includes(item.id);
            const isActive = activeMenu === item.id || (hasSubItems && item.subItems.some((sub: any) => sub.id === activeMenu));
            
            return (
              <div key={item.id} className="relative">
                <button
                  onClick={() => {
                    if (hasSubItems) {
                      // 사이드바 축소/확장 상태 관계없이 서브메뉴 펼치기/접기
                      // 아코디언 방식: 하나만 열리도록 수정
                      setExpandedMenus((prev: string[]) => 
                        prev.includes(item.id) 
                          ? [] // 현재 열린 메뉴를 다시 클릭하면 모두 닫기
                          : [item.id] // 새 메뉴를 열면 다른 메뉴는 닫고 이것만 열기
                      );
                    } else {
                      // 서브메뉴가 없으면 메뉴 이동
                      handleMenuClick(item.id);
                    }
                  }}
                  className={`w-full flex items-center rounded-xl transition-all duration-200 ease-out touch-manipulation group relative overflow-hidden sidebar-menu-item ${
                    isCollapsed ? 'p-3 justify-center' : 'space-x-2.5 p-3 md:p-3.5'
                  } ${
                    isActive
                      ? "text-white clean-shadow scale-[0.98]"
                      : "text-foreground hover:bg-accent hover:scale-[1.02] active:scale-[0.98]"
                  }`}
                  style={isActive ? { backgroundColor: '#3B82F6' } : {}}
                  title={isCollapsed ? item.label : undefined}
                >
                  <div className={`rounded-lg flex items-center justify-center transition-all duration-200 sidebar-menu-icon aspect-square ${
                    isCollapsed ? 'w-7' : 'w-8'
                  } ${
                    isActive
                      ? "bg-white/20" 
                      : "bg-primary/10 group-hover:bg-primary/20"
                  }`}>
                    <Icon className={`transition-all duration-200 ${
                      isCollapsed ? 'h-4 w-4' : 'h-4.5 w-4.5'
                    } ${
                      isActive ? "text-white" : "text-primary"
                    }`} />
                  </div>
                  {!isCollapsed && (
                    <>
                      <span className={`flex-1 font-medium transition-all duration-200 opacity-100 text-left text-sm`}>
                        {item.label}
                      </span>
                      {hasSubItems && (
                        <div className={`transition-transform duration-200 ${
                          isExpanded ? 'rotate-180' : ''
                        }`}>
                          <ChevronDown className="transition-all duration-200 h-4.5 w-4.5" />
                        </div>
                      )}
                    </>
                  )}
                  {isActive && !isCollapsed && (
                    <div className="absolute inset-0 bg-gradient-to-r from-transparent via-white/10 to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-500" />
                  )}
                </button>
                
                {/* 서브메뉴 */}
                {hasSubItems && isExpanded && (
                  <div className={`mt-1.5 transition-all duration-200 ${
                    isCollapsed 
                      ? 'flex flex-col gap-1.5 items-center w-full' 
                      : 'ml-3 space-y-1.5 border-l-2 border-primary/20 pl-3'
                  }`}>
                    {item.subItems.map((subItem: any) => {
                      const SubIcon = subItem.icon;
                      const hasSubSubItems = subItem.subItems && subItem.subItems.length > 0;
                      const isSubExpanded = expandedMenus.includes(subItem.id);
                      const isSubActive = activeMenu === subItem.id || (hasSubSubItems && subItem.subItems.some((sub: any) => sub.id === activeMenu));
                      
                      return (
                        <div key={subItem.id}>
                          <Tooltip>
                            <TooltipTrigger asChild>
                              <button
                                onClick={() => {
                                  if (hasSubSubItems) {
                                    setExpandedMenus((prev: string[]) => 
                                      prev.includes(subItem.id) 
                                        ? prev.filter(id => id !== subItem.id)
                                        : [...prev, subItem.id]
                                    );
                                  } else {
                                    handleMenuClick(subItem.id);
                                  }
                                }}
                                className={`flex items-center rounded-lg transition-all duration-200 group ${
                                  isCollapsed 
                                    ? 'p-2.5 justify-center' 
                                    : 'w-full p-2.5 space-x-2.5'
                                } ${
                                  isSubActive
                                    ? "bg-primary/10 text-primary"
                                    : "text-muted-foreground hover:bg-accent hover:text-foreground"
                                }`}
                              >
                                <SubIcon className="h-4 w-4" />
                                {!isCollapsed && (
                                  <>
                                    <span className="flex-1 text-left text-sm font-medium">{subItem.label}</span>
                                    {hasSubSubItems && (
                                      <ChevronDown className={`h-4 w-4 transition-transform duration-200 ${
                                        isSubExpanded ? 'rotate-180' : ''
                                      }`} />
                                    )}
                                  </>
                                )}
                              </button>
                            </TooltipTrigger>
                            {isCollapsed && (
                              <TooltipContent side="right" className="font-medium">
                                <p>{subItem.label}</p>
                              </TooltipContent>
                            )}
                          </Tooltip>
                          
                          {hasSubSubItems && isSubExpanded && !isCollapsed && (
                            <div className="ml-3 mt-1.5 space-y-1.5 border-l-2 border-primary/10 pl-3">
                              {subItem.subItems.map((subSubItem: any) => {
                                const SubSubIcon = subSubItem.icon;
                                return (
                                  <button
                                    key={subSubItem.id}
                                    onClick={() => handleMenuClick(subSubItem.id)}
                                    className={`flex items-center w-full p-2 space-x-2 rounded-lg transition-all duration-200 group ${
                                      activeMenu === subSubItem.id
                                        ? "bg-primary/10 text-primary"
                                        : "text-muted-foreground hover:bg-accent hover:text-foreground"
                                    }`}
                                  >
                                    <SubSubIcon className="h-3.5 w-3.5" />
                                    <span className="text-xs font-medium">{subSubItem.label}</span>
                                  </button>
                                );
                              })}
                            </div>
                          )}
                        </div>
                      );
                    })}
                  </div>
                )}
              </div>
            );
          })}
        </div>
      </div>
    </div>
    </TooltipProvider>
  );

  if (isMobile) {
    return (
      <div className="min-h-screen flex-col">
        {/* Demo Mode Badge - Bottom Center */}
          {isDemoMode && demoConfig && (
            <div className="fixed bottom-4 left-1/2 -translate-x-1/2 z-50 w-[calc(100%-2rem)] animate-in slide-in-from-bottom-4 duration-500">
              <Badge className="bg-gradient-to-r from-green-500 to-green-600 text-white px-4 py-2.5 text-xs clean-shadow-lg rounded-full border-2 border-green-400/30 flex items-center justify-center">
                <Eye className="w-3 h-3 mr-1.5 inline" />
                <span className="font-semibold">{demoConfig.company} 데모</span>
                <span className="mx-1.5">•</span>
                {Math.max(0, Math.ceil((new Date(demoConfig.expiryDate).getTime() - Date.now()) / (1000 * 60 * 60 * 24)))}일 남음
              </Badge>
            </div>
          )}

        {/* Mobile Header - Clean style */}
        <header className="clean-glass sticky top-0 z-40 px-4 py-4 m-3 rounded-2xl clean-shadow">
          <div className="flex items-center justify-between">
            {/* 좌측 영역: 대시보드일 때는 로고, 다른 페이지일 때는 이전/홈 버튼 */}
            <div className="flex items-center space-x-3">
              {activeMenu === 'dashboard' ? (
                // 대시보드: 로고만 표시
                <div className="flex items-center space-x-3 ml-4">
                  <div className="w-10 h-10 min-w-10 min-h-10 flex-shrink-0 aspect-square rounded-xl flex items-center justify-center shadow-md relative overflow-hidden bg-gradient-to-br from-blue-500 to-blue-600">
                    <div className="text-white font-bold text-lg">S</div>
                  </div>
                  <div>
                    <h1 className="font-bold text-gray-900 text-left">SAM</h1>
                    <p className="text-xs text-gray-500 text-left hidden md:block">Smart Automation Management</p>
                  </div>
                </div>
              ) : (
                // 다른 페이지: 이전/홈 버튼 표시
                <div className="flex items-center space-x-2">
                  <Button 
                    variant="ghost" 
                    size="sm" 
                    className="min-w-[44px] min-h-[44px] p-0 rounded-xl hover:bg-accent transition-all duration-200 flex items-center justify-center"
                    onClick={handleGoBack}
                    title="이전 페이지"
                  >
                    <ChevronLeft className="h-5 w-5" />
                  </Button>
                  <Button 
                    variant="ghost" 
                    size="sm" 
                    className="min-w-[44px] min-h-[44px] p-0 rounded-xl hover:bg-accent transition-all duration-200 flex items-center justify-center"
                    onClick={() => setActiveMenu('dashboard')}
                    title="홈으로"
                  >
                    <Home className="h-5 w-5" />
                  </Button>
                </div>
              )}
            </div>

            <div className="flex items-center space-x-1">
              {/* Search Icon */}
              <Button 
                variant="ghost" 
                size="sm" 
                className="min-w-[44px] min-h-[44px] p-0 rounded-xl hover:bg-accent transition-all duration-200 flex items-center justify-center"
                onClick={() => setIsIntegratedSearchOpen(true)}
              >
                <Search className="h-5 w-5" />
              </Button>
              
              <Sheet open={isMobileSearchOpen} onOpenChange={setIsMobileSearchOpen}>
                <SheetTrigger asChild>
                  <Button variant="ghost" size="sm" className="min-w-[44px] min-h-[44px] p-0 rounded-xl hover:bg-accent transition-all duration-200 flex items-center justify-center hidden">
                    <Search className="h-5 w-5" />
                  </Button>
                </SheetTrigger>
                <SheetContent side="top" className="h-auto max-h-[80vh] overflow-y-auto">
                  <SheetHeader>
                    <SheetTitle>통합 검색</SheetTitle>
                  </SheetHeader>
                  <div className="mt-4">
                    <div className="relative">
                      <Search className="absolute left-4 top-1/2 transform -translate-y-1/2 text-muted-foreground h-5 w-5 pointer-events-none" />
                      <Input 
                        placeholder="메뉴 검색..." 
                        className="pl-12 text-base" 
                        value={searchQuery}
                        onChange={(e) => setSearchQuery(e.target.value)}
                        autoFocus
                      />
                    </div>
                    
                    {/* 검색 결과 */}
                    {searchResults.length > 0 && (
                      <div className="mt-4 space-y-2">
                        {searchResults.map((result) => {
                          const Icon = result.icon;
                          return (
                            <button
                              key={result.id}
                              onClick={() => {
                                handleSearchResultClick(result.id);
                                setIsMobileSearchOpen(false);
                                setSearchQuery("");
                              }}
                              className="w-full flex items-center gap-3 p-3 hover:bg-accent transition-colors text-left rounded-lg"
                            >
                              <div className="w-10 h-10 rounded-lg bg-primary/10 flex items-center justify-center flex-shrink-0">
                                <Icon className="h-5 w-5 text-primary" />
                              </div>
                              <div className="flex-1 min-w-0">
                                <div className="font-medium text-sm text-foreground">
                                  {result.label}
                                </div>
                                {result.parentLabel && (
                                  <div className="text-xs text-muted-foreground">
                                    {result.parentLabel}
                                  </div>
                                )}
                              </div>
                              <Badge variant="outline" className="text-xs">
                                {result.type === 'main' ? '메인' : '서브'}
                              </Badge>
                            </button>
                          );
                        })}
                      </div>
                    )}
                    
                    {/* 검색어가 있지만 결과가 없을 때 */}
                    {searchQuery.trim() !== "" && searchResults.length === 0 && (
                      <div className="mt-8 text-center text-muted-foreground text-sm">
                        검색 결과가 없습니다.
                      </div>
                    )}
                  </div>
                </SheetContent>
              </Sheet>
              
              {/* Theme Toggle */}
              <DropdownMenu>
                <DropdownMenuTrigger asChild>
                  <Button variant="ghost" size="sm" className="min-w-[44px] min-h-[44px] p-0 rounded-xl hover:bg-accent transition-all duration-200 flex items-center justify-center">
                    {theme === 'light' && <Sun className="h-5 w-5" />}
                    {theme === 'dark' && <Moon className="h-5 w-5" />}
                  </Button>
                </DropdownMenuTrigger>
                <DropdownMenuContent align="end">
                  <DropdownMenuItem onClick={() => setTheme('light')}>
                    <Sun className="mr-2 h-4 w-4" />
                    일반모드
                  </DropdownMenuItem>
                  <DropdownMenuItem onClick={() => setTheme('dark')}>
                    <Moon className="mr-2 h-4 w-4" />
                    다크모드
                  </DropdownMenuItem>
                </DropdownMenuContent>
              </DropdownMenu>

              <div className="min-w-[44px] min-h-[44px] w-11 h-11 bg-muted rounded-xl flex items-center justify-center clean-shadow-sm">
                <User className="h-4 w-4 text-primary" />
              </div>

              {/* 햄버거 메뉴 - 맨 우측 */}
              <Sheet open={isMobileSidebarOpen} onOpenChange={setIsMobileSidebarOpen}>
                <SheetTrigger asChild>
                  <Button variant="ghost" size="sm" className="min-w-[44px] min-h-[44px] p-0 rounded-xl hover:bg-accent transition-all duration-200 flex items-center justify-center">
                    <Menu className="h-6 w-6" />
                  </Button>
                </SheetTrigger>
                <SheetContent side="right" className="w-80 p-1 bg-transparent border-none">
                  <SheetHeader className="sr-only">
                    <SheetTitle>메뉴</SheetTitle>
                  </SheetHeader>
                  <SidebarContent isCollapsed={false} />
                </SheetContent>
              </Sheet>
            </div>
          </div>
        </header>

        {/* Mobile Content */}
        <main className={`flex-1 overflow-auto px-3 ${isDemoMode ? 'pb-20' : ''}`}>
          {activeMenu === "dashboard" ? (
            <Dashboard userRole={userRole} />
          ) : activeMenu === "leads" ? (
            <SalesLeadDashboard />
          ) : activeMenu === "sales" ? (
            <SalesManagement />
          ) : activeMenu === "production" ? (
            <ProductionManagement userRole={userRole} />
          ) : activeMenu === "performance" ? (
            <WorkerPerformance />
          ) : activeMenu === "quality" ? (
            <QualityManagement />
          ) : activeMenu === "materials" ? (
            <MaterialManagement />
          ) : activeMenu === "shipping" ? (
            <ShippingManagement />
          ) : activeMenu === "accounting" ? (
            <AccountingManagement />
          ) : activeMenu === "master" ? (
            <MasterData />
          ) : activeMenu === "system" ? (
            <SystemManagement userRole={userRole} defaultTab={systemManagementTab} />
          ) : activeMenu === "bom-create" ? (
            <BOMCreatePage 
              bomToEdit={bomToEdit}
              onBack={() => {
                setActiveMenu("production-bom");
                setBomToEdit(null);
              }}
              onSave={(bomData) => {
                console.log('BOM 저장:', bomData);
                setActiveMenu("production-bom");
                setBomToEdit(null);
              }}
            />
          ) : activeMenu === "production-bom" ? (
            <BOMManagement 
              onNavigateToBOMCreate={() => {
                setBomToEdit(null);
                setActiveMenu("bom-create");
              }}
              onNavigateToBOMEdit={(bomData) => {
                setBomToEdit(bomData);
                setActiveMenu("bom-create");
              }}
              onNavigateToBOMView={(bomData) => {
                setBomToEdit(bomData);
                setActiveMenu("bom-create");
              }}
            />
          ) : activeMenu === "bom-registration-new" ? (
            <BOMRegistration 
              onBack={() => setActiveMenu("bom-management-production-admin")}
            />
          ) : activeMenu === "bom-management-production-admin" ? (
            <BOMManagementEnhanced 
              onNavigateToBOMRegister={() => setActiveMenu("bom-registration-new")}
            />
          ) : (
            renderActiveComponent()
          )}
        </main>
        
        {/* 통합검색 다이얼로그 (모바일) */}
        <IntegratedSearch 
          open={isIntegratedSearchOpen}
          onOpenChange={setIsIntegratedSearchOpen}
          onNavigate={(page, id) => {
            setActiveMenu(page);
          }}
        />
      </div>
    );
  }

  return (
        <>
        <SidebarProvider>
        <div className="h-screen flex flex-col w-full overflow-hidden">
        {/* Demo Mode Badge - Bottom Center */}
        {isDemoMode && demoConfig && (
          <div className="fixed bottom-6 left-1/2 -translate-x-1/2 z-50 animate-in slide-in-from-bottom-4 duration-500">
            <Badge className="bg-gradient-to-r from-green-500 to-green-600 text-white px-6 py-3 text-sm clean-shadow-lg rounded-full border-2 border-green-400/30">
              <Eye className="w-4 h-4 mr-2 inline" />
              <span className="font-semibold">
                {demoConfig.company} 전용 데모
              </span>
              <span className="mx-2">•</span>
              <span>
                남은 기간: {Math.max(0, Math.ceil((new Date(demoConfig.expiryDate).getTime() - Date.now()) / (1000 * 60 * 60 * 24)))}일
              </span>
            </Badge>
          </div>
        )}

        {/* Desktop Header - Clean style with SAM Logo - Full Width */}
        <header className="clean-glass px-8 py-5 mx-3 mt-3 mb-3 rounded-2xl clean-shadow relative overflow-hidden flex-shrink-0 z-50 bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/60">
            <div className="flex items-center justify-between relative z-10">
              <div className="flex items-center space-x-6">
                {/* SAM Logo Section */}
                <div className="flex items-center space-x-4 pr-6 border-r border-border/30">
                  <div className="w-12 h-12 rounded-xl flex items-center justify-center shadow-md relative overflow-hidden bg-gradient-to-br from-blue-500 to-blue-600 flex-shrink-0 aspect-square">
                    <div className="text-white font-bold text-xl">S</div>
                  </div>
                  <div>
                    <h1 className="text-xl font-bold text-gray-900">SAM</h1>
                    <p className="text-xs text-gray-500 font-medium">Smart Automation Management</p>
                  </div>
                </div>

                {isDemoMode && demoConfig && (
                  <div className="flex items-center gap-4">
                    <div className="bg-green-50 border border-green-200 rounded-xl px-4 py-2">
                      <p className="text-xs text-green-700 font-semibold">
                        {demoConfig.clientName}님 환영합니다!
                      </p>
                      <p className="text-xs text-green-600">
                        {demoConfig.industryPreset} 산업 맞춤 데모
                      </p>
                    </div>
                  </div>
                )}
                <Button 
                  variant="ghost" 
                  size="sm" 
                  onClick={() => setIsSidebarCollapsed(!isSidebarCollapsed)}
                  className="rounded-xl transition-all duration-200 hover:bg-accent p-3"
                >
                  <Menu className="h-5 w-5" />
                </Button>
                
                <div className="relative hidden lg:block flex-1 max-w-96">
                  <Search className="absolute left-5 top-1/2 transform -translate-y-1/2 text-muted-foreground h-5 w-5 pointer-events-none z-10" />
                  <Input 
                    placeholder="통합 검색..." 
                    className="pl-14 w-full clean-input border-0 bg-input-background/60 text-base" 
                    value={searchQuery}
                    onChange={(e) => setSearchQuery(e.target.value)}
                    onFocus={() => setIsSearchFocused(true)}
                    onBlur={() => {
                      // 검색 결과 클릭을 위해 약간의 지연 추가
                      setTimeout(() => setIsSearchFocused(false), 200);
                    }}
                  />
                  
                  {/* 검색 결과 드롭다운 */}
                  {isSearchFocused && searchResults.length > 0 && (
                    <div className="absolute top-full left-0 right-0 mt-2 bg-white dark:bg-gray-800 rounded-xl shadow-lg border border-border/50 overflow-hidden z-50 max-h-96 overflow-y-auto">
                      {searchResults.map((result) => {
                        const Icon = result.icon;
                        return (
                          <button
                            key={result.id}
                            onClick={() => handleSearchResultClick(result.id)}
                            className="w-full flex items-center gap-3 px-4 py-3 hover:bg-accent transition-colors text-left"
                          >
                            <div className="w-8 h-8 rounded-lg bg-primary/10 flex items-center justify-center flex-shrink-0">
                              <Icon className="h-4 w-4 text-primary" />
                            </div>
                            <div className="flex-1 min-w-0">
                              <div className="font-medium text-sm text-foreground">
                                {result.label}
                              </div>
                              {result.parentLabel && (
                                <div className="text-xs text-muted-foreground">
                                  {result.parentLabel}
                                </div>
                              )}
                            </div>
                            <Badge variant="outline" className="text-xs">
                              {result.type === 'main' ? '메인' : '서브'}
                            </Badge>
                          </button>
                        );
                      })}
                    </div>
                  )}
                  
                  {/* 검색어가 있지만 결과가 없을 때 */}
                  {isSearchFocused && searchQuery.trim() !== "" && searchResults.length === 0 && (
                    <div className="absolute top-full left-0 right-0 mt-2 bg-white dark:bg-gray-800 rounded-xl shadow-lg border border-border/50 overflow-hidden z-50">
                      <div className="px-4 py-8 text-center text-muted-foreground text-sm">
                        검색 결과가 없습니다.
                      </div>
                    </div>
                  )}
                </div>
              </div>

              <div className="flex items-center space-x-6">
                {/* Theme Toggle - Desktop */}
                <DropdownMenu>
                  <DropdownMenuTrigger asChild>
                    <Button variant="ghost" size="sm" className="p-3 rounded-xl hover:bg-accent transition-all duration-200">
                      {theme === 'light' && <Sun className="h-6 w-6" />}
                      {theme === 'dark' && <Moon className="h-6 w-6" />}
                    </Button>
                  </DropdownMenuTrigger>
                  <DropdownMenuContent align="end">
                    <DropdownMenuItem onClick={() => setTheme('light')}>
                      <Sun className="mr-2 h-4 w-4" />
                      일반모드
                    </DropdownMenuItem>
                    <DropdownMenuItem onClick={() => setTheme('dark')}>
                      <Moon className="mr-2 h-4 w-4" />
                      다크모드
                    </DropdownMenuItem>
                  </DropdownMenuContent>
                </DropdownMenu>

                <div className="flex items-center space-x-4 pl-6 border-l border-border/30 min-w-fit">
                  <div className="flex items-center space-x-3 min-w-fit">
                    <div className="w-11 h-11 bg-primary/10 rounded-xl flex items-center justify-center clean-shadow-sm flex-shrink-0">
                      <User className="h-5 w-5 text-primary" />
                    </div>
                    <div className="text-sm hidden lg:block text-left min-w-fit">
                      <p className="font-bold text-foreground text-base whitespace-nowrap">
                        {userRole === "CEO" ? "김대표" : userRole === "ProductionManager" ? "이생산" : userRole === "Worker" ? "박작업" : userRole === "SystemAdmin" ? "최시스템" : userRole === "Accountant" ? "정회계" : userRole === "SalesManager" ? "김판매" : "박영업"}
                      </p>
                      <p className="text-muted-foreground text-sm whitespace-nowrap">
                        {userRole === "CEO" && "대표이사"}
                        {userRole === "ProductionManager" && "생산관리자"}
                        {userRole === "Worker" && "생산작업자"}
                        {userRole === "SystemAdmin" && "시스템관리자"}
                        {userRole === "Accountant" && "회계담당자"}
                        {userRole === "SalesManager" && "판매담당자"}
                        {userRole === "Sales" && "영업사원"}
                      </p>
                    </div>
                  </div>
                  <select 
                    value={userRole} 
                    onChange={(e) => setUserRole(e.target.value)}
                    className="ml-4 bg-accent/60 border border-border/50 rounded-2xl backdrop-blur-sm transition-all duration-300 hover:bg-accent/80 hover:scale-105 focus:bg-white focus:border-primary/50 font-semibold text-sm px-4 py-3 whitespace-nowrap flex-shrink-0"
                    style={{
                      backdropFilter: 'blur(16px)',
                    }}
                    onFocus={(e) => {
                      e.target.style.boxShadow = 'var(--clean-shadow)';
                    }}
                    onBlur={(e) => {
                      e.target.style.boxShadow = '';
                    }}
                  >
                    <option value="CEO">대표이사</option>
                    <option value="ProductionManager">생산관리자</option>
                    <option value="Worker">생산작업자</option>
                    <option value="SystemAdmin">시스템관리자</option>
                    <option value="Accountant">회계담당자</option>
                    <option value="SalesManager">판매담당자</option>
                    <option value="Sales">영업사원</option>
                  </select>
                </div>
              </div>
            </div>
            
            {/* Subtle gradient overlay */}
            <div className="absolute top-0 left-0 right-0 h-1 bg-gradient-to-r from-transparent via-primary/30 to-transparent"></div>
          </header>

        {/* Content Area with Sidebar */}
        <div className="flex flex-1 gap-3 px-3 pb-3 overflow-hidden">
          {/* Sidebar - Fixed (No Scroll) */}
          <div className={`border-none bg-transparent hidden md:block transition-all duration-300 flex-shrink-0 overflow-hidden ${
            isSidebarCollapsed ? 'w-24' : 'w-64'
          }`}>
            <SidebarContent isCollapsed={isSidebarCollapsed} />
          </div>

          {/* Main Content - Scrollable */}
          <main className={`flex-1 min-w-0 overflow-y-auto ${isDemoMode ? 'pb-20' : ''}`}>
            {activeMenu === "dashboard" ? (
              <Dashboard userRole={userRole} />
            ) : activeMenu === "sales" ? (
              <SalesManagement />
            ) : activeMenu === "production" ? (
              <ProductionManagement userRole={userRole} />
            ) : activeMenu === "performance" ? (
              <WorkerPerformance />
            ) : activeMenu === "quality" ? (
              <QualityManagement />
            ) : activeMenu === "materials" ? (
              <MaterialManagement />
            ) : activeMenu === "shipping" ? (
              <ShippingManagement />
            ) : activeMenu === "accounting" ? (
              <AccountingManagement />
            ) : activeMenu === "master" ? (
              <MasterData />
            ) : activeMenu === "system" ? (
              <SystemManagement userRole={userRole} defaultTab={systemManagementTab} />
            ) : (
              renderActiveComponent()
            )}
          </main>
        </div>
      </div>
        </SidebarProvider>
        
        {/* 통합검색 다이얼로그 */}
        <IntegratedSearch 
          open={isIntegratedSearchOpen}
          onOpenChange={setIsIntegratedSearchOpen}
          onNavigate={(page, id) => {
            setActiveMenu(page);
          }}
        />
      </>
  );
}