const CheckBoxCtl = ({
  label,
  checked,
  onChange,
  disabled = false,
  id, name,
  style,
  tabIndex='-1',
  type='checkbox' // checkbox | switch
}) => {
  const { Form } =ReactBootstrap
  return (
      <Form.Group controlId={id} style={style} >
          <Form.Check
              type={type}
              label={label}
              checked={checked}
              onChange={onChange}
              disabled={disabled}
              custom={type === 'switch'}
              name = {name}
              tabindex={tabIndex}
          />
      </Form.Group>
  );
};

const TextInputCtl = ({
    label,
    placeholder,
    value,
    onChange,
    onEnter,
    onBlur,
    autoFocus = false,
    type = 'text',
    required = false,    
    disabled = false,
    size = 'sm',
    feedback,
    style,
    styleInput,
    id, name, styleLabel={fontSize:11}, min, max, inValidInput, inputRef=null, onFocus= null, tabIndex="-1",
    // Thêm option mới
    allowClear = false,
    error
  }) => {
    const { Form } = ReactBootstrap

    const handleKeyDown = (e) => {
      if (e.key === 'Enter' && onEnter) {
        onEnter();
      }
    };
  
    const handleBlur = () => {
      if (onBlur) {
        onBlur();
      }
    };

    // Hàm xử lý xóa text
    const handleClear = () => {
      if (onChange) {
        // Giả lập một sự kiện target để phù hợp với logic onChange hiện tại của bạn
        onChange({ target: { name: name, value: '', id: id } });
      }
    };
      
    let message = feedback
    const invalidObj = inValidInput?.find((n) => n.id === id)
    let isInvalid = invalidObj?.isInvalid || false
    if (error) {
      isInvalid = true;
      message = error;
    } else if (invalidObj){
      message = invalidObj?.msg
    }
    
    return (
      <Form.Group controlId={id} style={{ ...style, position: 'relative' }}>
        {label && <Form.Label style={{...styleLabel, marginBottom:'0px'}} htmlFor={id}>{label}</Form.Label>}
        
        <div style={{ position: 'relative', display: 'flex', alignItems: 'center' }}>
            <Form.Control
              type={type}
              placeholder={placeholder}
              value={value || ''}
              onChange={onChange}          
              onKeyDown={handleKeyDown}
              onBlur={handleBlur}
              autoFocus={autoFocus}
              onFocus={onFocus}
              required={required}
              isInvalid={isInvalid}
              disabled={disabled}
              size={size}
              ref={inputRef}
              id={id}
              name={name}
              tabindex={tabIndex}
              style={{ 
                ...styleInput, 
                paddingRight: allowClear && (value !== '' && value !== null && value !== undefined) ? '28px' : styleInput?.paddingRight 
              }}
              min={type === 'number' ? min : undefined}
              max={type === 'number' ? max : undefined}
            />

            {/* Icon Clear Text */}
            {allowClear && (value !== '' && value !== null && value !== undefined) && !disabled && (
              <span
                onClick={handleClear}
                title="Xóa / Clear"
                style={{
                  position: 'absolute',
                  right: isInvalid ? '35px' : '10px', // Né icon cảnh báo của Bootstrap nếu bị Invalid
                  top: '50%',
                  transform: 'translateY(-50%)',
                  cursor: 'pointer',
                  color: '#aaa',
                  zIndex: 5,
                  fontSize: '14px',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center'
                }}
                onMouseOver={(e) => (e.currentTarget.style.color = '#dc3545')}
                onMouseOut={(e) => (e.currentTarget.style.color = '#aaa')}
              >
                <i className="fa fa-times-circle"></i>
              </span>
            )}
            
            {isInvalid && message && (
              <div className="custom-error-tooltip-wrapper">
                <span className="custom-error-icon">!</span>
                <div className="custom-error-tooltip-text">{message}</div>
              </div>
            )}
        </div>

        {message && <Form.Control.Feedback type="invalid" style={{ display: isInvalid ? 'block' : 'none' }}>
            {message}
        </Form.Control.Feedback>}
      </Form.Group>
    );
  };
  
 const DropdownCtl = ({
    label,
    options = [],
    value, 
    onChange,
    onBlur,
    autoFocus = false,
    required = false,
    disabled = false,
    size = 'sm',
    feedback,
    style,
    valueFieldName = 'id',
    labelFieldName = 'name',
    labelRenderer,
    optionDefault = 'All',
    name,
    id,
    inValidInput,
    styleLabel = { fontSize: 11, marginBottom: '0px' },
    allowNull = true,
    isSort = true,
    multiple = false,
    closeOnSelect = true,
    error
}) => {
    const { Form, Dropdown, Badge } = ReactBootstrap;
    const [searchTerm, setSearchTerm] = React.useState("");

    const getOptionLabel = (opt) => {
        if (!opt) return "";
        if (typeof labelRenderer === 'function') {
            return labelRenderer(opt);
        }
        return opt[labelFieldName] !== undefined && opt[labelFieldName] !== null ? String(opt[labelFieldName]) : "";
    };

    // 1. Filter & Sort Options
    const processedOptions = React.useMemo(() => {
        let list = Array.isArray(options) ? [...options] : [];
        if (isSort) {
            list.sort((a, b) => String(getOptionLabel(a)).localeCompare(String(getOptionLabel(b))));
        }
        if (!searchTerm) return list;
        const searchLower = searchTerm.toLowerCase();
        return list.filter(opt => 
            String(getOptionLabel(opt)).toLowerCase().includes(searchLower) ||
            String(opt[valueFieldName]).toLowerCase().includes(searchLower)
        );
    }, [options, searchTerm, isSort, labelFieldName, valueFieldName, labelRenderer]);

    // 2. Selected Label Logic
    const selectedLabel = React.useMemo(() => {
        if (multiple) {
            if (!Array.isArray(value) || value.length === 0) return optionDefault;
            if (value.length === options.length && options.length > 0) return "Tất cả (" + options.length + ")";
            if (value.length > 1) {
                const firstItem = options.find(opt => String(opt[valueFieldName]) === String(value[0]));
                const firstLabel = firstItem ? getOptionLabel(firstItem) : "";
                return `${firstLabel} (+${value.length - 1})`;
            }
            const selectedItem = options.find(opt => String(opt[valueFieldName]) === String(value[0]));
            return selectedItem ? getOptionLabel(selectedItem) : optionDefault;
        }
        if (value === "None" || value === null || value === undefined || value === "") return optionDefault;
        const found = options.find(opt => String(opt[valueFieldName]) === String(value));
        return found ? getOptionLabel(found) : optionDefault;
    }, [value, options, multiple, valueFieldName, labelFieldName, optionDefault, labelRenderer]);

    // 3. Handlers
    const handleItemClick = (val) => {
        let newValue;
        if (multiple) {
            const currentArray = Array.isArray(value) ? value : [];
            const isExist = currentArray.some(v => String(v) === String(val));
            newValue = isExist 
                ? currentArray.filter(v => String(v) !== String(val))
                : [...currentArray, val];
        } else {
            newValue = val;
            setSearchTerm("");
        }
        onChange({ target: { name, id, value: newValue } });
    };

    const handleSelectAll = (e) => {
        e.stopPropagation();
        const isAllSelected = Array.isArray(value) && value.length === options.length;
        const newValue = isAllSelected ? [] : options.map(opt => opt[valueFieldName]);
        onChange({ target: { name, id, value: newValue } });
    };

    const handleClear = (e) => {
        e.stopPropagation();
        const resetValue = multiple ? [] : "";
        onChange({ target: { name, id, value: resetValue } });
        setSearchTerm("");
    };

    const isChecked = (val) => {
        if (multiple) return Array.isArray(value) && value.some(v => String(v) === String(val));
        return String(value) === String(val);
    };

    const hasValue = multiple 
        ? (Array.isArray(value) && value.length > 0)
        : (value !== null && value !== undefined && value !== "" && value !== "None");

    const invalidObj = inValidInput?.find((n) => String(n.id) === String(id));
    let isInvalid = invalidObj?.isInvalid || false;
    let message = value == null ? feedback : '';
    if (error) {
        isInvalid = true;
        message = error;
    } else if (isInvalid) {
        message = invalidObj?.msg;
    }

    return (
        <Form.Group className="dropdown-ctl-wrapper" style={style}>
            <style>{`
                /* Ẩn mũi tên mặc định của Bootstrap */
                .custom-dropdown-toggle::after { display: none !important; }
                .clear-icon:hover { color: #dc3545 !important; opacity: 1 !important; }
                .dropdown-item.active, .dropdown-item:active {
                    color: #ffffff !important;
                    text-decoration: none;
                    background-color: #7c3aed !important;
                }
                .dropdown-item.active span, .dropdown-item:active span {
                    color: #ffffff !important;
                }
            
            `}</style>
            
            {label && <Form.Label style={styleLabel} >{label}</Form.Label>}
            
            <div style={{ position: 'relative' }}>
                <Dropdown className="w-100" autoClose={multiple ? "outside" : true}>
                    <Dropdown.Toggle 
                        variant="outline-secondary" 
                        id={id}
                        size={size}
                        disabled={disabled}
                        className={`w-100 d-flex align-items-center bg-white text-dark shadow-sm custom-dropdown-toggle ${required && !hasValue ? 'border-danger' : (isInvalid ? 'border-danger' : '')}`}
                    >
                        {/* Phần chữ hiển thị bên trái */}
                        <div className="text-truncate me-auto text-start" title={selectedLabel}>
                            {selectedLabel}
                            {multiple && Array.isArray(value) && value.length > 1 && (
                                <Badge bg="primary" pill className="ms-2" style={{ fontSize: '10px' }}>
                                    {value.length}
                                </Badge>
                            )}
                        </div>
                        
                        {/* Cụm icon bên phải - Phân tách xa nhau */}
                        <div className="d-flex align-items-center ms-2">
                            {hasValue && !disabled && (
                                <i 
                                    className="fa fa-times-circle me-3 text-muted clear-icon" 
                                    style={{ cursor: 'pointer', opacity: 0.6, fontSize: '14px' }}
                                    onClick={handleClear}
                                    title="Xóa chọn"
                                />
                            )}
                            <i 
                                className="fa fa-chevron-down text-muted" 
                                style={{ fontSize: '10px', opacity: 0.5 }}
                            />
                        </div>
                    </Dropdown.Toggle>

                    <Dropdown.Menu className="w-100 shadow border-0" style={{ maxHeight: '350px', overflowY: 'auto' }}>
                        <div className="p-2 sticky-top bg-white border-bottom">
                            <Form.Control
                                size="sm"
                                type="text"
                                placeholder="Tìm kiếm..."
                                value={searchTerm}
                                autoComplete="off"
                                onChange={(e) => setSearchTerm(e.target.value)}
                                onClick={(e) => e.stopPropagation()}
                            />
                            {multiple && options.length > 0 && !searchTerm && (
                                <div 
                                    className="d-flex align-items-center py-2 px-2 mt-1 border-bottom" 
                                    style={{ cursor: 'pointer', fontSize: '13px', fontWeight: 'bold', color: '#007bff' }}
                                    onClick={handleSelectAll}
                                >
                                    <Form.Check 
                                        type="checkbox"
                                        label="Chọn tất cả"
                                        checked={Array.isArray(value) && value.length === options.length}
                                        onChange={() => {}} 
                                        style={{ pointerEvents: 'none' }} 
                                    />
                                </div>
                            )}
                        </div>

                        <div className="py-1">
                            {processedOptions.length > 0 ? processedOptions.map((option, index) => {
                                const optValue = option[valueFieldName];
                                const isSel = isChecked(optValue);
                                return (
                                    <Dropdown.Item 
                                        key={index}
                                        as="div"
                                        className={`d-flex align-items-center py-2 px-3 ${!multiple && isSel ? 'active' : ''}`}
                                        style={{ cursor: 'pointer', fontSize: '13px' }}
                                        onClick={() => handleItemClick(optValue)}
                                    >
                                        {multiple && (
                                            <Form.Check 
                                                type="checkbox"
                                                checked={isSel}
                                                onChange={() => {}} 
                                                className="me-2"
                                                style={{ pointerEvents: 'none' }} 
                                            />
                                        )}
                                        <span className="text-truncate" style={{ color: option?.color }}>
                                            {getOptionLabel(option)}
                                        </span>
                                    </Dropdown.Item>
                                );
                            }) : <div className="text-center p-3 text-muted small">Không có dữ liệu</div>}
                        </div>
                    </Dropdown.Menu>
                </Dropdown>
                
                {isInvalid && message && (
                    <div className="custom-error-tooltip-wrapper">
                        <span className="custom-error-icon">!</span>
                        <div className="custom-error-tooltip-text">{message}</div>
                    </div>
                )}
            </div>
             {message && (
                <Form.Control.Feedback type="invalid" style={{ display: isInvalid ? 'block' : 'none' }}>{message}</Form.Control.Feedback>
            )}
        </Form.Group>
    );
};

  const DateTimeCtl = ({ id,value, setValue, disabled=false, showTimePicker = true, 
    labelDate='Choose Date', labelTime='Choose Time', size='sm', feedback=null, name, inValidInput,styleLabel={fontSize:11, marginBottom:'0px'} }) => {
    const {Form,Row, Col} = ReactBootstrap
    
    const dateValue = value ? value.split(' ')[0] : '';
    const timeValue = value ? value.split(' ')[1] : '';

    const handleDateChange = (e) => {
        const newDate = e.target.value;
        const newValue = showTimePicker ? `${newDate} ${timeValue}` : newDate;
        setValue(newValue);
    };

    const handleTimeChange = (e) => {
        const newTime = e.target.value;
        const newValue = `${dateValue} ${newTime}`;
        setValue(newValue);
    };  
    let message = feedback
    const invalidObj = inValidInput?.find((n) => n.id === id)
    const isInvalid = invalidObj?.isInvalid || false
    if (invalidObj){
      message = invalidObj?.msg
    }

    return (    
        <Row>
          <Col>          
            <Form.Group controlId={id}>
                {
                  labelDate &&
                  <Form.Label style={styleLabel}>{labelDate}</Form.Label>
                }                
                <Form.Control
                    type="date"
                    value={dateValue}
                    onChange={handleDateChange}
                    name = {name}
                    size={size}
                    disabled={disabled}
                    id={id}
                    isInvalid={isInvalid}
                />
            
            </Form.Group>
            {message  && <Form.Control.Feedback type="invalid">{message}</Form.Control.Feedback>}   
          </Col>
      
          {showTimePicker && (
                <Col>
                <Form.Group controlId="timePicker">
                    <Form.Label style={styleLabel}>{labelTime}</Form.Label>
                    <Form.Control
                        size={size}
                        type="time"
                        value={timeValue}
                        onChange={handleTimeChange}
                        disabled={disabled}
                    />
                 
                </Form.Group>                
                </Col>
            )}          
          
        </Row>
    );
};


