let workspace;
let codeVisible = true;

document.addEventListener("DOMContentLoaded", () => {
    // TOOLBOX SETUP (JSON)
    const toolbox = {
        "kind": "categoryToolbox",
        "contents": [
// 1. BOARD
            { 
                "kind": "category", "name": "Board", "colour": "210",
                "contents": [
                    {"kind": "block", "type": "arduino_main"},
                    {"kind": "block", "type": "board_pc_interrupt"},
					{"kind": "block", "type": "kommentar"}, 
					{"kind": "block", "type": "ard_sys_reset"},
					{"kind": "block", "type": "ard_return"},
					{"kind": "block", "type": "ard_break"}, 
					{"kind": "label", "text": "--- Farb-Container ---"},
					{"kind": "block", "type": "ard_container_red"},
					{"kind": "block", "type": "ard_container_orange"},
					{"kind": "block", "type": "ard_container_yellow"},
					{"kind": "block", "type": "ard_container_green"},
					{"kind": "block", "type": "ard_container_cyan"},
					{"kind": "block", "type": "ard_container_blue"},
					{"kind": "block", "type": "ard_container_purple"}
                ] 
            },
			
// 2. STEUERUNG
            {
                "kind": "category", "name": "Steuerung", "colour": "290",
                "contents": [
                    {"kind": "block", "type": "logic_if"},
					{"kind": "block", "type": "ard_loop_while"},
                    {"kind": "block", "type": "logic_if_else"},
                    {"kind": "block", "type": "loop_repeat"},
                    {"kind": "block", "type": "loop_for"},
					{"kind": "label", "text": "--- erweitert ---"},
					{"kind": "block", "type": "ard_logic_if_plus"},
                    {"kind": "block", "type": "ard_loop_until"},
                    {"kind": "block", "type": "ard_loop_control"},
                    {"kind": "block", "type": "ard_run_once"},
                    {"kind": "block", "type": "ard_system_halt"},
                    {"kind": "label", "text": "--- Flankenerkennung ---"},
                    {"kind": "block", "type": "ard_edge_value"},
                    {"kind": "block", "type": "ard_edge_statement"}

                        ]
            },
					
					
// 3. STEUERUNG
            {
                "kind": "category", "name": "States", "colour": "290",
                "contents": [
					
                    {"kind": "label", "text": "--- wähle nur eine aus ---"},
                    
                    {"kind": "label", "text": "--- symple ---"},
                    {"kind": "block", "type": "ard_switch"},
                    {"kind": "block", "type": "ard_case"},
                    {"kind": "block", "type": "ard_default"},
                    
                    {"kind": "label", "text": "--- complex ---"},
                    {"kind": "block", "type": "ard_switch_2"},
                    {"kind": "block", "type": "ard_case_2"},
					{"kind": "block", "type": "ard_case_cond_2"},
                    {"kind": "block", "type": "ard_default_2"},
                    {"kind": "block", "type": "ard_state_time"},
                    {"kind": "block", "type": "ard_break"},
                    {"kind": "block", "type": "ard_return"},
                    {"kind": "block", "type": "ard_static_var"},
                    
					{"kind": "label", "text": "--- state engine ---"},
					{"kind": "block", "type": "ard_state_engine_main"},
					{"kind": "block", "type": "ard_state_engine_state"},
					{"kind": "block", "type": "ard_state_engine_change"},
					{"kind": "block", "type": "ard_state_engine_time"},
					{"kind": "block", "type": "ard_return"},
					
					{"kind": "label", "text": "--- state classes ---"},
                    {"kind": "block", "type": "ard_class_register"},
                    {"kind": "block", "type": "ard_class_state"},
                    {"kind": "block", "type": "ard_class_change"}
						
                ]
            },

// 4 Zeiten
            {
                "kind": "category", "name": "Zeit", "colour": "290",
                "contents": [
                    {
                        "kind": "category", "name": "Zeiten", "colour": "290",
                        "contents": [
						    {"kind": "block", "type": "ard_time_sys"},
						    {"kind": "label", "text": "--- ⚠️ (Pausiert alles) ---"},
                            {"kind": "block", "type": "delay_ms"},
                            {"kind": "block", "type": "delay_micros"}
                        ]
                    },
                    {
                        "kind": "category", "name": "Generatoren", "colour": "290",
                        "contents": [
                            {"kind": "label", "text": "--- Mache alle X ---"},
                            {"kind": "block", "type": "do_them_all"},
							{"kind": "label", "text": "--- Mache alle X zähle ---"},
                            {"kind": "block", "type": "timer_counter_main"},
                            {"kind": "block", "type": "timer_counter_get"},
                            {"kind": "block", "type": "timer_counter_set"},
                            {"kind": "block", "type": "timer_counter_reset"},
                            {"kind": "label", "text": "--- Stoppuhr ---"},
                            {"kind": "block", "type": "stopwatch_define"},
                            {"kind": "block", "type": "stopwatch_command"},
                            {"kind": "block", "type": "stopwatch_read"},
                            {"kind": "label", "text": "--- Blinker ---"},
                            {"kind": "block", "type": "ard_blinker_define"},
                            {"kind": "block", "type": "ard_blinker"},
                            {"kind": "block", "type": "ard_blinker_get"}
                        ]
                    },
					
					
                   {
                        "kind": "category", "name": "Echtzeituhr", "colour": "290",
                        "contents": [
                            {"kind": "label", "text": "--- Interne RTC (R4 / NTP) ---"},
                            {"kind": "block", "type": "ard_rtc_setup"},
                            {"kind": "block", "type": "ard_rtc_read"},
                            {"kind": "block", "type": "ard_rtc_write"},
                            {"kind": "block", "type": "ard_rtc_get_string"},
                            {"kind": "block", "type": "ard_rtc_unix"},
                            {"kind": "block", "type": "ard_rtc_ntp_sync"},
                            
                            {"kind": "label", "text": "--- Externe RTC (I2C) ---"},
                            {"kind": "block", "type": "ard_rtc_ext_setup"},
                            {"kind": "block", "type": "ard_rtc_ext_read"},
                            
                            {"kind": "label", "text": "--- Schaltuhr Universal ---"},
                            {"kind": "block", "type": "ard_timer_encoder_ctrl"},
                            {"kind": "block", "type": "ard_timer_get_display_text"},
                            {"kind": "block", "type": "ard_timer_slot_eval"},
                            
                            {"kind": "label", "text": "--- Schaltuhr TM1638 ---"},
                            {"kind": "block", "type": "ard_timer_tm1638_ctrl"},
                            {"kind": "block", "type": "ard_timer_tm1638_eval"}
                        ]
                    }
                ]
            },

// 5. EINGÄNGE
            { 
                "kind": "category", "name": "Eingänge", "colour": "45",
                "contents": [
                    {
                        "kind": "category", "name": "Standard Pins", "colour": "45",
                        "contents": [
                            {"kind": "block", "type": "ard_setup_pullup"}, 
                            {"kind": "block", "type": "ard_read_digital"}, 
                            {"kind": "block", "type": "read_analog"},
                            {"kind": "label", "text": "--- (Tasten & Joystick) ---"},
                            {"kind": "block", "type": "ard_analog_smooth_pro"},
                            {"kind": "block", "type": "ard_analog_button_ladder"},
                            {"kind": "block", "type": "ard_analog_button_setup"},
                            {"kind": "block", "type": "ard_joy_universal"},
                            {"kind": "block", "type": "ard_joy_setup"}
                        ]
                    },
                   {
                        "kind": "category", "name": "Taster & Zähler", "colour": "65",
                        "contents": [
                            {"kind": "block", "type": "input_counter"},
                            {"kind": "block", "type": "input_encoder"},
                            
                            {"kind": "label", "text": "--- Basis-Taster (!Entweder...) ---"},
                            {"kind": "block", "type": "ard_button_event"},
                            {"kind": "block", "type": "ard_button_get_counter"}, 
                            {"kind": "block", "type": "ard_button_set_counter"}, 
                            {"kind": "block", "type": "ard_button_reset_counter"},
                            
                            {"kind": "label", "text": "--- Profi-Taster (...Oder!) ---"},
                            {"kind": "block", "type": "ard_button_pro"},
                            {"kind": "block", "type": "ard_button_pro_get_counter"},
                            {"kind": "block", "type": "ard_button_pro_set_counter"},
                            {"kind": "block", "type": "ard_button_pro_reset"}
                        ]
                    },
					
					
				{
                        "kind": "category", "name": "TTP229 Touch", "colour": "85",
                        "contents": [
                            {"kind": "block", "type": "ttp229_setup"},
							{"kind": "label", "text": "--- loop ---"},
                            {"kind": "block", "type": "ttp229_update"},
                            {"kind": "label", "text": "--- Lese Zahlen ---"},
                            {"kind": "block", "type": "ttp229_read_pad"},
							{"kind": "block", "type": "ttp229_read__save_pad"},
							{"kind": "block", "type": "ttp229_read__sequence"},
                            {"kind": "label", "text": "--- T9 Text-Modus ---"},
                            {"kind": "block", "type": "ttp229_get_string"},
                            {"kind": "block", "type": "ttp229_is_enter"},
                            {"kind": "block", "type": "ttp229_reset"}
                        ]
                    },
					
	
                    {
                        "kind": "category", "name": "Sensoren", "colour": "85",
                        "contents": [
                            {"kind": "block", "type": "read_dht"},
							{"kind": "block", "type": "read_ultrasonic"},
							{"kind": "label", "text": "--- DS18B20 OneWire ---"},
                            {"kind": "block", "type": "ds18b20_setup"},
                            {"kind": "block", "type": "ds18b20_name_by_index"},
                            {"kind": "block", "type": "ds18b20_name_by_address"},
                            {"kind": "block", "type": "ds18b20_read"},
                            {"kind": "block", "type": "ds18b20_diagnostic"},
                            {"kind": "label", "text": "--- Gyro (MPU6050) ---"},
                            {"kind": "block", "type": "gyro_setup"}, 
                            {"kind": "block", "type": "gyro_read"},  
                            {"kind": "label", "text": "--- RFID (RC522) ---"},
                            {"kind": "block", "type": "ard_rfid_setup"},
                            {"kind": "block", "type": "ard_rfid_on_card"},
                            {"kind": "block", "type": "ard_rfid_get_id"}
                        ]
                    }
                ] 
            },

// 6. AUSGÄNGE
            { 
                "kind": "category", "name": "Ausgänge", "colour": "160",
                "contents": [
                    {
                        "kind": "category", "name": "Standard Pins", "colour": "160",
                        "contents": [
                            {"kind": "block", "type": "write_digital"}, 
                            {"kind": "block", "type": "write_analog"},
                            {"kind": "block", "type": "output_tone"}, 
							{"kind": "label", "text": "--- analog Ausgang ---"},
							{"kind": "block", "type": "r4_dac_preset"},
							{"kind": "block", "type": "r4_dac_voltage_var"},
							{"kind": "block", "type": "r4_dac_raw_var"}
	
                        ]
                    },
					
					{
                        "kind": "category", "name": "Audio", "colour": "160",
                        "contents": [
                            {"kind": "block", "type": "mp3_setup"},
                            {"kind": "block", "type": "mp3_volume"},
                            {"kind": "block", "type": "mp3_play_folder"},
                            {"kind": "block", "type": "mp3_control"}
                        ]
                    },

                   {
                        "kind": "category", "name": "Motoren", "colour": "180",
                        "contents": [
						    {"kind": "label", "text": "--- Servo ---"},
                            {"kind": "block", "type": "out_servo"},
                            {"kind": "block", "type": "out_servo_ramp"},
                            {"kind": "block", "type": "out_servo_attach"},
                            {"kind": "block", "type": "out_servo_detach"},
							{"kind": "label", "text": "--- PCA9685 ---"},	
							{"kind": "block", "type": "pca9685_setup"},
							{"kind": "block", "type": "pca9685_start_pos"},
							{"kind": "block", "type": "pca9685_servo_180"},
							{"kind": "block", "type": "pca9685_servo_ramp"},
							{"kind": "block", "type": "pca9685_servo_detach"},
							{"kind": "block", "type": "pca9685_servo_attach"},
							{"kind": "block", "type": "pca9685_servo_360"},
							{"kind": "block", "type": "pca9685_pwm"},
							{"kind": "label", "text": "--- Stepper ---"},
                            {"kind": "block", "type": "stepper_setup"},
                            {"kind": "block", "type": "stepper_move"},
                            {"kind": "block", "type": "stepper_reset"},
							{"kind": "label", "text": "--- Nema ---"},
                            {"kind": "block", "type": "stepper_nema_control"},
                            {"kind": "block", "type": "stepper_nema_coop"},
							{"kind": "block", "type": "stepper_nema_position"},
							{"kind": "block", "type": "stepper_nema_reset"}
                        ]
                    },
					
					
                    {
                        "kind": "category", "name": "Licht & Matrix", "colour": "140",
                        "contents": [
                            {"kind": "label", "text": "--- NeoPixel (FastLED) ---"},
                            {"kind": "block", "type": "neopixel_setup"},
                            {"kind": "block", "type": "neopixel_set_single"},
                            {"kind": "block", "type": "neopixel_set_list"},
                            {"kind": "block", "type": "neopixel_show"},
                            {"kind": "block", "type": "neopixel_brightness"},
                            {"kind": "block", "type": "neopixel_clear"},
                            {"kind": "block", "type": "neopixel_custom_code"},

                            // --- R4 ONBOARD MATRIX ---
                            {"kind": "label", "text": "--- R4 Onboard Matrix ---"},
                            {"kind": "block", "type": "r4_matrix_setup"},
                            {"kind": "block", "type": "r4_matrix_symbol"},
                            {"kind": "block", "type": "r4_matrix_print_static"}, 
                            {"kind": "block", "type": "r4_matrix_print"},
                            {"kind": "block", "type": "r4_matrix_pixels"},
                            {"kind": "block", "type": "r4_matrix_clear"},

                            // --- MAX7219  ---
                            {"kind": "label", "text": "--- MAX7219 Matrix ---"},
                            {"kind": "block", "type": "max7219_setup"},
                            {"kind": "block", "type": "max7219_print"},
                            {"kind": "block", "type": "max7219_animation"},  
                            {"kind": "block", "type": "max7219_set_intensity"},
                            {"kind": "block", "type": "max7219_set_pixel"},
                            {"kind": "block", "type": "max7219_set_list"},
                            {"kind": "block", "type": "max7219_control"},
							
							
							{"kind": "label", "text": "--- Bit / Byte Anzeige ---"},
							{"kind": "block", "type": "bit_display_setup_pins"},
							{"kind": "block", "type": "bit_display_setup_neopixel"},
							{"kind": "block", "type": "bit_display_setup_max"},
							{"kind": "block", "type": "bit_display_write"}
										
                        ]
                    },
					
                 {
                        "kind": "category", "name": "Displays", "colour": "120",
                        "contents": [
                            {"kind": "label", "text": "--- I2C LCD ---"},
                            {"kind": "block", "type": "setup_lcd_i2c"},
                            {"kind": "block", "type": "out_lcd_i2c"},
                            {"kind": "block", "type": "out_lcd_clear"},
                            {"kind": "block", "type": "out_lcd_action"},
                            {"kind": "label", "text": "--- TFT Displays ---"},
                            {"kind": "block", "type": "tft_setup_st7735"},
                            {"kind": "block", "type": "tft_setup_ili9486"},
                            {"kind": "block", "type": "tft_print_text"},
                            {"kind": "block", "type": "tft_draw_shape"},
                            {"kind": "block", "type": "tft_dimensions"},						
                            {"kind": "label", "text": "--- TM Displays ---"},
                            {"kind": "block", "type": "ard_visu_tm1637_setup"},  
							{"kind": "block", "type": "ard_visu_tm1637_brightn"},  
                            {"kind": "block", "type": "ard_visu_tm1637_print"},      
                            {"kind": "label", "text": "--- TM1638 Modell 1  ---"},
							{"kind": "block", "type": "ard_visu_tm1638_setup_mod1"},   
							{"kind": "block", "type": "ard_visu_tm1638_brightn_mod1"},  
							{"kind": "block", "type": "ard_visu_tm1638_print_mod1"},     
                            {"kind": "block", "type": "ard_visu_tm1638_read_key_mod1"},   
                            {"kind": "block", "type": "ard_visu_tm1638_key_pressed_mod1"},   
                            {"kind": "block", "type": "ard_visu_tm1638_any_key_mod1"},      
                            {"kind": "block", "type": "ard_visu_tm1638_led"},  
                            {"kind": "block", "type": "ard_visu_tm1638_led_var"},							
                            {"kind": "label", "text": "--- TM1638 Modell 2  ---"},
							{"kind": "block", "type": "ard_visu_tm1638_setup"},          
							{"kind": "block", "type": "ard_visu_tm1638_brightn"},  
							{"kind": "block", "type": "ard_visu_tm1638_print"},     
                            {"kind": "block", "type": "ard_visu_tm1638_read_key"},     
                            {"kind": "block", "type": "ard_visu_tm1638_key_pressed"}, 
                            {"kind": "block", "type": "ard_visu_tm1638_any_key"},
                            {"kind": "label", "text": "--- OLED Display ---"},
                            {"kind": "block", "type": "ard_oled_setup"},
                            {"kind": "block", "type": "ard_oled_set_font"},
                            {"kind": "block", "type": "ard_oled_clear"},
                            {"kind": "block", "type": "ard_oled_fill"},
                            {"kind": "block", "type": "ard_oled_print"},
                            {"kind": "block", "type": "ard_oled_print_xy"},
                            {"kind": "block", "type": "ard_oled_print_xy_color"},
                            {"kind": "block", "type": "ard_oled_draw_shape"},
                            {"kind": "block", "type": "ard_oled_draw_picture"},
							{"kind": "label", "text": "--- E-Paper ---"},
                            {"kind": "block", "type": "eink_setup"},
                            {"kind": "block", "type": "eink_control"},
                            {"kind": "block", "type": "eink_set_font"},
                            {"kind": "block", "type": "eink_text_xy"},
                            {"kind": "block", "type": "eink_print"},
                            {"kind": "block", "type": "eink_shape"},
                            {"kind": "block", "type": "eink_pixel"},
                            {"kind": "block", "type": "eink_draw_picture"}
                        ]
                    },
					
				{
							"kind": "category", "name": "DMX", "colour": "250",
							"contents": [
							{"kind": "label", "text": "--- DMX direkt ---"},
							{"kind": "block", "type": "dmx_setup_direct"},
							{"kind": "block", "type": "dmx_write_direct"},
							{"kind": "label", "text": "--- DMX buffer ---"},
							{"kind": "block", "type": "dmx_setup_buffered"},
							{"kind": "block", "type": "dmx_frame_buffered"},
							{"kind": "block", "type": "dmx_write_buffered"},
							{"kind": "label", "text": "--- DMX einfach ---"},
							{"kind": "block", "type": "dmx_setup_simple"},
							{"kind": "block", "type": "dmx_begin_simple"},
							{"kind": "block", "type": "dmx_write_simple"},
							{"kind": "block", "type": "dmx_end_simple"},
							{"kind": "label", "text": "--- DMX lesen---"},
							{"kind": "block", "type": "dmx_read"},
							{"kind": "block", "type": "dmx_available"},
							{"kind": "block", "type": "dmx_stop"}
					]
				}
										
                ] 
            },

// 7 P-Manipulation
            { 
                "kind": "category", "name": "Virtuelle P.", "colour": "160",
                "contents": [
                    {
                        "kind": "category", "name": "Arduino Ports", "colour": "160",
                        "contents": [
                            {"kind": "block", "type": "ard_virtual_port_define"},
                            {"kind": "block", "type": "ard_virtual_port_write"},
                            {"kind": "block", "type": "ard_virtual_port_read"}
                        ]
                    },
					
                    {
                        "kind": "category", "name": "TCA9555", "colour": "160",
                        "contents": [
                            {"kind": "block", "type": "tca_write_pin"},
                            {"kind": "block", "type": "tca_read_pin"},
                            {"kind": "block", "type": "tca_write_pattern"},
                            {"kind": "block", "type": "tca_read_pattern"}
                        ]
                    },
					
					
										{
						"kind": "category", "name": "Infrarot (IR)", "colour": "160",
						"contents": [
							{"kind": "label", "text": "--- Infrarot (IR) ---"},
							{"kind": "block", "type": "ir_transceiver_setup"},
							{"kind": "block", "type": "ir_receive_event"},
							{"kind": "block", "type": "ir_read_value"},
							{"kind": "block", "type": "ir_fill_array"},
							{"kind": "block", "type": "ir_raw_length"},
							{"kind": "label", "text": "--- IR Senden ---"},
							{"kind": "block", "type": "ir_send_standard"},
							{"kind": "block", "type": "ir_send_raw"}
						]
					}
										
										
                ] 
            },

// 8. LOGIK
            { 
                "kind": "category", "name": "Logik", "colour": "230",
                "contents": [
                    {"kind": "block", "type": "ard_logic_compare"},
                    {"kind": "block", "type": "ard_logic_operation"},
                    {"kind": "block", "type": "ard_logic_negate"},
                    {"kind": "block", "type": "ard_logic_boolean"},
                    {"kind": "block", "type": "logic_ternary"}, 
                    {"kind": "block", "type": "ard_math_arithmetic"},
					{"kind": "block", "type": "ard_math_even_odd"},
                    {"kind": "block", "type": "ard_math_number"},
                    {"kind": "block", "type": "ard_math_map"},
                    {"kind": "block", "type": "ard_math_constrain"},
                    {"kind": "block", "type": "ard_math_random_seed"},
                    {"kind": "block", "type": "ard_math_random_int"},
					{"kind": "label", "text": "--- Erweiterte Mathe ---"},
					{"kind": "block", "type": "math_correction_single"},
					{"kind": "block", "type": "math_correction_double"},
					{"kind": "block", "type": "math_trig_root"},
					{"kind": "block", "type": "math_power"},
					{"kind": "block", "type": "math_pi"},
					{"kind": "label", "text": "--- Multi-Logik ---"},
                    {"kind": "block", "type": "ard_logic_and_3"},
                    {"kind": "block", "type": "ard_logic_and_4"},
                    {"kind": "block", "type": "ard_logic_or_3"},
                    {"kind": "block", "type": "ard_logic_or_4"}
                ] 
            },

            { 
                "kind": "category", "name": "Variablen", "colour": "330",
                "contents": [
                    {
                        "kind": "button",
                        "text": "Neue Variable erstellen...",
                        "callbackKey": "CREATE_VAR_BTN"
                    },
                    {"kind": "block", "type": "var_text_literal"},
					{"kind": "block", "type": "ard_text_join"},
					{"kind": "block", "type": "ard_text_join_3"},
                    {"kind": "block", "type": "ard_text_join_4"},
					{"kind": "block", "type": "var_space_literal"},
                    {"kind": "block", "type": "var_number_literal"},
                    {"kind": "block", "type": "var_declare"},
                    {"kind": "block", "type": "var_declare_interrupt"},
                    {"kind": "label", "text": "--- Lokale Merker ---"},
                    {"kind": "block", "type": "ard_static_var"},
                    {"kind": "label", "text": "--- Setzen & Lesen ---"},
                    {"kind": "block", "type": "var_set"},
                    {"kind": "block", "type": "var_get"}
					
                ] 
            },
			
// 9. Tabellen
			{ 
					"kind": "category", "name": "Tabellen", "colour": "315",
					"contents": [
					{"kind": "label", "text": "--- (!Entweder) Einfach ---"},
					{"kind": "block", "type": "array_declare"}, 
					{"kind": "block", "type": "array_write"},   
					{"kind": "block", "type": "array_read"},

					{"kind": "label", "text": "--- (...Oder!) Erweitert ---"},
					{"kind": "block", "type": "array_declare_pro"}, 
        
					{"kind": "label", "text": "--- Signal & Puffer ---"},
					{"kind": "block", "type": "array_fifo_push"},
					{"kind": "block", "type": "array_average"},
					{"kind": "block", "type": "array_min_max"},
					{"kind": "block", "type": "array_fill"},

					{"kind": "label", "text": "--- Mathematik ---"},
					{"kind": "block", "type": "array_sum"},
					{"kind": "block", "type": "array_replace"},
					{"kind": "block", "type": "array_scale_offset"},
					{"kind": "block", "type": "array_count_cond"}
			] 
				},
			
			


// 10. UNTERPROGRAMME
            { 
                "kind": "category", "name": "Unterprog.", "colour": "290",
                "contents": [
                    {"kind": "label", "text": "--- Ohne Rückgabewert ---"},
                    {"kind": "block", "type": "ard_function_define"},
                    {"kind": "block", "type": "ard_function_call"},
                    {"kind": "label", "text": "--- Mit Rückgabewert ---"},
                    {"kind": "block", "type": "ard_function_define_return"},
                    {"kind": "block", "type": "ard_function_return"},
                    {"kind": "block", "type": "ard_function_call_return"}
                ] 
            },

// 11. ERWEITERT
            { 
                "kind": "category", "name": "Erweitert", "colour": "160",
                "contents": [
                    {
                        "kind": "category", "name": "Serial (PC)", "colour": "160",
                        "contents": [
                            {"kind": "block", "type": "ard_serial_begin"},
                            {"kind": "block", "type": "ard_serial_print"},
                            {"kind": "block", "type": "ard_serial_available"},
                            {"kind": "block", "type": "ard_serial_read_string"},
                            {"kind": "block", "type": "ard_serial_read_number"}
                        ]
                    },
                    {
                        "kind": "category", "name": "EEPROM", "colour": "160",
                        "contents": [
                            {"kind": "block", "type": "ard_eeprom_write"},
                            {"kind": "block", "type": "ard_eeprom_read"}
                        ]
                    },
                    {
                        "kind": "category", "name": "SD Karte", "colour": "160",
                        "contents": [
                            {"kind": "block", "type": "ard_sd_begin"},
                            {"kind": "block", "type": "ard_sd_write"},
                            {"kind": "block", "type": "ard_sd_exists"},
                            {"kind": "block", "type": "ard_sd_remove"}
                        ]
                    },
					
                    {
                        "kind": "category", "name": "C++", "colour": "160",
                        "contents": [
                            {"kind": "block", "type": "ard_custom_code_inline"},
                            {"kind": "block", "type": "ard_custom_code_global"}
                        ]
                    },
					
					{
						"kind": "category", "name": "CAN Bus", "colour": "200",
						"contents": [
							{"kind": "block", "type": "can_setup"},
							{"kind": "block", "type": "can_send_cyclic"},
							{"kind": "block", "type": "can_send_change"},
							{"kind": "block", "type": "can_on_receive"}
						]
					},
								
                ] 
            },
			
			{ 
                "kind": "category", "name": "WLAN", "colour": "210",
                "contents": [
                    {"kind": "block", "type": "web_setup"},
                    {"kind": "block", "type": "web_listen"},
					{"kind": "block", "type": "web_ip"},
                    {"kind": "block", "type": "web_status_read"},
                    {"kind": "label", "text": "--- Daten senden (zu Web) ---"},
                    {"kind": "block", "type": "web_digital_write"},
                    {"kind": "block", "type": "web_analog_write"},
                    {"kind": "label", "text": "--- Daten empfangen (von Web) ---"},
                    {"kind": "block", "type": "web_digital_read"},
                    {"kind": "block", "type": "web_analog_read"}
                ] 
            },
			
// 12 Processing APP

         { 
                "kind": "category", "name": "Processing", "colour": "130",
                "contents": [
                    {"kind": "block", "type": "ard_hmi_setup"},
                    {"kind": "label", "text": "--- von PC Empfangen ---"},
                    {"kind": "block", "type": "ard_hmi_receive"},
                    {"kind": "block", "type": "ard_hmi_get_number"},
                    {"kind": "block", "type": "ard_hmi_get_string"},
                    {"kind": "label", "text": "--- zu PC Senden ---"},
                    {"kind": "block", "type": "ard_hmi_send"}
                ] 
            },
			
			
// 13 G-ENGINE KATEGORIE
            { 
                "kind": "category", "name": "G-Engine", "colour": "160",
                "contents": [
                    {"kind": "label", "text": "--- System ---"},
                    {"kind": "block", "type": "g_engine_main"},
                    {"kind": "block", "type": "g_engine_timer"},
                    {"kind": "block", "type": "g_engine_game_over"},
                    
                    {"kind": "label", "text": "--- Akteure (Sprites) ---"},
                    {"kind": "block", "type": "g_engine_sprite_create"},
                    {"kind": "block", "type": "g_engine_sprite_move"},
                    {"kind": "block", "type": "g_engine_sprite_destroy"},

                    {"kind": "label", "text": "--- Steuerung ---"},
                    {"kind": "block", "type": "g_engine_input_button"},
                    
                    {"kind": "label", "text": "--- Logik & Events ---"},
                    {"kind": "block", "type": "g_engine_collision_check"}
                ] 
            },
			
			
			
			// 14 Shield:
					{ 
			"kind": "category", "name": "Shields", "colour": "210",
			"contents": [
	{
            "kind": "category", "name": "Joystick Shield", "colour": "45",
            "contents": [
                {"kind": "block", "type": "ard_shield_joy_dir"},
                {"kind": "block", "type": "ard_shield_joy_val"},
                {"kind": "block", "type": "ard_shield_joy_button"}
            ]
        },
		
		
	{
            "kind": "category", "name": "LCD Keypad", "colour": "210",
            "contents": [
                {"kind": "block", "type": "lcd_keypad_setup"},
                {"kind": "label", "text": "--- Display ---"},
                {"kind": "block", "type": "lcd_keypad_print"},
                {"kind": "block", "type": "lcd_keypad_print_overwrite"},
                {"kind": "block", "type": "lcd_keypad_action"},
                {"kind": "label", "text": "--- Taster ---"},
                {"kind": "block", "type": "lcd_keypad_button"}
            ]
        },
		
		
		{
            "kind": "category", "name": "L298 Shield", "colour": "210",
            "contents": [
                {"kind": "label", "text": "--- Einzel Motoren ---"},
                {"kind": "block", "type": "l298_shield_motor"},
                {"kind": "block", "type": "l298_shield_stop"},
                {"kind": "label", "text": "--- Beide Motoren ---"},
                {"kind": "block", "type": "l298_shield_robot"},
                {"kind": "label", "text": "--- Sensoren ---"},
                {"kind": "block", "type": "l298_shield_current"}
            ]
        },
		
		
		{
            "kind": "category", "name": "Servo Shield", "colour": "210",
            "contents": [
                {"kind": "block", "type": "ks0258_setup"},
                {"kind": "label", "text": "--- Servos (0-180°) ---"},
                {"kind": "block", "type": "ks0258_servo_write"},
                {"kind": "block", "type": "ks0258_servo_all"},
                {"kind": "block", "type": "ks0258_servo_ramp"},
                {"kind": "label", "text": "--- Steuerung & Lesen ---"},
                {"kind": "block", "type": "ks0258_servo_detach"},
                {"kind": "block", "type": "ks0258_servo_attach"},
                {"kind": "block", "type": "ks0258_get_position"},
                {"kind": "label", "text": "--- LED / Dimmer ---"},
                {"kind": "block", "type": "ks0258_pwm_write"}
            ]
        },
		
		{
    "kind": "category", "name": "NFC (PN532)", "colour": "210",
    "contents": [
        {"kind": "block", "type": "ks_pn532_setup"},
        {"kind": "label", "text": "--- Ausführen ---"},
        {"kind": "block", "type": "ks_pn532_update"},
        {"kind": "label", "text": "--- Abfragen & Werte ---"},
        {"kind": "block", "type": "ks_pn532_check_event"},
        {"kind": "block", "type": "ks_pn532_check_uid"},
        {"kind": "block", "type": "ks_pn532_get_data"},
        {"kind": "label", "text": "--- Helfer ---"},
        {"kind": "block", "type": "ks_pn532_action_serial"}
    ]
},
		
		
		{
            "kind": "category", "name": "KS Motor/Servo", "colour": "180",
            "contents": [
                {"kind": "label", "text": "--- Servos & Sensoren ---"},
                {"kind": "block", "type": "ks_shield_servo"},
                {"kind": "label", "text": "--- DC Motoren (KS0363) ---"},
                {"kind": "block", "type": "ks0363_motor"},
                {"kind": "label", "text": "--- PS2 Gamepad ---"},
                {"kind": "block", "type": "ks_shield_ps2_setup"},
                {"kind": "block", "type": "ks_shield_ps2_button"}
            ]
        },
	
	
        {
            "kind": "category", "name": "Multi Shield", "colour": "210",
            "contents": [
                {"kind": "block", "type": "mfs_button_event"},
                {"kind": "block", "type": "mfs_button_counter"},
                {"kind": "block", "type": "mfs_button_reset"},
                {"kind": "label", "text": "--- Display ---"},
                {"kind": "block", "type": "mfs_display_number"},
                {"kind": "block", "type": "mfs_display_word"},
                {"kind": "block", "type": "mfs_display_clear"},
                {"kind": "label", "text": "--- LEDs ---"},
                {"kind": "block", "type": "mfs_led_digital"},
                {"kind": "block", "type": "mfs_led_pwm"},
                {"kind": "label", "text": "--- Summer & Poti ---"},
                {"kind": "block", "type": "mfs_buzzer_digital"},
                {"kind": "block", "type": "mfs_buzzer_tone"},
                {"kind": "block", "type": "mfs_read_poti"},
                {"kind": "block", "type": "mfs_map_simple"},
                {"kind": "label", "text": "--- Erweiterungen ---"},
                {"kind": "block", "type": "mfs_ext_digital"},
                {"kind": "block", "type": "mfs_ext_servo"}
            ]
        },
     


//RICH SHIELD 1:
        {
            "kind": "category", "name": "Rich Shield 1", "colour": "20",
            "contents": [
                {"kind": "block", "type": "rsv1_button_event"},
                {"kind": "block", "type": "rsv1_button_counter"},
                {"kind": "block", "type": "rsv1_button_reset"},
                {"kind": "label", "text": "--- Ausgaben & Töne ---"},
                {"kind": "block", "type": "rsv1_led_digital"},
                {"kind": "block", "type": "rsv1_led_pwm"},
                {"kind": "block", "type": "rsv1_buzzer_tone"},
                {"kind": "label", "text": "--- Display ---"},
                {"kind": "block", "type": "rsv1_display_number"},
                {"kind": "block", "type": "rsv1_display_word"},
                {"kind": "block", "type": "rsv1_display_clear"},
                {"kind": "label", "text": "--- Sensoren & Helfer ---"},
                {"kind": "block", "type": "rsv1_read_analog"},
                {"kind": "block", "type": "rsv1_read_dht"},
                {"kind": "block", "type": "rsv1_read_voltage"},
				{"kind": "label", "text": "--- Infrarot (Fernbedienung) ---"},
				{"kind": "block", "type": "rsv1_ir_print"},
				{"kind": "block", "type": "rsv1_ir_check"}
            ]
        },
		
		//RICH SHIELD 2:
		{
            "kind": "category", "name": "Rich Shield 2", "colour": "290",
            "contents": [
                {"kind": "label", "text": "--- Sensoren ---"},
                {"kind": "block", "type": "rsv2_read_sensor"},
                {"kind": "block", "type": "rsv2_pir_motion"},
                {"kind": "block", "type": "rsv2_joy_dir"},
                {"kind": "label", "text": "--- Drehgeber (Encoder) ---"},
                {"kind": "block", "type": "rsv2_encoder_pos"},
                {"kind": "block", "type": "rsv2_encoder_reset"},
                {"kind": "block", "type": "rsv2_button_event"},
                {"kind": "label", "text": "--- Ausgaben (LEDs & Batterie) ---"},
                {"kind": "block", "type": "rsv2_battery_level"},
                {"kind": "block", "type": "rsv2_battery_pct"},
                {"kind": "block", "type": "rsv2_rgb_led"},
                {"kind": "label", "text": "--- 16x8 LED Matrix ---"},
                {"kind": "block", "type": "rsv2_matrix_text"},
                {"kind": "block", "type": "rsv2_matrix_num"},
                {"kind": "block", "type": "rsv2_matrix_pixel"},
                {"kind": "block", "type": "rsv2_matrix_clear"}
            ]
        },
		
		{
            "kind": "category", "name": "Keyestudio V1", "colour": "180",
            "contents": [
                {"kind": "label", "text": "--- Taster ---"},
                {"kind": "block", "type": "ks_button_event"},
                {"kind": "label", "text": "--- Ausgaben ---"},
                {"kind": "block", "type": "ks_single_led"},
                {"kind": "block", "type": "ks_rgb_led"},
                {"kind": "block", "type": "ks_buzzer"},
                {"kind": "label", "text": "--- Sensoren ---"},
                {"kind": "block", "type": "ks_read_analog"},
                {"kind": "block", "type": "ks_read_dht"},
                {"kind": "label", "text": "--- Infrarot ---"},
                {"kind": "block", "type": "ks_ir_print"},
                {"kind": "block", "type": "ks_ir_check"}
            ]
        },
		
		{
    "kind": "category", "name": "Keyestudio V2", "colour": "210",
    "contents": [
	    {"kind": "label", "text": "--- Taster ---"},
        {"kind": "block", "type": "mfs_v2_button_event"},
        {"kind": "block", "type": "mfs_v2_button_counter"},
        {"kind": "block", "type": "mfs_v2_button_reset"},
        {"kind": "label", "text": "--- Display ---"},
        {"kind": "block", "type": "mfs_v2_display_number"},
        {"kind": "block", "type": "mfs_v2_display_word"},
        {"kind": "block", "type": "mfs_v2_display_clear"},
        {"kind": "label", "text": "--- LEDs ---"},
        {"kind": "block", "type": "mfs_v2_led_digital"},
        {"kind": "block", "type": "mfs_v2_led_pwm"},
        {"kind": "label", "text": "--- Summer & Poti ---"},
        {"kind": "block", "type": "mfs_v2_buzzer_digital"},
        {"kind": "block", "type": "mfs_v2_buzzer_tone"},
        {"kind": "block", "type": "mfs_v2_read_poti"}
    ]
},


    ]
},
		
// 15 SIMULATION
{ 
    "kind": "category", "name": "Simulation", "colour": "20",
    "contents": [
        {
            "kind": "category", "name": "Einstellung", "colour": "20",
            "contents": [
                {"kind": "block", "type": "sim_config_zyklus"}
            ]
        },
        {
            "kind": "category", "name": "Presse", "colour": "20",
            "contents": [
                {"kind": "label", "text": "--- Ausgänge (Aktionen) ---"},
                {"kind": "block", "type": "sim_presse_motor"},
                {"kind": "block", "type": "sim_presse_stempel"},
                {"kind": "block", "type": "sim_presse_zeit"},
                {"kind": "label", "text": "--- Eingänge (Sensoren) ---"},
                {"kind": "block", "type": "sim_presse_druck"},
                {"kind": "block", "type": "sim_presse_ls"},
                {"kind": "block", "type": "sim_presse_es_oben"},
                {"kind": "block", "type": "sim_presse_es_unten"},
                {"kind": "block", "type": "sim_presse_notaus"},
                {"kind": "block", "type": "sim_presse_taster_l"},
                {"kind": "block", "type": "sim_presse_taster_r"}
            ]
        },
		
		{
            "kind": "category", "name": "Rolltor", "colour": "20",
            "contents": [
                {"kind": "label", "text": "--- Ausgänge (Aktionen) ---"},
                {"kind": "block", "type": "sim_tor_motor"},
                {"kind": "block", "type": "sim_tor_stepper_target"},
                {"kind": "block", "type": "sim_tor_hmi_text"},
                {"kind": "label", "text": "--- Eingänge (Sensoren) ---"},
                {"kind": "block", "type": "sim_tor_stepper_pos"},
                {"kind": "block", "type": "sim_tor_ls"},
                {"kind": "block", "type": "sim_tor_es_oben"},
                {"kind": "block", "type": "sim_tor_es_unten"},
                {"kind": "label", "text": "--- HMI Taster ---"},
                {"kind": "block", "type": "sim_tor_btn_hoch"},
                {"kind": "block", "type": "sim_tor_btn_stop"},
                {"kind": "block", "type": "sim_tor_btn_runter"}
            ]
        },
		
		{
            "kind": "category", "name": "Ampel", "colour": "20",
            "contents": [
                {"kind": "label", "text": "--- Ausgänge (Lichter) ---"},
                {"kind": "block", "type": "sim_ampel_auto_softw"},
                {"kind": "block", "type": "sim_ampel_auto_pin"},
				{"kind": "label", "text": "--- Grünphase Fussgänger min 3 Sekunden ---"},
                {"kind": "block", "type": "sim_ampel_fuss_softw"},
                {"kind": "block", "type": "sim_ampel_fuss_pin"},
                {"kind": "label", "text": "--- Eingänge (Sensoren) ---"},
                {"kind": "block", "type": "sim_ampel_taster_softw"},
                {"kind": "block", "type": "sim_ampel_taster_pin"}
            ]
        },
		
		{
            "kind": "category", "name": "Förderband", "colour": "20",
            "contents": [
                {"kind": "label", "text": "--- Ausgänge (Aktionen) ---"},
                {"kind": "block", "type": "sim_fband_motor_softw"},
                {"kind": "block", "type": "sim_fband_motor_pin"},
                {"kind": "block", "type": "sim_fband_ampel_softw"},
                {"kind": "block", "type": "sim_fband_ampel_pin"},
                {"kind": "label", "text": "--- Eingänge (Sensoren) ---"},
                {"kind": "block", "type": "sim_fband_ls"},
                {"kind": "block", "type": "sim_fband_taster_softw"},
                {"kind": "block", "type": "sim_fband_taster_pin"},
                {"kind": "block", "type": "sim_fband_counter"}
            ]
        },
		
		{
            "kind": "category", "name": "WC", "colour": "20",
            "contents": [
                {"kind": "label", "text": "--- Ausgänge (Aktionen) ---"},
                {"kind": "block", "type": "sim_wc_licht_softw"},
                {"kind": "block", "type": "sim_wc_licht_pin"},
                {"kind": "block", "type": "sim_wc_luefter_softw"},
                {"kind": "block", "type": "sim_wc_luefter_pin"},
                {"kind": "block", "type": "sim_wc_hmi_text"},
                {"kind": "label", "text": "--- Eingänge (Sensoren) ---"},
                {"kind": "block", "type": "sim_wc_schalter_softw"},
                {"kind": "block", "type": "sim_wc_schalter_pin"}
            ]
        }
		
    ] 
}
		
				
        ]
    };

    workspace = Blockly.inject('blocklyDiv', {
        toolbox: toolbox,
        media: './media/',
        grid: {spacing: 20, length: 3, colour: '#ccc', snap: true},
        move: {
            scrollbars: true,
            wheel: true
        }
    });

    workspace.registerButtonCallback('CREATE_VAR_BTN', function(button) {
        Blockly.Variables.createVariableButtonHandler(button.getTargetWorkspace(), null, '');
    });

    let debounceTimer = null;

    function generateCode() {
        const root = workspace.getBlocksByType('arduino_main')[0];
        const codeDisplay = document.getElementById('codeExport');

        if (root) {
            try {
                if (typeof ArduinoGenerator !== 'undefined') {
                    ArduinoGenerator.init(workspace);
                    codeDisplay.innerText = ArduinoGenerator.blockToCode(root);
                } else {
                    codeDisplay.innerText = "// WARNUNG: ArduinoGenerator ist nicht definiert.";
                }
            } catch (error) {
                console.error("Code-Generierungs-Fehler:", error);
                codeDisplay.innerText = "// FEHLER bei der C++ Generierung.\n// Bitte öffne die F12 Entwicklerkonsole für Details.";
            }
        } else {
            codeDisplay.innerText = "// Bitte Start-Block einfügen";
        }
    }

    workspace.addChangeListener((event) => {
        const relevant = [
            Blockly.Events.BLOCK_CHANGE,
            Blockly.Events.BLOCK_MOVE,
            Blockly.Events.BLOCK_CREATE,
            Blockly.Events.BLOCK_DELETE,
        ];
        if (!relevant.includes(event.type)) return;

        if (workspace.isDragging && workspace.isDragging()) return;

        clearTimeout(debounceTimer);
        debounceTimer = setTimeout(generateCode, 250);
    });

    Blockly.serialization.workspaces.load({
        "blocks": {
            "languageVersion": 0, 
            "blocks": [
                {
                    "type": "arduino_main", 
                    "x": 50, 
                    "y": 50,
                    "deletable": false,
                    "movable": true
                }
            ]
        }
    }, workspace);
});

