/**
 * Select Component - ProRank SEO
 *
 * Shared select primitive backed by the shipped ProRank form styles.
 */

import React from 'react';
import clsx from 'clsx';

const sizeStyles = {
  sm: { fontSize: '13px', padding: '7px 36px 7px 12px' },
  md: { fontSize: '14px', padding: '8px 36px 8px 12px' },
  lg: { fontSize: '16px', padding: '10px 40px 10px 14px' },
};

const Select = React.forwardRef(({
  label,
  id,
  name,
  value,
  onChange,
  onBlur,
  error,
  helperText,
  disabled = false,
  required = false,
  className = '',
  selectClassName = '',
  fullWidth = true,
  size = 'md',
  children,
  options,
  placeholder = 'Select an option',
  ...props
}, ref) => {
  const selectId = id || name || `select-${Math.random().toString(36).slice(2, 11)}`;
  const hasError = Boolean(error);

  return (
    <div
      className={className}
      style={{
        display: 'grid',
        gap: '8px',
        width: fullWidth ? '100%' : undefined,
        opacity: disabled ? 0.6 : 1,
      }}
    >
      {label && (
        <label
          htmlFor={selectId}
          style={{
            fontSize: '13px',
            fontWeight: 600,
            color: hasError ? '#b91c1c' : '#374151',
          }}
        >
          {label}
          {required && <span style={{ color: '#dc2626', marginLeft: 4 }}>*</span>}
        </label>
      )}

      <select
        ref={ref}
        id={selectId}
        name={name}
        value={value}
        onChange={(event) => onChange?.(event.target.value)}
        onBlur={onBlur}
        disabled={disabled}
        required={required}
        aria-invalid={hasError}
        aria-describedby={
          error ? `${selectId}-error` : helperText ? `${selectId}-helper` : undefined
        }
        className={clsx('prorank-select', { error: hasError }, selectClassName)}
        style={sizeStyles[size] || sizeStyles.md}
        {...props}
      >
        {options ? (
          <>
            {placeholder && (
              <option value="" disabled>
                {placeholder}
              </option>
            )}
            {options.map((option) => (
              <option
                key={option.value}
                value={option.value}
                disabled={option.disabled}
              >
                {option.label}
              </option>
            ))}
          </>
        ) : (
          children
        )}
      </select>

      {error && (
        <p
          id={`${selectId}-error`}
          role="alert"
          style={{ margin: 0, fontSize: '12px', color: '#b91c1c' }}
        >
          {error}
        </p>
      )}

      {helperText && !error && (
        <p
          id={`${selectId}-helper`}
          style={{ margin: 0, fontSize: '12px', color: '#6b7280', lineHeight: 1.5 }}
        >
          {helperText}
        </p>
      )}
    </div>
  );
});

Select.displayName = 'Select';

export default Select;