const LabelInput=(props)=>{
  const {label, htmlFor, style={fontSize:'12px', padding:'0px'}} = props
  const {Form} = ReactBootstrap
  return(
    <Form.Label style={style}  column   htmlFor={htmlFor}>{label}</Form.Label> 
  )
}
const DropdownSuggest = (props) => {
  const {id,data, setData, searchText, setSearchText, caption,  itemSelected, setItemSelected, handleCustom,onEnter,inValidInput ,height, width='100%', lineId,styleLabel, feedback} = props

  const { Dropdown, FormControl,InputGroup, Button, Form } = ReactBootstrap;

  const dropdownStyle = {
      width: width || 'auto', // Mặc định là auto nếu không có width
      border:'1px solid #ced4da',
      borderRadius:4
  };
  const toggleStyle = {
    height: '30px', // Chiều cao của Dropdown.Toggle
    width: width, // Chiều rộng của Dropdown.Toggle
    textAlign:'left',
    lineHeight:'10px',
    overflow:'hidden',
    fontSize:'14px',
    color:'gray'
  };
  const itemStyle = {
      whiteSpace: 'nowrap', // Ngăn không cho nội dung vượt quá một dòng
      overflow: 'hidden', // Ẩn nội dung thừa
      textOverflow: 'ellipsis', // Hiển thị dấu ba chấm nếu nội dung bị cắt
      maxWidth: '100%', // Đảm bảo nội dung không vượt quá chiều rộng của item
  };

  let message = feedback
    const invalidObj = inValidInput?.find((n) => n.id === id)
    const isInvalid = invalidObj?.isInvalid || false
    if (invalidObj){
      message = invalidObj?.msg
    }

  return (
    <>
    <Form.Group controlId="formBasicSelect" >
      <Form.Label style={styleLabel}>{caption} </Form.Label>
      
      <Dropdown style={dropdownStyle} isInvalid={isInvalid}>
          <Dropdown.Toggle variant="" id="dropdown-basic" style={toggleStyle}>
              {itemSelected ? itemSelected?.name : caption}
          </Dropdown.Toggle>
          <Dropdown.Menu style={{ maxHeight: height || '200px', overflowY: 'auto', width:'100%' }}>
              <InputGroup>
                  <FormControl
                      placeholder="Search customers..."
                      value={searchText}
                      onChange={(e) => setSearchText(e.target.value)}
                      onKeyUp={(e)=> onEnter(e)}
                      autoFocus={true}
                      id={id}
                      
                  />
              </InputGroup>
              
              {data == null || data?.length === 0 ? (
                  <Dropdown.Item disabled>Loading...</Dropdown.Item>
              ) : (
                  data?.map((row) => (
                      <Dropdown.Item 
                          key={row.id}  
                          onClick={() => {
                            if(setItemSelected){
                              setItemSelected(row);  // Cập nhật khách hàng đã chọn
                            }
                            if(handleCustom){
                              handleCustom(row, lineId)
                            }
                              
                              setSearchText('');      // Xóa ô tìm kiếm
                            
                              
                          }}
                          style={itemStyle} // Áp dụng kiểu cho từng item
                      >
                          {row.name}
                      </Dropdown.Item>
                  ))
              )}
              <Dropdown.Item 
                        as={Button} 
                        variant="link" 
                        onClick={() => {
                            setItemSelected(null); // Đặt itemSelected về null
                            setSearchText(''); 
                            setData([])     // Xóa ô tìm kiếm
                        }}
                        style={{ textAlign: 'left' }} // Đặt kiểu cho nút Clear
                    >
                        <i class="fa fa-times" aria-hidden="true" style={{color:'red'}}> <span style={{fontSize:12, paddingLeft:'5px'}}>Clear</span> </i>
                    </Dropdown.Item>
          </Dropdown.Menu>
      </Dropdown>
      {message  && <Form.Control.Feedback type="invalid">{message}</Form.Control.Feedback>}
      </Form.Group>
    </>
  );
};