function insertQuickBlock(blockType) {
    if (!workspace) return;
    const block = workspace.newBlock(blockType);
    block.initSvg();
    block.render();
    block.moveBy(150, 150); 
}





function saveWorkspace() {
    const state = Blockly.serialization.workspaces.save(workspace);
    const jsonString = JSON.stringify(state, null, 2);
    const blob = new Blob([jsonString], {type: "application/json"});
    const a = document.createElement("a");
    a.href = URL.createObjectURL(blob);
    a.download = "mein_projekt.json";
    a.click();
    URL.revokeObjectURL(a.href);
}

function loadWorkspace(event) {
    const file = event.target.files[0];
    if (!file) return;
    const reader = new FileReader();
    reader.onload = function(e) {
        try {
            const json = JSON.parse(e.target.result);
            workspace.clear();
            Blockly.serialization.workspaces.load(json, workspace);
        } catch (err) {
            alert("Fehler beim Laden der Datei. Ist es eine gültige JSON Datei?");
            console.error(err);
        }
    };
    reader.readAsText(file);
    event.target.value = '';
}

function copyGeneratedCode() {
    const code = document.getElementById('codeExport').innerText;
    navigator.clipboard.writeText(code).then(() => {
        const btn = document.getElementById('copyBtn');
        const originalText = btn.innerHTML;
        btn.innerHTML = '✅ Kopiert!';
        setTimeout(() => { btn.innerHTML = originalText; }, 2000);
    }).catch(err => {
        console.error('Fehler beim Kopieren: ', err);
    });
}

