/**
 * Dynamic Text Control Component
 *
 * TextControl with integrated dynamic variables button.
 *
 * @package
 * @since   1.0.0
 */

import { TextControl } from '@wordpress/components';
import { useRef } from '@wordpress/element';
import DynamicVariables from './DynamicVariables';

const DynamicTextControl = ({
  label,
  value,
  onChange,
  help,
  placeholder,
  context = 'post',
  disabled = false,
  showVariables = true,
  ...props
}) => {
  const inputRef = useRef();

  const handleInsertVariable = (variable) => {
    // Get the input element
    const input = inputRef.current?.querySelector('input');
    if (!input) {
      // If no cursor position, append to end
      onChange(value + variable);
      return;
    }

    // Get cursor position
    const start = input.selectionStart;
    const end = input.selectionEnd;

    // Insert variable at cursor position
    const newValue = value.substring(0, start) + variable + value.substring(end);
    onChange(newValue);

    // Set cursor position after the inserted variable
    setTimeout(() => {
      const newPosition = start + variable.length;
      input.setSelectionRange(newPosition, newPosition);
      input.focus();
    }, 0);
  };

  return (
    <div className="prorank-dynamic-text-control" ref={inputRef}>
      <div className="prorank-dynamic-text-control__wrapper">
        <TextControl
          label={
            <span className="prorank-dynamic-text-control__label">
              {label}
              {showVariables && !disabled && (
                <DynamicVariables
                  onInsert={handleInsertVariable}
                  context={context}
                  disabled={disabled}
                />
              )}
            </span>
          }
          value={value}
          onChange={onChange}
          help={help}
          placeholder={placeholder}
          disabled={disabled}
          {...props}
        />
      </div>
    </div>
  );
};

export default DynamicTextControl;