const TextAreaCtl =(props)=>{    
    var Form = ReactBootstrap.Form
    const InputGroup = ReactBootstrap.InputGroup
    const {id,value, setValue, onChangeMaster, placeholder, width='100%', disabled = false, rows=3, label,styleLabel={fontSize:11}} = props
    const onChange =(e)=>{
      setValue(e.target.value)
    }
    
    return(
      <>
        <Form.Label style={styleLabel} htmlFor={id}>{label}</Form.Label>
        <InputGroup className="mb-3">
           
            <Form.Control as="textarea" rows={rows} 
              placeholder={placeholder}
              value={value} 
              aria-describedby={id}
              width = {width}
              disabled = {disabled}
              onChange = {onChangeMaster == null ? onChange : onChangeMaster}
              id={id}
            />
          </InputGroup>
        </>
    )
  }

const RichTextBox = (props) => {
  
    const {id, title,  text, setText, readOnly=false, disabled=false, handleOnchange,autoFocus=false, inValidInput } = props;
    const editorRef = useRef();
    
    const {CKEditor} = window.CKEditor
    const ClassicEditor = window.ClassicEditor

    const invalidObj = inValidInput?.find((n) => n.id === id)
    const isInvalid = invalidObj?.isInvalid || false
    const message = invalidObj?.msg
    useEffect(() => {
      console.log('5345DFGDFGDFGDFGD')
      if (editorRef.current && editorRef.current.editorInstance === null) {
        ClassicEditor.create(editorRef.current)
          .then(editor => {
            editorRef.current.editorInstance = editor;
            editor.setData(text);
         
          })
          .catch(error => {
            console.error('Error initializing editor', error);
          });
      }
    }, []);
  
    const handleEditorReady = (editor) => {
      console.log('Editor is ready to use!', editor);
    };
  
    const handleEditorChange = (event, editor) => {
      const newData = editor.getData();
      handleOnchange(newData)
      setText(newData)
    };
  
    return (
      <div id={`div_${id}`} className="rich-textbox-container" style={{ backgroundColor: (isInvalid ==false ?  'rgba(241, 170, 240, 0.24)':'red') }}>
        <div style={{border:'1px solid #80808066', paddingLeft:'5px', paddingRight:'5px'}}>
          <h6 >{title}</h6>
        </div> 
        <CKEditor
          autoFocus = {autoFocus}
          id = {id}
          editor={ClassicEditor}
          onReady={handleEditorReady}
          onChange={handleEditorChange}
          
          isInvalid = {isInvalid}
          config={{
            toolbar: ['heading', '|', 'bold', 'italic', 'link', 'bulletedList', 'numberedList', 'blockQuote'],
            language: 'en',
            readOnly: {readOnly},
            toolbarStartupExpanded: true,
            toolbarGroups: [
              { name: 'styles', groups: ['styles'] },
              { name: 'basicstyles', groups: ['basicstyles', 'cleanup'] },
              { name: 'links', groups: ['links'] },
              { name: 'paragraph', groups: ['list', 'indent', 'blocks', 'align', 'bidi', 'paragraph'] },
              { name: 'clipboard', groups: ['clipboard', 'undo'] },
              { name: 'editing', groups: ['find', 'selection', 'spellchecker', 'editing'] },
              { name: 'document', groups: ['mode', 'document', 'doctools'] },
              { name: 'others', groups: ['others'] },
              { name: 'about', groups: ['about'] }
            ],
            skin: 'moono-lisa',
            toolbarCanCollapse: true,
            toolbarLocation: 'top',
            toolbar_Basic: [
              ['Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript', '-', 'RemoveFormat']
            ],
            toolbar_Full: [
              ['Styles', 'Format', 'Font', 'FontSize'],
              ['Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript', '-', 'RemoveFormat'],
              ['TextColor', 'BGColor'],
              ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', 'Blockquote'],
              ['JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock'],
              ['Link', 'Unlink'],
              ['Image', 'Table', 'HorizontalRule', 'SpecialChar', 'PageBreak'],
              ['Source']
            ],
            ckfinder: {
              uploadUrl: '/upload'
            }
          }}
          data={text}
          ref={editorRef}
          contenteditable={false}
          disabled={disabled}
        />
         {
            isInvalid==true &&
              <span style={{color:'white'}}>{message}</span>
         }
      </div>
    );
  }

  const HtmlContentEditor = (props) => {
    const { id, title, text, setText, isInvalid, message, disabled = false } = props;
    const editorRef = React.useRef(null);
    const [isFocused, setIsFocused] = React.useState(false);

    React.useEffect(() => {
        if (editorRef.current && editorRef.current.innerHTML !== text) {
            editorRef.current.innerHTML = text || "";
        }
    }, [text]);

    const execCommand = (command, value = null) => {
        if (disabled) return;
        document.execCommand(command, false, value);
        editorRef.current.focus();
    };

    const handleInput = () => {
        if (editorRef.current) {
            setText(editorRef.current.innerHTML);
        }
    };

    const handlePaste = (e) => {
        e.preventDefault();
        const text = e.clipboardData.getData('text/plain');
        document.execCommand('insertText', false, text);
    };

    const ToolbarBtn = ({ cmd, icon, title }) => (
        <button type="button" className="btn-toolbar-action" onClick={() => execCommand(cmd)} disabled={disabled} title={title}>
            <i className={`fa ${icon}`}></i>
        </button>
    );

    return (
        <div className="html-editor-container mb-3">
            {title && <label className="editor-label">{title}</label>}
            
            <div className={`editor-box ${isFocused ? 'focused' : ''} ${isInvalid ? 'invalid' : ''}`}>
                
                {/* Toolbar chỉ hiện các nút cơ bản để tiết kiệm diện tích */}
                <div className="editor-toolbar-wrapper py-1 px-2 d-flex align-items-center justify-content-between">
                    <div className="d-flex gap-1">
                        <ToolbarBtn cmd="bold" icon="fa-bold" title="In đậm" />
                        <ToolbarBtn cmd="italic" icon="fa-italic" title="In nghiêng" />
                        <div className="toolbar-separator"></div>
                        <ToolbarBtn cmd="insertUnorderedList" icon="fa-list-ul" title="Danh sách" />
                    </div>
                    {/* Hiển thị số ký tự hoặc trạng thái nhỏ bên góc phải nếu cần */}
                    <div style={{fontSize: '10px', color: '#ccc'}}>HTML Editor</div>
                </div>

                <div
                    ref={editorRef}
                    contentEditable={!disabled}
                    onInput={handleInput}
                    onPaste={handlePaste}
                    onFocus={() => setIsFocused(true)}
                    onBlur={() => setIsFocused(false)}
                    className="editor-editable-area"
                    style={{
                        // ĐÂY LÀ PHẦN THAY ĐỔI CHÍNH
                        minHeight: '38px', // Tương đương 1 hàng input thông thường
                        height: 'auto',    // Tự động nở theo nội dung
                        maxHeight: '600px', // Giới hạn chiều cao tối đa để không làm vỡ layout
                        padding: '8px 12px'
                    }}
                />
            </div>
            {isInvalid && <small className="editor-error-message">{message}</small>}
            
            <style>{`
                .editor-box {
                    border: 1px solid #dee2e6;
                    border-radius: 4px;
                    transition: all 0.2s;
                    background: #fff;
                }
                .editor-box.focused {
                    border-color: #28a745;
                    box-shadow: 0 0 0 0.2rem rgba(40, 167, 69, 0.1);
                }
                .editor-toolbar-wrapper {
                    background-color: #fdfdfd;
                    border-bottom: 1px solid #eee;
                }
                .btn-toolbar-action {
                    width: 28px;
                    height: 28px;
                    border: none;
                    background: transparent;
                    border-radius: 3px;
                    color: #666;
                    cursor: pointer;
                }
                .btn-toolbar-action:hover {
                    background: #f0f0f0;
                    color: #000;
                }
                .toolbar-separator {
                    width: 1px;
                    height: 15px;
                    background: #eee;
                    margin: 0 5px;
                }
                .editor-editable-area {
                    outline: none;
                    font-size: 14px;
                    line-height: 1.5;
                    word-break: break-word;
                }
                .editor-editable-area:empty:before {
                    content: attr(placeholder) "Bấm để nhập nội dung...";
                    color: #adb5bd;
                }
                /* Tùy chỉnh thanh cuộn khi nội dung quá dài */
                .editor-editable-area::-webkit-scrollbar {
                    width: 4px;
                }
                .editor-editable-area::-webkit-scrollbar-thumb {
                    background: #ccc;
                    border-radius: 10px;
                }
            `}</style>
        </div>
    );
};