function toggleCode() {
    const codeDiv = document.getElementById('codeExport');
    const headerText = document.getElementById('codeHeader');
    codeVisible = !codeVisible;
    if (codeVisible) {
        codeDiv.style.display = 'block';
        headerText.style.display = 'block';
    } else {
        codeDiv.style.display = 'none';
        headerText.style.display = 'none';
    }
    setTimeout(() => { Blockly.svgResize(workspace); }, 310);
}

function toggleGrid() {
    const blocklyDiv = document.getElementById('blocklyDiv');
    blocklyDiv.classList.toggle('hide-grid');
}

function newProject() {
    // Sicherheitsabfrage, damit kein Code aus Versehen gelöscht wird
    if (confirm("Möchtest du wirklich ein neues Programm anfangen? Alle ungespeicherten Blöcke gehen verloren.")) {
        
        // 1. Arbeitsfläche komplett leeren
        workspace.clear();
        
        // 2. Den "PROGRAMM START"-Block an Position X:50, Y:50 wieder frisch einfügen
        Blockly.serialization.workspaces.load({
            "blocks": {
                "languageVersion": 0, 
                "blocks": [
                    {
                        "type": "arduino_main", 
                        "x": 50, 
                        "y": 50,
                        "deletable": false,
                        "movable": true
                    }
                ]
            }
        }, workspace);
        
        // 3. Den C++ Export-Text zurücksetzen
        document.getElementById('codeExport').innerText = "// Bitte Start-Block einfügen";
    }
}