
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://fonts.googleapis.com/css?family=Roboto:300,400,500" rel="stylesheet" rel="preload" as="font" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css" />

<style>
  body { display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0; 
        user-select: none; -moz-user-select: none; -webkit-user-select: none; -ms-user-select: none;}
  
  #main_container { display: flex; flex:1; }

  ul.region_shape { font-size:xx-large; list-style-type:none; overflow:hidden; padding:0.4em 0; margin:0; }
  ul.region_shape li { float:left; padding:0 0.2em; fill:#ffffff; stroke:#000000; }
  ul.region_shape li:hover { cursor:pointer; fill:#ffffff; stroke:#ff0000; }
  ul.region_shape .selected { fill:#ffffff; stroke:#ff0000; }

  #container { position: relative; width:800px; height:800px;}
  
  #annotatationImage {z-index: 1; draggable="false"; pointer-events: none; }

  #annotationCanvas, #annotationImage { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); }
  #img_wh {position: absolute; top: 0; right: 0; font-size: 12px; }
  #img_name {position: absolute; top: 0; left: 0; font-size: 12px; }
  
  #right_display_panel {width: 400px; background-color: #f0f0f0; padding:20px;}

  #img_fn_title { font-size: 14px; text-decoration: underline; }
  #img_filter {float: right; border:none; font-size:16px; }

  #img_fn_list { display: none; font-size: small; overflow-y: auto; min-height: 10rem; max-height: 25rem; }
  #img_fn_list ul { position: relative; line-height: 1.3em; margin: 0; padding: 0; list-style-type: none;}
  #img_fn_list li { white-space: nowrap; display: flex; align-items: center; padding: 5px; margin-bottom: 10px; font-size: 10px; border-bottom: 1px solid #ccc; position: relative; overflow: visible; }
  #img_fn_list li:hover { background-color: #d5e5ff; cursor: pointer; white-space: nowrap; overflow: visible; }
  #img_fn_list li .button { display: none;  cursor: pointer; position: absolute; top: 55%; right: 5px; }
  #img_fn_list li .download-button { display: none; cursor: pointer; position: absolute; top: 55%; right: 40px; }
  
  #img_fn_list li .inference-button { display: none; cursor: pointer; position: absolute; top: 55%; right: 75px; }

  #img_fn_list li:hover .button, #img_fn_list li:hover .download-button , #img_fn_list li:hover .inference-button { display: block; }
  #img_fn_list li .button i, #img_fn_list li .download-button i, #img_fn_list li .inference-button i {font-size: 18px; }
  

  #img_fn_list .sel { border-left: 0.2rem solid black !important; font-weight: bold; }
  #img_fn_list img {  width: 35px; height: 35px; margin-right: 10px; }
  .image-filename-container { display: flex; align-items: center;}
  .text-container { margin-left: 10px; }
  .filename {font-weight: bold; }
  .region-count { color: #888; }
    
  #file_btn_panel { display:inline-block; width:100%; margin:0.2rem 0; margin-top:20px; margin-bottom: 20px; }
  #file_btn_panel .text_button, .text_button { color: #0000ff; padding: 0.2rem 0.2rem; -moz-user-select:none; -webkit-user-select:none; -ms-user-select:none; }
  #file_btn_panel .flush_right { float:right; }
  #file_btn_panel .text_button:hover, .text_button:hover { cursor:pointer; }
  #file_btn_panel .text_button:active, .text_button:active { color: #000000; }
  #file_btn_panel .active { border-bottom:1px solid black; }
  #file_btn_panel .button { display:inline-block; padding:0.35rem 0.5rem; margin:0 0.05rem; margin-right:5px; cursor:pointer; background-color:#cccccc; border-radius:0.2rem; -moz-user-select:none; -webkit-user-select:none; -ms-user-select:none; }
  #file_btn_panel .button:hover { background-color:black; color:white; }

  #lbl_key_title   {font-size:14px; text-decoration: underline;}
  #lbl_key_list    { display:none; font-size:small; overflow-y:auto; min-height:10rem; max-height:25rem; }
  #lbl_key_list ul { position:relative; line-height:1.3em; margin:0; padding:0; list-style-type:none;}
  #lbl_key_list li { white-space:nowrap; display:block; padding:5px; margin-bottom:10px; font-size:10px; border-bottom:1px solid #ccc; box-sizing:border-box; }
  #lbl_key_list li:hover  { background-color:#d5e5ff; cursor:pointer; }
  #lbl_key_list .sel      { border-left:0.2rem solid black !important; font-weight:bold; }

  #custom_dropdown ul { position:relative; line-height:1.3em; margin:0; padding:0; list-style-type:none;}
  #custom_dropdown li { white-space:nowrap; display:block; padding:5px; margin-bottom:10px; font-size:10px; border-bottom:1px solid #ccc; }
  #custom_dropdown li:hover  { background-color:#d5e5ff; cursor:pointer; }
  #custom_dropdown .sel      { border-left:0.2rem solid black !important; font-weight:bold; }
  #custom_dropdown img       {width: 30px; height: 30px; margin-right: 10px; }
  #custom_dropdown span      {margin-left: 10px; }

  #search_input {padding: 10px; border:1px solid #acc; border-radius: 5px; margin-bottom: 20px; width: calc(100% - 40px);}
  #search_input:focus {outline: none; border-color: #007bff; box-shadow: 0 0 5px rgba(0, 123, 255, 0.5);}

  #drp_down_list .search_container    { position: relative;}
  #drp_down_list #clear_button { position: absolute; right: 8px; top: 30%; transform: translateY(-50%); cursor: pointer; border: none; background: none; font-size: 16px; color: #FF0000; outline: none;}
  #drp_down_list #add_button { position: absolute; left: -30px; top: 30%;transform: translateY(-50%); cursor: pointer; border: none; background: none; font-size: 16px; color: #000000; outline: none;}
  #drp_down_list .scrollable-dropdown { max-height: 300px;  overflow-y: auto; }
  #drp_down_list {margin-top: 20px; position: relative; width:400px; }

  .modal {display:none; position:fixed; z-index:1; left:0; top:0; width:100%; height:100%; overflow:auto; background-color: rgba(0,0,0,0.5);}
  .modal-content { position: relative; margin:15% auto; padding:20px; width:60%; background-color: #fff; border-radius:10px;}
  .btn {padding: 10px 20px; margin:0 10px; cursor: pointer;}
  .btn:hover {background-color:#d5e5ff !important;}

  table  { width:100%; border-collapse:collapse; margin-bottom:15px;}
  .table-container { max-height: 300px; overflow-y: auto; margin-top: 20px; }
  thead { background-color: #f2f2f2; position: sticky; top:0;}
  th, td { padding:10px; border:1px solid #ddd; text-align:left; }
  tbody tr:nth-child(even) { background-color:#f9f9f9;}
  #main_blob_modal {display:none; position:fixed; z-index:1; left:0; top:0; width:100%; height:100%; background-color: rgba(0,0,0,0.5);}
  #sub_blob_model { display: none; position: fixed; z-index: 1; left: 0; top: 0; width: 100%; height: 100%; overflow: auto; background-color: rgba(0,0,0,0.4); padding-top: 60px;}
  #mulsel_blob_modal { background-color: #fefefe; margin: 5% auto; padding: 20px; border: 1px solid #888; width: 80%; max-width: 90%; }
  
  .highlighted {background-color:#FFFF00 !important; cursor:pointer;}
  .selected    {border-left:0.2rem solid black !important; font-weight:bold;}

  label { margin-right: 5px; }
  input[type="checkbox"], input[type="radio"] { margin-right: 3px; }

  #header_panel { padding: 5px; background-color: #f0f0f0; border: 1px solid #ccc; }
  div.ctrl-panel { padding: 5px;  background-color: #f9f9f9; border: 1px solid #ddd; display: inline-block; float: right; }
  label { margin-right: 10px;}
  input[type="text"] { margin-right: 3px; width: 300px;}
  
  #url_ctrl_title, #cust_ctrl_title { font-weight: bold; padding-right: 10px; }
  .remove { cursor: pointer; border: none; background: none; font-size: 16px; color: #FF0000; outline: none;}

  #model_type {width: 90%; }
  #adv_panel {float:right; }
  #img_adv_label, #img_adv_chk {padding-left: 10px; }
  #img_filter_panel { position: fixed; top: 0px; right: 160px; background-color: #fff; border: 1px solid #ccc; padding: 10px; box-shadow: 0 0 10px rgba(0, 0, 0, 0.1); }

</style>

<link href="https://fonts.googleapis.com/css?family=Titillium+Web" rel="stylesheet" />
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet" />
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.5/jszip.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pako/2.0.4/pako.min.js"></script>



<body>
  
  <div>
    <div anvil-slot-repeat="default" class="anvil-measure-this"></div>
    <div id="main_modal" class="modal">
      <div id="sel_modal" class="modal-content">
      </div>
    </div>

    <div id="main_blob_modal" class="modal">
      <div id="sel_blob_modal" class="modal-content">
      </div>
    </div>

    <div id="sub_blob_model" class="modal">
      <div id="mulsel_blob_modal" class="modal-content">
      </div>
    </div>

    <div id="ir_model_modal" class="modal">
      <div id="sel_ir_model_modal" class="modal-content">
      </div>
    </div>


    <div anvil-slot="default" id="main_container">

      <div id="drp_down_list">
        <div class="search_container">
          <input type="text" id="search_input" placeholder="Search for an option">
          <button id="clear_button" title="Clear Search Input">X</button>
          <button id="add_button" title="Create New Class">+</button>
        </div>
        <ul id="custom_dropdown" class="scrollable-dropdown"></ul>
      </div>

      
      <div id="container">
        <div style="display:none"></div>
      </div> 

      <div id="right_display_panel">
        <div>
          <label id="img_fn_title"><strong>IMAGE LIST : ( 0 )</strong></label>
          <button id="img_filter"></button>
          
          <div id="img_filter_panel"></div>
        </div>
        <div id="img_fn_list"></div>
        <div id="file_btn_panel"></div>
        <label id="lbl_key_title"><strong>LABEL KEY LIST : ( 0 )</strong></label>
        <div id="lbl_key_list"></div>
        
      </div>
        
    </div>
  </div>
  
  <script>

  
    // declaration
    //var sourceImgContainer = document.getElementById("main_container");
    var container = document.getElementById('container');
  
    var img_name_tag = document.createElement('label')
    img_name_tag.id = "img_name";
    var img_wh_tag = document.createElement('label')
    img_wh_tag.id = "img_wh";
    
    var canvas = document.createElement('canvas');
    canvas.id = "annotationCanvas";
    var canvas_width; var canvas_height;
    
    var canvas_scale = 1.0;
    var reg_ctx = canvas.getContext('2d');
  
    //var right_display_panel = document.getElementById("right_display_panel");
  
    var img_layer = document.createElement('img');
    img_layer.id = 'annotationImage';
    
    var image_id_list = [];
    var temp_image_id_list = [];
    var image_filename_list = [];
    var labelkey_list = [];
    //var img_lbl_list = [];
    
    var filter_signal = '';
    var sub_filter = '';
    
    var img_filter = document.getElementById('img_filter');
    img_filter.classList = "fa fa-filter";
    img_filter.title = "Image Filtering";
    
    var img_fn_list = document.getElementById('img_fn_list');
    img_fn_list.style.display = "block";
    
    var file_btn_panel = document.getElementById('file_btn_panel');
  
    var lbl_key_list = document.getElementById('lbl_key_list');
    lbl_key_list.style.display = "block";
  
    var drp_down_list = document.getElementById('drp_down_list');
    var search_input = document.getElementById('search_input');
    var clear_button = document.getElementById('clear_button');
    var add_button = document.getElementById('add_button');
    add_button.onclick = add_class_labelkey;
    
    var custom_dropdown = document.getElementById('custom_dropdown');
  
    var selected_label=''; var selected_color='';
    
    var current_img_id = 0; //default 
    var current_filename = '';
  
    var REGION_SHAPE = { 
      RECT:'rect', CIRCLE:'circle', ELLIPSE:'ellipse', POLYGON:'polygon', POINT:'point', POLYLINE:'polyline', BITMAP:'bitmap'
    };
  
    // default value
    var MOUSE_CLICK_TOL = 2;
    var REGION_EDGE_TOL = 5;
    var REGION_MIN_DIM = 3;
    var THEME_REGION_BOUNDARY_WIDTH = 2;
    var THEME_BOUNDARY_LINE_COLOR   = "yellow";//"black";
    var THEME_BOUNDARY_FILL_COLOR   = "yellow";
    var THEME_SEL_REGION_FILL_COLOR = "#808080";
    var THEME_SEL_REGION_FILL_BOUNDARY_COLOR = "yellow";
    var THEME_SEL_REGION_OPACITY    = 0.5;
  
    // region
    var current_shape = REGION_SHAPE.RECT;
    var sel_region_id  = -1;
    var click_x0 = 0; var click_y0 = 0;
    var click_x1 = 0; var click_y1 = 0;
    var region_click_x, region_click_y;
    var region_edge = [-1, -1];
    var current_x = 0; var current_y = 0;
    var canvas_region = [];
    var region_selected_flag = [];
  
    var region_label_font = '10px Sans';
    var raw_data; var dropdown_data=[];
    var filter_option;
  
    // state of the application 
    var is_drawing = false;
    var is_resizing = false;
    var is_moving = false;
    var is_ctrl_pressed = false;
    var is_shift_pressed = false;
    var is_region_selected = false;
    var is_all_region_selected = false;
    var is_region_id_visible = true;
    var is_region_boundary_visible  = true;
  
  
    var is_right_click_selecting = false;
    var selection_rect = { x: 0, y: 0, width: 0, height: 0 };
  
  
    const zip = new JSZip();

    // initialization
    init_mouse_handler();
    init_keyboard_handler();

    image_filter();
    file_button();
    input_handler();
    clear_input_handler();

    current_img_id = 0;



    function init_mouse_handler() {
      canvas.addEventListener('dblclick', canvas_dblclick_handler, false);
      canvas.addEventListener('mousedown', canvas_mousedown_handler, false);
      canvas.addEventListener('mouseup', canvas_mouseup_handler, false);
      canvas.addEventListener('mouseover', canvas_mouseover_handler, false);
      canvas.addEventListener('mousemove', canvas_mousemove_handler, false);
      canvas.addEventListener('contextmenu', canvas_mouserightclick_handler, false);
  
      lbl_key_list.addEventListener('mouseover',lbl_list_mouseover_handler ,false);
      lbl_key_list.addEventListener('mouseout',lbl_list_mouseout_handler ,false);
      
    }
  
    function init_keyboard_handler() {
      window.addEventListener('keydown', window_keydown_handler, false);
      window.addEventListener('keyup', window_keyup_handler, false);
    }
  
    function canvas_dblclick_handler(e) {
      e.stopPropagation();
    }
  
    function canvas_mousedown_handler(e) {
      e.stopPropagation();
      click_x0 = e.offsetX; click_y0 = e.offsetY;
  
      // TEST RIGHT HIGHLIGHT 
      if (e.button === 2){
        e.preventDefault();
        is_right_click_selecting = true;
        selection_rect.x = click_x0;
        selection_rect.y = click_y0;

        return;
      }
  
      
      region_edge = is_on_region_corner(click_x0, click_y0);
      var region_id = is_inside_region(click_x0, click_y0);
  
      if (is_region_selected){
        if (region_edge[1] > 0) {
          if (!is_resizing) {
            if (region_edge[0] !== sel_region_id){
              sel_region_id = region_edge[0];
            }
            is_resizing = true;
          }
        } else {
          var yes = is_inside_this_region(click_x0, click_y0, sel_region_id);
          if (yes) {
            if (!is_moving){
              is_moving = true;
              region_click_x = click_x0; region_click_y = click_y0;
              
            }
          } 
          if (region_id === -1){
            is_drawing = true;
            is_region_selected = false;
            sel_region_id = -1;
            toggle_all_region_selection(false);
  
            remove_sel_satus(lbl_key_list);
          }
        }
      } else {
        // if (region_id === -1) {
        //   is_drawing = true;
        // } else {
        //   is_drawing = true;
        // } 
        is_drawing = true;
      } 
    }
  
    function canvas_mouseup_handler(e) {
      e.stopPropagation();
      click_x1 = e.offsetX; click_y1 = e.offsetY;
  
      // TEST RIGHT HIGHLIGHT 
      // Handle right-click selection completion
      if (is_right_click_selecting) {
        is_right_click_selecting = false;

        // RESET 
        is_drawing = false;
        is_region_selected = false;
        sel_region_id = -1;
        toggle_all_region_selection(false);

        remove_sel_satus(lbl_key_list);

          
        // Standardize selection coordinates
        var [select_x0, select_y0, select_x1, select_y1] = standardize_rect_coordinates(
          selection_rect.x,
          selection_rect.y,
          selection_rect.x + selection_rect.width,
          selection_rect.y + selection_rect.height
        );
        
        // Select all regions that intersect with the selection rectangle
        canvas_region[current_img_id].annotations.forEach((region, index) => {
          var [region_x0, region_y0, region_x1, region_y1] = [
            region.box[0],
            region.box[1],
            region.box[0] + region.box[2],
            region.box[1] + region.box[3]
          ];
          
          if (rectangles_intersect(
            select_x0, select_y0, select_x1, select_y1,
            region_x0, region_y0, region_x1, region_y1
          )) {
            set_region_select_state(index, true);
            is_region_selected = true;
          }
        });
        
        redraw_reg_canvas();
        return;
      }
  
      
  
      var click_dx = Math.abs(click_x1 - click_x0);
      var click_dy = Math.abs(click_y1 - click_y0);
  
      
      if (is_moving){
        is_moving = false;
        canvas.style.cursor = "default";
        
        var move_x = Math.round(click_x1 - region_click_x);
        var move_y = Math.round(click_y1 - region_click_y);
  
        if (Math.abs(move_x) > MOUSE_CLICK_TOL || Math.abs(move_y) > MOUSE_CLICK_TOL){
          move_selected_regions(move_x, move_y);
        } else {
          var nested_region_id = is_inside_region(click_x0, click_y0, true);
          if (nested_region_id >= 0 && nested_region_id !== sel_region_id) {
            sel_region_id = nested_region_id;
            is_region_selected = true;
            is_moving = false;
  
            if (!is_shift_pressed) {
              toggle_all_region_selection(false);
            }
            set_region_select_state(nested_region_id, true);
          } else {
            toggle_all_region_selection(false);
            is_region_selected = false;
          }
        }
        image_id_list[current_img_id].Status = "CHANGED";
        console.log("test_MOV_CHANGED")
        redraw_reg_canvas();
        canvas.focus();
        return;
      }
    
      if (is_resizing) {
        is_resizing = false;
        canvas.style.cursor = "default";
  
        var region_id = region_edge[0];
        var canvas_attr = canvas_region[current_img_id].annotations;
        var bbox = canvas_attr[region_id].box;
        
        var d = [bbox[0], bbox[1], 0,0];
  
        d[2] = d[0] + bbox[2];
        d[3] = d[1] + bbox[3];
        
        var mx = current_x; var my = current_y;
        var preserve_aspect_ratio = false;
  
        if ( is_ctrl_pressed) {
          preserve_aspect_ratio = true;
        }
  
        rect_update_corner(region_edge[1], d, mx, my, preserve_aspect_ratio);
        rect_standardize_coordinates(d);
  
        var w = Math.abs(d[2] - d[0]);
        var h = Math.abs(d[3] - d[1]);
  
        bbox[0] = Math.round(d[0] * canvas_scale); 
        bbox[1] = Math.round(d[1] * canvas_scale);
        bbox[2] = Math.round(w * canvas_scale);
        bbox[3] = Math.round(h * canvas_scale);
        image_id_list[current_img_id].Status = "CHANGED";
        console.log("test_RES_CHANGED")
        redraw_reg_canvas();
        canvas.focus();
        return;
      }
  
      if (click_dx < MOUSE_CLICK_TOL || click_dy < MOUSE_CLICK_TOL){
        var region_id = is_inside_region(click_x0, click_y0);
  
        if (region_id >= 0 ){
          sel_region_id = region_id;
          is_region_selected = true;
          is_moving = false;
          is_drawing = false;
  
          //de-select all if not shift pressed
          if (!is_shift_pressed) {
            toggle_all_region_selection(false);
            scroll_to_labelkey_item(region_id);
          }
          set_region_select_state(region_id , true);
  
        } else {
          if (is_drawing){
            is_drawing = false;
            is_region_selected = false;
            toggle_all_region_selection(false);
          }
        
        }
        
        redraw_reg_canvas();
        canvas.focus();
        return;
      }
      
      if (is_drawing){
        is_drawing = false;
  
        var region_x0 = click_x0; var region_y0 = click_y0; 
        var region_x1 = click_x1; var region_y1 = click_y1;
  
        var region_dx = Math.abs(region_x1 - region_x0);
        var region_dy = Math.abs(region_y1 - region_y0);
        var new_region_added = false;
  
        // region shape == rectangle
  
        if (region_dx > REGION_MIN_DIM && region_dy > REGION_MIN_DIM) {
          // ensure x0,y0 = top-left, x1,y1 = bottom-right
          if (click_x0 < click_x1){
            region_x0 = click_x0; region_x1 = click_x1;
          } else{
            region_x0 = click_x1; region_x1 = click_x0;
          }
          
          if (click_y0 < click_y1){
            region_y0 = click_y0; region_y1 = click_y1;
          } else {
            region_y0 = click_y1; region_y1 = click_y0;
          }
    
          var x1 = Math.round(region_x0 * canvas_scale);
          var y1 = Math.round(region_y0 * canvas_scale);
          var x2 = Math.round(region_dx * canvas_scale);
          var y2 = Math.round(region_dy * canvas_scale);
    
          new_region_added = true;
    
          if (new_region_added){
          
            var n = canvas_region[current_img_id].annotations.push({
              "filename":current_filename, "label":selected_label, "box":[x1,y1,x2,y2], "color": selected_color
            });
  
            var new_region_id = n - 1;
            select_only_region(new_region_id);
            image_id_list[current_img_id].Status = "CHANGED";
  
            console.log("test_ADD_CHANGED")
          }
  
          redraw_reg_canvas();
          canvas.focus();
        }
        var n_region = canvas_region[current_img_id].annotations.length - 1;
        scroll_to_labelkey_item(n_region);
        
        return;
      }
    
    }
  
    // Helper function to standardize rectangle coordinates
    function standardize_rect_coordinates(x0, y0, x1, y1) {
        return [
            Math.min(x0, x1),
            Math.min(y0, y1),
            Math.max(x0, x1),
            Math.max(y0, y1)
        ];
    }
  
    // Helper function to check if two rectangles intersect
    function rectangles_intersect(ax0, ay0, ax1, ay1, bx0, by0, bx1, by1) {
        return !(ax0 > bx1 || 
                ax1 < bx0 || 
                ay0 > by1 || 
                ay1 < by0);
    }
  
    function canvas_mouseover_handler(e) {
      redraw_reg_canvas();
      canvas.focus();
    }
    
    function canvas_mousemove_handler(e) {
      current_x = e.offsetX; current_y = e.offsetY;
  
      // TEST RIGHT HIGHLIGHT 
      if (is_right_click_selecting) {
        reg_ctx.clearRect(0,0, canvas.width, canvas.height);
  
        // Calculate selection rectangle
          selection_rect.width = current_x - selection_rect.x;
          selection_rect.height = current_y - selection_rect.y;
          
          // Draw selection rectangle
          reg_ctx.setLineDash([5, 5]);
          reg_ctx.lineWidth   = 3;
          reg_ctx.strokeStyle = 'white';//'#0066ff';
        

          reg_ctx.strokeRect(
              selection_rect.x,
              selection_rect.y,
              selection_rect.width,
              selection_rect.height
          );

          // Fill the rectangle
          reg_ctx.globalAlpha = 0.5; // Set transparency for the fill
          reg_ctx.fillStyle = 'rgba(255, 255, 255, 0.5)'; // Fill color with opacity
          reg_ctx.fillRect(
              selection_rect.x,
              selection_rect.y,
              selection_rect.width,
              selection_rect.height
          );
          reg_ctx.setLineDash([]);

          
          // Redraw existing regions
          if (is_region_boundary_visible) {
              draw_all_regions();
          }
          return;
      }
  
      
      var region_status = check_regions();
      var region_id = is_inside_region(current_x, current_y);
  
      // bounding box hover
      reg_ctx.clearRect(0, 0, canvas.width, canvas.height);
      if (region_id !== -1) {
        var attr = canvas_region[current_img_id].annotations[region_id].box;
        draw_rect_hover(attr[0], attr[1], attr[2], attr[3], true);
  
        if (is_region_boundary_visible){
          draw_all_regions();
        }
        if (is_region_id_visible) {
          draw_all_region_id();
        }
        
      } else {
        redraw_reg_canvas();
      }
      
  
      if (is_region_selected) {
        if (sel_region_id !== -1){
          if(!is_resizing) {
            region_edge = is_on_region_corner(current_x, current_y);
            if (region_edge[0] === sel_region_id) {
              switch(region_edge[1]){
                case 1: // Fall-through // top-left corner of rect
                case 3: // bottom-right corner of rect
                  canvas.style.cursor = "nwse-resize";
                  break;
                case 2: // Fall-through // top-right corner of rect
                case 4: // bottom-left corner of rect
                  canvas.style.cursor = "nesw-resize";
                  break;
        
                case 5: // Fall-through // top-middle point of rect
                case 7: // bottom-middle point of rect
                  canvas.style.cursor = "ns-resize";
                  break;
                case 6: // Fall-through // top-middle point of rect
                case 8: // bottom-middle point of rect
                  canvas.style.cursor = "ew-resize";
                  break;
        
                default:
                  canvas.style.cursor = "default";
                  break;
              }
            } else {
              var yes = is_inside_this_region(current_x, current_y, sel_region_id);
              if (yes){
                canvas.style.cursor = "move";
              } else {
                canvas.style.cursor = "default";
              }
            }
          }
        }
      } 
  
      if (is_drawing) {
  
        clear_regions(region_status);
  
        var region_x0 = click_x0; var region_y0 = click_y0;
  
        var dx = Math.round(Math.abs(current_x - click_x0));
        var dy = Math.round(Math.abs(current_y - click_y0));
        reg_ctx.strokeStyle = selected_color;//THEME_BOUNDARY_FILL_COLOR;
  
        if (click_x0 < current_x) {
          if (click_y0 < current_y) {
            region_x0 = click_x0; region_y0 = click_y0;
          } else{
            region_x0 = click_x0; region_y0 = current_y;
          }
        } else{
          if (click_y0 < current_y) {
            region_x0 = current_x; region_y0 = click_y0;
          } else {
            region_x0 = current_x; region_y0 = current_y;
          }
        }
        draw_rect_region(region_x0, region_y0, dx, dy, false);
        canvas.focus();
      }
  
      if (is_resizing) {
        
        clear_regions(region_status);
  
        if (region_status){
          var region_id = region_edge[0];
          var attr = canvas_region[current_img_id]?.annotations;
          if (attr) {
            var bbox = attr[region_id].box;
            var d = [bbox[0], bbox[1], 0, 0];
            d[2] = d[0] + bbox[2];
            d[3] = d[1] + bbox[3];
      
            var mx = current_x; var my = current_y;
            var preserve_aspect_ratio = false;
            if (is_ctrl_pressed) {
              preserve_aspect_ratio = true; 
            }
      
            rect_update_corner(region_edge[1], d , mx, my , preserve_aspect_ratio);
            rect_standardize_coordinates(d);
      
            var w = Math.abs(d[2] - d[0]);
            var h = Math.abs(d[3] - d[1]);
      
            draw_rect_region(d[0], d[1], w, h, true);
          }
          
          canvas.focus();
        }
      }
  
      if (is_moving) {
        
        clear_regions(region_status);
  
        if (region_status){
          var move_x = (current_x - region_click_x);
          var move_y = (current_y - region_click_y);
          var attr = canvas_region[current_img_id].annotations;
          var bbox = attr[sel_region_id].box;
    
          draw_rect_region(bbox[0] + move_x, bbox[1] + move_y, bbox[2], bbox[3], true);
          canvas.focus();
          return;
        }
      }
    }
  
    function canvas_mouserightclick_handler(e) {
      e.preventDefault(); // Prevent context menu
      e.stopPropagation();
  
      // reset the selection_rect to remove cache
      selection_rect = { x: 0, y: 0, width: 0, height: 0 };
  
      // right click and delete
      // if(is_region_selected || is_all_region_selected) {
      //   e.preventDefault();
      //   //del_sel_regions();
      // } 
      
      // highlight and delete 
      // if (!is_right_click_selecting && (is_region_selected || is_all_region_selected)) {
      //     del_sel_regions();
      // }
    }
  
    function lbl_list_mouseover_handler(e) {
      
      var li = e.target;
      if (li.id && li.id.startsWith('lbl') && li.id !== "lbl_key_list"){
        
        var region_index = li.id.match(/\d+/g).map(Number);
        if (labelkey_list) {
  
          var attr = canvas_region[current_img_id].annotations[region_index].box;
          draw_rect_hover(attr[0], attr[1], attr[2], attr[3], true);
        } 
      } 
    }
  
    function draw_rect_hover(x,y,w,h,is_selected) {
    
      if (is_selected){
    
        draw_rect(x,y,w,h);
    
        reg_ctx.fillStyle   = THEME_SEL_REGION_FILL_COLOR;
        reg_ctx.globalAlpha = THEME_SEL_REGION_OPACITY;
        reg_ctx.fill();
        reg_ctx.globalAlpha = 1.0;
        
      } else {
        
        reg_ctx.clearRect(0, 0, canvas.width, canvas.height);
      }
    }
    
    function lbl_list_mouseout_handler(e) {
      
      var li = e.target;
      if (li.id && li.id.startsWith('lbl') && li.id !== "lbl_key_list") {
        
        draw_rect_hover(0, 0, 0, 0, false);
      }
      redraw_reg_canvas();
    }
  
    function window_keydown_handler(e) {
      console.log(e.keyCode);
  
      const isTextInput = e.target.tagName.toLowerCase() === 'input' || e.target.tagName.toLowerCase() === 'textarea';
  
      if (isTextInput) {
        // If the event target is a text input field, do nothing
        return;
      }
      
      if (!drp_down_list.contains(e.target)){
        
        var del = 1;
        
        switch(e.keyCode){
          case 16:
            del = 10
            is_shift_pressed = true;
            console.log("SHIFT PRESSED");
            break;
          
          case 17:
            is_ctrl_pressed = true;
            console.log("CTRL PRESSED");
            break;
  
          case 32:
            console.log("SPACEBAR PRESSED");
            e.preventDefault();
            search_input.focus();
            search_input.value = '';
            break;
            
          case 78:
            console.log("N PRESSED");
            add_class_labelkey();
            break;
          /*
          // page up
          case 33:
            show_img(current_img_id +1);
            e.preventDefault();
            return;
  
          // page down
          case 34:
            show_img(current_img_id -1);
            e.preventDefault();
            return;
  
          // end
          case 35:
            show_img(image_id_list.length - 1);
            e.preventDefault();
            return;
  
          // home
          case 36:
            show_img(0);
            e.preventDefault();
            return;
            */
          case 37:
          case 38:
          case 39:
          case 40:
          case 65:
          case 68:
          case 83:
          case 87:
          
            if (is_region_selected) {
              
              var move_x = 0; var move_y = 0;
              switch(e.keyCode){
                case 37:
                case 65:
                  move_x = -del;
                  break;
  
                case 38:
                case 87:
                  move_y = -del;
                  break;
                
                case 39:
                case 68:
                  move_x = del;
                  break;
  
                case 40:
                case 83:
                  move_y = del;
                  break;
              }
              move_selected_regions(move_x, move_y);
              redraw_reg_canvas();
              e.preventDefault();
              return;
            } else {
              switch(e.keyCode){
                case 37:
                case 65:
                 // var current_id = current_img_id -1;
                  show_img(current_img_id -1);
                  scroll_to_imagelist_item(current_img_id);
                  e.preventDefault();
                  break;
  
                case 39:
                case 68:
                  //var current_id = current_img_id +1;
                  show_img(current_img_id +1);
                  scroll_to_imagelist_item(current_img_id);
                  e.preventDefault();
                  break;
              }
            }
          break;
            
          /*
          case 65:
            sel_all_regions();
            e.preventDefault();
            break;
            */
          case 46:
          case 82:
            if(is_region_selected || is_all_region_selected) {
              del_sel_regions();
              break;
            }
            e.preventDefault();
            break;
    
          case 66:
            toggle_region_boundary_visibility();
            e.preventDefault();
            break;
    
          case 72:
            toggle_region_boundary_visibility();
            toggle_region_id_visibility();
            break;
    
          case 76:
            toggle_region_id_visibility();
            e.preventDefault();
            break;
  
        }
      }
    }
  
    function window_keyup_handler(e) {
  
      if (!drp_down_list.contains(e.target)){
        switch(e.keyCode){
          case 16:
            is_shift_pressed = false;
            console.log("SHIFT RELEASE");
            break;
            
          case 17:
            is_ctrl_pressed = false;
            console.log("CTRL RELEASE");
            break;
  
          case 32:
            console.log("SPACEBAR RELEASE");
            break;
        }
      }
    }
    
    function redraw_reg_canvas() {
      
      var region_status = check_regions();
      if (region_status){
        reg_ctx.clearRect(0,0, canvas.width, canvas.height);
        
        //region list not null
        if (canvas_region[current_img_id].annotations.length >= 0){
  
          canvas_region_color();
          display_image_list();
          
          if (is_region_boundary_visible){
            draw_all_regions();
          }
          if (is_region_id_visible) {
            draw_all_region_id();
          }
        }
      } else {
        reg_ctx.clearRect(0,0, canvas.width, canvas.height);
      }
    }
  
    function canvas_region_color() {
  
      dropdown_data?.forEach(item=> {
  
        for (var i = 0; i < canvas_region[current_img_id].annotations.length; ++i) {
          if (canvas_region[current_img_id].annotations[i].label === item.Label_key){
            canvas_region[current_img_id].annotations[i].color = item.bbox_color; 
          }
        }
      });
      
    }
  
    function rect_update_corner(corner_id, d, x, y, preserve_aspect_ratio) {
      if(preserve_aspect_ratio) {
        switch(corner_id) {
          case 1:
          case 3:
            var dx = d[2] - d[0]; var dy = d[3] - d[1];
            var norm = Math.sqrt(dx * dx + dy * dy);
            var nx = dx / norm; var ny = dy / norm;
            var proj = (x - d[0]) * nx + (y - d[1]) * ny;
            var proj_x = nx * proj; var proj_y = ny * proj;
  
            x = Math.round(d[0] + proj_x);
            y = Math.round(d[1] + proj_y);
            break;
  
          case 2:
          case 4:
            var dx = d[2] - d[0]; var dy = d[1] - d[3];
            var norm = Math.sqrt(dx * dx + dy* dy);
            var nx = dx / norm; var ny = dy / norm;
            var proj = (x - d[0]) * nx + (y - d[3]) * ny;
            var proj_x = nx * proj; var proj_y = ny * proj;
  
            x = Math.round(d[0] + proj_x);
            y = Math.round(d[3] + proj_y);
            break;
        }
      }
  
      switch(corner_id) {
        case 1: // top-left
          d[0] = x;
          d[1] = y;
          break;
      
        case 3: // bottom-right
          d[2] = x;
          d[3] = y;
          break;
      
        case 2: // top-right
          d[2] = x;
          d[1] = y;
          break;
      
        case 4: // bottom-left
          d[0] = x;
          d[3] = y;
          break;
      
        case 5: // top-middle
          d[1] = y;
          break;
      
        case 6: // right-middle
          d[2] = x;
          break;
      
        case 7: // bottom-middle
          d[3] = y;
          break;
      
        case 8: // left-middle
          d[0] = x;
          break;
      }
    }
  
    function rect_standardize_coordinates(d) {
      // d[x0,y0,x1,y1]
      // ensures that (d[0],d[1]) is top-left corner while
      // (d[2],d[3]) is bottom-right corner
      if ( d[0] > d[2] ) {
        // swap
        var t = d[0];
        d[0] = d[2];
        d[2] = t;
      }
    
      if ( d[1] > d[3] ) {
        // swap
        var t = d[1];
        d[1] = d[3];
        d[3] = t;
      }
      
    }
  
    function check_region_img_indexing() {
  
      var read_image_list = image_id_list;
      if (temp_image_id_list?.length > 0){
        read_image_list = temp_image_id_list; 
      }
      
      if (read_image_list.length < canvas_region.length) {
        // Create a map of 'filename' to index in image_id_list
        var imageIndexMap = {};
        read_image_list.forEach(function (img, index) {
          imageIndexMap[img.Photo_name] = index;
        });
    
        // Sort canvas_region based on the order in image_id_list
        canvas_region.sort(function (a, b) {
          var indexA = imageIndexMap[a['filename']];
          var indexB = imageIndexMap[b['filename']];
    
          // Handle cases where 'filename' is not found in image_id_list
          if (indexA === undefined) return 1;
          if (indexB === undefined) return -1;
    
          return indexA - indexB;
        });
      } else if (read_image_list.length >= canvas_region.length) {
        // Create a map of 'Photo_name' to index in canvas_region
        var regionIndexMap = {};
        canvas_region.forEach(function (region, index) {
          regionIndexMap[region.filename] = index;
        });
    
        // Sort image_id_list based on the order in canvas_region
        read_image_list.sort(function (a, b) {
          var indexA = regionIndexMap[a['Photo_name']];
          var indexB = regionIndexMap[b['Photo_name']];
    
          // Handle cases where 'Photo_name' is not found in canvas_region
          if (indexA === undefined) return 1;
          if (indexB === undefined) return -1;
    
          return indexA - indexB;
        });
      } 
  
    }
  
    function draw_all_regions() {
  
      var attr, is_selected;
      var region_status = check_regions();
      
      if (region_status){
        attr = canvas_region[current_img_id].annotations;
  
        for (var j=0; j < attr.length; ++j){
          is_selected = region_selected_flag[j];
    
          reg_ctx.strokeStyle = attr[j].color;//THEME_BOUNDARY_FILL_COLOR;
          var bbox = attr[j].box;
    
          // if rectangle 
          draw_rect_region(bbox[0], bbox[1], bbox[2], bbox[3], is_selected);
        }
      } else {
        console.log("err_draw_all_regions");
      }
    }
  
    function draw_all_region_id() {
      
      reg_ctx.shadowColor = "transparent";
      reg_ctx.font = region_label_font;
      var region_status = check_regions();
      
      if (region_status) {
        var attr = canvas_region[current_img_id].annotations;
        
        for (var j = 0; j < attr.length; ++j){
          var bbox = attr[j].box;
          
          var x = bbox[0]; var y = bbox[1];
          var w = Math.abs((x+bbox[2]) - bbox[0]);
    
          var char_width = reg_ctx.measureText('M').width;
          var char_height = 1.8 * char_width;
    
          var annotation_str = (j+1).toString();
          var bgnd_rect_width;
          var strw = reg_ctx.measureText(annotation_str).width;
          if (strw > w) {
            //bgnd_rect_width = strw + char_width;
            
            var str_max = Math.floor((w * annotation_str.length) / strw);
            if (str_max >1) {
              annotation_str = annotation_str.substr(0, str_max-1) + '.';
              bgnd_rect_width = w;
            } else {
              annotation_str = annotation_str.substr(0,1) + '.';
              bgnd_rect_width = 2 * char_width;
            }
            
          } else {
            bgnd_rect_width = strw + char_width;
          }
          // center the label
          x = x- (bgnd_rect_width/2 - w/2);
    
          // ensure text is whithin img boundaries
          if (y < char_height) {
            y = char_height;
          }
          
          // draw background rectangle
          reg_ctx.fillStyle = 'black';
          reg_ctx.globalAlpha = 0.8;
          reg_ctx.fillRect(Math.floor(x), Math.floor(y - 1.1*char_height), Math.floor(bgnd_rect_width), Math.floor(char_height));
    
          // draw text over bacground
          reg_ctx.globalAlpha = 1.0;
          reg_ctx.fillStyle = 'white';
          reg_ctx.fillText(annotation_str, Math.floor(x + 0.4*char_width), Math.floor(y - 0.35*char_height));
        }
      } else {
        console.log("err_draw_all_region_id")
      }
    }
  
    function draw_sel_region_name() {
      
      reg_ctx.font = "10px Sans";
      var region_status = check_regions();
  
      if (region_status || is_region_selected){
        for (var j = 0; j < canvas_region[current_img_id].annotations.length; ++j) {
          var attr = canvas_region[current_img_id].annotations;
  
          var region_id = is_all_region_selected ? j : sel_region_id;
  
          if (region_id !== -1){
            var bbox = attr[region_id].box;
            // console.log("test_ bbox", bbox)
            var x = bbox[0]; var y = bbox[1] + bbox[3] + 20;
            var w = Math.abs((x + bbox[2]) - bbox[0]);
      
            var char_width = reg_ctx.measureText('M').width;
            var char_height = 1.8 * char_width;
        
            // Measure the width of the label text
            var labelWidth = reg_ctx.measureText(attr[region_id]['label']).width;
        
            // Adjust the background rectangle width based on the label width
            var bgnd_rect_width = labelWidth + 2 * char_width; // You can adjust this as needed
        
            // Center the label
            x = x - (bgnd_rect_width / 2 - w / 2);
        
            // Ensure text is within img boundaries
            if (y < char_height) {
              y = char_height;
            }
        
            // Draw background rectangle
            reg_ctx.fillStyle = 'black';
            reg_ctx.globalAlpha = 0.8;
            reg_ctx.fillRect(Math.floor(x), Math.floor(y - 1.1 * char_height), Math.floor(bgnd_rect_width), Math.floor(char_height));
        
            // Draw text over background
            reg_ctx.globalAlpha = 1.0;
            reg_ctx.fillStyle = 'white';
            
            reg_ctx.fillText(attr[region_id]['label'], Math.floor(x + 0.4 * char_width), Math.floor(y - 0.35 * char_height));
          }
        
        }
      } 
    }
  
    function draw_rect_region(x,y,w,h,is_selected) {
      
      if (is_selected){
  
    
        draw_rect(x,y,w,h);
  
        reg_ctx.strokeStyle = selected_color;//THEME_SEL_REGION_FILL_BOUNDARY_COLOR;
        reg_ctx.lineWidth   = THEME_REGION_BOUNDARY_WIDTH/2;
        reg_ctx.stroke(); 
  
        reg_ctx.fillStyle   = THEME_SEL_REGION_FILL_COLOR;
        reg_ctx.globalAlpha = THEME_SEL_REGION_OPACITY;
        reg_ctx.fill();
        reg_ctx.globalAlpha = 1.0;
  
        draw_control_point(x,y);
        draw_control_point(x+w,y+h);
        draw_control_point(x,y+h);
        draw_control_point(x+w,y);
        draw_control_point(x+w/2,y);
        draw_control_point(x+w/2,y+h);
        draw_control_point(x,y+h/2);
        draw_control_point(x+w,y+h/2);
        
        display_labelkey_list();
        draw_sel_region_name();
        
      } else {
        // draw a fill line
        reg_ctx.lineWidth   = THEME_REGION_BOUNDARY_WIDTH/2;
        draw_rect(x, y, w, h);
        reg_ctx.stroke();
    
        if ( w > THEME_REGION_BOUNDARY_WIDTH && h > THEME_REGION_BOUNDARY_WIDTH ) {
          // draw a boundary line on both sides of the fill line
          //reg_ctx.strokeStyle = THEME_BOUNDARY_LINE_COLOR;
          reg_ctx.lineWidth   = THEME_REGION_BOUNDARY_WIDTH/4;
          draw_rect(x - THEME_REGION_BOUNDARY_WIDTH/2, y - THEME_REGION_BOUNDARY_WIDTH/2,
                    w + THEME_REGION_BOUNDARY_WIDTH, h + THEME_REGION_BOUNDARY_WIDTH);
          reg_ctx.stroke();
    
          draw_rect(x + THEME_REGION_BOUNDARY_WIDTH/2, y + THEME_REGION_BOUNDARY_WIDTH/2,
                    w - THEME_REGION_BOUNDARY_WIDTH, h - THEME_REGION_BOUNDARY_WIDTH);
          reg_ctx.stroke();
        }
      }
    }
  
    function draw_control_point(cx, cy) {
  
      reg_ctx.beginPath();
      reg_ctx.arc(cx, cy, 3, 0, 2*Math.PI, false);
      reg_ctx.closePath();
    
      reg_ctx.fillStyle = "red";
      reg_ctx.globalAlpha = 1.0;
      reg_ctx.fill();
    }
  
    function draw_rect(x, y, w, h) {
  
      reg_ctx.beginPath();
      reg_ctx.moveTo(x  , y);
      reg_ctx.lineTo(x+w, y);
      reg_ctx.lineTo(x+w, y+h);
      reg_ctx.lineTo(x  , y+h);
      reg_ctx.closePath();
    }
  
    function select_only_region(region_id) {
      
      toggle_all_region_selection(false);
      set_region_select_state(region_id, true);
      is_region_selected = true;
      is_all_region_selected = false;
      sel_region_id = region_id;
      
    }
  
    function sel_all_regions() {
      
      toggle_all_region_selection(true);
      is_all_region_selected = true;
      redraw_reg_canvas();
    }
    
    function move_selected_regions(move_x, move_y) {
      var n = region_selected_flag.length;
      for (var i = 0; i < n; ++i) {
        if (region_selected_flag[i]) {
          move_region(i, move_x, move_y);
        }
      }
    }
  
    function move_region(region_id, move_x, move_y) {
  
      var region_status = check_regions();
      
      if (region_status){
        var canvas_attr = canvas_region[current_img_id].annotations;
        var bbox = canvas_attr[region_id].box;
    
        var new_x = bbox[0] + Math.round(move_x * canvas_scale);
        var new_y = bbox[1] + Math.round(move_y * canvas_scale);
    
        var is_valid = validate_move_region(new_x, new_y, bbox);
        if (!is_valid) { return -1; }
    
        bbox[0] = Math.round(new_x / canvas_scale);
        bbox[1] = Math.round(new_y / canvas_scale);
      }
    }
  
    function validate_move_region(x,y, canvas_attr) {
      if (x < 0 || y <0) {
        return false;
      }
      if ((x + canvas_attr[2]) > canvas_width || (y + canvas_attr[3]) > canvas_height){
        return false;
      }
      return true;
    }
    
    function set_region_select_state(region_id, is_select) {
      
      region_selected_flag[region_id] = is_select;
    }
  
    function init_load_canvas_region() {
      //canvas_region = [];
  
      if (raw_data) {
        raw_data.forEach(function(xmlString) {
    
          //add_XML_format_data(xmlString);
          append_XML_format_data(xmlString);
        });
      }
      
    }
  
    function add_XML_format_data(xmlString){
  
      var parser = new DOMParser();
      var xmlDoc = parser.parseFromString(xmlString, "text/xml");
  
      var filename = remove_file_extension(xmlDoc.querySelector("filename").textContent);
      var path = xmlDoc.querySelector("path").textContent;
      
      var size = xmlDoc.querySelector("size");
      var img_w = parseFloat(size.querySelector("width").textContent);
      var img_h = parseFloat(size.querySelector("height").textContent);
      
      var objs = xmlDoc.querySelectorAll("object");
      
  
      var result = {
        "filename":filename ,"path":path, "img_w":img_w, "img_h":img_h,
        "annotations": []
      };
  
      canvas_width_height(img_w, img_h);
  
      objs.forEach( function (obj) {
        var label = obj.querySelector("name").textContent.toUpperCase();
        var bbox = obj.querySelector("bndbox");
  
        var x1 = Math.round(parseFloat(bbox.querySelector("xmin").textContent) * (canvas_width / img_w));
        var x2 = Math.round(parseFloat(bbox.querySelector("xmax").textContent) * (canvas_width / img_w));
        var y1 = Math.round(parseFloat(bbox.querySelector("ymin").textContent) * (canvas_height/ img_h));
        var y2 = Math.round(parseFloat(bbox.querySelector("ymax").textContent) * (canvas_height/ img_h));
  
        var box = [ x1, y1, x2-x1, y2-y1 ];
        var hexadecimal = generateRandomHexColor();
        
        if (["UNKNOWN-SKU", "UNKNOWNS-SKU", "UNKNOWN_SKU","UNKNOWN"].includes(label)) {
          hexadecimal = "#FF0000";
        } else if (label === "BAD") {
          hexadecimal = "#000000"
        }
  
        result.annotations.push({ "filename":filename, "label": label, "box": box });
  
        if (dropdown_data){
          var i = 0;
          i = dropdown_data?.length;
  
          const labelKeyExists = dropdown_data.some(item => item.Label_key === label);
          if (!labelKeyExists) {
            dropdown_data.push({"Label_key":label, "prod_id":`0${i}`, "prod_image":'', "bbox_color": hexadecimal, "status": "SELF"});
          }      
        }
      });
      canvas_region.push(result);
    }
  
    function append_XML_format_data(xmlString){
  
      var parser = new DOMParser();
      var xmlDoc = parser.parseFromString(xmlString, "text/xml");
  
      var filename = remove_file_extension(xmlDoc.querySelector("filename").textContent);
      
      var size = xmlDoc.querySelector("size");
      var img_w = parseFloat(size.querySelector("width").textContent);
      var img_h = parseFloat(size.querySelector("height").textContent);
  
      canvas_width_height(img_w, img_h);
  
      for (var i =0; i< canvas_region.length; ++i) {
        
        if (canvas_region[i].filename === filename ) {
          //overwrite annotations
          canvas_region[i].annotations = [];
  
          var objs = xmlDoc.querySelectorAll("object");
  
          objs.forEach( function (obj) {
            var label = obj.querySelector("name").textContent.toUpperCase();
            var bbox = obj.querySelector("bndbox");
  
            if (!label || !bbox) {
              // Skip processing if either name or bbox is null
              return;
            }
  
            var x1 = Math.round(parseFloat(bbox.querySelector("xmin").textContent) * (canvas_width/ img_w));
            var x2 = Math.round(parseFloat(bbox.querySelector("xmax").textContent) * (canvas_width/ img_w));
            var y1 = Math.round(parseFloat(bbox.querySelector("ymin").textContent) * (canvas_height/ img_h));
            var y2 = Math.round(parseFloat(bbox.querySelector("ymax").textContent) * (canvas_height/ img_h));
  
            /*
            if (!x1 || !x2 || !y1 || !y2) {
              // Skip processing if either name or bbox is null
              return;
            }*/
            
            var box = [ x1, y1, x2-x1, y2-y1 ];
            var hexadecimal = generateRandomHexColor();
        
            if (["UNKNOWN-SKU", "UNKNOWNS-SKU", "UNKNOWN_SKU","UNKNOWN"].includes(label)) {
              hexadecimal = "#FF0000";
            } else if (label === "BAD") {
              hexadecimal = "#000000"
            }
  
            canvas_region[i].annotations.push({"filename":filename, "label": label, "box": box});
            
            if (dropdown_data){
              var index = 0;
              index = dropdown_data?.length;
      
              const labelKeyExists = dropdown_data.some(item => item.Label_key === label);
              if (!labelKeyExists) {
                dropdown_data.push({"Label_key":label, "prod_id":`0${index}`, "prod_image":'', "bbox_color":hexadecimal, "status":"SELF"});
                
              }    
            }
           
          });
        }
      }
   
    }
    
    function is_inside_region(px, py, descending_order) {
     
      try{
        var N = canvas_region[current_img_id]?.annotations?.length;
      } catch {
        return -1;
      }
        
      if (N === 0){
        return -1;
      }
      var start, end, del;
      if (descending_order) {
        start = N - 1; end = -1; del = -1;
      } else {
        start = 0; end = N; del = 1;
      }
  
      var i = start;
      while (i !== end) {
        var yes = is_inside_this_region(px, py, i);
  
        if (yes) {
          return i;
        }
        i += del;
      }
      return -1;
      
    }
  
    function is_inside_this_region(px, py, region_id) {
  
      var region_status = check_regions();
      if (region_status) {
          var bbox = canvas_region[current_img_id]?.annotations[region_id]?.box;
          var result = false;
  
        // avoid right highlighted error
        try {
          result = is_inside_rect(bbox[0], bbox[1], bbox[2], bbox[3], px, py);
        } catch(err){
          console.log("inside_Rect", err)
        }
        
          return result;
        
      } else {
        console.log("err_is_inside_this_region");
        return false;
      }
      
    }
  
    function is_inside_rect(x, y, w, h, px, py) {
       return px > x && px < (x + w) && py > y && py < (y + h);
    }
  
    function is_on_region_corner(px , py) {
      var region_edge = [-1, -1];
  
      var attr = canvas_region[current_img_id].annotations;
  
      for (var j = 0; j < attr.length; ++j) {
        region_edge[0] = j;
        var result = false;
  
        var bbox = attr[j].box;
        result = is_on_rect_edge(bbox[0], bbox[1], bbox[2], bbox[3], px, py);
  
        if (result> 0){
          region_edge[1] = result;
          return region_edge;
        }
      }
      region_edge[0] = -1;
      return region_edge;
      
    }
  
    function is_on_rect_edge(x, y, w, h, px, py) {
      var dx0 = Math.abs(x - px);
      var dy0 = Math.abs(y - py);
      var dx1 = Math.abs(x + w - px);
      var dy1 = Math.abs(y + h - py);
      //[top-left=1,top-right=2,bottom-right=3,bottom-left=4]
      if ( dx0 < REGION_EDGE_TOL && dy0 < REGION_EDGE_TOL ) {
        return 1;
      }
      if ( dx1 < REGION_EDGE_TOL && dy0 < REGION_EDGE_TOL ) {
        return 2;
      }
      if ( dx1 < REGION_EDGE_TOL && dy1 < REGION_EDGE_TOL ) {
        return 3;
      }
      if ( dx0 < REGION_EDGE_TOL && dy1 < REGION_EDGE_TOL ) {
        return 4;
      }
    
      var mx0 = Math.abs(x + w/2 - px);
      var my0 = Math.abs(y + h/2 - py);
      //[top-middle=5,right-middle=6,bottom-middle=7,left-middle=8]
      if ( mx0 < REGION_EDGE_TOL && dy0 < REGION_EDGE_TOL ) {
        return 5;
      }
      if ( dx1 < REGION_EDGE_TOL && my0 < REGION_EDGE_TOL ) {
        return 6;
      }
      if ( mx0 < REGION_EDGE_TOL && dy1 < REGION_EDGE_TOL ) {
        return 7;
      }
      if ( dx0 < REGION_EDGE_TOL && my0 < REGION_EDGE_TOL ) {
        return 8;
      }
    
      return 0;
    }
  
    function toggle_all_region_selection(is_selected) {
      var region_status = check_regions();
      
      if (region_status){
        var n = canvas_region[current_img_id].annotations.length;
        region_selected_flag = [];
        for (var i = 0; i < n; ++i) {
          region_selected_flag[i] = is_selected;
        }
        is_all_region_selected = is_selected;
      } else {
        console.log("err_toggle_all_region_selection")
      }
  
    }
  
    function del_sel_regions() {
      //var del_region_count = 0;
      var region_status = check_regions();
  
      if (region_status){
        if (is_all_region_selected){
          //del_region_count = canvas_region[current_img_id].annotations.length;
          canvas_region[current_img_id].annotations.splice(0);
        } else {
          var sorted_sel_reg_id = [];
          for(var j = 0; j < canvas_region[current_img_id].annotations.length; ++j){
            if(region_selected_flag[j]) {
              sorted_sel_reg_id.push(j);
              region_selected_flag[j] = false;
            }
          }
          sorted_sel_reg_id.sort( function(a,b) {
            return (b-a);
          });
          for (var i =0; i < sorted_sel_reg_id.length; ++i){
            canvas_region[current_img_id].annotations.splice(sorted_sel_reg_id[i],1);
            //del_region_count +=1;
          }
          if (sorted_sel_reg_id.length){
            canvas.style.cursor = "default";
          }
        }
      
        is_all_region_selected = false;
        is_region_selected = false;
        sel_region_id = -1;
        
        image_id_list[current_img_id].Status = "CHANGED";
        console.log("test_DEL_CHANGED")
        
        if (canvas_region[current_img_id].annotations.length === 0 ){
          reg_ctx.clearRect(0,0, canvas.width, canvas.height);
        } else {
          redraw_reg_canvas();
        }
        display_labelkey_list();
        canvas.focus();
    
      }
      
    }
  
    function toggle_region_id_visibility() {
      is_region_id_visible = !is_region_id_visible;
      redraw_reg_canvas();
      canvas.focus();
    }
  
    function toggle_region_boundary_visibility() {
      is_region_boundary_visible = !is_region_boundary_visible;
      redraw_reg_canvas();
      canvas.focus();
    }
  
    function show_img(img_index) {
      reset_value();
  
      var read_image_list = image_id_list;
      /*
      if (temp_image_id_list?.length > 0){
        read_image_list = temp_image_id_list; 
      }
      */
      ///if (filter_signal) {
      if (filter_signal === "LABELED" || filter_signal === "UNLABELED" || sub_filter === "FILTER") {
      //if (temp_image_id_list?.length > 0){
        read_image_list = temp_image_id_list; 
      }
      //}
      //if (image_id_list?.length > 0) {
      if (read_image_list?.length > 0) {
      
        // Normalize img_index to stay within the bounds of image_id_list
        //img_index = (img_index + image_id_list.length) % image_id_list.length;
        img_index = (img_index + read_image_list.length) % read_image_list.length;
  
        current_img_id = img_index;
        //image_filename_list_entry_selected(current_img_id, false);
        
        //console.log("test_img_id", img_index)
        /*
        img_layer.src = image_id_list[img_index]["Photo_URI"];
        current_filename = image_id_list[img_index]["Photo_name"];
  
        var photo_w = image_id_list[img_index]["Photo_w"];
        var photo_h = image_id_list[img_index]["Photo_h"];*/
  
        var reader = new FileReader();
        var read_img = read_image_list[img_index]["Photo_URI"];
        
        reader.onload = function(event) {
          var result = event.target.result;
          img_layer.src = result;
        };
        
        if (read_img instanceof File) {
          reader.readAsDataURL(read_img);
        } else {
          img_layer.src = read_img;
        }
        
        current_filename = read_image_list[img_index]["Photo_name"];
  
        var photo_w = read_image_list[img_index]["Photo_w"];
        var photo_h = read_image_list[img_index]["Photo_h"];
  
        img_layer.onload = function () {
          canvas_width_height(photo_w, photo_h);
  
          canvas.width = canvas_width;
          canvas.height = canvas_height;
          img_layer.width = canvas_width;
          img_layer.height = canvas_height;
          img_name_tag.style.fontWeight = 'bold';
          img_name_tag.textContent = current_filename;

          img_wh_tag.style.fontWeight = 'bold';
          img_wh_tag.textContent = `${photo_w} x ${photo_h}`;
            
          container.appendChild(img_layer);
          container.appendChild(canvas);
          container.appendChild(img_name_tag);
          container.appendChild(img_wh_tag);
          
          redraw_reg_canvas();
          canvas.style.pointerEvents = "auto";
        };
  
        img_layer.onerror = function () {
          img_layer.src = '';
          img_name_tag.textContent = '';
          img_wh_tag.textContent = '';
          canvas.style.pointerEvents = "none";
        };
        
        //image_filename_list_entry_selected(img_index, true);
        display_labelkey_list();
      } else {
        current_img_id = -1;
        display_labelkey_list();
        img_layer.src = '';
        img_name_tag.textContent = '';
        img_wh_tag.textContent = '';
        canvas.style.pointerEvents = "none";
      }
  
    }
  
    function display_image_list() {
      var read_image_list = image_id_list;
  
      //if (filter_signal || sub_filter) {
      if (filter_signal === "LABELED" || filter_signal === "UNLABELED" || sub_filter === "FILTER") {
      //if (temp_image_id_list?.length > 0){
        read_image_list = temp_image_id_list;
      }
      //}
      //if (image_id_list) {
      if (read_image_list) {
  
        image_filename_list = [];
        image_filename_list.push('<ul>');
        
        //image_id_list.forEach(function(img, i) {
        
        read_image_list.forEach(function(img, i) { 
  
          // local image not display {File Type != Base64}
          var photo = img.Photo_URI; 
          var filename = img.Photo_name;

           // Check if the `photo` or `filename` is a File object and extract properties
  
          var total_region = 0;
          total_region = canvas_region[i]?.annotations?.length;
          image_filename_list.push(image_filename_list_entry_html(photo, filename, i, total_region));
        });
        
        /*if (temp_image_id_list === [] ){
          img_layer.src = '';
        }*/
        
        image_filename_list.push('</ul>');
        
        img_fn_list.innerHTML = image_filename_list.join('');

        update_canvas_region();
        check_region_img_indexing();
  
        var img_fn_title = document.getElementById('img_fn_title');
        img_fn_title.style.fontWeight = 'bold';
        img_fn_title.textContent = `IMAGE LIST : ( ${read_image_list.length} )`;
      } 
    }
  
    function image_filename_list_entry_html(photo, filename, i, total_region) {
      var htmli = '';
      
      htmli += '<li id="fl' + i +'"';
      if (i === current_img_id) {
          htmli += ' class="sel"';
      }
      htmli += ' onclick="jump_to_image(' + (i) + ')" title="' + filename + '">';
      htmli += '<div class="image-filename-container"><img src="' + photo + '" alt="Image"><div class="text-container"><div class="filename"> [' + (i+1) + '] '+ filename + '</div>';
      htmli += '<div class="region-count"><i class="fas fa-layer-group"></i> ' + total_region + '</div></div></div>';
      htmli += '<div class="button" title="Delete Image & Annotation" onclick="delete_image(event, ' + i + ')"><i class="fas fa-trash-alt"></i></div>';
      htmli += '<div class="download-button" title="Download Image & Annotation" onclick="download_image(event,' + i + ')"><i class="fa fa-download"></i></div>';
      htmli += '<div class="inference-button" title="Objectness Inference" onclick="process_inference(null, ' + i +')"><i class="fa fa-refresh"></i></div></li>';
      return htmli;
    }
  
    function scroll_to_imagelist_item(index) {
      const listItem = document.getElementById('fl' + index);
      if (listItem) {
        listItem.scrollIntoView({ behavior: 'auto', block: 'nearest', inline: 'start' });
        listItem.click();
      }
    }
  
    function image_filter() {
      var img_filter_panel = document.getElementById('img_filter_panel');
      img_filter_panel.style.display = 'none';
      
      var sel = create_element('select', "filter_type");
      
      var filter_options = ["ALL IMAGE", "LABELED", "UNLABELED"];
      
      filter_options.forEach(item => {
        var opt = create_element('option', null, item);
        opt.value = item;
        sel.appendChild(opt);
      });
      
      sel.addEventListener('change', function(event){
        var selected_type = event.target.value;
        sub_filter = '';
        
        if (selected_type === "ALL IMAGE") {
          temp_image_id_list = [];
          filter_signal = '';
          
        } else if (selected_type === "LABELED") {
  
          temp_image_id_list = image_id_list.filter(item => canvas_region.some(region =>
            region.annotations.some(annotation => annotation.filename === item.Photo_name)));
  
          filter_signal = 'LABELED';
          
        } else if (selected_type === "UNLABELED") {
  
          temp_image_id_list = image_id_list.filter(item =>!canvas_region.some(region =>
            region.annotations.some(annotation =>annotation.filename === item.Photo_name )));
          
          filter_signal = 'UNLABELED';
        }
        
        display_image_list();
        show_img(0);
        redraw_reg_canvas();
  
      });
  
      var img_modal = create_element('div');
      img_filter_panel.appendChild(img_modal);
      
      var img_search_input = create_element('input','img_search_input');
      //img_search_input.placeholder="Search for Image Name";
      img_search_input.placeholder="Search Area";
      
      var custom_title = create_element('label','custom_title', 'Custom Filter :');
  
      var sel2 = create_element('select', "sub_filter");
      var arr = ["IMAGE NAME :", "LABEL_KEY :"];
  
      arr.forEach(item => {
        var opt = create_element('option', null, item);
        if (item === 'IMAGE NAME :') {
          opt.value = "IMG";
        } else if (item === 'LABEL_KEY :') {
          opt.value = 'LBL';
        }
  
        sel2.appendChild(opt);
      });
  
      var lbl_search_drp = create_element('select', 'lbl_search_drp');
      var filter_btn = create_button('Filter','btn',() =>{
        sub_filter = 'FILTER';
  
        if (sel2.value === "LBL") { 
          temp_image_id_list = image_id_list.filter(item => canvas_region.some(region =>
            region.annotations.some(annotation => annotation.filename === item.Photo_name && annotation.label === lbl_search_drp.value)));
        } else if (sel2.value === "IMG") {
          //temp_image_id_list = image_id_list.filter(item => item.Photo_name === img_search_input.value);
          temp_image_id_list = image_id_list.filter(item => item.Photo_name.includes(img_search_input.value.toUpperCase()));
        }
        
        display_image_list();
        show_img(0);
        redraw_reg_canvas();
        
      });
      
      var search_label_key_list = [];
  
      var img_search_clear = create_button('X', "remove", () =>{
        img_search_input.value = '';
      });
      img_search_clear.title = "Clear Image Search Input";
  
      // Event listener for img_search_input changes
      img_search_input.addEventListener('input', function() {
        if (sel2.value === 'LBL') {
          lbl_search_drp.innerHTML = '';  // Clear the dropdown first
          if (dropdown_data) {
            // Filter search_label_key_list based on img_search_input value
            search_label_key_list = dropdown_data.filter(item => canvas_region.some(region =>
              region.annotations.some(annotation => annotation.label === item.Label_key && item.status === "SELF" &&
                item.Label_key.includes(img_search_input.value.toUpperCase()))));
  
            // Populate the dropdown based on the filtered list
            search_label_key_list.forEach(item => {
              var opt = create_element('option', null, item.Label_key);
              opt.value = item.Label_key;
              lbl_search_drp.appendChild(opt);
            });
          }
        }
      });
      
      sel2.addEventListener('change', function(event) {
        var selected_type = event.target.value;
        img_modal.innerHTML = '';
        
        if (selected_type === 'IMG') {
          append_children(img_modal,[custom_title, sel2, img_search_input, img_search_clear, filter_btn]);
          
        } else if (selected_type === 'LBL') {
          lbl_search_drp.innerHTML = '';
          if (dropdown_data) {
        
            search_label_key_list = dropdown_data.filter(item => canvas_region.some(region => region.annotations.some(annotation => annotation.label === item.Label_key && item.status === "SELF")));
            search_label_key_list.forEach(item => {
              var opt = create_element('option', null, item.Label_key);
              //opt.value = item.prod_id;
              opt.value = item.Label_key;
              lbl_search_drp.appendChild(opt);
            });
          }
          
          append_children(img_modal, [custom_title, sel2, img_search_input, img_search_clear, lbl_search_drp, filter_btn]);
        }
        
        if (!img_filter_panel.contains(img_modal)) { 
          img_filter_panel.appendChild(img_modal);
        }
      });
  
      var img_adv_chk = create_checkbox(() => {
        
        if (img_adv_chk.checked){
          search_label_key_list = [];
          
          if (!img_filter_panel.contains(img_modal)) { 
            append_children(img_modal,[custom_title, sel2, img_search_input, img_search_clear, filter_btn]);
            img_filter_panel.appendChild(img_modal);
          }
          img_modal.style.display = "block";
          
          
        } else {
          img_modal.style.display = "none";
        }
      });
      img_adv_chk.id = "img_adv_chk";
  
      var img_adv_label = create_element('label','img_adv_label','Advanced :');
      img_adv_label.style.textDecoration = "underline";
  
      img_filter_panel.innerHTML = '<label>Show Images :</label>';
      append_children(img_filter_panel,[sel, img_adv_label, img_adv_chk]);
      
      img_filter.addEventListener('click', function(){
        
        img_filter_panel.style.display = (img_filter_panel.style.display === 'none') ? 'block' : 'none';
      }); 
  
    }
    
    function update_canvas_region() {
     
  
      // Update canvas_region path according to the image_id_list photo_uri
      image_id_list.forEach(function(image, i) {
        if (canvas_region[i]?.filename === image.Photo_name) {
          canvas_region[i].path = image.Photo_URI;
        }
      });
  
    }
  
    function jump_to_image(img_index) {
  
      if (img_index >= 0 && img_index < image_id_list.length) {
        show_img(img_index);
      }
    }
  
    function image_filename_list_entry_selected(img_index, is_selected) {
      var li = document.getElementById('fl' + img_index);
      var classname = 'sel';
      
      if (li) {
        if (is_selected) {
          li.classList.add(classname);
        } else {
          li.classList.remove(classname);
        }
      }
    }
  
    function display_labelkey_list() {
  
      labelkey_list = [];
      labelkey_list.push('<ul>');
  
      var region_status = check_regions();
      var lbl_key_title = document.getElementById('lbl_key_title');
      var total_label = 0;
      
      if (region_status){
        
        var region_obj = canvas_region[current_img_id].annotations;
        total_label = region_obj.length;
        
        for (var i =0; i < region_obj.length; ++i){
          var lbl = region_obj[i].label;
          
          labelkey_list.push(labelkey_list_entry_html(lbl, i));
        }
        
      } else {
        labelkey_list.push('<li></li>')
      }
      
      labelkey_list.push('</ul>')
      lbl_key_list.innerHTML = labelkey_list.join('');
      lbl_key_title.style.fontWeight = 'bold';
      lbl_key_title.textContent = `LABEL KEY LIST : ( ${total_label} )`;
    }
  
    function labelkey_list_entry_html(label, i) {
      var htmli = '';
    
      htmli += '<li id="lbl' + i +'"';
      
      if (is_region_selected || is_all_region_selected || region_selected_flag.length !== 0) {
        var attr = canvas_region[current_img_id].annotations;
  
        if (is_all_region_selected || region_selected_flag.length !== 0) {
          for (var j = 0; j < attr.length; ++j) {
            if (region_selected_flag[j] && j === i) {
              
              htmli += ' class="sel"';
  
              remove_sel_satus(custom_dropdown);
              add_sel_status(custom_dropdown, j);
  
              search_input.value = '';
              update_dropdown(dropdown_data);
            }
          }
          
        } 
        if (is_region_selected && i === sel_region_id && dropdown_data) {
          htmli += ' class="sel"';
    
          dropdown_data.forEach(function (drp) {
            
            if (drp.Label_key === label) {
              selected_label = drp.Label_key;
              selected_color = drp.color;
              search_input.value = drp.Label_key;
              
              var search_term = search_input.value.toUpperCase();
              filter_option = dropdown_data.filter(function (option) {
                return option.Label_key.toUpperCase().includes(search_term);
              });
              
              update_dropdown(filter_option);
              remove_sel_satus(custom_dropdown);
              add_sel_status(custom_dropdown, drp.prod_id);
            }
          });
        }
      }
      
      htmli += ' onclick="hightlight_labelkey(' + (i) + ')" title="' + label + '"> [' + (i+1) + '] ' + label +' </li>';
  
      return htmli;
    }
  
    function hightlight_labelkey(region_index,is_selected) {
      
      var li = document.getElementById('lbl' + region_index);
      var classname = 'sel';
  
      select_only_region(region_index);
      redraw_reg_canvas();
       
      if (li) {
        if (is_selected) {
          li.classList.add(classname);
        } else {
          li.classList.remove(classname);
        }
      }
    }
    
    function scroll_to_labelkey_item(index) {
      const listItem = document.getElementById('lbl' + index);
      if (listItem) {
        listItem.scrollIntoView({ behavior: 'auto', block: 'nearest', inline: 'start' });
        listItem.click();
      }
    }
    
    function reset_value() {
  
      click_x0 = 0; click_y0 = 0;
      click_x1 = 0; click_y1 = 0;
      is_drawing = false;
      is_resizing = false;
      is_moving = false;
      is_region_selected = false;
      sel_region_id = -1;
      toggle_all_region_selection(false);
  
    }
  
    function check_regions() {
      return !!(canvas_region[current_img_id] && canvas_region[current_img_id].annotations);
    }
  
    function clear_regions(region_status) {
      if (region_status && canvas_region[current_img_id]?.annotations?.length) {
        redraw_reg_canvas();
      } else {
        reg_ctx.clearRect(0, 0, canvas.width, canvas.height);
      }
    }
  
    function input_handler() {
      if (dropdown_data){
        search_input.addEventListener('input', function () {
          var search_term = search_input.value.toUpperCase();
          filter_option = dropdown_data.filter(function (option) {
            
            return option.Label_key.toUpperCase().includes(search_term);
          });
  
          // SEARCH AND USED
          selected_label = filter_option[0]?.Label_key;
          selected_color = filter_option[0]?.bbox_color;
          
          update_dropdown(filter_option);
        });
      }
    }
  
    function clear_input_handler() {
      clear_button.addEventListener('click', function () {
        search_input.value = '';
        search_input.focus();
        update_dropdown(dropdown_data);
      });
    }
    
    function update_dropdown(options) {
      custom_dropdown.innerHTML = '';
  
      if (options) {
        options.forEach(function (option ) {
          var li = create_element('li', option.prod_id);
          
          var img = create_element('img');
          img.src = option.prod_image;
          li.appendChild(img);
    
          var lbl_span = create_element('span', null, `[ ${option.prod_id} ] ${option.Label_key}`);
          li.appendChild(lbl_span);
    
          li.addEventListener('click', function () {
            search_input.value = option.Label_key;
            selected_label = option.Label_key;
            selected_color = option.bbox_color;
            
            remove_sel_satus(custom_dropdown);
            li.classList.add("sel");
            
            if (is_region_selected || is_all_region_selected || region_selected_flag.length !== 0) {
              var attr = canvas_region[current_img_id]?.annotations;
            
  
              if (is_all_region_selected || region_selected_flag.length !== 0) {
                for (const annotation of attr) {
                  if (region_selected_flag[attr.indexOf(annotation)]) {
                    annotation.label = selected_label;
                  }
                }
              } else {
                attr[sel_region_id].label = selected_label;
              }
              
              redraw_reg_canvas();
              canvas.focus();
            }
          });
          custom_dropdown.appendChild(li);
        });
      }
    }
  
    function remove_sel_satus(item_list) {
      const li_items = item_list.querySelectorAll('li');
      li_items.forEach(item => item.classList.remove('sel'));
    }
  
    function add_sel_status(item_list, condition) {
      const selectedItem = item_list.querySelector(`li[id="${condition}"]`);
      if (selectedItem) {
        selectedItem.classList.add("sel");
      }
     
    }
  
    function file_button() {
      const file_input      = '<input type="file" id="file_input" name="files[]" style="display:none">';
      const folder_input    = '<div><input type="file" id="folder_input" style="display:none" webkitdirectory multiple></div>';
      const add_files_btn   = '<span class="button" onclick="sel_local_files()" title="Add new files from local"> Add Files </span>';
      const add_folder_btn  = '<span class="button" onclick="sel_local_folder()" title="Add new folder from local"> Add Folder </span>';
      const download_all_btn = '<span class="button" onclick="download_all_region_data()" title="Downlaod All Image & XML file"> Download All </span>';
      
      file_btn_panel.innerHTML = file_input + folder_input + add_files_btn + add_folder_btn + download_all_btn ;
    }
  
    function sel_local_files() {
      var file_input = document.getElementById("file_input");
  
      if (file_input) {
        file_input.setAttribute('multiple', 'multiple');
        file_input.accept = '.jpg, .jpeg, .png, .xml';
        file_input.onchange = reorder_local_files;
        file_input.click();
      }
    }

    function sel_local_folder() {
      var folder_input = document.getElementById("folder_input");
      
      if (folder_input) {
        folder_input.onchange = reorder_local_files;
        folder_input.click();
      } 
    }
  
    function reorder_local_files(e) {
      
      var selected_files = e.target.files;
  
      var imageFiles = [];
      var nonImageFiles = [];
      //UPLOAD_FILE = 0;
  
      for (var i = 0; i < selected_files.length; i++){
        var file_type = selected_files[i].type.substr(0, 5);
        var file_extension = selected_files[i].name.split('.').pop().toUpperCase();
  
        if (file_type === 'image' && (file_extension === 'JPG' || file_extension === 'JPEG' || file_extension === 'PNG')) {
          //++UPLOAD_FILE;
          imageFiles.push(selected_files[i]);
        } else {
          nonImageFiles.push(selected_files[i]);
        }
      }
    
      add_local_files(imageFiles.concat(nonImageFiles));
      
    }
  
    async function add_local_files(local_files) {
      var ori_img_count = image_id_list.length;
      for (var i = 0; i < local_files.length; ++i) {
  
        var new_img_id = ori_img_count + i;
  
        const currentFile = local_files[i];
        
        var file_type = local_files[i].type.substr(0, 5);
        var file_name = local_files[i].name;
        var file_extension = file_name.split('.').pop().toUpperCase();
  
        if (file_type === 'image' && (file_extension === 'JPG' || file_extension === 'JPEG' || file_extension === 'PNG')) {
          await processLocalImage(currentFile, new_img_id);
        }
       
        if (file_extension === "XML") {
          try {
            await processLocalXML(currentFile);
          } catch (error) {
            console.error(`Error processing XML: ${error.message}`);
          }
        }
      }
      update_image_list();
      
      search_input.value = dropdown_data[0]?.Label_key;
      selected_label = dropdown_data[0]?.Label_key;
      selected_color = dropdown_data[0]?.bbox_color;
      update_dropdown(dropdown_data);
      add_sel_status(custom_dropdown, dropdown_data[0]?.prod_id);
      display_labelkey_list();

    }
  
    function processLocalImage(currentFile, new_img_id) {
      return new Promise((resolve, reject) => {
        var clear_img_name = remove_file_extension(currentFile.name);
        var img_index = image_id_list.findIndex(img => img.Photo_name === clear_img_name);
        
        if (img_index === -1) {
  
          var reader = new FileReader();
          var photo_w; var photo_h;
          
          reader.onload = function (e) {
            
            const img_url = currentFile;
            var temp_img = new Image();
           
            temp_img.onload = function(){
              photo_w = temp_img.width;
              photo_h = temp_img.height;
              
              image_id_list.push({
                "Photo_name": clear_img_name, "Photo_id": new_img_id, "Photo_w": photo_w, "Photo_h": photo_h, "Photo_URI":  img_url, "Status":'', "Type":"LOCAL" 
              });
              var result = {"filename":clear_img_name, "path":"", "img_w":photo_w, "img_h":photo_h, "annotations":[]};
              canvas_region.push(result);
    
              display_image_list();
              show_img(current_img_id);
              resolve();
            };
            temp_img.src = e.target.result;
          };
          reader.readAsDataURL(currentFile);
        }else {
          resolve();
        }
      }); 
    }
  
    function processLocalXML(currentFile) {
      return new Promise((resolve, reject) => {
        var reader = new FileReader();
        reader.onload = function (e) {
          try {
            var xmlString = e.target.result;
            append_XML_format_data(xmlString);
            resolve();
          } catch (error) {
            reject(`Error processing XML: ${error.message}`);
          }
        };
        reader.readAsText(currentFile);
      });
    }
  
    function jsonToXml(jsonData) {
      // Create the XML document with the XML declaration
      var region = jsonData;
  
      const xmlDoc = document.implementation.createDocument(null, 'annotation', null);
      const ann = xmlDoc.documentElement;
  
      const createElementWithText = (tagName, textContent) => {
        const element = xmlDoc.createElement(tagName);
        element.textContent = textContent;
        return element;
      };
  
      ann.appendChild(createElementWithText('filename', `${region.filename}.jpg`));
      ann.appendChild(createElementWithText('path', null));
      ann.appendChild(createElementWithText('segmented', '0'));
  
      const size = xmlDoc.createElement('size');
      size.appendChild(createElementWithText('width', region.img_w));
      size.appendChild(createElementWithText('height', region.img_h));
      size.appendChild(createElementWithText('depth', '3'));
      ann.appendChild(size);
  
      canvas_width_height(region.img_w, region.img_h)
  
      region.annotations.forEach(ann_info => {
        const object = xmlDoc.createElement('object');
        object.appendChild(createElementWithText('name', ann_info.label));
        object.appendChild(createElementWithText('pose', 'Unspecified'));
        object.appendChild(createElementWithText('truncated', '0'));
        object.appendChild(createElementWithText('difficult', '0'));
  
        //const [x1, y1, w, h] = ann_info.box.map(val => Math.round(parseFloat(val)));
  
        var x1 = Math.round(parseFloat(ann_info.box[0] / (canvas_width / region.img_w)));
        var y1 = Math.round(parseFloat(ann_info.box[1] / (canvas_height / region.img_h)));
        var w = Math.round(parseFloat(ann_info.box[0] + ann_info.box[2]) / (canvas_width / region.img_w));
        var h = Math.round(parseFloat(ann_info.box[1] + ann_info.box[3]) / (canvas_height / region.img_h));
  
        // prevent bbox out of image 
        x1 = Math.max(0, x1);
        y1 = Math.max(0, y1);
        w = Math.max(0, w);
        h = Math.max(0, h);
        
        const bndbox = xmlDoc.createElement('bndbox');
        bndbox.appendChild(createElementWithText('xmin', x1));
        bndbox.appendChild(createElementWithText('xmax', w));
        bndbox.appendChild(createElementWithText('ymin', y1));
        bndbox.appendChild(createElementWithText('ymax', h));
       
        object.appendChild(bndbox);
        ann.appendChild(object);
      });
      
      return new XMLSerializer().serializeToString(xmlDoc);
    }
  
    async function download_all_region_data() {
      var zip = new JSZip();
  
      var read_image_list = image_id_list;
      //if (filter_signal) {
      if (filter_signal === "LABELED" || filter_signal === "UNLABELED" || sub_filter === "FILTER") {
        read_image_list = temp_image_id_list; 
      }
      //}
      
      for (var i = 0; i < read_image_list?.length; ++i) {
  
        var new_region = canvas_region.find(item=> read_image_list[i].Photo_name === item.filename);
        var data = new_region.path;
  
        //if (isBase64(data)) {
        if (data instanceof File){
          try {
            const uint8Array = base64StringToBlob(data);
            zip.file('img/'+new_region.filename + '.jpg', uint8Array, { binary: true });
          } catch (error) {
            console.error("Error handling base64 data:", error);
          }
        } else {
          const response = await fetch(data);
          const bb = await response.blob();
          zip.file('img/'+new_region.filename + '.jpg', bb);
        }
  
        var xmlString = jsonToXml(new_region);
        //const xmlString = new XMLSerializer().serializeToString(result);
        zip.file("xml/"+new_region.filename + ".xml", xmlString);
         
      }
      
      zip.generateAsync({ type: "blob" }).then(function (content) {
        var zipLink = create_element('a');
        zipLink.href = URL.createObjectURL(content);
        zipLink.download = "anvil_img_xml.zip";
        zipLink.click();
        URL.revokeObjectURL(zipLink.href);
      });
    }
    
    function delete_image(event, image_index) {
      event.stopPropagation();
  
      var read_image_list = image_id_list;
  
      //if (filter_signal) {
      if (filter_signal === "LABELED" || filter_signal === "UNLABELED" || sub_filter === "FILTER") {
        read_image_list = temp_image_id_list; 
      }
      //}
  
      //  image_id_list.splice(image_index,1);
      //  canvas_region.splice(image_index,1);
      image_id_list = image_id_list.filter(item=> read_image_list[image_index].Photo_name !== item.Photo_name);
      canvas_region = canvas_region.filter(item=> read_image_list[image_index].Photo_name !== item.filename);
      temp_image_id_list.splice(image_index, 1);
      
      display_image_list();
      show_img(current_img_id);
      redraw_reg_canvas();
  
    }
  
    async function download_image(event, image_index) {
      event.stopPropagation();
      
      var read_image_list = image_id_list;
      //if (filter_signal) {
      if (filter_signal === "LABELED" || filter_signal === "UNLABELED" || sub_filter === "FILTER") {
        read_image_list = temp_image_id_list; 
      }
      //}
  
      var new_region = canvas_region.find(item=> read_image_list[image_index].Photo_name === item.filename);
      var data = new_region.path;
  
      //if (isBase64(data)) {
      if (data instanceof File){
        try {
          const uint8Array = base64StringToBlob(data);
          var zip = new JSZip();
          zip.file('img/'+new_region.filename + '.jpg', uint8Array, { binary: true });
        } catch (error) {
          console.error("Error handling base64 data:", error);
        }
      } else {
        const response = await fetch(data);
        const bb = await response.blob();
        var zip = new JSZip();
        zip.file('img/'+new_region.filename + '.jpg', bb);
      }
      
      var xmlString = jsonToXml(new_region);
      //const xmlString = new XMLSerializer().serializeToString(result);
      var zip = zip || new JSZip();
        
      zip.file("xml/"+new_region.filename + ".xml", xmlString);
      
      zip.generateAsync({ type: "blob" }).then(function (content) {
        var zipLink = create_element('a');
        zipLink.href = URL.createObjectURL(content);
        zipLink.download = new_region.filename + ".zip";
        zipLink.click();
        URL.revokeObjectURL(zipLink.href);
      });
     // }
    }
  
    // TESTING
    async function sendImage(file, file_name) {

      const formData = new FormData();
      formData.append('image', file); // Correctly append the file
      formData.append('img_name', file_name); // Correctly append the file name
      
      const response = await fetch('http://localhost:8000/obj/inferenceObjectness', {
        method: 'POST',
        body: formData,
      });

      // AKS - cluster
      // const response = await fetch('http://57.155.59.71/obj/inferenceObjectness', {
      //   method: 'POST',
      //   body: formData,
      // });

      const result = await response.text();

      // APPEND 
      server_update_canvas_region(result);
      
    }

    function remove_file_extension(filename) {
      return filename.replace(/\.[^/.]+$/, "");
    }
  
    /*
    function isBase64(str) {
      try {
        return btoa(atob(str)) === str;
      } catch (err) {
        return false;
      }
    }*/
  
    function base64StringToBlob(data){
      return new Promise((resolve, reject) => {
  
        var reader = new FileReader();
        reader.readAsDataURL(data);
    
        reader.onload = function(event) {
          var result = event.target.result;
          //const byteCharacters = atob(result);
          const byteCharacters = atob(result.split(',')[1]);
  
          const byteNumbers = new Array(byteCharacters.length);
      
          for (let i = 0; i < byteCharacters.length; i++) {
              byteNumbers[i] = byteCharacters.charCodeAt(i);
          }
          const byteArray = new Uint8Array(byteNumbers);
          resolve(new Blob([byteArray], { type: 'application/octet-stream' }));
        };
  
        reader.onerror = function(error) {
          reject(error);
        }
      });
    }
  
    // ANVIL ONLY - modified
    function process_inference(model=null, img_id){
      return new Promise((resolve, reject) => {
        var model_url = null;
        var model_api = null;
        var reader = new FileReader();
        
        var read_image_list = image_id_list;
       // if (filter_signal) {
        if (filter_signal === "LABELED" || filter_signal === "UNLABELED" || sub_filter === "FILTER") {
          read_image_list = temp_image_id_list; 
        }
        //}
  
        // var new_img = image_id_list.find(item=> read_image_list[current_img_id].Photo_name === item.Photo_name);
        var new_img = image_id_list.find(item=> read_image_list[img_id].Photo_name === item.Photo_name);

  
        if (model === null) {
          var uri = new_img?.Photo_URI;
          var img_name = new_img?.Photo_name;
  
          reader.onload = function(event) {
            var result = event.target.result;
            // resolve([result, img_name]);

            sendImage(result, img_name);
          };
  
          if (uri instanceof File) {
            reader.readAsDataURL(uri);
          } else {
            // resolve([uri, img_name]);
            sendImage(uri, img_name);

          }
          
        }
    
        if (model) {
          var uri = new_img?.Photo_URI;
          var img_name = new_img?.Photo_name;
    
          var top = document.getElementById('ir_model_modal');
          var top_content = document.getElementById('sel_ir_model_modal');
          top_content.innerHTML = '';
  
          var new_div = create_element('div');
          var adv_div = create_element('div', 'adv_panel');
          
          var display_type = create_element('label', null, "CATEGORY TYPE :" );
          var sel = create_element('select', "model_type");
  
          var cloud_advanced_label = create_element('label', null, "Advanced :");
          cloud_advanced_label.style.textDecoration = "underline"; 
          
          var cloud_adv_modal = create_element('div')
          cloud_adv_modal.style.display = "none";
  
          var cloud_advanced = create_checkbox(() => {
            if (cloud_advanced.checked){
              cloud_adv_modal.style.display = "block";
              
            } else {
              cloud_adv_modal.style.display = "none";
            }
          });
  
          var cloud_api_lbl = create_element('label', null, "CLOUD API KEY :");
          var cloud_api = create_element('input');
          cloud_api.type = "text";
  
          var cloud_api_clear = create_button('X', "remove", () =>{
            cloud_api.value = '';
          });
          cloud_api_clear.title = "Clear Cloud API Input";
  
          var cloud_url_lbl = create_element('label', null, "CLOUD URL WITH PUBLISHED NAME :");
          var cloud_url = create_element('input');
          cloud_url.type = "text";
  
          var cloud_url_clear = create_button('X', "remove", () =>{
            cloud_url.value = '';
          });
          cloud_url_clear.title = "Clear Cloud URL Input";
  
          var connect_btn = create_button("CONNECT", "btn", () => {
            var selected = sel.value;
            var selectedModel = model.find(item => item.model_name === selected);
  
            model_url = cloud_url.value;
            model_api = cloud_api.value;
  
            if (model_url && model_api){
              
              top.style.display = "none";
  
              reader.onload = function(event) {
                var result = event.target.result;
                resolve([result, img_name, model_api, model_url]);
              };
      
              if (uri instanceof File) {
                reader.readAsDataURL(uri);
              } else {
                resolve([uri, img_name, model_api, model_url]);
              }
              //resolve([uri, img_name, model_api, model_url]);
              
            } else {
              model_url = selectedModel.model_cloud_url + selectedModel.model_cloud_name;
              model_api = selectedModel.model_api;
              top.style.display = "none";
  
              reader.onload = function(event) {
                var result = event.target.result;
                resolve([result, img_name, model_api, model_url]);
              };
      
              if (uri instanceof File) {
                reader.readAsDataURL(uri);
              } else {
                resolve([uri, img_name, model_api, model_url]);
              }
  
              //resolve([uri, img_name, model_api, model_url]);
            }
  
          });
  
          var cancel_btn = create_button("CANCEL", "btn", () => {
            top.style.display = "none";
            //cloud_api.value = '';
            //cloud_url.value = '';
            // reject(["null", "null", "null", "null"]);
            resolve([null, null, null, null]);
          });
  
          model.forEach(item => {
            var opt = create_element('option', null, item.model_name);
            opt.value = item.model_name;
            sel.appendChild(opt);
          });
  
          top_content.appendChild(new_div);
          append_children(adv_div, [cloud_advanced_label, cloud_advanced]);
          append_children(new_div, [display_type, sel, adv_div]);
          
          top_content.appendChild(cloud_adv_modal);
          append_children(cloud_adv_modal, [cloud_api_lbl, cloud_api, cloud_api_clear, cloud_url_lbl, cloud_url, cloud_url_clear]);
          append_children(top_content, [connect_btn, cancel_btn]);
          
          top.style.display = "block";
        }
      });
    }

    
    // ANVIL ONLY - modified
    function server_update_canvas_region(xmlString){
  
      if (xmlString){
        append_XML_format_data(xmlString);
      
        display_labelkey_list();
        redraw_reg_canvas();
      }
    }
  
    
    // ANVIL ONLY
    /*
    function cate_name_prod_type(){
      return new Promise((resolve, reject) => {
        
        var selectedDrpTypeValue = null;
        var selectedDrpClassnameValue = null;
  
        var top = document.getElementById('main_modal');
        var top_content = document.getElementById('sel_modal');
        top_content.innerHTML = '';
  
        var display_type = create_element('label', null, "CATEGORY TYPE :");
        var sel = create_element('select', "drp_type");
  
        var prod_name = create_element('label', null, "PRODUCT TYPE :");
        var sel2 = create_element('select', "drp_classname");
  
        var connect_btn = create_button("CONNECT", "btn", () => {
          selectedDrpTypeValue = sel.value;
          selectedDrpClassnameValue = sel2.value;
          top.style.display = "none";
          resolve([selectedDrpTypeValue, selectedDrpClassnameValue]);
        });
  
        var cancel_btn = create_button("CANCEL", "btn", () => {
          top.style.display = "none";
          // reject(["null", "null"]);
          resolve([null, null]);
          
        });
  
        // IC_PRICE_STICKER, POSM, CTA ++ for temp
        var arr = ["PRODUCT", "COMPETITOR", "OTHERS"];
        var arr2 = ["DEODORANTS & FRAGRANCES","DRESSING","FABRIC CLEANING & ENHANCERS","FUNCTIONAL NUTRITION",
                    "HOME & HYGIENE","ICE CREAM", "HAIR CARE", "NUTRITIONS","SCRATCH COOKING AIDS","SKIN CARE", "SKIN CLEANSING"];
        
        arr.forEach(item => {
          var opt = create_element('option', null, item);
          opt.value = item;
          sel.appendChild(opt);
        });
  
        arr2.forEach(item => {
          var opt2 = create_element('option', null, item);
          opt2.value = item;
          sel2.appendChild(opt2);
        });
  
        append_children(top_content, [prod_name, sel, display_type, sel2, connect_btn, cancel_btn]);
        top.style.display = "block";
      });
    }
    */

    // ANVIL ONLY
    /*
    function server_update_drp(drp) {

      dropdown_data = dropdown_data.filter(item => item.status !== 'SERVER');
  
      if (drp){
        drp.forEach(drp_result => {
          var hexadecimal = generateRandomHexColor();
          var label = drp_result.Label_key.toUpperCase();
        
          if (["UNKNOWN-SKU", "UNKNOWNS-SKU", "UNKNOWN_SKU","UNKNOWN"].includes(label)) {
            hexadecimal = "#FF0000";
          } else if (label === "BAD") {
            hexadecimal = "#000000"
          }
          
          const exisiting_index = dropdown_data.findIndex(item => item.Label_key === label);
          if (exisiting_index !== -1){
            dropdown_data[exisiting_index].prod_id = drp_result.prod_id
            dropdown_data[exisiting_index].prod_image = drp_result.prod_image;
          } else{
            dropdown_data.push({"Label_key":label, "prod_id":drp_result.prod_id, "prod_image":drp_result.prod_image, "bbox_color":hexadecimal, "status":"SERVER"});
          }
        });
      }
      
      search_input.value = dropdown_data[0]?.Label_key;
      selected_label = dropdown_data[0]?.Label_key;
      selected_color = dropdown_data[0]?.bbox_color;
      
      update_dropdown(dropdown_data);
      add_sel_status(custom_dropdown, dropdown_data[0]?.prod_id);
      
      input_handler();
      clear_input_handler();
      update_dropdown(dropdown_data);
    }
    */
  
    function add_class_labelkey() {
  
      var label = prompt("Create Label Key:")?.toUpperCase();
      if (!label || label === '') return;
      
      var hexadecimal = generateRandomHexColor();
  
      if (["UNKNOWN-SKU", "UNKNOWNS-SKU", "UNKNOWN_SKU","UNKNOWN"].includes(label)) {
        hexadecimal = "#FF0000";
      } else if (label === "BAD") {
        hexadecimal = "#000000";
      }
  
      var i = 0; 
      i = dropdown_data?.length;
  
      const labelKeyExists = dropdown_data.some(item => item.Label_key === label);
      if (!labelKeyExists) {
        dropdown_data.push({"Label_key":label, "prod_id":`0${i}`, "prod_image":'', "bbox_color":hexadecimal, "status":"SELF"});
  
        selected_label = label;
        selected_color = hexadecimal;
        search_input.value = label;
      } else {
   
        const existingItem = dropdown_data.find(item => item.Label_key === label);
      
        if (existingItem) {
          selected_label = existingItem.Label_key;
          selected_color = existingItem.bbox_color;
          search_input.value = existingItem.Label_key;  // Optionally set input value to existing label
        }
      }
  
      update_dropdown(dropdown_data);
      input_handler();
      clear_input_handler();
    }
  
    // ANVIL WORK
    /*
    function blob_file_sel(blob_cate){
      return new Promise((resolve, reject) => {
  
        var blob_top = document.getElementById('main_blob_modal');
        var blob_top_content = document.getElementById('sel_blob_modal');
        blob_top_content.innerHTML = '';
  
        var blob_connect_btn = create_button("CONNECT", "btn", () => {
          var selectedRow = document.querySelector('tbody tr.selected');
          
          if (selectedRow) {
            var sel_blob_url = selectedRow.querySelector('td:nth-child(6)').textContent;
            blob_top.style.display = "none";
            resolve(sel_blob_url);
          } else {
            // reject("NULL");
            resolve(null);
          }
        });
        
        var blob_cancel_btn = create_button("CANCEL", "btn", () => {
          blob_top.style.display = "none";
          // reject("NULL");
          resolve(null);
        });
  
        var tableContainer = create_element('div', null, null,'table-container');
  
        var table = create_element('table');
        var thread = create_element('thead');
        var tr = create_element('tr');
        var tbody = create_element('tbody');
  
        thread.appendChild(tr);
        tr.innerHTML ='<th>Id</th><th>Description</th><th>Type</th><th>Folder</th><th>Client</th><th>URL</th>';
        blob_cate.forEach(item=> {
          var row = create_element('tr');
          row.innerHTML =`
            <td>${item.blob_id}</td>
            <td>${item.blob_desc}</td>
            <td>${item.blob_type}</td>
            <td>${item.blob_folder}</td>
            <td>${item.blob_client}</td>
            <td>${item.blob_url}</td>
          `
          tbody.appendChild(row);
        })
        
        append_children(table, [thread, tbody]);
        tableContainer.appendChild(table);
        
        append_children(blob_top_content, [tableContainer, blob_connect_btn, blob_cancel_btn]);
  
        blob_top.style.display = "block";
  
        tbody.addEventListener('mouseover', function (event) {
          var targetRow = event.target.closest('tr');
          if (targetRow) {
            document.querySelectorAll('tbody tr').forEach(row => row.classList.remove('highlighted'));
            targetRow.classList.add('highlighted');
          }
        });
      
        tbody.addEventListener('mouseout', function () {
          document.querySelectorAll('tbody tr').forEach(row => row.classList.remove('highlighted'));
        });
  
        tbody.addEventListener('click', function (event) {
          var targetRow = event.target.closest('tr');
          if (targetRow) {
            document.querySelectorAll('tbody tr').forEach(row => row.classList.remove('selected'));
            targetRow.classList.add('selected');
          }
        });
      });
    }
    */

    // ANVIL WORK
    /*
    async function read_blob_files(blob_files) {
  
      // Check if blob_files is null, undefined, or not an array
      if (!Array.isArray(blob_files) || blob_files.length === 0) {
        console.log("Invalid input: blob_files is null, undefined, or empty.");
        return; // Exit early if input is invalid
      }
      
      var ori_img_count = image_id_list.length;
      for (var i = 0; i < blob_files.length; ++i) {
        var new_img_id = ori_img_count + i;
        
        const currentFile = blob_files[i];
        const segments = blob_files[i].split('.');
        const file_extension = segments[segments.length - 1].toUpperCase();
  
        if (file_extension === 'JPG' || file_extension === 'JPEG' || file_extension === 'PNG') {
          await processImage(currentFile,new_img_id);
        }
        if ( file_extension === "XML"){
          await processXML(currentFile);
        }
      }
      update_image_list();
  
      search_input.value = dropdown_data[0]?.Label_key;
      selected_label = dropdown_data[0]?.Label_key;
      selected_color = dropdown_data[0]?.bbox_color;
      update_dropdown(dropdown_data);
      add_sel_status(custom_dropdown, dropdown_data[0]?.prod_id);
      display_labelkey_list();
    }
    */

    function processImage(currentImage, new_img_id) {
      return new Promise((resolve, reject) => {
        
        const urlParts = currentImage.split("/");
        const fileNameWithQueryString = urlParts[urlParts.length - 1];
        const fileName = fileNameWithQueryString.split("?")[0];
    
        var clear_img_name = remove_file_extension(fileName);
        var img_index = image_id_list.findIndex(function (img) {
          return img.Photo_name === clear_img_name;
        });
    
        if (img_index === -1) {
          var photo_w; var photo_h;
          var temp_img = new Image();
    
          temp_img.onload = function () {
            photo_w = temp_img.width;
            photo_h = temp_img.height;
    
            image_id_list.push({
              "Photo_name": clear_img_name, "Photo_id": new_img_id, "Photo_w": photo_w, "Photo_h": photo_h, "Photo_URI": currentImage, "Status": '', "Type": "BLOB"
            });
    
            var result = { "filename": clear_img_name, "path": "", "img_w": photo_w, "img_h": photo_h, "annotations": [] };
            canvas_region.push(result);
  
            display_image_list();
            show_img(current_img_id);
            resolve();
          };
          temp_img.src = currentImage;
        } else {
          resolve();
        }
      });
    }
  
    function processXML(currentFile) {
      return new Promise((resolve, reject) => {
        fetch(currentFile)
          .then(response => {
            if (!response.ok) {
              throw new Error(`HTTP error! Status: ${response.status}`);
            }
            return response.text();
          })
          .then(data => {
            append_XML_format_data(data);
            resolve();
          })
          .catch(error => {
            reject(error); 
          });
      });
    }
  
    function sync_blob_files(selected_result) {
      var changed_blob = []
      
      /*
      for (var i = 0; i < image_id_list?.length; ++i) {
        if (canvas_region[i]?.annotations && canvas_region[i].annotations.length > 0){
  
          if (image_id_list[i].Status === "CHANGED" && image_id_list[i].Type === "BLOB" ){
  
            var img_uri = canvas_region[i].path+".xml";
            //var img_uri = canvas_region[i].filename+ ".xml";
            var xmlString = jsonToXml(canvas_region[i]);
            changed_blob.push({"blob":img_uri, "xml":xmlString});
          }
        }
      }
      */
      
      selected_result.forEach(function(item) {
        var reader = new FileReader();
        
        if (item.blob_url !== "NULL" || item.custom_url !== "NULL"){
  
          var xmlString = jsonToXml(canvas_region[item.img_id]);
          var imgUrl = image_id_list[item.img_id].Photo_URI;
  
          reader.onload = function(event) {
            var result = event.target.result;
            changed_blob.push({"image_name":item.img_name, "image_type":item.img_type,"image_url":result ,"blob_url":item.blob_url, "custom_url":item.custom_url, "xml":xmlString});
          };
  
          if (imgUrl instanceof File) {
            reader.readAsDataURL(imgUrl);
          } else {
            changed_blob.push({"image_name":item.img_name, "image_type":item.img_type,"image_url":imgUrl ,"blob_url":item.blob_url, "custom_url":item.custom_url, "xml":xmlString});
          }
        }
      });
      
      return changed_blob;
    
    }
    // ANVIL WORK
    /*
    function mul_blob_file_sel(blob_cate){
      //###
      return new Promise((resolve, reject) => {
  
        // ## header_panel
        var blob_top = document.getElementById('sub_blob_model');
        var header_panel = create_element('div', 'header_panel');
  
        // ## dropdown URL
        var mul_drp_url = create_element('select');
        var mul_none = create_button('X', 'remove', () => {
          mul_drp_url.selectedIndex = 0;
  
          var drpUrlItems = document.querySelectorAll('[id^="drp_url"]');
  
          drpUrlItems.forEach(item=> {
            if (!item.disabled) {
              item.selectedIndex = mul_drp_url.selectedIndex;
            }
          });
        });
        mul_none.title = "Reset Blob URL";
        
        var mul_unique_url = [...new Set(blob_cate.map(item => item.blob_url))];
  
        var customOption = create_element('option', null, 'None');
        customOption.value = '';
        mul_drp_url.insertBefore(customOption, mul_drp_url.firstChild);
        
        mul_unique_url.forEach(value => {
          var option = create_element('option', null, value);
          option.value = value;
          mul_drp_url.appendChild(option);
        });
        
        var drp_label = create_element('label', null, "Blob URL : ");
  
        // ## input URL
        var mul_input = create_element('input');
        mul_input.type = "text";
  
        var mul_clear = create_button('X', "remove", () =>{
          mul_input.value = '';
  
          var inputElements = document.querySelectorAll('[id^="inputElement"]');
          inputElements.forEach(item => {
            if (!item.disabled) {
              item.value = mul_input.value;
            }
          });
        });
        mul_clear.title = "Clear Custom URL Input";
        
        var input_label = create_element('label', null, "Custom URL : ");
  
        // ## advanced checkbox
        var advanced = create_checkbox(() => {
          if (advanced.checked){
            adv_modal.style.display = "block";
            var lower_case = drp_blob_type.value.toLowerCase().split("-")[1];
            const today = new Date();
            var formatted_date = display_formatted_date(today);
  
            var drp_blob_client_value = '';
            if (drp_blob_folder.value === "Datasets/Products"){
              drp_blob_client_value = drp_blob_client.value + "/";
            }
            
            mul_input.value = drp_blob_folder.value + "/" + drp_blob_type.value + "/" + drp_blob_client_value + lower_case + "_" + formatted_date;
  
            var inputElements = document.querySelectorAll('[id^="inputElement"]');
  
            inputElements.forEach(item =>{
              if (!item.disabled){
                item.value = mul_input.value;
              }
            });
            
          } else {
            adv_modal.style.display = "none";
          }
        });
  
        var advanced_label = create_element('label', null, " Advanced :");
        advanced_label.style.textDecoration = "underline"; 
  
        // ## lock control panel
        var url_ctrl_panel = create_element('div', 'url_ctrl_panel', null, 'ctrl-panel');
        var url_ctrl_title = create_element('label', null, 'BLOB URL : ');
        
        var url_local_ctrl = create_element('label', null, "LOCAL : ");
        var url_all_local_check =  create_element('input');
        url_all_local_check.type = "checkbox"
  
        var url_blob_ctrl = create_element('label', null, "BLOB : ");
        var url_all_blob_check = create_element('input');
        url_all_blob_check.type = "checkbox";
        
        append_children(url_ctrl_panel, [url_ctrl_title, url_local_ctrl, url_all_local_check, url_blob_ctrl, url_all_blob_check])
  
        var cust_ctrl_panel = create_element('div', 'cust_ctrl_panel', null, 'ctrl-panel');
        var cust_ctrl_title = create_element('label', null, 'CUSTOM URL : ');
        
        var cust_local_ctrl = create_element('label', null, "LOCAL : ");
        var cust_all_local_check = create_element('input');
        cust_all_local_check.type = "checkbox"
  
        var cust_blob_ctrl = create_element('label', null,"BLOB : ");
        var cust_all_blob_check = create_element('input');
        cust_all_blob_check.type = "checkbox";
              
        append_children(cust_ctrl_panel, [cust_ctrl_title, cust_local_ctrl, cust_all_local_check, cust_blob_ctrl, cust_all_blob_check])
  
        var blob_top_content = document.getElementById('mulsel_blob_modal');
        blob_top_content.innerHTML = '';
  
        // ## table button
        var blob_save_btn = create_button("SAVE (0)", "btn", () => {
          var selectedRows = document.querySelectorAll('tbody tr.selected');
          var selected_result = [];
          if (selectedRows.length > 0) {
            // Loop through each selected row
            selectedRows.forEach(function(selectedRow) {
              var sel_img_id = selectedRow.querySelector('td:nth-child(2)').textContent;
              var sel_img_name = selectedRow.querySelector('td:nth-child(3)').textContent;
              var sel_img_type = selectedRow.querySelector('td:nth-child(4)').textContent;
              var sel_blob_url = null;
              var sel_cust_url = null;
  
              var blobUrlSelect = selectedRow.querySelector('td:nth-child(6) select');
  
              if (blobUrlSelect) {
                sel_blob_url = blobUrlSelect.value;
              }
              var sel_cust_td = selectedRow.querySelector('td:nth-child(8)');
  
              if (sel_cust_td) {
                var sel_cust_input = sel_cust_td.querySelector('input');
                if (sel_cust_input) {
                  sel_cust_url = sel_cust_input.value;
                } else {
                  console.log("No input element found inside td:nth-child(8)");
                }
              }
              
              /*
              var sel_blob_url = selectedRow.querySelector('td:nth-child(6) select').value;
              var sel_cust_td = selectedRow.querySelector('td:nth-child(8)');
              var sel_cust_url = sel_cust_td.querySelector('input').value;
              var sel_cust_url = '';
              if (sel_cust_td){
                try{
                  sel_cust_url = sel_cust_td.querySelector('input').value;
                } catch {
                  sel_cust_url = '';
                }
              }
              ///
              
              sel_blob_url = (sel_blob_url === '' || sel_blob_url === null) ? 'NULL' : sel_blob_url;
              sel_cust_url = (sel_cust_url === '' || sel_cust_url === null) ? 'NULL' : sel_cust_url;
        
              //console.log("test Selected Row:", sel_img_id, sel_img_name, sel_img_type, sel_blob_url, sel_cust_url);
              if (sel_img_id !== "test") {
                selected_result.push({"img_id":sel_img_id, "img_name":sel_img_name, "img_type":sel_img_type, "blob_url":sel_blob_url, "custom_url":sel_cust_url})
              }
            });
            blob_top.style.display = "none";
            var result = sync_blob_files(selected_result);
            resolve(result);
          } else {
            // reject("NULL");
            resolve(null);
          }
        });
  
        var blob_cancel_btn = create_button('CANCEL', 'btn', ()=> {
          blob_top.style.display = "none";
          // reject("NULL");
          resolve(null);
        });
  
        // ## table content
        var tableContainer = create_element('div', 'table-container', null, 'table-container');
  
        var table = create_element('table');
        var thread = create_element('thead');
        var tr = create_element('tr');
        var tbody = create_element('tbody');
  
        // ## table content header
        thread.appendChild(tr);
        tr.innerHTML = '<th>Save</th><th>Id</th><th>Image Name</th><th>Image Type</th><th>Lock</th><th>Blob URL</th><th>Lock</th><th>Custom URL</th>';
  
        var read_image_list = image_id_list;
        if (filter_signal === "LABELED" || filter_signal === "UNLABELED" || sub_filter === "FILTER") {
          read_image_list = temp_image_id_list;
        }
        if (read_image_list) {
        
          read_image_list.forEach(function (item, i) {
            if (canvas_region[i]?.annotations && canvas_region[i].annotations.length >= 0){
            //if (item.Status === "CHANGED" || item.Type === "LOCAL") {
              var row = create_element('tr');
      
              var td_check = create_element('td');
              var checkElement = create_checkbox(() => {
  
                var targetRow = event.target.closest('tr');
                if (targetRow) {
    
                  if (checkElement.checked ){
                    targetRow.classList.add('selected');
                  } else {
                    targetRow.classList.remove('selected');
                    
                    //document.querySelectorAll('tbody tr').forEach(row => row.classList.remove('selected'));
                  }
                  updateTotalSelectedRows();
                }
              });
              checkElement.id = "checkElement";
              td_check.appendChild(checkElement);
      
              var td_i = create_element('td', null, `${i}`);
      
              var td_photo_name = create_element('td', null, item.Photo_name);
      
              var td_type = create_element('td', null, item.Type);
      
              var td_url_check = create_element('td');
              var url_check = create_checkbox(() => {
                drp_url.disabled = url_check.checked;
              });
              td_url_check.appendChild(url_check);
      
              var td_url = create_element('td');
              var drp_url = create_element('select', "drp_url");
              var unique_url = [...new Set(blob_cate.map(item => item.blob_url))];
    
              var customOption = create_element('option', null, 'None');
              customOption.value = '';
              drp_url.insertBefore(customOption, unique_url.firstChild);
      
              unique_url.forEach(value => {
                var option = create_element('option', null, value);
                option.value = value;
                drp_url.appendChild(option);
              });
      
              td_url.appendChild(drp_url);
  
              var td_input_check = create_element('td');
              var input_check = create_checkbox(() => {
                inputElement.disabled = input_check.checked;
              });
              td_input_check.appendChild(input_check);
         
              var td_input = create_element('td');
              var inputElement = create_element('input', "inputElement");
              inputElement.type = "text";
              td_input.appendChild(inputElement);
            
              if (item.Type === "BLOB") {
                url_check.checked = true;
                input_check.checked = true;
                checkElement.checked = true;
    
                inputElement.disabled = url_check.checked;
                drp_url.disabled = input_check.checked;
                row.classList.add('selected');
  
                var header = "https://alwaysepst.blob.core.windows.net/ulm-ir/"
                var photo = item.Photo_URI.replace(header, '');
                var targetValue = photo.replace(/img.*$/, '');
  
                var selectedIndex = Array.from(drp_url.options).findIndex(option => option.value === targetValue);
  
                if (selectedIndex !== -1) {
                  drp_url.selectedIndex = selectedIndex;
                  
                } else {
                  console.log(targetValue + " not found in the dropdown.");
                }
                //updateTotalSelectedRows();
              }
    
              url_all_local_check.addEventListener('change', function () {
                if (item.Type === "LOCAL") {
                  drp_url.disabled = url_all_local_check.checked;
                  url_check.checked =url_all_local_check.checked;
                }
              });
    
              url_all_blob_check.addEventListener('change', function () {
                if (item.Type === "BLOB") {
                  drp_url.disabled = url_all_blob_check.checked;
                  url_check.checked = url_all_blob_check.checked;
                }
              });
    
              cust_all_local_check.addEventListener('change', function () {
                if (item.Type === "LOCAL") {
                  inputElement.disabled = cust_all_local_check.checked;
                  input_check.checked = cust_all_local_check.checked;
                }
              });
    
              cust_all_blob_check.addEventListener('change', function () {
                if (item.Type === "BLOB") {
                  inputElement.disabled = url_all_blob_check.checked;
                  input_check.checked = url_all_blob_check.checked;
                }
              });
    
              mul_input.addEventListener('input', function () {
                if (inputElement.disabled === false){
                  inputElement.value = mul_input.value;
                }
              });
    
              mul_drp_url.addEventListener('change', function () {
                if (drp_url.disabled === false) {
                  drp_url.selectedIndex = mul_drp_url.selectedIndex;
                }
              });
  
              append_children(row, [td_check, td_i, td_photo_name, td_type, td_url_check, td_url, td_input_check, td_input])
              tbody.appendChild(row);
            //}
            }
          });
        }
  
        append_children(table, [thread, tbody]);
        tableContainer.appendChild(table);
        
        // ## save configuration panel
        var save_config_panel = create_element('div');
        var save_config = create_element('label', null, "Save Configure : ");
        var all_local_lbl = create_element('label', null, "Local");
        var all_local_chk = create_checkbox(() => {
          var tableRows = document.querySelectorAll('tbody tr');
                                                       
          if (tableRows.length > 0) {
            tableRows.forEach(function(row){
              var img_type = row.querySelector('td:nth-child(4)').textContent;
              var save_chk = row.querySelector('td:first-child input[type="checkbox"]');
              if (save_chk){
                if (all_local_chk.checked && img_type === "LOCAL") {
                  save_chk.checked = true;
                  var changeEvent = new Event('change');
                  save_chk.dispatchEvent(changeEvent);
                } else {
                  save_chk.checked = false;
                  var changeEvent = new Event('change');
                  save_chk.dispatchEvent(changeEvent);
                }
              }
            });
          }
        });
        
        var all_blob_lbl = create_element('label', null, "Blob");
        var all_blob_chk = create_checkbox(() => {
          var tableRows = document.querySelectorAll('tbody tr');
                                                       
          if (tableRows.length > 0) {
            tableRows.forEach(function(row){
              var img_type = row.querySelector('td:nth-child(4)').textContent;
              var save_chk = row.querySelector('td:first-child input[type="checkbox"]');
              if (save_chk){
                if (all_blob_chk.checked && img_type === "BLOB") {
                  save_chk.checked = true;
                  var changeEvent = new Event('change');
                  save_chk.dispatchEvent(changeEvent);
                } else {
                  save_chk.checked = false;
                  var changeEvent = new Event('change');
                  save_chk.dispatchEvent(changeEvent);
                }
              }
            });
          }
        });
  
        append_children(save_config_panel, [save_config, all_local_lbl, all_local_chk, all_blob_lbl, all_blob_chk]);
        
        function updateTotalSelectedRows() {
          
          var countTableContainer = document.getElementById('table-container');
          var totalSelectedRows = countTableContainer.querySelectorAll('tbody tr.selected');
        
          blob_save_btn.textContent = "SAVE (" + `${totalSelectedRows.length}` + ")";
        }
  
        append_children(blob_top_content, [header_panel, tableContainer, save_config_panel, blob_save_btn, blob_cancel_btn])
  
        blob_top.style.display = "block";
  
        tbody.addEventListener('mouseover', function (event) {
          var targetRow = event.target.closest('tr');
          if (targetRow) {
            document.querySelectorAll('tbody tr').forEach(row => row.classList.remove('highlighted'));
            targetRow.classList.add('highlighted');
          }
        });
      
        tbody.addEventListener('mouseout', function () {
          document.querySelectorAll('tbody tr').forEach(row => row.classList.remove('highlighted'));
        });
  
        // ## advanced panel
        var adv_modal = create_element('div')
        adv_modal.style.display = "none";
  
        append_children(header_panel, [drp_label, mul_drp_url, mul_none, input_label, mul_input, mul_clear, advanced_label, advanced, cust_ctrl_panel, url_ctrl_panel, adv_modal])
  
        var lbl_blob_folder = create_element('label', null, "Folder :");
        var drp_blob_folder = create_element('select')
        var unique_blob_folder = [...new Set(blob_cate.map(item => item.blob_folder))];
  
        unique_blob_folder.forEach(value => {
          var option = create_element('option', null, value);
          if ("CTA" === value ||  "POSM" === value) {
            option.value = "Datasets/"+value;
          }
          if ("PRICE STICKER" === value) {
            option.value = "Datasets/PriceSticker";
          }
          if ("PRODUCT" === value) {
            option.value = "Datasets/Products";
          }
          drp_blob_folder.appendChild(option);
        });
  
        var lbl_blob_type = create_element('label', null, "Sub-Folder :");
        var drp_blob_type = create_element('select')
        var unique_blob_type = [...new Set(blob_cate.map(item => item.blob_type).filter(type => !type.includes('COM')))];
  
        unique_blob_type.forEach(value => {
          var option = create_element('option', null, value);
  
          option.value = "ULM-"+value;
          drp_blob_type.appendChild(option);
        });
  
        var lbl_blob_client = create_element('label', null, "Sub2-Folder :");
        var drp_blob_client = create_element('select')
        var unique_blob_client = [...new Set(blob_cate.map(item => item.blob_client))];
  
        unique_blob_client.forEach(value => {
          var option = create_element('option', null, value);
          if ("ULM" === value ){
            option.value = "ulm";
          }
          if ("COMPETITOR" === value) {
            option.value = "ulm+com"
          }
          drp_blob_client.appendChild(option);
        });
  
        var lbl_blob_filename = create_element('label', null,  "File :");
        var date_blob = create_element('input', "selected_date");
        date_blob.type = 'date';
  
        append_children(adv_modal, [lbl_blob_folder, drp_blob_folder, lbl_blob_type, drp_blob_type, lbl_blob_client, drp_blob_client, lbl_blob_filename, date_blob])
          
        function changes() {
          adv_modal.style.display = "block";
          var lower_case = drp_blob_type.value.toLowerCase().split("-")[1];
          var formatted_date = display_formatted_date(date_blob.value);
  
          var drp_blob_client_value = '';
          if (drp_blob_folder.value === "Datasets/Products"){
            drp_blob_client_value = drp_blob_client.value + "/";
          }
        
          mul_input.value = drp_blob_folder.value + "/" + drp_blob_type.value + "/" + drp_blob_client_value + lower_case + "_" + formatted_date;
  
          var inputElements = document.querySelectorAll('[id^="inputElement"]');
          inputElements.forEach(item =>{
            if (!item.disabled){
              item.value = mul_input.value;
            }
          });
        }
  
        drp_blob_folder.addEventListener('change', changes);
        drp_blob_type.addEventListener('change', changes);
        drp_blob_client.addEventListener('change', changes);
        date_blob.addEventListener('change', changes);
        updateTotalSelectedRows();
      });
    }
    */

    function update_image_list() {
      if (filter_signal === '') return ;
  
      if (filter_signal === "LABELED") {
        temp_image_id_list = image_id_list.filter(item => canvas_region.some(region =>
          region.annotations.some(annotation => annotation.filename === item.Photo_name)));
  
      } else if (filter_signal === "UNLABELED") {
        temp_image_id_list = image_id_list.filter(item =>!canvas_region.some(region =>
          region.annotations.some(annotation =>annotation.filename === item.Photo_name )));
      } 
      
      display_image_list();
      show_img(0);
      redraw_reg_canvas();
      
    }
  
    function display_formatted_date(selected_date) {
      let formatted_date = '';
  
      if (selected_date) {
        const dateObject = new Date(selected_date);
        const day = String(dateObject.getDate()).padStart(2, '0');
        const month = String(dateObject.getMonth() + 1).padStart(2, '0');
        const year = String(dateObject.getFullYear()).slice(-2);
        formatted_date = `${day}${month}${year}`;
  
        var selected_date = document.getElementById('selected_date');
        selected_date.valueAsDate = new Date(`${dateObject.getFullYear()}-${month}-${day}`);
      }
      
      return formatted_date;
    }
  
    function generateRandomHexColor() {
      const characters = 'ABCDEF0123456789';
      let hexadecimal = '#';
    
      for (let i = 0; i < 6; i++) {
        hexadecimal += characters[Math.floor(Math.random() * characters.length)];
      }
  
      if (["#FF0000", "#000000"].includes(hexadecimal)){
        // SAME COLOR RE-GEN
        return generateRandomHexColor();
      }
    
      return hexadecimal;
    }
  
    function canvas_width_height(img_w, img_h){
  
      if (img_h > img_w){
        canvas_width = 550;
        canvas_height = 750;
      } 
      if (img_h < img_w){
        canvas_width = 750;
        canvas_height = 550;
      }
      if (img_h === img_w){
        canvas_width = 750;
        canvas_height = 750;
      }
    }
  
    function create_button(text, className, onClick) {
      var btn = document.createElement('button');
      btn.textContent = text;
      btn.className = className;
      btn.addEventListener("click", onClick);
      return btn;
    }
  
    function create_checkbox(onChange) {
      var chk = document.createElement('input');
      chk.type = "checkbox";
      chk.addEventListener('change', onChange);
      return chk;
    }
  
    function append_children(parent, children) {
      children.forEach(child => {
        parent.appendChild(child);
      });
    }
  
    function create_element(tagName, id = null, text = null, className = null){
      var element = document.createElement(tagName);
  
      if (id) {
        element.id = id;
      }
      if (className) {
        element.className = className;
      }
      if (text) {
        element.textContent = text;
      }
      return element;
    }
  
  </script>
  
</body>