const TagInputCtl = ({ label, value = [], onChange, disabled }) => {
    // Đảm bảo value luôn là mảng để tránh lỗi .map
    const tags = Array.isArray(value) ? value : [];

    const handleKeyDown = (e) => {
        if (e.key === 'Enter') {
            // Chặn tuyệt đối việc trigger submit form hoặc các sự kiện cha
            e.preventDefault();
            e.stopPropagation();

            const inputValue = e.target.value.trim();
            
            // Kiểm tra: Không rỗng và không trùng lặp
            if (inputValue && !tags.includes(inputValue)) {
                const newTags = [...tags, inputValue];
                onChange(newTags);
                e.target.value = ''; // Reset input
            }
        }
    };

    const removeTag = (idxToRemove, e) => {
        e.preventDefault();
        e.stopPropagation();
        const newTags = tags.filter((_, i) => i !== idxToRemove);
        onChange(newTags);
    };

    return (
        <div className="mb-3">
            {label && <label className="editor-label">{label}</label>}
            <div 
                className={`form-control form-control-sm d-flex flex-wrap align-items-center gap-2 ${disabled ? 'bg-light' : ''}`}
                style={{ minHeight: '38px', cursor: 'text' }}
                onClick={() => !disabled && document.getElementById(`input-${label}`)?.focus()}
            >
                {tags.map((tag, idx) => (
                    <span 
                        key={`${tag}-${idx}`} // Key kết hợp để tránh trùng lặp DOM
                        className="badge d-flex align-items-center gap-1"
                        style={{ backgroundColor: '#e9ecef', color: '#495057', border: '1px solid #ced4da', padding: '4px 8px', borderRadius: '4px' }}
                    >
                        {tag}
                        {!disabled && (
                            <i 
                                className="fa fa-times text-muted cursor-pointer" 
                                style={{ fontSize: '10px' }}
                                onClick={(e) => removeTag(idx, e)}
                            ></i>
                        )}
                    </span>
                ))}
                
                {!disabled && (
                    <input 
                        id={`input-${label}`}
                        className="border-0 outline-none flex-grow-1" 
                        style={{ fontSize: '13px', minWidth: '80px', background: 'transparent' }}
                        placeholder={tags.length === 0 ? "Nhập giá trị..." : ""}
                        onKeyDown={handleKeyDown}
                        onBlur={(e) => {
                            // Tùy chọn: Tự động thêm tag khi mất focus (blur)
                            if (e.target.value.trim()) handleKeyDown({ ...e, key: 'Enter', preventDefault: () => {}, stopPropagation: () => {} });
                        }}
                    />
                )}
            </div>
        </div>
    );
};

