/**
 * PercentageInput widget component with % suffix.
 *
 * ⚠️ AUTO-GENERATED BY PRISM - DO NOT EDIT
 */

import type { ChangeEvent } from 'react';
import type { WidgetBaseProps } from '../types';

interface PercentageInputProps extends WidgetBaseProps<number | null> {
  /** If true, value is stored as decimal (0.5 = 50%), otherwise as percentage (50 = 50%) */
  storeAsDecimal?: boolean;
  min?: number;
  max?: number;
  step?: number;
}

export function PercentageInput({
  name,
  value,
  onChange,
  label,
  description,
  placeholder = '0',
  required,
  disabled,
  error,
  className,
  storeAsDecimal = false,
  min = 0,
  max = 100,
  step = 0.01,
}: PercentageInputProps): JSX.Element {
  // Convert value for display (always show as percentage)
  const displayValue = value !== null && value !== undefined
    ? (storeAsDecimal ? value * 100 : value)
    : '';

  const handleChange = (e: ChangeEvent<HTMLInputElement>) => {
    const raw = e.target.value;
    if (raw === '') {
      onChange(null);
      return;
    }
    const parsed = parseFloat(raw);
    if (!isNaN(parsed)) {
      // Convert back if storing as decimal
      onChange(storeAsDecimal ? parsed / 100 : parsed);
    }
  };

  return (
    <div className={className}>
      {label && (
        <label htmlFor={name} className="label">
          {label}
          {required && <span className="text-red-500 ml-1">*</span>}
        </label>
      )}
      <div className="relative">
        <input
          id={name}
          type="number"
          name={name}
          value={displayValue}
          onChange={handleChange}
          placeholder={placeholder}
          disabled={disabled}
          required={required}
          min={min}
          max={max}
          step={step}
          className={`${error ? 'input-error' : 'input'} pr-8`}
          aria-invalid={!!error}
          aria-describedby={description ? `${name}-desc` : error ? `${name}-error` : undefined}
        />
        <span className="absolute right-3 top-1/2 -translate-y-1/2 text-nordic-500">%</span>
      </div>
      {description && !error && (
        <p id={`${name}-desc`} className="mt-1.5 text-sm text-nordic-500">{description}</p>
      )}
      {error && (
        <p id={`${name}-error`} className="mt-1.5 text-sm text-red-600">
          {error}
        </p>
      )}
    </div>
  );
}
