import React from 'react'
import { Icon } from './icon.js'

/**
 * Single-line text input with optional label, hint/error and leading icon.
 */
export interface InputProps {
  label?: string;
  /** Small gray helper under the field */
  hint?: string;
  /** Replaces hint; turns the border madder red */
  error?: string;
  /** Lucide icon name, leading */
  icon?: string;
  /** Mono text for machine values (urls, tokens) @default false */
  mono?: boolean;
  placeholder?: string;
  value?: string;
  defaultValue?: string;
  onChange?: (e: React.ChangeEvent<HTMLInputElement>) => void;
  disabled?: boolean;
  type?: string;
  style?: React.CSSProperties;
}

const CSS = `
.ct-field { display: flex; flex-direction: column; gap: 6px; }
.ct-field__label { font: 600 13px/1.2 var(--font-sans); color: var(--ink-1); }
.ct-field__wrap { position: relative; display: flex; align-items: center; }
.ct-field__icon { position: absolute; left: 10px; color: var(--ink-3); pointer-events: none; display: flex; }
.ct-input {
  width: 100%; height: 34px;
  font: var(--text-body);
  color: var(--ink-1);
  background: var(--surface-card);
  border: 1px solid var(--line-2);
  border-radius: var(--radius-2);
  padding: 0 12px;
  transition: border-color var(--duration-fast) var(--ease-out);
}
.ct-input::placeholder { color: var(--ink-3); }
.ct-input:hover:not(:disabled):not(:focus) { border-color: var(--border-strong); background: var(--paper-1); }
.ct-input:focus { outline: none; border-color: var(--accent); box-shadow: 0 0 0 1px var(--accent); }
.ct-input:disabled { opacity: 0.5; background: var(--paper-2); cursor: not-allowed; }
.ct-input--icon { padding-left: 32px; }
.ct-input--error { border-color: var(--danger); }
.ct-input--error:focus { border-color: var(--danger); box-shadow: 0 0 0 1px var(--danger); }
.ct-input--mono { font: var(--text-data); }
.ct-field__hint { font: var(--text-caption); color: var(--ink-3); margin: 0; }
.ct-field__error { font: var(--text-caption); color: var(--danger); margin: 0; }
`;
(function inject() {
  if (typeof document !== 'undefined' && !document.getElementById('ct-input-css')) {
    const s = document.createElement('style'); s.id = 'ct-input-css'; s.textContent = CSS;
    document.head.appendChild(s);
  }
})();

export function Input({ label, hint, error, icon, mono = false, style, ...rest }: InputProps) {
  const cls = [
    'ct-input',
    icon ? 'ct-input--icon' : '',
    error ? 'ct-input--error' : '',
    mono ? 'ct-input--mono' : '',
  ].filter(Boolean).join(' ');
  return (
    <div className="ct-field" style={style}>
      {label ? <label className="ct-field__label">{label}</label> : null}
      <div className="ct-field__wrap">
        {icon ? <span className="ct-field__icon"><Icon name={icon} size={15} /></span> : null}
        <input className={cls} {...rest} />
      </div>
      {error ? <p className="ct-field__error">{error}</p> : hint ? <p className="ct-field__hint">{hint}</p> : null}
    </div>
  );
}