const DynamicMetaCtl = ({ 
    title = "Thông tin mở rộng",
    meta = {}, 
    setMeta, 
    inValidInput = [],
    // Config default
    config = {
        field_name_tag: { type: "TagInputCtl", visible: true, disable:false, caption: "Field name tag" },    
        field_name_text: { type: "TextInputCtl", visible: true, disable:false, caption: "Field name text" },        
        field_name_html: { type: "HtmlContentEditor", visible: true, disable:false, disable:false, caption: "Field name html" },        
        field_name_number: { type: "Number", visible: true, disable:false, disable:false, caption: "Field name number" },        
        field_name_check: { type: "Check", visible: true, disable:false, disable:false, caption: "Field name check" },       
    }
}) => {
    const { Row, Col, Accordion, Form } = ReactBootstrap;
    const [isOpen, setIsOpen] = React.useState(false);

    const handleMetaChange = (key, value) => {
        // Chặn cập nhật nếu config định nghĩa field này là disable
        if (config[key]?.disable) return;
        setMeta(prev => ({ ...prev, [key]: value }));
    };

    const renderControl = (key, value) => {
        const fieldConfig = config[key];
        
        // Chỉ render nếu visible: true
        if (!fieldConfig || fieldConfig.visible === false) return null;

        // Ưu tiên hiển thị đúng CAPTION từ config
        const label = fieldConfig.caption; 
        const isFieldDisabled = fieldConfig.disable; // Trạng thái khóa field
        const invalidObj = inValidInput?.find(n => n.id === key);

        // Render dựa theo type
        switch (fieldConfig.type) {
            case 'TagInputCtl':
                return (
                    <Col key={key} xs={12} md={6} >
                        <TagInputCtl 
                            label={label} 
                            value={value} 
                            onChange={(val) => handleMetaChange(key, val)}
                            disabled={isFieldDisabled} // Không thể chỉnh sửa
                        />
                    </Col>
                );

            case 'HtmlContentEditor':
                return (
                    <Col key={key} xs={12} md={6}>
                        <HtmlContentEditor
                            id={key}
                            title={label}
                            text={value || ''}
                            setText={(val) => handleMetaChange(key, val)}
                            disabled={isFieldDisabled} // Khóa trình soạn thảo
                            isInvalid={invalidObj?.isInvalid}
                            message={invalidObj?.msg}
                        />
                    </Col>
                );

            case 'Check':
                return (
                    <Col key={key} xs={6} md={3}>
                        <Form.Group className="mb-2 d-flex align-items-center h-100 mt-2">
                            <Form.Check 
                                type="checkbox"
                                id={`check-${key}`}
                                // Hiển thị nguyên văn Caption
                                label={<small className="ms-1 fw-bold text-secondary">{label}</small>}
                                checked={!!value}
                                disabled={isFieldDisabled} // Khóa checkbox
                                onChange={(e) => handleMetaChange(key, e.target.checked)}
                            />
                        </Form.Group>
                    </Col>
                );
            case 'RadioOptionsCtl':
                // Tách chuỗi "1_INV|3_PXK" thành mảng ["1_INV", "3_PXK"]
                const options = fieldConfig.default_value ? fieldConfig.default_value.split('|') : [];
                
                return (
                    <Col key={key} xs={6} md={3}>
                        <Form.Group className="mb-2">
                            <Form.Label className="fw-bold mb-1" style={{ fontSize: '0.85rem' }}>
                                {label}
                            </Form.Label>
                            <div className="d-flex flex-wrap gap-3 p-2 border rounded bg-white">
                                {options.map((opt, index) => (
                                    <Form.Check
                                        key={`${key}-${index}`}
                                        type="radio"
                                        id={`radio-${key}-${index}`}
                                        label={<span className="ms-1">{opt}</span>}
                                        name={`group-${key}`} // Đảm bảo chỉ chọn được 1 trong group
                                        value={opt}
                                        checked={value === opt}
                                        disabled={isFieldDisabled}
                                        onChange={() => handleMetaChange(key, opt)}
                                        // Tăng diện tích chạm cho mobile
                                        className="d-flex align-items-center me-3"
                                        style={{ cursor: isFieldDisabled ? 'not-allowed' : 'pointer' }}
                                    />
                                ))}
                            </div>
                            {invalidObj?.isInvalid && (
                                <small className="text-danger d-block mt-1">{invalidObj?.msg}</small>
                            )}
                        </Form.Group>
                    </Col>
                );

            case 'Number':
            case 'TextInputCtl':
            default:
                return (
                    <Col key={key} xs={12} md={6} lg={3}>
                        <TextInputCtl
                            label={label}
                            value={value ?? ''}
                            type={fieldConfig.type === 'Number' ? 'number' : 'text'}
                            onChange={(e) => handleMetaChange(key, e.target.value)}
                            size="sm"
                            disabled={isFieldDisabled} // Input sẽ mờ và không thể gõ
                            allowClear={!isFieldDisabled} 
                            id={key}
                            inValidInput={inValidInput}
                        />
                    </Col>
                );
        }
    };

    return (
        <Accordion className="mt-2 shadow-sm border-0 dynamic-meta-ctl">
            <Accordion.Item eventKey="0" className="border-0">
                <Accordion.Header onClick={() => setIsOpen(!isOpen)} className="bg-white">
                    <div className="d-flex justify-content-between align-items-center w-100 pe-2 p-2">
                        <span className="text-dark">
                            <i className="fa fa-sliders me-2 text-primary"></i>
                            <span className="fw-bold" style={{ fontSize: '1.2rem' }}>{title}</span>
                        </span>
                        <i className={`fa ${isOpen ? 'fa-angle-up' : 'fa-angle-down'} text-muted`} style={{ fontSize: '12px' }}></i>
                    </div>
                </Accordion.Header>
                <Accordion.Body className="bg-white p-2 border-top">
                    <Row className="g-2">
                        {/* Map qua config để đảm bảo thứ tự hiển thị và dùng đúng key */}
                        {Object.keys(config).map(key => renderControl(key, meta[key]))}
                    </Row>
                </Accordion.Body>
            </Accordion.Item>
        </Accordion>
    );
};


