<Window xmlns:ctreditor="clr-namespace:CtrEditor"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:i="http://schemas.microsoft.com/xaml/behaviors"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:Siemens="clr-namespace:LibS7Adv;assembly=LibS7Adv"
        xmlns:local="clr-namespace:CtrEditor"        
        xmlns:controls="clr-namespace:CtrEditor.Controls"
        xmlns:uc="clr-namespace:CtrEditor.ObjetosSim.UserControls"
        xmlns:converters="clr-namespace:CtrEditor.Converters"
        xmlns:xctk="http://schemas.xceed.com/wpf/xaml/toolkit"
        xmlns:sys="clr-namespace:System;assembly=mscorlib"
        xmlns:ObjetosSim="clr-namespace:CtrEditor.ObjetosSim"
        xmlns:helix="http://helix-toolkit.org/wpf"
        xmlns:ObjetosExtraccion="clr-namespace:CtrEditor.ObjetosSim.Extraccion_Datos"
        x:Class="CtrEditor.MainWindow"
        Height="900" Width="1600" WindowState="Maximized" ResizeMode="CanResize" Title="{Binding directorioTrabajo, Converter={StaticResource UnsavedChangesConverter}}"
        Icon="/app2.png">

    <Window.DataContext>
        <ctreditor:MainViewModel />
    </Window.DataContext>

    <Window.Resources>

        <!-- Style for Start/Stop Button -->
        <Style x:Key="StartStopButtonStyle" TargetType="Button">
            <Setter Property="Background" Value="Transparent" />
            <Style.Triggers>
                <DataTrigger Binding="{Binding IsSimulationRunning}" Value="True">
                    <Setter Property="Background" Value="LightGreen" />
                </DataTrigger>
            </Style.Triggers>
        </Style>

        <!-- Style for Connect/Disconnect Button -->
        <Style x:Key="ConnectDisconnectButtonStyle" TargetType="Button">
            <Setter Property="Background" Value="Transparent" />
            <Setter Property="Padding" Value="5" />
            <Setter Property="MinWidth" Value="80" />
            <Style.Triggers>
                <DataTrigger Binding="{Binding IsConnected}" Value="True">
                    <Setter Property="Background" Value="#90EE90" />
                </DataTrigger>
            </Style.Triggers>
        </Style>

        <!-- Converter for PLC Connect/Disconnect button text -->
        <local:ConnectStateToBtnTextConverter x:Key="ConnectStateToBtnTextConverter" />

        <!-- Converter for PLC Connect/Disconnect image -->
        <local:ConnectStateToImageConverter x:Key="ConnectStateToImageConverter" />

        <!-- Converter for Image Display Names -->
        <converters:ImageDisplayNameConverter x:Key="ImageDisplayNameConverter" />

    </Window.Resources>

    <Grid>
        <!-- Menú Principal sobre toda la ventana -->
        <Menu VerticalAlignment="Top" HorizontalAlignment="Stretch">
            <MenuItem Header="Projecto">
                <MenuItem Header="Abrir Directorio de trabajo" Command="{Binding OpenWorkDirectoryCommand}" />
                <MenuItem Header="Ultimos Directorios Utilizados" ItemsSource="{Binding RecentDirectories}">
                    <MenuItem.ItemTemplate>
                        <DataTemplate>
                            <MenuItem Header="{Binding}" Command="{Binding DataContext.OpenRecentDirectoryCommand, RelativeSource={RelativeSource AncestorType=MenuItem, AncestorLevel=2}}" 
                                      CommandParameter="{Binding}"/>
                        </DataTemplate>
                    </MenuItem.ItemTemplate>
                </MenuItem>
                <MenuItem Header="Iniciar Simulacion" Command="{Binding StartSimulationCommand}" />
                <MenuItem Header="Detenet Simulacion" Command="{Binding StopSimulationCommand}" />
                <MenuItem Header="Debug Window" Command="{Binding DebugWindowCommand}" />
                <MenuItem Header="Guardar" Command="{Binding SaveCommand}" />
                <MenuItem Header="Salir" Command="{Binding ExitCommand}" />
            </MenuItem>
        </Menu>

        <Grid x:Name="MainGrid" Margin="0,20,0,0">
            <!-- Margen superior para el menú -->
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="1*" MinWidth="200" />
                <ColumnDefinition Width="8*" MinWidth="200" />
                <ColumnDefinition Width="2*" MinWidth="100" />
            </Grid.ColumnDefinitions>

            <!-- Primera Columna -->
            <Grid Grid.Column="0">
                <Grid.RowDefinitions>
                    <RowDefinition Height="1*" />
                    <RowDefinition Height="2*" />
                    <RowDefinition Height="Auto" />
                </Grid.RowDefinitions>
                <ListBox x:Name="ListaImagenes" Grid.Row="0" Margin="5" ItemsSource="{Binding ListaImagenes}"
                        SelectedItem="{Binding SelectedImage}">
                    <ListBox.ItemTemplate>
                        <DataTemplate>
                            <TextBlock Text="{Binding Converter={StaticResource ImageDisplayNameConverter}}"/>
                        </DataTemplate>
                    </ListBox.ItemTemplate>
                    <ListBox.ContextMenu>
                        <ContextMenu>
                            <MenuItem Header="Propiedades" Command="{Binding RenameImageCommand}" CommandParameter="{Binding PlacementTarget.SelectedItem, RelativeSource={RelativeSource AncestorType=ContextMenu}}"/>
                        </ContextMenu>
                    </ListBox.ContextMenu>
                </ListBox>
                <TreeView x:Name="ListaFunciones" Grid.Row="1" Margin="5" ItemsSource="{Binding CategoriasOsBase}">
                    <TreeView.ItemTemplate>
                        <HierarchicalDataTemplate DataType="{x:Type local:CategoriaNode}" ItemsSource="{Binding Elementos}">
                            <TextBlock Text="{Binding Nombre}" FontWeight="Bold" Foreground="DarkBlue"/>
                            <HierarchicalDataTemplate.ItemTemplate>
                                <DataTemplate DataType="{x:Type local:TipoSimulable}">
                                    <TextBlock Text="{Binding Nombre}" Margin="10,0,0,0">
                                        <TextBlock.InputBindings>
                                            <MouseBinding MouseAction="LeftDoubleClick" 
                                                        Command="{Binding DataContext.ItemDoubleClickCommand, RelativeSource={RelativeSource AncestorType=TreeView}}" 
                                                        CommandParameter="{Binding}" />
                                        </TextBlock.InputBindings>
                                    </TextBlock>
                                </DataTemplate>
                            </HierarchicalDataTemplate.ItemTemplate>
                        </HierarchicalDataTemplate>
                    </TreeView.ItemTemplate>
                </TreeView>

                <Siemens:PLCControl x:Name="PLCSim" Grid.Row="2" Margin="5" DataContext="{Binding PLCViewModel}" />
            </Grid>
            <!-- GridSplitter -->
            <GridSplitter Grid.Column="0" Grid.Row="0" HorizontalAlignment="Right" Width="5" Background="LightGray" />

            <!-- Segunda Columna -->
            <Grid x:Name="MiddleColumnGrid" Grid.Column="1">
                <Grid.RowDefinitions>
                    <RowDefinition Height="Auto" />
                    <RowDefinition Height="3*" />
                    <RowDefinition Height="5" />
                    <RowDefinition Height="0" />
                </Grid.RowDefinitions>

                <ToolBarTray Grid.Row="0">
                    <ToolBar>
                        <StackPanel Orientation="Horizontal">
                            <Button Command="{Binding TBStartSimulationCommand}" ToolTip="Iniciar Simulación"
                                    Style="{StaticResource StartStopButtonStyle}">
                                <StackPanel>
                                    <Image Source="Icons/start.png" Width="24" Height="24" />
                                    <TextBlock Text="Iniciar" />
                                </StackPanel>
                            </Button>
                            
                            <!-- Grid para el indicador de Simulación -->
                            <Grid Width="15" Margin="2,0">
                                <TextBlock Text="{Binding SimulationSpeed, StringFormat={}{0:F1}}"
                                         RenderTransformOrigin="0.5,0.5" TextAlignment="Center"
                                        Background="{DynamicResource {x:Static SystemColors.ActiveCaptionBrushKey}}">
                                    <TextBlock.LayoutTransform>
                                        <RotateTransform Angle="-90"/>
                                    </TextBlock.LayoutTransform>
                                </TextBlock>
                            </Grid>
                        </StackPanel>

                        <Button Command="{Binding TBStopSimulationCommand}" ToolTip="Detener Simulación">
                            <StackPanel>
                                <Image Source="Icons/stop.png" Width="24" Height="24" />
                                <TextBlock Text="Detener" />
                            </StackPanel>
                        </Button>
                        <Button Command="{Binding TBSaveCommand}" ToolTip="Guardar">
                            <StackPanel>
                                <Image Source="Icons/save.png" Width="24" Height="24" />
                                <TextBlock Text="Guardar" />
                            </StackPanel>
                        </Button>

                        <StackPanel Orientation="Horizontal">
                            <Button Command="{Binding TBTogglePLCConnectionCommand}"
                                    ToolTip="{Binding IsConnected, Converter={StaticResource ConnectStateToBtnTextConverter}}"
                                    Style="{StaticResource ConnectDisconnectButtonStyle}">
                                <StackPanel>
                                    <Image Source="{Binding IsConnected, Converter={StaticResource ConnectStateToImageConverter}}"
                                            Width="24" Height="24" />
                                    <TextBlock Text="{Binding IsConnected, Converter={StaticResource ConnectStateToBtnTextConverter}}" />
                                </StackPanel>
                            </Button>
                            
                            <!-- Grid para el indicador de PLC -->
                            <Grid Width="15" Margin="2,0">
                                <TextBlock Text="{Binding PlcUpdateSpeed, StringFormat={}{0:F1}}"
                                         RenderTransformOrigin="0.5,0.5" TextAlignment="Center"
                                        Background="{DynamicResource {x:Static SystemColors.ActiveCaptionBrushKey}}">
                                    <TextBlock.LayoutTransform>
                                        <RotateTransform Angle="-90"/>
                                    </TextBlock.LayoutTransform>
                                </TextBlock>
                            </Grid>
                        </StackPanel>

                        <Button Command="{Binding TBMultiPageAnalizeCommand}"
                                ToolTip="Analyze Tags in multiple pages.">
                            <StackPanel>
                                <Image Source="Icons/match.png" Width="24" Height="24" />
                                <TextBlock Text="Multi Page Analyze" />
                            </StackPanel>
                        </Button>

                        <Button Command="{Binding TBMultiPageMatrixCommand}" ToolTip="Analyze Matrix (Multiple Pages)">
                            <StackPanel>
                                <Image Source="Icons/ocr.png" Width="24" Height="24" />
                                <TextBlock Text="Exportar Tags a Excel" />
                            </StackPanel>
                        </Button>

                        <Button Command="{Binding TBToggle3DUpdateCommand}" ToolTip="Activar/Desactivar actualización Debug 3D para mejorar rendimiento">
                            <StackPanel>
                                <Image Source="Icons/app.png" Width="24" Height="24" />
                                <TextBlock>
                                    <TextBlock.Text>
                                        <MultiBinding StringFormat="Debug3D: {0}">
                                            <Binding Path="Is3DUpdateEnabled">
                                                <Binding.Converter>
                                                    <converters:BooleanToLocalizedTextConverter TrueText="Activado" FalseText="Desactivado" />
                                                </Binding.Converter>
                                            </Binding>
                                        </MultiBinding>
                                    </TextBlock.Text>
                                </TextBlock>
                            </StackPanel>
                            <Button.Style>
                                <Style TargetType="Button">
                                    <Setter Property="Background" Value="Transparent" />
                                    <Style.Triggers>
                                        <DataTrigger Binding="{Binding Is3DUpdateEnabled}" Value="True">
                                            <Setter Property="Background" Value="LightGreen" />
                                        </DataTrigger>
                                        <DataTrigger Binding="{Binding Is3DUpdateEnabled}" Value="False">
                                            <Setter Property="Background" Value="LightCoral" />
                                        </DataTrigger>
                                    </Style.Triggers>
                                </Style>
                            </Button.Style>
                        </Button>

                    </ToolBar>
                </ToolBarTray>

                <ScrollViewer Grid.Row="1" x:Name="ImagenEnTrabajoScrollViewer" 
                              HorizontalScrollBarVisibility="Auto"
                              VerticalScrollBarVisibility="Auto" 
                              PanningMode="Both"
                              PreviewKeyDown="ScrollViewer_PreviewKeyDown">
                    <Canvas x:Name="ImagenEnTrabajoCanvas" 
                            Margin="0" 
                            Background="Transparent" 
                            Focusable="True" 
                            FocusVisualStyle="{x:Null}"
                            KeyDown="Canvas_KeyDown">
                        <!-- Agregar Background="Transparent" para que capture los eventos del mouse y -->
                        <!-- asegurar que el Canvas reciba los eventos del botón derecho -->
                        <Canvas.RenderTransform>
                            <TransformGroup>
                                <ScaleTransform x:Name="CanvasScaleTransform" ScaleX="1" ScaleY="1" />
                                <TranslateTransform x:Name="CanvasTranslateTransform" />
                            </TransformGroup>
                        </Canvas.RenderTransform>
                    </Canvas>
                </ScrollViewer>

                <!-- Separador entre vistas -->
                <GridSplitter Grid.Row="2" Height="5" HorizontalAlignment="Stretch" Background="DarkGray"
                        ResizeDirection="Rows" VerticalAlignment="Center" />

                <!-- Vista 3D (Inferior) -->
                <Border Grid.Row="3" BorderBrush="Gray" BorderThickness="1" Margin="2">
                    <Grid>
                        <Grid.RowDefinitions>
                            <RowDefinition Height="Auto" />
                            <RowDefinition Height="*" />
                        </Grid.RowDefinitions>

                        <!-- Header del panel 3D -->
                        <TextBlock Grid.Row="0" Text="Debug 3D - Mundo BEPU" Background="DarkGray" Foreground="White"
                                Padding="5" FontWeight="Bold" />

                        <!-- HelixViewport3D -->
                        <helix:HelixViewport3D x:Name="Debug3DViewport" Grid.Row="1" ShowCoordinateSystem="True"
                                ShowFrameRate="True" CoordinateSystemLabelZ="Z - Altura" EnableCurrentPosition="True"
                                ShowFieldOfView="True" CalculateCursorPosition="True" IsManipulationEnabled="True"
                                Orthographic="True">
                            <helix:DefaultLights />
                            <helix:GridLinesVisual3D Width="100" Length="100" MinorDistance="1" Thickness="0.01"
                                    MajorDistance="7" />
                            <!-- Contenido del viewport se configurará desde code-behind -->
                        </helix:HelixViewport3D>
                    </Grid>
                </Border>
            </Grid>

            <!-- GridSplitter -->
            <GridSplitter Grid.Column="1" Grid.Row="0" HorizontalAlignment="Right" Width="5" Background="LightGray" />

            <!-- Tercera Columna -->
            <Grid Grid.Column="2">
                <Grid.RowDefinitions>
                    <RowDefinition Height="Auto" />
                    <RowDefinition Height="Auto" />
                    <RowDefinition Height="Auto" />
                    <RowDefinition Height="Auto" />
                    <RowDefinition Height="Auto" />
                    <RowDefinition Height="*" />
                    <RowDefinition Height="Auto" />
                </Grid.RowDefinitions>

                <ToolBarTray Grid.Row="0">
                    <ToolBar>
                        <Button Command="{Binding TBEliminarTodosCommand}" ToolTip="Eliminar Todos">
                            <StackPanel>
                                <Image Source="Icons/borrar.png" Width="16" Height="16" />
                                <TextBlock Text="All Objects" />
                            </StackPanel>
                        </Button>
                        <Button Command="{Binding TBEliminarAutoCreatedCommand}" ToolTip="Eliminar Auto">
                            <StackPanel>
                                <Image Source="Icons/borrar.png" Width="16" Height="16" />
                                <TextBlock Text="Auto Created" />
                            </StackPanel>
                        </Button>
                        <Button Command="{Binding TBEliminarClonedCommand}" ToolTip="Eliminar Cloned for tag Extraction">
                            <StackPanel>
                                <Image Source="Icons/borrar.png" Width="16" Height="16" />
                                <TextBlock Text="Cloned" />
                            </StackPanel>
                        </Button>
                        <Button Command="{Binding TBAssingPagesCommand}" ToolTip="Assing Pages">
                            <StackPanel>
                                <Image Source="Icons/choose.png" Width="16" Height="16" />
                                <TextBlock Text="Assing Pages"  />
                            </StackPanel>
                        </Button>
                        <Button Command="{Binding TBLibraryManagerCommand}" ToolTip="Gestión de Biblioteca de Objetos">
                            <StackPanel>
                                <Image Source="Icons/app.png" Width="16" Height="16" />
                                <TextBlock Text="Biblioteca"  />
                            </StackPanel>
                        </Button>

                    </ToolBar>
                </ToolBarTray>
                <!-- Filter Control -->
                <Expander Grid.Row="1" Header="Filters" IsExpanded="False">
                    <controls:osVisFilter x:Name="VisFilter" Margin="5"/>
                </Expander>

                <!-- ListBox -->
                <Expander Grid.Row="2" Header="Objects List" IsExpanded="False">
                    <ListBox x:Name="ListaOs" 
                            Margin="5" 
                            MinHeight="100"
                            MaxHeight="300"
                            ItemsSource="{Binding ObjetosSimulables}"
                            SelectedItem="{Binding SelectedItemOsList, Mode=TwoWay}"
                            SelectionChanged="ListaOs_SelectionChanged">
                        <ListBox.ItemTemplate>
                            <DataTemplate>
                                <TextBlock Text="{Binding Nombre}">
                                    <TextBlock.Style>
                                        <Style TargetType="TextBlock">
                                            <Style.Triggers>
                                                <DataTrigger Binding="{Binding Path=Enable_On_All_Pages}" Value="True">
                                                    <Setter Property="Foreground" Value="Blue" />
                                                </DataTrigger>
                                                <DataTrigger Binding="{Binding Path=Enable_On_All_Pages}" Value="False">
                                                    <Setter Property="Foreground" Value="Black" />
                                                </DataTrigger>
                                                <DataTrigger Binding="{Binding Path=IsVisFilter}" Value="False">
                                                    <Setter Property="Opacity" Value="0.5" />
                                                </DataTrigger>
                                            </Style.Triggers>
                                        </Style>
                                    </TextBlock.Style>
                                </TextBlock>
                            </DataTemplate>
                        </ListBox.ItemTemplate>
                    </ListBox>
                </Expander>

                <!-- Object Hierarchy -->
                <Expander Grid.Row="3" Header="Object Hierarchy" IsExpanded="True">
                    <controls:ObjectHierarchyView x:Name="ObjectHierarchy" 
                                                 Margin="5"
                                                 MinHeight="100"
                                                 MaxHeight="300"/>
                </Expander>

                <!-- GridSplitter -->
                <GridSplitter Grid.Row="4" Height="5" 
                              HorizontalAlignment="Stretch" 
                              Background="Gray"
                              ResizeDirection="Rows" 
                              VerticalAlignment="Center" />

                <!-- PanelEdicion -->
                <controls:PanelEdicionControl Grid.Row="5" 
                                             x:Name="PanelEdicion" 
                                             Margin="5"/>

                <ToolBarTray Grid.Row="6">
                    <ToolBar>
                        <Button Command="{Binding TBEliminarUserControlCommand}" ToolTip="Eliminar Control">
                            <StackPanel>
                                <Image Source="Icons/borrar.png" Width="16" Height="16" />
                                <TextBlock Text="Eliminar" />
                            </StackPanel>
                        </Button>
                        <Button Command="{Binding TBDuplicarUserControlCommand}" ToolTip="Duplicar Control">
                            <StackPanel>
                                <Image Source="Icons/duplicate.png" Width="16" Height="16" />
                                <TextBlock Text="Duplicar" />
                            </StackPanel>
                        </Button>
                    </ToolBar>
                </ToolBarTray>

            </Grid>

        </Grid>
    </Grid>
</Window>