const MetaRender = ({ configStructureMeta, meta, setMeta, level = 0, actionCallBack, parentList, parentIndex, errors = {} }) => {
    const { Form, Row, Col, Button } = ReactBootstrap;

    // Helper: Định dạng số hàng nghìn
    const isVi = window.config?.lang === 'vi' || !window.config?.lang;
    const thousandSep = isVi ? '.' : ',';
    const decimalSep = isVi ? ',' : '.';

    const formatNumber = (val) => {
        if (val === undefined || val === null || val === '') return '';
        let str = val.toString();
        
        // Preserve negative sign if it is alone
        if (str === '-') return '-';
        
        const isNegative = str.startsWith('-');
        if (isNegative) {
            str = str.substring(1);
        }
        
        const parts = str.split('.');
        const intPart = parseFloat(parts[0]);
        if (isNaN(intPart)) return isNegative ? '-' : '';
        
        const formattedInt = new Intl.NumberFormat(isVi ? 'vi-VN' : 'en-US').format(intPart);
        
        let result = formattedInt;
        if (parts.length > 1) {
            result = formattedInt + decimalSep + parts[1];
        }
        return isNegative ? '-' + result : result;
    };

    const styles = {
        container: { fontSize: '13px', fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif' },
        fieldWrapper: { marginBottom: '8px', padding: '0 4px' },
        nestedSection: {
            marginLeft: level > 0 ? '10px' : '0',
            paddingLeft: level > 0 ? '10px' : '0',
            borderLeft: level > 0 ? '2px solid #dee2e6' : 'none',
            marginBottom: '12px'
        },
        label: (isRequired) => ({
            fontSize: '11.5px',
            fontWeight: '600',
            color: isRequired ? '#dc3545' : '#555',
            marginBottom: '3px',
            display: 'block'
        }),
        input: { 
            fontSize: '13px', 
            borderRadius: '6px', 
            border: '1px solid #ced4da',
            transition: 'border-color 0.15s ease-in-out'
        },
        numberInput: { textAlign: 'right', fontWeight: '500' },
        listCard: {
            backgroundColor: '#ffffff',
            border: '1px solid #e0e0e0',
            borderRadius: '8px',
            padding: '10px',
            marginBottom: '6px',
            position: 'relative',
            boxShadow: '0 1px 3px rgba(0,0,0,0.05)'
        },
        deleteBtn: {
            position: 'absolute',
            top: '-8px',
            right: '-8px',
            padding: '0',
            width: '20px',
            height: '20px',
            fontSize: '12px',
            borderRadius: '50%',
            zIndex: 10
        }
    };

    const hasFieldError = (fieldKey, parentList, parentIndex) => {
        if (!errors) return false;
        
        if (parentList !== undefined && parentIndex !== undefined) {
            if (fieldKey === 'threshold_from') {
                return !!(
                    errors[`tiers_${parentIndex}_from`] ||
                    errors[`tiers_${parentIndex}_from_neg`] ||
                    errors[`tiers_${parentIndex}_overlap`] ||
                    errors[`tiers_${parentIndex}_gap`]
                );
            }
            if (fieldKey === 'threshold_to') {
                return !!(
                    errors[`tiers_${parentIndex}_to`] ||
                    errors[`tiers_${parentIndex}_to_neg`] ||
                    errors[`tiers_${parentIndex}_to_compare_from`]
                );
            }
            if (fieldKey === 'tier_value') {
                return !!errors[`tiers_${parentIndex}_value`];
            }
        } else {
            return !!errors[fieldKey];
        }
        return false;
    };

    const getFieldErrorText = (fieldKey, parentList, parentIndex) => {
        if (!errors) return '';
        
        if (parentList !== undefined && parentIndex !== undefined) {
            if (fieldKey === 'threshold_from') {
                return (
                    errors[`tiers_${parentIndex}_from`] ||
                    errors[`tiers_${parentIndex}_from_neg`] ||
                    errors[`tiers_${parentIndex}_overlap`] ||
                    errors[`tiers_${parentIndex}_gap`] ||
                    ''
                );
            }
            if (fieldKey === 'threshold_to') {
                return (
                    errors[`tiers_${parentIndex}_to`] ||
                    errors[`tiers_${parentIndex}_to_neg`] ||
                    errors[`tiers_${parentIndex}_to_compare_from`] ||
                    ''
                );
            }
            if (fieldKey === 'tier_value') {
                return errors[`tiers_${parentIndex}_value`] || '';
            }
        } else {
            return errors[fieldKey] || '';
        }
        return '';
    };

    const handleUpdate = (path, value) => {
        const updateDeep = (obj, pathArray, val) => {
            const [current, ...rest] = pathArray;
            if (rest.length === 0) {
                let finalVal = val;
                // Tự động chuẩn hóa liên kết mốc khi cập nhật mảng (ví dụ: sau khi xóa)
                if (Array.isArray(val) && val.length > 0 && typeof val[0] === 'object' && val[0] !== null && 'threshold_from' in val[0] && 'threshold_to' in val[0]) {
                    finalVal = val.map((item, idx) => {
                        if (idx === 0) return item;
                        return {
                            ...item,
                            threshold_from: val[idx - 1].threshold_to
                        };
                    });
                }
                return { ...obj, [current]: finalVal };
            }
            return {
                ...obj,
                [current]: updateDeep(obj[current] || {}, rest, val)
            };
        };

        const pathParts = path.split('.');
        if (pathParts.length === 3 && pathParts[2] === 'threshold_to') {
            const listKey = pathParts[0];
            const idx = parseInt(pathParts[1]);
            const nextIdx = idx + 1;
            
            setMeta(prev => {
                let updated = updateDeep(prev, pathParts, value);
                const list = updated[listKey];
                if (Array.isArray(list) && nextIdx < list.length) {
                    const nextPath = `${listKey}.${nextIdx}.threshold_from`;
                    updated = updateDeep(updated, nextPath.split('.'), value);
                }
                return updated;
            });
        } else {
            setMeta(prev => updateDeep(prev, pathParts, value));
        }
    };

    // Xử lý sự kiện nhấn phím Enter
    const handleKeyDown = (e, cfg, key, val) => {
        if (e.key === 'Enter' && cfg.action_callback && actionCallBack) {
            e.preventDefault(); // Ngăn submit form mặc định
            actionCallBack(key, val);
        }
    };

    const handleAddListItem = (path, itemProperties, currentList) => {
        const newItem = {};
        Object.keys(itemProperties).forEach(key => {
            if (itemProperties[key].type === 'list_object') newItem[key] = [];
            else if (itemProperties[key].type === 'object') newItem[key] = {};
            else newItem[key] = itemProperties[key].defaultValue || (itemProperties[key].type === 'number' ? 0 : '');
        });
        
        // Tự động điền mốc Từ của dòng mới bằng mốc Đến của dòng cuối cùng trước đó
        if (currentList && currentList.length > 0) {
            const lastItem = currentList[currentList.length - 1];
            if ('threshold_from' in newItem && lastItem && 'threshold_to' in lastItem) {
                newItem.threshold_from = lastItem.threshold_to;
            }
        }
        
        handleUpdate(path, [...(currentList || []), newItem]);
    };

    const renderControl = (cfg, val, path, fieldKey) => {
        const isRequired = cfg.required === true;
        
        // Khóa cứng Từ mốc (threshold_from) của các dòng từ dòng thứ 2 trở đi (index > 0)
        let isControlDisabled = cfg.disabled;
        if (fieldKey === 'threshold_from' && parentIndex !== undefined && parentIndex > 0) {
            isControlDisabled = true;
        }

        const commonProps = {
            size: "sm",
            style: { ...styles.input, ...(cfg.type === 'number' ? styles.numberInput : {}) },
            disabled: isControlDisabled,
            placeholder: cfg.placeholder || '',
            onKeyDown: (e) => handleKeyDown(e, cfg, fieldKey, val) // Gắn sự kiện Enter
        };

        switch (cfg.type) {
            case 'dropdown':
                return (
                    <Form.Select 
                        {...commonProps} 
                        value={val || ''} 
                        isInvalid={hasFieldError(fieldKey, parentList, parentIndex)}
                        onChange={(e) => handleUpdate(path, e.target.value)}
                    >
                        <option value="">-- Chọn --</option>
                        {cfg.options?.map(opt => <option key={opt.value} value={opt.value}>{opt.label}</option>)}
                    </Form.Select>
                );
            case 'check':
                return (
                    <div className="d-flex align-items-center h-100 pt-3">
                        <Form.Check 
                            type="switch" 
                            id={path}
                            label={<span style={styles.label(isRequired)}>{cfg.label} {isRequired && '*'}</span>} 
                            checked={!!val} 
                            disabled={cfg.disabled}
                            onChange={(e) => {
                                const newValue = e.target.checked;
                                handleUpdate(path, newValue);
                                // Call nhanh nếu là checkbox và có action_callback (thường Enter cho text, nhưng trigger on change cho switch sẽ tiện hơn)
                                if(cfg.action_callback && actionCallBack) actionCallBack(fieldKey, newValue);
                            }} 
                        />
                    </div>
                );
            case 'multicheck':
                const selectedList = Array.isArray(val) ? val : [];
                return (
                    <div className="d-flex flex-wrap gap-2 border rounded p-2 bg-white" style={{ minHeight: '31px', borderColor: '#ced4da', width: '100%' }}>
                        {cfg.options?.map(opt => {
                            const isChecked = selectedList.includes(opt.value);
                            return (
                                <Form.Check
                                    inline
                                    type="checkbox"
                                    id={`${path}-${opt.value}`}
                                    key={opt.value}
                                    label={opt.label}
                                    checked={isChecked}
                                    disabled={cfg.disabled}
                                    onChange={(e) => {
                                        let newList;
                                        if (e.target.checked) {
                                            newList = [...selectedList, opt.value];
                                        } else {
                                            newList = selectedList.filter(v => v !== opt.value);
                                        }
                                        handleUpdate(path, newList);
                                    }}
                                    style={{ fontSize: '11.5px', marginRight: '8px', marginBottom: '2px' }}
                                />
                            );
                        })}
                    </div>
                );
            case 'number':
                let customPlaceholder = cfg.placeholder || '';
                if (fieldKey === 'threshold_to' && parentList && parentIndex === parentList.length - 1) {
                    customPlaceholder = isVi ? "Trở đi" : "∞";
                }
                return (
                    <Form.Control 
                        {...commonProps} 
                        placeholder={customPlaceholder}
                        step={cfg.step || "any"}
                        type="text" 
                        value={formatNumber(val)} 
                        isInvalid={hasFieldError(fieldKey, parentList, parentIndex)}
                        onChange={(e) => {
                            let valStr = e.target.value;
                            const stepStr = String(cfg.step || 'any');
                            let allowDecimals = stepStr !== '1';
                            if (fieldKey === 'threshold_from' || fieldKey === 'threshold_to') {
                                allowDecimals = false;
                            }
                            
                            let raw = valStr;
                            
                            if (!allowDecimals) {
                                // Chỉ cho phép số nguyên
                                raw = valStr.replace(/[^0-9-]/g, '');
                            } else {
                                // Tự động phát hiện và xử lý dấu thập phân (dấu chấm hoặc phẩy)
                                const dots = (valStr.match(/\./g) || []).length;
                                const commas = (valStr.match(/,/g) || []).length;
                                
                                if (dots > 0 && commas > 0) {
                                    const lastDot = valStr.lastIndexOf('.');
                                    const lastComma = valStr.lastIndexOf(',');
                                    if (lastDot > lastComma) {
                                        raw = valStr.split(',').join('');
                                    } else {
                                        raw = valStr.split('.').join('').replace(',', '.');
                                    }
                                } else if (dots > 1) {
                                    raw = valStr.split('.').join('');
                                } else if (commas > 1) {
                                    raw = valStr.split(',').join('');
                                } else if (dots === 1) {
                                    raw = valStr;
                                } else if (commas === 1) {
                                    raw = valStr.replace(',', '.');
                                }
                                
                                raw = raw.replace(/[^0-9.-]/g, '');
                                
                                const hasMinus = raw.startsWith('-');
                                if (hasMinus) {
                                    raw = '-' + raw.substring(1).replace(/-/g, '');
                                } else {
                                    raw = raw.replace(/-/g, '');
                                }
                                
                                const dotIndex = raw.indexOf('.');
                                if (dotIndex !== -1) {
                                    raw = raw.substring(0, dotIndex + 1) + raw.substring(dotIndex + 1).replace(/\./g, '');
                                }
                            }
                            
                            if (raw === '' || raw === '-') {
                                handleUpdate(path, raw);
                                return;
                            }
                            
                            const parsed = parseFloat(raw);
                            if (!isNaN(parsed)) {
                                handleUpdate(path, raw);
                            }
                        }} 
                    />
                );
            case 'textarea':
                return (
                    <Form.Control 
                        {...commonProps} 
                        as="textarea"
                        rows={cfg.rows || 3}
                        value={val || ''} 
                        isInvalid={hasFieldError(fieldKey, parentList, parentIndex)}
                        onChange={(e) => handleUpdate(path, e.target.value)} 
                    />
                );
            default:
                return (
                    <Form.Control 
                        {...commonProps} 
                        type={cfg.type || 'text'} 
                        value={val || ''} 
                        isInvalid={hasFieldError(fieldKey, parentList, parentIndex)}
                        onChange={(e) => handleUpdate(path, e.target.value)} 
                    />
                );
        }
    };

    const renderFields = (config, data, currentPath = "") => {
        if (!config) return null;
        const keys = Object.keys(config);

        return keys.map((key, index) => {
            const fieldConfig = config[key];
            const fieldPath = currentPath ? `${currentPath}.${key}` : key;
            const fieldValue = data ? data[key] : undefined;
            const isRequired = fieldConfig.required === true;
            
            if (fieldConfig.visible === false) return null;

            if (fieldConfig.type === 'list_object') {
                const list = Array.isArray(fieldValue) ? fieldValue : [];
                return (
                    <Col xs={12} key={fieldPath} style={styles.nestedSection}>
                        <div className="d-flex justify-content-between align-items-center mb-2 border-bottom pb-1">
                            <span style={{...styles.label(isRequired), color: '#007bff', fontSize: '12px'}}>
                                <i className="fa fa-list-ul me-1"></i> {fieldConfig.label} {isRequired && '*'}
                            </span>
                            <Button variant="outline-primary" size="sm" style={{padding: '0px 8px', fontSize: '11px'}} 
                                onClick={() => handleAddListItem(fieldPath, fieldConfig.itemProperties, list)}>
                                <i className="fa fa-plus me-1"></i>Thêm
                            </Button>
                        </div>
                        {list.map((item, idx) => (
                            <div key={`${fieldPath}.${idx}`} style={styles.listCard}>
                                <Button variant="danger" size="sm" style={styles.deleteBtn} 
                                    onClick={() => {
                                        const newList = [...list];
                                        newList.splice(idx, 1);
                                        handleUpdate(fieldPath, newList);
                                    }}>
                                    <i className="fa fa-times"></i>
                                </Button>
                                <Row className="g-2">
                                    <MetaRender 
                                        configStructureMeta={fieldConfig.itemProperties} 
                                        meta={item} 
                                        setMeta={(updatedItem) => {
                                            const newArray = [...list];
                                            newArray[idx] = typeof updatedItem === 'function' ? updatedItem(item) : updatedItem;
                                            handleUpdate(fieldPath, newArray);
                                        }}
                                        level={level + 1}
                                        actionCallBack={actionCallBack} // Truyền callback xuống đệ quy
                                        parentList={list}
                                        parentIndex={idx}
                                        errors={errors}
                                    />
                                </Row>
                            </div>
                        ))}
                    </Col>
                );
            }

            if (fieldConfig.type === 'object') {
                return (
                    <Col xs={12} key={fieldPath} style={styles.nestedSection}>
                        <div className="mb-2 border-bottom pb-1">
                            <span style={{...styles.label(isRequired), color: '#28a745', fontSize: '12px'}}>
                                <i className="fa fa-cube me-1"></i> {fieldConfig.label} {isRequired && '*'}
                            </span>
                        </div>
                        <div style={{...styles.listCard, borderStyle: 'dashed', backgroundColor: '#fcfcfc'}}>
                            <Row className="g-2">
                                <MetaRender 
                                    configStructureMeta={fieldConfig.itemProperties || fieldConfig.properties} 
                                    meta={fieldValue || {}} 
                                    setMeta={(updatedObj) => {
                                        const newVal = typeof updatedObj === 'function' ? updatedObj(fieldValue || {}) : updatedObj;
                                        handleUpdate(fieldPath, newVal);
                                    }}
                                    level={level + 1}
                                    actionCallBack={actionCallBack} // Truyền callback xuống đệ quy
                                    errors={errors}
                                />
                            </Row>
                        </div>
                    </Col>
                );
            }

            const errorText = getFieldErrorText(key, parentList, parentIndex);

            return (
                <Col 
                    xs={12} 
                    md={fieldConfig.width || 6} 
                    key={fieldPath} 
                    style={styles.fieldWrapper}
                    className={index === keys.length - 1 ? "d-flex flex-column align-items-md-end" : ""}
                >
                    <div style={{width: '100%'}}>
                        {fieldConfig.type !== 'check' && (
                            <Form.Label style={styles.label(isRequired)}>
                                {fieldConfig.label} {isRequired && <span className="ms-1">*</span>}
                            </Form.Label>
                        )}
                        <div style={{ position: 'relative' }}>
                            {renderControl(fieldConfig, fieldValue, fieldPath, key)}
                            {errorText && (
                                <div className="custom-error-tooltip-wrapper">
                                    <span className="custom-error-icon">!</span>
                                    <div className="custom-error-tooltip-text">{errorText}</div>
                                </div>
                            )}
                        </div>
                    </div>
                </Col>
            );
        });
    };

    return (
        <div style={styles.container} className="meta-render-root">
            <style>{`
                /* CSS Tooltip lỗi tùy chỉnh */
                .custom-error-tooltip-wrapper {
                    position: absolute;
                    top: -8px;
                    right: 8px;
                    z-index: 100;
                    display: inline-block;
                }
                .custom-error-icon {
                    display: inline-flex;
                    align-items: center;
                    justify-content: center;
                    width: 16px;
                    height: 16px;
                    border-radius: 50%;
                    background-color: #dc3545;
                    color: #fff;
                    font-size: 10px;
                    font-weight: bold;
                    cursor: help;
                    box-shadow: 0 2px 4px rgba(0,0,0,0.2);
                }
                .custom-error-tooltip-text {
                    visibility: hidden;
                    width: 220px;
                    background-color: #333;
                    color: #fff;
                    text-align: center;
                    border-radius: 6px;
                    padding: 6px 10px;
                    position: absolute;
                    z-index: 101;
                    bottom: 130%;
                    right: -10px;
                    opacity: 0;
                    transition: opacity 0.2s, visibility 0.2s;
                    font-size: 11.5px;
                    box-shadow: 0 4px 8px rgba(0,0,0,0.25);
                    pointer-events: none;
                    line-height: 1.4;
                }
                .custom-error-tooltip-text::after {
                    content: "";
                    position: absolute;
                    top: 100%;
                    right: 13px;
                    border-width: 5px;
                    border-style: solid;
                    border-color: #333 transparent transparent transparent;
                }
                .custom-error-tooltip-wrapper:hover .custom-error-tooltip-text {
                    visibility: visible;
                    opacity: 1;
                }
                
                /* Ẩn dấu chấm than mặc định của Bootstrap và tăng padding-right */
                .form-control.is-invalid, .was-validated .form-control:invalid {
                    background-image: none !important;
                    padding-right: 32px !important;
                }
                .form-select.is-invalid, .was-validated .form-select:invalid {
                    background-image: none !important;
                    padding-right: 32px !important;
                }
            `}</style>
            <Row className="g-0">
                {renderFields(configStructureMeta, meta)}
            </Row>
        </div>
    );
};

const JsonViewCard = ({ meta }) => {
    const { Card, Accordion, Badge, Button } = ReactBootstrap;

    const jsonStyle = {
        backgroundColor: '#1e1e1e',
        padding: '15px',
        borderRadius: '8px',
        fontSize: '13px',
        fontFamily: '"Fira Code", "Cascadia Code", Monaco, monospace',
        maxHeight: '400px',
        overflowY: 'auto',
        color: '#d4d4d4',
        border: '1px solid #333'
    };

    const syntaxHighlight = (json) => {
        if (!json) return '<span style="color: #6a9955;">// [Trống]: Không có dữ liệu</span>';
        let displayJson = json;
        try {
            if (typeof json === 'string') displayJson = JSON.parse(json);
        } catch (e) {
            displayJson = json;
        }
        const jsonString = JSON.stringify(displayJson, undefined, 2);
        return jsonString.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+-]?\d+)?)/g, function (match) {
            let cls = 'color: #ce9178;';
            if (/^"/.test(match)) {
                if (/:$/.test(match)) cls = 'color: #9cdcfe; font-weight: bold;';
            } else if (/true|false/.test(match)) {
                cls = 'color: #569cd6;';
            } else if (/null/.test(match)) {
                cls = 'color: #6c757d;';
            } else {
                cls = 'color: #b5cea8;';
            }
            return `<span style="${cls}">${match}</span>`;
        });
    };

    return (
        <Accordion className="shadow-sm mb-3"> {/* Không có defaultActiveKey = Mặc định đóng */}
            <Accordion.Item eventKey="0" style={{ border: 'none', borderRadius: '8px', overflow: 'hidden' }}>
                <Accordion.Button 
                    className="bg-white d-flex justify-content-between align-items-center shadow-none custom-accordion-btn"
                    style={{ padding: '12px 20px', borderBottom: '1px solid #f0f0f0' }}
                >
                    <div className="d-flex align-items-center">
                        <div className="bg-dark-subtle p-2 rounded me-3 d-flex align-items-center justify-content-center" style={{width: '32px', height: '32px'}}>
                            <i className="fa fa-database text-dark" style={{fontSize: '14px'}}></i>
                        </div>
                        <div className="text-start">
                            <span className="fw-bold text-dark d-block" style={{ fontSize: '13px', lineHeight: '1' }}>DỮ LIỆU JSON META</span>
                            <small className="text-muted" style={{fontSize: '11px'}}>Click để xem chi tiết cấu hình raw</small>
                        </div>
                    </div>
                    {/* Icon mũi tên sẽ được tự động thêm bởi class .accordion-button của Bootstrap */}
                </Accordion.Button>

                <Accordion.Body className="bg-white p-3">
                    <div style={jsonStyle}>
                        <pre 
                            className="m-0"
                            style={{ whiteSpace: 'pre-wrap', wordBreak: 'break-all' }}
                            dangerouslySetInnerHTML={{ __html: syntaxHighlight(meta) }} 
                        />
                    </div>
                    <div className="d-flex justify-content-between align-items-center mt-2">
                        <Badge bg="light" text="dark" className="border fw-normal">Format: JSON Pretty</Badge>
                        <Button 
                            variant="link" 
                            size="sm" 
                            className="text-decoration-none text-primary p-0"
                            onClick={(e) => {
                                e.stopPropagation(); // Ngăn việc đóng accordion khi bấm nút copy
                                const text = typeof meta === 'string' ? meta : JSON.stringify(meta, null, 2);
                                navigator.clipboard.writeText(text);
                                alert("Đã copy!");
                            }}
                        >
                            <i className="fa fa-copy me-1"></i> Copy
                        </Button>
                    </div>
                </Accordion.Body>
            </Accordion.Item>

            {/* CSS bổ sung để tinh chỉnh icon collapse của Bootstrap */}
            <style>{`
                .custom-accordion-btn::after {
                    margin-left: auto;
                    font-size: 12px;
                    width: 1.25rem;
                    height: 1.25rem;
                    background-size: 1.25rem;
                }
                .custom-accordion-btn:not(.collapsed) {
                    background-color: #fff !important;
                    color: inherit !important;
                    box-shadow: none !important;
                }
            `}</style>
        </Accordion>
    );
};

const DynamicFieldRenderer = ({ fieldKey, config, value, onChange }) => {
    const { type, label, options, placeholder } = config;

    const handleChange = (e) => {
        const { value, type, checked } = e.target;
        onChange(fieldKey, type === 'checkbox' ? checked : value);
    };

    switch (type) {
        case 'number':
        case 'text':
            return <TextInputCtl label={label} type={type} value={value || ''} onChange={handleChange} placeholder={placeholder} />;
        case 'dropdown':
            return <DropdownCtl label={label} options={options || []} value={value || ''} onChange={handleChange} />;
        case 'switch':
            return <CheckBoxCtl type="switch" label={label} checked={!!value} onChange={handleChange} />;
        default:
            return (
                <Form.Group>
                    <Form.Label>{label}</Form.Label>
                    <Form.Control
                        type="text"
                        value={value || ''}
                        onChange={handleChange}
                        placeholder={`Kiểu dữ liệu không xác định: ${type}`}
                        disabled
                    />
                </Form.Group>
            );
    }
};